Compare commits
10 commits
6a3de67267
...
991fcdda6d
Author | SHA1 | Date | |
---|---|---|---|
991fcdda6d | |||
928f0beebe | |||
4c0e47830c | |||
15d28a54dc | |||
d3c319c876 | |||
b75f7ae9fe | |||
4c6eb04cdd | |||
fa2b8dd384 | |||
0330e905e9 | |||
4ed84bcb4f |
19 changed files with 151 additions and 176 deletions
|
@ -3,9 +3,6 @@
|
|||
<pre>
|
||||
<a href='.'>.</a>
|
||||
├─ <a href='jekyll_site'>jekyll_site</a>
|
||||
│ ├─ <a href='jekyll_site/_includes'>_includes</a>
|
||||
│ │ ├─ <a href='jekyll_site/_includes/counters_body.html'>counters_body.html</a>
|
||||
│ │ └─ <a href='jekyll_site/_includes/counters_head.html'>counters_head.html</a>
|
||||
│ ├─ <a href='jekyll_site/css'>css</a>/<a href='jekyll_site/css/pomodoro5.css'>pomodoro5.css</a>
|
||||
│ ├─ <a href='jekyll_site/en'>en</a>
|
||||
│ │ ├─ <a href='jekyll_site/en/2023'>2023</a>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
© Головин Г.Г., 2021-2023
|
||||
© Головин Г.Г., 2021-2024
|
||||
|
||||
Опубликовано под [Открытой лицензией 1.1](OPEN_LICENSE.txt)
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
|||
|
||||
---
|
||||
|
||||
© Golovin G.G., translation from Russian, 2021-2023
|
||||
© Golovin G.G., translation from Russian, 2021-2024
|
||||
|
||||
Published under the [Open License 1.1](OPEN_LICENSE.txt)
|
||||
|
||||
|
|
88
build.sh
88
build.sh
|
@ -1,39 +1,36 @@
|
|||
#!/bin/bash
|
||||
echo "Сборка сайта в двух помидорных темах и оптимизация результатов."
|
||||
currentTimeMillis=$(date '+%s%3N')
|
||||
rm -rf _site
|
||||
rm -rf _site_older
|
||||
rm -rf _site_color
|
||||
echo "Сборка старого помидора."
|
||||
mkdir -p _site_older
|
||||
cp -r jekyll_site/_includes _site_older
|
||||
cp -r jekyll_site/ru _site_older
|
||||
cp -r jekyll_site/en _site_older
|
||||
cp -r jekyll_site/ru/index.md _site_older
|
||||
cp -r jekyll_site/_config_older.yml _site_older/_config.yml
|
||||
cp -r jekyll_site/Gemfile_older _site_older/Gemfile
|
||||
cd _site_older || exit
|
||||
jekyll build --disable-disk-cache
|
||||
cp -r _site ..
|
||||
cd ..
|
||||
echo "Сборка цветного помидора."
|
||||
mkdir -p _site_color
|
||||
cp -r jekyll_site/_includes _site_color
|
||||
cp -r jekyll_site/ru _site_color
|
||||
cp -r jekyll_site/en _site_color
|
||||
cp -r jekyll_site/ru/index.md _site_color
|
||||
cp -r jekyll_site/_config_color.yml _site_color/_config.yml
|
||||
cp -r jekyll_site/Gemfile_color _site_color/Gemfile
|
||||
cd _site_color || exit
|
||||
jekyll build --disable-disk-cache
|
||||
cp -r _site ../_site/color
|
||||
cd ..
|
||||
echo "Копирование без сборки."
|
||||
time_ms="$(date '+%s%3N')"
|
||||
# удаление каталогов предыдущей сборки, если таковые имеются
|
||||
find . -maxdepth 1 -type d -name "_site*" -exec rm -rf {} \;
|
||||
# сборка сайта в двух помидорных темах
|
||||
function jekyll_build {
|
||||
case "$1" in
|
||||
"older") echo "Сборка старого помидора." ;;
|
||||
"color") echo "Сборка цветного помидора." ;;
|
||||
*) return ;; # две помидорные темы оформления
|
||||
esac
|
||||
mkdir -p "_site_$1"
|
||||
cp -r "jekyll_site/ru" "_site_$1"
|
||||
cp -r "jekyll_site/en" "_site_$1"
|
||||
cp -r "jekyll_site/ru/index.md" "_site_$1"
|
||||
cp -r "jekyll_site/_config_$1.yml" "_site_$1/_config.yml"
|
||||
cp -r "jekyll_site/Gemfile_$1" "_site_$1/Gemfile"
|
||||
cd "_site_$1" || return
|
||||
jekyll build --disable-disk-cache --quiet
|
||||
}
|
||||
export -f jekyll_build
|
||||
# запуск параллельной сборки сайта в двух помидорных темах оформления
|
||||
printf 'jekyll_build "%s"\0' {older,color} | xargs -n1 -0 -P0 bash -c
|
||||
# объединение двух сборок
|
||||
cp -r _site_older/_site .
|
||||
cp -r _site_color/_site ./_site/color
|
||||
# копирование без сборки
|
||||
cp -r jekyll_site/css _site
|
||||
cp -r jekyll_site/img _site
|
||||
cp -r jekyll_site/js _site
|
||||
cp -r jekyll_site/robots.txt _site
|
||||
echo "Оптимизация собранного контента."
|
||||
# оптимизация собранного контента
|
||||
cd _site || exit
|
||||
cp -r assets/* .
|
||||
rm -r assets
|
||||
|
@ -41,15 +38,22 @@ rm -r color/assets/favicon.ico
|
|||
cp -r color/assets/* .
|
||||
rm -r color/assets
|
||||
rm -r color/404.html
|
||||
find . -type f -name '*.html' | sort -r | while read -r file; do
|
||||
sed -i 's/layout-padding=""/layout-padding/g' "$file"
|
||||
sed -i 's/ class="language-plaintext highlighter-rouge"//g' "$file"
|
||||
sed -i 's/ class="language-java highlighter-rouge"//g' "$file"
|
||||
sed -i 's/ class="language-js highlighter-rouge"//g' "$file"
|
||||
sed -i 's/ class="language-bash highlighter-rouge"//g' "$file"
|
||||
sed -i 's/<div><div class="highlight"><pre class="highlight">/<div class="highlight"><pre class="highlight">/g' "$file"
|
||||
sed -i 's/<\/code><\/pre><\/div><\/div>/<\/code><\/pre><\/div>/g' "$file"
|
||||
sed -i 's/<hr \/>/<hr>/g' "$file"
|
||||
sed -i -r 's/<img(.+) \/>/<img\1>/g' "$file"
|
||||
done
|
||||
echo "Время выполнения сборки: $(("$(date '+%s%3N')" - "$currentTimeMillis")) мс."
|
||||
rm -r color/return.html
|
||||
# шаблоны для оптимизации ряда тегов
|
||||
expr+=('s|layout-padding=""|layout-padding|g')
|
||||
expr+=('s| class="language-plaintext highlighter-rouge"||g')
|
||||
expr+=('s| class="language-java highlighter-rouge"||g')
|
||||
expr+=('s| class="language-js highlighter-rouge"||g')
|
||||
expr+=('s| class="language-bash highlighter-rouge"||g')
|
||||
expr+=('s|<div><div class="highlight">|<div class="highlight">|g')
|
||||
expr+=('s|</pre></div></div>|</pre></div>|g')
|
||||
expr+=('s|<hr />|<hr>|g')
|
||||
expr+=('s|<input(.+) />|<input\1>|g')
|
||||
expr+=('s|<img(.+) />|<img\1>|g')
|
||||
# запуск параллельной обработки собранных страниц и оптимизация ряда тегов
|
||||
find . -type f -name "*.html" -printf '%p\0' | xargs -I{} -n1 -0 -P0 bash -c \
|
||||
"echo 'Оптимизация: {}' && sed -i -E $(printf " -e '%s'" "${expr[@]}") '{}'"
|
||||
# переход в корень сайта для каталогов без заглавной страницы
|
||||
find . -type d -exec cp -n return.html {}/index.html \;
|
||||
rm -r return.html
|
||||
echo "Общее время выполнения: $(($(date '+%s%3N') - time_ms)) мс."
|
||||
|
|
|
@ -4,12 +4,12 @@ name: "Код с комментариями"
|
|||
name_translated: "Code with comments"
|
||||
# URL адрес сайта, включая протокол
|
||||
url: "https://pomodoro5.mircloud.ru"
|
||||
# подпапка этой сборки для относительных URLs
|
||||
# подпапка этой сборки для относительных URL-ов
|
||||
baseurl: "/color"
|
||||
# ссылка в верхнем левом углу заглавных страниц
|
||||
homepage_url: "https://git.org.ru/pomodoro/5"
|
||||
homepage_url: "https://gitea.com/pomodoro/5"
|
||||
# представление ссылки
|
||||
homepage_name: "GIT.ORG.RU"
|
||||
homepage_name: "GITEA"
|
||||
# подпапка альтернативной сборки
|
||||
older_tomato_baseurl: ""
|
||||
# часовой пояс для формата даты ISO-8601
|
||||
|
@ -20,6 +20,9 @@ author: "Головин Г.Г."
|
|||
author_translated: "Golovin G.G."
|
||||
# дополнение к подписи в футере для переведённых страниц
|
||||
translation_caption: "translation from Russian"
|
||||
# номера счётчиков для страниц
|
||||
live_internet: "pomodoro"
|
||||
yandex_metrika: "95699485"
|
||||
# тема оформления для сборки
|
||||
theme: color-tomato-theme
|
||||
# макет для сборки
|
||||
|
|
|
@ -4,12 +4,12 @@ name: "Код с комментариями"
|
|||
name_translated: "Code with comments"
|
||||
# URL адрес сайта, включая протокол
|
||||
url: "https://pomodoro5.mircloud.ru"
|
||||
# подпапка этой сборки для относительных URLs
|
||||
# подпапка этой сборки для относительных URL-ов
|
||||
baseurl: ""
|
||||
# ссылка в верхнем левом углу заглавных страниц
|
||||
homepage_url: "https://git.org.ru/pomodoro/5"
|
||||
homepage_url: "https://gitea.com/pomodoro/5"
|
||||
# представление ссылки
|
||||
homepage_name: "GIT.ORG.RU"
|
||||
homepage_name: "GITEA"
|
||||
# подпапка альтернативной сборки
|
||||
color_tomato_baseurl: "/color"
|
||||
# часовой пояс для формата даты ISO-8601
|
||||
|
@ -20,6 +20,9 @@ author: "Головин Г.Г."
|
|||
author_translated: "Golovin G.G."
|
||||
# дополнение к подписи в футере для переведённых страниц
|
||||
translation_caption: "translation from Russian"
|
||||
# номера счётчиков для страниц
|
||||
live_internet: "pomodoro"
|
||||
yandex_metrika: "95699485"
|
||||
# тема оформления для сборки
|
||||
theme: older-tomato-theme
|
||||
# макет для сборки
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
<noscript><div><img src="https://mc.yandex.ru/watch/91925585" style="position:absolute; left:-9999px;" alt=""></div></noscript>
|
||||
<!-- /Yandex.Metrika counter -->
|
|
@ -1,16 +0,0 @@
|
|||
<!-- Google tag (gtag.js) -->
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id=G-071GTXN2K2"></script>
|
||||
<script>
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
gtag('config', 'G-071GTXN2K2');
|
||||
</script>
|
||||
<!-- Yandex.Metrika counter -->
|
||||
<script>
|
||||
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
|
||||
m[i].l=1*new Date();for(var j=0;j<document.scripts.length;j++){if(document.scripts[j].src===r){return;}}
|
||||
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
|
||||
(window,document,"script","https://mc.yandex.ru/metrika/tag.js","ym");
|
||||
ym(91925585,"init",{clickmap:true,trackLinks:true,accurateTrackBounce:true,webvisor:true});
|
||||
</script>
|
|
@ -16,10 +16,10 @@ and digits with the *Comic Sans* font — we will draw a simple captcha for a we
|
|||
|
||||
{% include picture.html id="captcha.png" src="/img/captcha.png" alt="Drawing simple captcha" %}
|
||||
|
||||
We'll consider special characters, but we won't use them, because it will be difficult for the
|
||||
user to guess them with such a text decoration. For example, the plus `+` is still possible
|
||||
to guess, but the minus `-` or the underscore `_` is already with difficulty, and even if you
|
||||
guess right, then to find these buttons with difficulty, especially on the phone. Therefore,
|
||||
We'll also consider special characters, but we won't use them, because it will be difficult for the
|
||||
user to guess special characters with such a text decoration. For example, the plus `+` is still
|
||||
possible to guess, but the minus `-` or the underscore `_` is already with difficulty, and even if
|
||||
you guess right, then to find these buttons with difficulty, especially on the phone. Therefore,
|
||||
for captcha we'll use a combination of only capital latin letters and digits.
|
||||
|
||||
Rendering special characters in a monospaced font: [Drawing heart in console]({{ '/en/2023/03/08/drawing-heart-in-console.html#text-as-picture-and-picture-as-text' | relative_url }}).
|
||||
|
|
|
@ -15,9 +15,9 @@ in the form of text. We will use Java tools. For calculations, we will use the `
|
|||
to bypass the range of coordinates, we will use two nested `for` loops. We draw in the console a
|
||||
graph of a circle and graphs of a rhombus and a square inscribed in it.
|
||||
|
||||
Graph of a function with filling: [Drawing heart in console]({{ '/en/2023/03/08/drawing-heart-in-console.html' | relative_url }}).
|
||||
Graph of a function with filling: [Drawing heart in console]({{ '/en/2023/03/08/drawing-heart-in-console.html#heart-shaped-graph' | relative_url }}).
|
||||
|
||||
{% include heading.html text="Equations of functions" hash="equations-of-functions" type="3" %}
|
||||
{% include heading.html text="Equations of functions" hash="equations-of-functions" %}
|
||||
|
||||
We will check each point `(x,y)` from the output range of coordinates for belonging to function
|
||||
graphs and output in accordance with this. We define the parameters of the functions and the
|
||||
|
@ -49,7 +49,7 @@ alt="\sqrt{(x-a)^2+(y-b)^2}=r." %}
|
|||
|
||||
`c` — half a side of a square.
|
||||
|
||||
{% include heading.html text="Mathematical operations" hash="mathematical-operations" type="3" %}
|
||||
{% include heading.html text="Mathematical operations" hash="mathematical-operations" %}
|
||||
|
||||
To perform *basic* mathematical operations, Java uses the `FdLibm` library — *Freely Distributable
|
||||
Math Library*. Most of the methods are implemented at the platform level to increase performance.
|
||||
|
@ -67,7 +67,7 @@ For floating point calculations and rounding of results, we will use the methods
|
|||
|
||||
`floor(a)` — rounding down the argument `a`.
|
||||
|
||||
{% include heading.html text="Algorithm description" hash="algorithm-description" type="3" %}
|
||||
{% include heading.html text="Algorithm description" hash="algorithm-description" %}
|
||||
|
||||
We take a range of coordinates on the plane in such a way that the displayed figure completely fits
|
||||
in the printing area. We bypass the selected range with two nested `for` loops: first along the `y`
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
---
|
||||
title: Drawing heart in console
|
||||
description: Let's write two versions of the algorithm in Java to output a heart to the console in the form of a text image — let's congratulate women on the eighth of...
|
||||
sections: [Geometric figures,Font rendering,Text image]
|
||||
sections: [Geometric figures,Text image,Font rendering]
|
||||
tags: [java,awt,console,rhombus,circumference,circle,text,image,font]
|
||||
canonical_url: /en/2023/03/08/drawing-heart-in-console.html
|
||||
url_translated: /ru/2023/03/08/drawing-heart-in-console.html
|
||||
|
@ -19,10 +19,9 @@ picture, and output the picture as text — console congratulations on the eight
|
|||
|
||||
Let's draw two half-circles and one half-rhombus, filled inside and outside. In the previous example,
|
||||
we output a [function graph to console]({{ '/en/2023/02/06/function-graph-in-console.html' | relative_url }})
|
||||
— we take the formulas for the circle and for the rhombus from it, and in this example, to fill the
|
||||
figure inside, in the formula instead of the *equals* sign we substitute the *less* sign, and to
|
||||
fill the outside, on the contrary, — the *greater* sign. There will be many conditions, unlike the
|
||||
previous example.
|
||||
— we take the formulas for the circle and for the rhombus from it, and in this example, we add the
|
||||
filling of the figure inside and outside — instead of the *equal* sign in the formulas, we substitute
|
||||
*less than* or *greater than* signs. There will be many conditions, unlike the previous example.
|
||||
|
||||
Let's draw a picture for clarity.
|
||||
|
||||
|
@ -102,8 +101,8 @@ o o
|
|||
|
||||
We bypass the coordinate range with two nested `for` loops: first along the `y` axis and then along
|
||||
the `x` axis. We check each point for compliance with the conditions and output it. In the upper part
|
||||
we draw two half-circles and optionally paint over them inside/outside. In the lower part we draw a
|
||||
half-rhombus and also optionally paint over inside/outside.
|
||||
we draw two half-circles and optionally paint over them inside and outside. In the lower part we draw
|
||||
a half-rhombus and also optionally paint over inside and outside.
|
||||
|
||||
```java
|
||||
/**
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
title: Directory tree with links
|
||||
description: We write a Bash script for building a directory tree for a repository in the Markdown file. We use only Bash tools and basic Linux software without additional.
|
||||
sections: [Recursion,File processing,Web-navigation]
|
||||
tags: [linux,bash,markdown,html,folders,files,references,sorting]
|
||||
tags: [linux,bash,markdown,html,structure,folders,files,references,sorting]
|
||||
canonical_url: /en/2023/08/04/directory-tree.html
|
||||
url_translated: /ru/2023/08/03/directory-tree.html
|
||||
title_translated: Дерево каталогов со ссылками
|
||||
|
@ -10,16 +10,17 @@ date: 2023.08.04
|
|||
lang: en
|
||||
---
|
||||
|
||||
We write a Bash script for building a directory tree for a repository in the Markdown
|
||||
file. We use only Bash tools and basic Linux software — `ls`, `sed`, `tr` and `echo` —
|
||||
without additional programs. The obtained file
|
||||
We write a Bash script for building a directory tree for a repository in
|
||||
the Markdown file. We use only Bash tools and basic Linux software — `ls`,
|
||||
`sed`, `tr` and `echo` — without additional programs. The obtained file
|
||||
[`DIRECTORY_TREE.md`]({{ site.homepage_url }} "{{ site.homepage_name }}")
|
||||
will be used in the web interface to navigate through the objects of the repository.
|
||||
|
||||
We create a recursive function and use it to bypass all files and directories of the repository,
|
||||
excluding the list from `.gitignore`. We output tree elements as links `<a>`, collapse folders
|
||||
with one nested element into one line, place the tree in the container `<pre>` and add the title
|
||||
— as a result, we get a short and concise Markdown file with links.
|
||||
excluding the list from `.gitignore` — we build a directory structure in the form of a tree. We
|
||||
output the elements as links `<a>`, collapse folders with one nested element into one line, place
|
||||
the constructed tree in a container `<pre>` and add the header — as a result, we get a short and
|
||||
concise Markdown file with links.
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
@ -35,25 +36,21 @@ function directory_tree {
|
|||
local head="$2"
|
||||
local tail="$3"
|
||||
# prefix for current element
|
||||
if [ "one" == "$4" ]; then
|
||||
echo -n "/"
|
||||
else
|
||||
echo -ne "\n$head"
|
||||
fi
|
||||
[ "one" == "$4" ] && printf '%s' "/" || printf '\n%s' "$head"
|
||||
# current element of the tree
|
||||
echo -n "<a href='${path#*/}'>${path##*/}</a>"
|
||||
printf '%s' "<a href='${path#*/}'>${path##*/}</a>"
|
||||
# recursive calls for subdirectories
|
||||
if [ -d "$path" ]; then
|
||||
local list # array of files and directories
|
||||
readarray -t list <<<"$(list_directory_contents "$path")"
|
||||
local len=${#list[@]} # size of array
|
||||
readarray -t list < <(list_directory_contents "$path")
|
||||
local size=${#list[@]} # length of array
|
||||
local i # counter
|
||||
for ((i = 0; i < len; i++)); do
|
||||
for ((i = 0; i < size; i++)); do
|
||||
if [ -z "${list[$i]}" ]; then
|
||||
continue # skip empty directory
|
||||
elif ((len == 1)); then
|
||||
elif ((size == 1)); then
|
||||
directory_tree "$path/${list[$i]}" "$tail" "$tail" "one"
|
||||
elif ((i < len - 1)); then
|
||||
elif ((i < size - 1)); then
|
||||
directory_tree "$path/${list[$i]}" "$tail├─ " "$tail│ "
|
||||
else
|
||||
directory_tree "$path/${list[$i]}" "$tail└─ " "$tail "
|
||||
|
@ -61,15 +58,11 @@ function directory_tree {
|
|||
done
|
||||
fi
|
||||
}
|
||||
# line of exclusions for 'ls' from '.gitignore' list — the untracked files
|
||||
exclusions="-I \".git\" $(sed 's/^/ -I "/;s/$/"/' .gitignore | tr -d '\n')"
|
||||
# put the tree in a container, add a title and output to a file
|
||||
{
|
||||
echo "## Directory tree"
|
||||
echo -ne "\n<pre>"
|
||||
directory_tree .
|
||||
echo -e "\n</pre>"
|
||||
} >DIRECTORY_TREE.md
|
||||
# line of exclusions for "ls" from the list of untracked files ".gitignore"
|
||||
exclusions="-I'.git' $(sed -E "s|^(.*)$|-I'\1'|" .gitignore | tr '\n' ' ')"
|
||||
# place the tree in a container, add a header and output to a file
|
||||
printf '%s\n' "## Directory tree" "" "<pre>" \
|
||||
"$(directory_tree . | grep '\S')" "</pre>" >DIRECTORY_TREE.md
|
||||
```
|
||||
|
||||
Run the script in the root of the repository and save the obtained file.
|
||||
|
|
|
@ -12,15 +12,16 @@ lang: en
|
|||
{%- assign articles = "" | split: "" %}
|
||||
{%- assign articles = articles | push: "Directory tree with links" %}
|
||||
{%- capture article_brief %}
|
||||
We write a Bash script for building a directory tree for a repository in the Markdown
|
||||
file. We use only Bash tools and basic Linux software — `ls`, `sed`, `tr` and `echo` —
|
||||
without additional programs. The obtained file `DIRECTORY_TREE.md` will be used in the
|
||||
web interface to navigate through the objects of the repository.
|
||||
We write a Bash script for building a directory tree for a repository in the Markdown file.
|
||||
We use only Bash tools and basic Linux software — `ls`, `sed`, `tr` and `echo` — without
|
||||
additional programs. The obtained file `DIRECTORY_TREE.md` will be used in the web interface
|
||||
to navigate through the objects of the repository.
|
||||
|
||||
We create a recursive function and use it to bypass all files and directories of the repository,
|
||||
excluding the list from `.gitignore`. We output tree elements as links `<a>`, collapse folders
|
||||
with one nested element into one line, place the tree in the container `<pre>` and add the title
|
||||
— as a result, we get a short and concise Markdown file with links.
|
||||
excluding the list from `.gitignore` — we build a directory structure in the form of a tree. We
|
||||
output the elements as links `<a>`, collapse folders with one nested element into one line, place
|
||||
the constructed tree in a container `<pre>` and add the title — as a result, we get a short and
|
||||
concise Markdown file with links.
|
||||
{%- endcapture %}
|
||||
{%- assign articles = articles | push: article_brief %}
|
||||
{%- assign articles = articles | push: "Password generator" %}
|
||||
|
@ -57,10 +58,10 @@ Let's write an algorithm for displaying text as an image using the Java AWT libr
|
|||
and font can be any, but for this example we will use a combination of uppercase latin letters
|
||||
and digits with the *Comic Sans* font — we will draw a simple captcha for a website or blog.
|
||||
|
||||
We'll consider special characters, but we won't use them, because it will be difficult for the
|
||||
user to guess them with such a text decoration. For example, the plus `+` is still possible
|
||||
to guess, but the minus `-` or the underscore `_` is already with difficulty, and even if you
|
||||
guess right, then to find these buttons with difficulty, especially on the phone. Therefore,
|
||||
We'll also consider special characters, but we won't use them, because it will be difficult for the
|
||||
user to guess special characters with such a text decoration. For example, the plus `+` is still
|
||||
possible to guess, but the minus `-` or the underscore `_` is already with difficulty, and even if
|
||||
you guess right, then to find these buttons with difficulty, especially on the phone. Therefore,
|
||||
for captcha we'll use a combination of only capital latin letters and digits.
|
||||
{%- endcapture %}
|
||||
{%- assign articles = articles | push: article_brief %}
|
||||
|
|
|
@ -15,11 +15,10 @@ date: 2023.01.03
|
|||
|
||||
{% include picture.html id="captcha.png" src="/img/captcha.png" alt="Рисуем простую капчу" %}
|
||||
|
||||
Спецсимволы рассмотрим, но пользоваться ими не будем, потому что угадать их с таким оформлением
|
||||
текста пользователю будет сложно. Например, плюс `+` угадать ещё можно, а вот минус `-` или
|
||||
нижнее подчёркивание `_` уже с трудом, и даже если угадаешь, тогда найти эти кнопки с трудом,
|
||||
особенно на телефоне. Поэтому для капчи будем использовать комбинацию только из заглавных
|
||||
латинских букв и цифр.
|
||||
Спецсимволы тоже рассмотрим, но использовать их не будем, потому что угадать спецсимволы пользователю
|
||||
будет сложно с таким оформлением текста. Например, плюс `+` угадать ещё можно, а вот минус `-` или
|
||||
нижнее подчёркивание `_` уже с трудом, и даже если угадаешь, тогда найти эти кнопки с трудом, особенно
|
||||
на телефоне. Поэтому для капчи будем использовать комбинацию только из заглавных латинских букв и цифр.
|
||||
|
||||
Отрисовка спецсимволов моноширинным шрифтом: [Рисуем сердечко в консоли]({{ '/ru/2023/03/08/drawing-heart-in-console.html#text-as-picture-and-picture-as-text' | relative_url }}).
|
||||
|
||||
|
|
|
@ -14,9 +14,9 @@ date: 2023.02.05
|
|||
координат — два вложенных цикла `for`. Нарисуем в консоли график окружности и графики вписанных
|
||||
в неё ромба и квадрата.
|
||||
|
||||
График функции с заполнением: [Рисуем сердечко в консоли]({{ '/ru/2023/03/08/drawing-heart-in-console.html' | relative_url }}).
|
||||
График функции с заполнением: [Рисуем сердечко в консоли]({{ '/ru/2023/03/08/drawing-heart-in-console.html#heart-shaped-graph' | relative_url }}).
|
||||
|
||||
{% include heading.html text="Уравнения функций" hash="equations-of-functions" type="3" %}
|
||||
{% include heading.html text="Уравнения функций" hash="equations-of-functions" %}
|
||||
|
||||
Каждую точку `(x,y)` из выводимого диапазона координат будем проверять на принадлежность графикам
|
||||
функций и в соответствии с этим выводить. Параметры функций и выводимый диапазон определим заранее
|
||||
|
@ -48,7 +48,7 @@ alt="\sqrt{(x-a)^2+(y-b)^2}=r." %}
|
|||
|
||||
`c` — половина стороны квадрата.
|
||||
|
||||
{% include heading.html text="Математические операции" hash="mathematical-operations" type="3" %}
|
||||
{% include heading.html text="Математические операции" hash="mathematical-operations" %}
|
||||
|
||||
Для выполнения *базовых* математических операций в Java используется библиотека `FdLibm` —
|
||||
*Свободно распространяемая математическая библиотека*. Большинство методов реализовано на уровне
|
||||
|
@ -66,7 +66,7 @@ alt="\sqrt{(x-a)^2+(y-b)^2}=r." %}
|
|||
|
||||
`floor(a)` — округление аргумента `a` в ме́ньшую сторону.
|
||||
|
||||
{% include heading.html text="Описание алгоритма" hash="algorithm-description" type="3" %}
|
||||
{% include heading.html text="Описание алгоритма" hash="algorithm-description" %}
|
||||
|
||||
Берём диапазон координат на плоскости таким образом, чтобы выводимая фигура полностью помещалась
|
||||
в печатаемой области. Обходим выбранный диапазон двумя вложенными циклами `for`: сначала по оси
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
---
|
||||
title: Рисуем сердечко в консоли
|
||||
description: Напишем два варианта алгоритма на Java для вывода сердечка в консоль в форме текстового изображения — поздравим женщин с восьмым марта. Нарисуем график...
|
||||
sections: [Геометрические фигуры,Отрисовка шрифта,Текстовое изображение]
|
||||
sections: [Геометрические фигуры,Текстовое изображение,Отрисовка шрифта]
|
||||
tags: [java,awt,консоль,ромб,окружность,круг,текст,изображение,шрифт]
|
||||
canonical_url: /ru/2023/03/08/drawing-heart-in-console.html
|
||||
url_translated: /en/2023/03/08/drawing-heart-in-console.html
|
||||
|
@ -18,9 +18,9 @@ date: 2023.03.08
|
|||
|
||||
Нарисуем два полукруга и один полуромб, заполненные внутри и снаружи. В предыдущем примере мы выводили
|
||||
[график функции в консоль]({{ '/ru/2023/02/05/function-graph-in-console.html' | relative_url }})
|
||||
— формулы для окружности и для ромба возьмём из него, а в этом примере для заполнения фигуры внутри,
|
||||
в формуле вместо знака *равно* подставляем знак *меньше*, а для заполнения снаружи, наоборот, — знак
|
||||
*больше*. Условий получится много, в отличие от предыдущего примера.
|
||||
— формулы для окружности и для ромба возьмём из него, а в этом примере добавим заполнение фигуры внутри и
|
||||
снаружи — вместо знака *равно* в формулах подставляем знаки *меньше* или *больше*. Условий получится много,
|
||||
в отличие от предыдущего примера.
|
||||
|
||||
Нарисуем картинку для наглядности.
|
||||
|
||||
|
@ -97,9 +97,10 @@ o o
|
|||
{% endcapture %}
|
||||
{%- include collapsed_block.html summary="Полный вывод" content=collapsed_md -%}
|
||||
|
||||
Обходим диапазон координат двумя вложенными циклами `for`: сначала по оси `y` и затем по оси `x`. Каждую
|
||||
точку проверяем на соответствие условиям и выводим. В верхней части рисуем два полукруга и опционально
|
||||
закрашиваем их внутри/снаружи. В нижней части рисуем полуромб и также опционально закрашиваем внутри/снаружи.
|
||||
Обходим диапазон координат двумя вложенными циклами `for`: сначала по оси `y` и затем по оси `x`.
|
||||
Каждую точку проверяем на соответствие условиям и выводим. В верхней части рисуем два полукруга и
|
||||
опционально закрашиваем их внутри и снаружи. В нижней части рисуем полуромб и также опционально
|
||||
закрашиваем внутри и снаружи.
|
||||
|
||||
```java
|
||||
/**
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
title: Дерево каталогов со ссылками
|
||||
description: Напишем скрипт Bash для построения дерева каталогов для репозитория в файле Markdown. Будем использовать только средства Bash и базовое ПО Linux без...
|
||||
sections: [Рекурсия,Обработка файлов,Вёб-навигация]
|
||||
tags: [linux,bash,markdown,html,каталоги,файлы,ссылки,сортировка]
|
||||
tags: [linux,bash,markdown,html,структура,каталоги,файлы,ссылки,сортировка]
|
||||
canonical_url: /ru/2023/08/03/directory-tree.html
|
||||
url_translated: /en/2023/08/04/directory-tree.html
|
||||
title_translated: Directory tree with links
|
||||
|
@ -15,10 +15,11 @@ date: 2023.08.03
|
|||
[`DIRECTORY_TREE.md`]({{ site.homepage_url }} "{{ site.homepage_name }}")
|
||||
будем использовать в вёб-интерфейсе для навигации по объектам репозитория.
|
||||
|
||||
Создаём рекурсивную функцию и с её помощью обходим все файлы и каталоги репозитория,
|
||||
за исключением списка из `.gitignore`. Выводим элементы дерева в виде ссылок `<a>`,
|
||||
сворачиваем папки с одним вложенным элементом в одну строку, помещаем дерево в контейнер `<pre>`
|
||||
и добавляем заголовок — в результате получаем краткий и лаконичный файл Markdown со ссылками.
|
||||
Создаём рекурсивную функцию и с её помощью обходим все файлы и каталоги репозитория, за
|
||||
исключением списка из `.gitignore` — строим структуру каталогов в форме дерева. Выводим
|
||||
элементы в виде ссылок `<a>`, сворачиваем папки с одним вложенным элементом в одну строку,
|
||||
помещаем собранное дерево в контейнер `<pre>` и добавляем заголовок — в результате получаем
|
||||
краткий и лаконичный файл Markdown со ссылками.
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
@ -34,25 +35,21 @@ function directory_tree {
|
|||
local head="$2"
|
||||
local tail="$3"
|
||||
# префикс для текущего элемента
|
||||
if [ "one" == "$4" ]; then
|
||||
echo -n "/"
|
||||
else
|
||||
echo -ne "\n$head"
|
||||
fi
|
||||
[ "one" == "$4" ] && printf '%s' "/" || printf '\n%s' "$head"
|
||||
# текущий элемент дерева
|
||||
echo -n "<a href='${path#*/}'>${path##*/}</a>"
|
||||
printf '%s' "<a href='${path#*/}'>${path##*/}</a>"
|
||||
# рекурсивные вызовы для подкаталогов
|
||||
if [ -d "$path" ]; then
|
||||
local list # массив файлов и каталогов
|
||||
readarray -t list <<<"$(list_directory_contents "$path")"
|
||||
local len=${#list[@]} # размер массива
|
||||
readarray -t list < <(list_directory_contents "$path")
|
||||
local size=${#list[@]} # длина массива
|
||||
local i # счётчик
|
||||
for ((i = 0; i < len; i++)); do
|
||||
for ((i = 0; i < size; i++)); do
|
||||
if [ -z "${list[$i]}" ]; then
|
||||
continue # пропустить пустой каталог
|
||||
elif ((len == 1)); then
|
||||
elif ((size == 1)); then
|
||||
directory_tree "$path/${list[$i]}" "$tail" "$tail" "one"
|
||||
elif ((i < len - 1)); then
|
||||
elif ((i < size - 1)); then
|
||||
directory_tree "$path/${list[$i]}" "$tail├─ " "$tail│ "
|
||||
else
|
||||
directory_tree "$path/${list[$i]}" "$tail└─ " "$tail "
|
||||
|
@ -60,15 +57,11 @@ function directory_tree {
|
|||
done
|
||||
fi
|
||||
}
|
||||
# строка исключений для 'ls' из списка '.gitignore' — неотслеживаемые файлы
|
||||
exclusions="-I \".git\" $(sed 's/^/ -I "/;s/$/"/' .gitignore | tr -d '\n')"
|
||||
# строка исключений для "ls" из списка неотслеживаемых файлов ".gitignore"
|
||||
exclusions="-I'.git' $(sed -E "s|^(.*)$|-I'\1'|" .gitignore | tr '\n' ' ')"
|
||||
# помещаем дерево в контейнер, добавляем заголовок и выводим в файл
|
||||
{
|
||||
echo "## Дерево каталогов"
|
||||
echo -ne "\n<pre>"
|
||||
directory_tree .
|
||||
echo -e "\n</pre>"
|
||||
} >DIRECTORY_TREE.md
|
||||
printf '%s\n' "## Дерево каталогов" "" "<pre>" \
|
||||
"$(directory_tree . | grep '\S')" "</pre>" >DIRECTORY_TREE.md
|
||||
```
|
||||
|
||||
Запускаем скрипт в корне репозитория и сохраняем полученный файл.
|
||||
|
|
|
@ -16,10 +16,11 @@ title_translated: Code with comments
|
|||
— без дополнительных программ. Полученный файл `DIRECTORY_TREE.md` будем использовать
|
||||
в вёб-интерфейсе для навигации по объектам репозитория.
|
||||
|
||||
Создаём рекурсивную функцию и с её помощью обходим все файлы и каталоги репозитория,
|
||||
за исключением списка из `.gitignore`. Выводим элементы дерева в виде ссылок `<a>`,
|
||||
сворачиваем папки с одним вложенным элементом в одну строку, помещаем дерево в контейнер `<pre>`
|
||||
и добавляем заголовок — в результате получаем краткий и лаконичный файл Markdown со ссылками.
|
||||
Создаём рекурсивную функцию и с её помощью обходим все файлы и каталоги репозитория, за
|
||||
исключением списка из `.gitignore` — строим структуру каталогов в форме дерева. Выводим
|
||||
элементы в виде ссылок `<a>`, сворачиваем папки с одним вложенным элементом в одну строку,
|
||||
помещаем собранное дерево в контейнер `<pre>` и добавляем заголовок — в результате получаем
|
||||
краткий и лаконичный файл Markdown со ссылками.
|
||||
{%- endcapture %}
|
||||
{%- assign articles = articles | push: article_brief %}
|
||||
{%- assign articles = articles | push: "Генератор паролей" %}
|
||||
|
@ -55,11 +56,10 @@ JavaScript, чтобы далеко не ходить.
|
|||
Символы и шрифт могут быть любыми, но для этого примера будем использовать комбинацию заглавных
|
||||
латинских букв и цифр со шрифтом *Comic Sans* — будем рисовать простую капчу для сайта или блога.
|
||||
|
||||
Спецсимволы рассмотрим, но пользоваться ими не будем, потому что угадать их с таким оформлением
|
||||
текста пользователю будет сложно. Например, плюс `+` угадать ещё можно, а вот минус `-` или
|
||||
нижнее подчёркивание `_` уже с трудом, и даже если угадаешь, тогда найти эти кнопки с трудом,
|
||||
особенно на телефоне. Поэтому для капчи будем использовать комбинацию только из заглавных
|
||||
латинских букв и цифр.
|
||||
Спецсимволы тоже рассмотрим, но использовать их не будем, потому что угадать спецсимволы пользователю
|
||||
будет сложно с таким оформлением текста. Например, плюс `+` угадать ещё можно, а вот минус `-` или
|
||||
нижнее подчёркивание `_` уже с трудом, и даже если угадаешь, тогда найти эти кнопки с трудом, особенно
|
||||
на телефоне. Поэтому для капчи будем использовать комбинацию только из заглавных латинских букв и цифр.
|
||||
{%- endcapture %}
|
||||
{%- assign articles = articles | push: article_brief %}
|
||||
{%- include main_page.html articles = articles -%}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
#!/bin/bash
|
||||
echo "Подготовка архива для последующего развёртывания."
|
||||
echo "Создание архива для последующего развёртывания."
|
||||
cd _site || exit
|
||||
rm -rf ../pomodoro5.zip
|
||||
7z a ../pomodoro5.zip ./*
|
||||
7z a ../pomodoro5.zip . | grep -E '\S'
|
||||
|
|
2
serve.sh
2
serve.sh
|
@ -1,4 +1,4 @@
|
|||
#!/bin/bash
|
||||
echo "Локальное развёртывание для проверки корректности сборки."
|
||||
jekyll serve --skip-initial-build --disable-disk-cache --host localhost
|
||||
jekyll serve --skip-initial-build --no-watch --disable-disk-cache --host localhost
|
||||
echo "Адрес сервера: http://localhost:4000"
|
||||
|
|
Loading…
Add table
Reference in a new issue