Compare commits

...

10 commits

Author SHA1 Message Date
991fcdda6d 2024-12-29 2024-12-29 10:39:46 +03:00
928f0beebe 2024-10-31 2024-10-31 21:39:03 +03:00
4c0e47830c 2024-09-30 2024-10-01 18:02:31 +03:00
15d28a54dc 2024-08-31 2024-09-01 08:46:27 +03:00
d3c319c876 2024-07-31 2024-07-31 21:10:04 +03:00
b75f7ae9fe 2024-03-31 2024-03-31 02:12:41 +03:00
4c6eb04cdd 2024-02-29 2024-02-29 22:55:26 +03:00
fa2b8dd384 2023-12-30 2023-12-30 23:49:34 +03:00
0330e905e9 2023-11-30 2023-12-17 09:51:44 +03:00
4ed84bcb4f 2023-10-31 2023-12-17 09:42:02 +03:00
19 changed files with 151 additions and 176 deletions

View file

@ -3,9 +3,6 @@
<pre> <pre>
<a href='.'>.</a> <a href='.'>.</a>
├─ <a href='jekyll_site'>jekyll_site</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/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'>en</a>
│ │ ├─ <a href='jekyll_site/en/2023'>2023</a> │ │ ├─ <a href='jekyll_site/en/2023'>2023</a>

View file

@ -1,4 +1,4 @@
© Головин Г.Г., 2021-2023 © Головин Г.Г., 2021-2024
Опубликовано под [Открытой лицензией 1.1](OPEN_LICENSE.txt) Опубликовано под [Открытой лицензией 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) Published under the [Open License 1.1](OPEN_LICENSE.txt)

View file

@ -1,39 +1,36 @@
#!/bin/bash #!/bin/bash
echo "Сборка сайта в двух помидорных темах и оптимизация результатов." echo "Сборка сайта в двух помидорных темах и оптимизация результатов."
currentTimeMillis=$(date '+%s%3N') time_ms="$(date '+%s%3N')"
rm -rf _site # удаление каталогов предыдущей сборки, если таковые имеются
rm -rf _site_older find . -maxdepth 1 -type d -name "_site*" -exec rm -rf {} \;
rm -rf _site_color # сборка сайта в двух помидорных темах
echo "Сборка старого помидора." function jekyll_build {
mkdir -p _site_older case "$1" in
cp -r jekyll_site/_includes _site_older "older") echo "Сборка старого помидора." ;;
cp -r jekyll_site/ru _site_older "color") echo "Сборка цветного помидора." ;;
cp -r jekyll_site/en _site_older *) return ;; # две помидорные темы оформления
cp -r jekyll_site/ru/index.md _site_older esac
cp -r jekyll_site/_config_older.yml _site_older/_config.yml mkdir -p "_site_$1"
cp -r jekyll_site/Gemfile_older _site_older/Gemfile cp -r "jekyll_site/ru" "_site_$1"
cd _site_older || exit cp -r "jekyll_site/en" "_site_$1"
jekyll build --disable-disk-cache cp -r "jekyll_site/ru/index.md" "_site_$1"
cp -r _site .. cp -r "jekyll_site/_config_$1.yml" "_site_$1/_config.yml"
cd .. cp -r "jekyll_site/Gemfile_$1" "_site_$1/Gemfile"
echo "Сборка цветного помидора." cd "_site_$1" || return
mkdir -p _site_color jekyll build --disable-disk-cache --quiet
cp -r jekyll_site/_includes _site_color }
cp -r jekyll_site/ru _site_color export -f jekyll_build
cp -r jekyll_site/en _site_color # запуск параллельной сборки сайта в двух помидорных темах оформления
cp -r jekyll_site/ru/index.md _site_color printf 'jekyll_build "%s"\0' {older,color} | xargs -n1 -0 -P0 bash -c
cp -r jekyll_site/_config_color.yml _site_color/_config.yml # объединение двух сборок
cp -r jekyll_site/Gemfile_color _site_color/Gemfile cp -r _site_older/_site .
cd _site_color || exit cp -r _site_color/_site ./_site/color
jekyll build --disable-disk-cache # копирование без сборки
cp -r _site ../_site/color
cd ..
echo "Копирование без сборки."
cp -r jekyll_site/css _site cp -r jekyll_site/css _site
cp -r jekyll_site/img _site cp -r jekyll_site/img _site
cp -r jekyll_site/js _site cp -r jekyll_site/js _site
cp -r jekyll_site/robots.txt _site cp -r jekyll_site/robots.txt _site
echo "Оптимизация собранного контента." # оптимизация собранного контента
cd _site || exit cd _site || exit
cp -r assets/* . cp -r assets/* .
rm -r assets rm -r assets
@ -41,15 +38,22 @@ rm -r color/assets/favicon.ico
cp -r color/assets/* . cp -r color/assets/* .
rm -r color/assets rm -r color/assets
rm -r color/404.html rm -r color/404.html
find . -type f -name '*.html' | sort -r | while read -r file; do rm -r color/return.html
sed -i 's/layout-padding=""/layout-padding/g' "$file" # шаблоны для оптимизации ряда тегов
sed -i 's/ class="language-plaintext highlighter-rouge"//g' "$file" expr+=('s|layout-padding=""|layout-padding|g')
sed -i 's/ class="language-java highlighter-rouge"//g' "$file" expr+=('s| class="language-plaintext highlighter-rouge"||g')
sed -i 's/ class="language-js highlighter-rouge"//g' "$file" expr+=('s| class="language-java highlighter-rouge"||g')
sed -i 's/ class="language-bash highlighter-rouge"//g' "$file" expr+=('s| class="language-js highlighter-rouge"||g')
sed -i 's/<div><div class="highlight"><pre class="highlight">/<div class="highlight"><pre class="highlight">/g' "$file" expr+=('s| class="language-bash highlighter-rouge"||g')
sed -i 's/<\/code><\/pre><\/div><\/div>/<\/code><\/pre><\/div>/g' "$file" expr+=('s|<div><div class="highlight">|<div class="highlight">|g')
sed -i 's/<hr \/>/<hr>/g' "$file" expr+=('s|</pre></div></div>|</pre></div>|g')
sed -i -r 's/<img(.+) \/>/<img\1>/g' "$file" expr+=('s|<hr />|<hr>|g')
done expr+=('s|<input(.+) />|<input\1>|g')
echo "Время выполнения сборки: $(("$(date '+%s%3N')" - "$currentTimeMillis")) мс." 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)) мс."

View file

@ -4,12 +4,12 @@ name: "Код с комментариями"
name_translated: "Code with comments" name_translated: "Code with comments"
# URL адрес сайта, включая протокол # URL адрес сайта, включая протокол
url: "https://pomodoro5.mircloud.ru" url: "https://pomodoro5.mircloud.ru"
# подпапка этой сборки для относительных URLs # подпапка этой сборки для относительных URL-ов
baseurl: "/color" 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: "" older_tomato_baseurl: ""
# часовой пояс для формата даты ISO-8601 # часовой пояс для формата даты ISO-8601
@ -20,6 +20,9 @@ author: "Головин Г.Г."
author_translated: "Golovin G.G." author_translated: "Golovin G.G."
# дополнение к подписи в футере для переведённых страниц # дополнение к подписи в футере для переведённых страниц
translation_caption: "translation from Russian" translation_caption: "translation from Russian"
# номера счётчиков для страниц
live_internet: "pomodoro"
yandex_metrika: "95699485"
# тема оформления для сборки # тема оформления для сборки
theme: color-tomato-theme theme: color-tomato-theme
# макет для сборки # макет для сборки

View file

@ -4,12 +4,12 @@ name: "Код с комментариями"
name_translated: "Code with comments" name_translated: "Code with comments"
# URL адрес сайта, включая протокол # URL адрес сайта, включая протокол
url: "https://pomodoro5.mircloud.ru" url: "https://pomodoro5.mircloud.ru"
# подпапка этой сборки для относительных URLs # подпапка этой сборки для относительных URL-ов
baseurl: "" 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" color_tomato_baseurl: "/color"
# часовой пояс для формата даты ISO-8601 # часовой пояс для формата даты ISO-8601
@ -20,6 +20,9 @@ author: "Головин Г.Г."
author_translated: "Golovin G.G." author_translated: "Golovin G.G."
# дополнение к подписи в футере для переведённых страниц # дополнение к подписи в футере для переведённых страниц
translation_caption: "translation from Russian" translation_caption: "translation from Russian"
# номера счётчиков для страниц
live_internet: "pomodoro"
yandex_metrika: "95699485"
# тема оформления для сборки # тема оформления для сборки
theme: older-tomato-theme theme: older-tomato-theme
# макет для сборки # макет для сборки

View file

@ -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 -->

View file

@ -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>

View file

@ -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" %} {% 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 We'll also 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 user to guess special characters with such a text decoration. For example, the plus `+` is still
to guess, but the minus `-` or the underscore `_` is already with difficulty, and even if you possible to guess, but the minus `-` or the underscore `_` is already with difficulty, and even if
guess right, then to find these buttons with difficulty, especially on the phone. Therefore, 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. 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 }}). 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 }}).

View file

@ -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 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 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 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 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. `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 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. 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`. `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 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` in the printing area. We bypass the selected range with two nested `for` loops: first along the `y`

View file

@ -1,7 +1,7 @@
--- ---
title: Drawing heart in console 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... 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] tags: [java,awt,console,rhombus,circumference,circle,text,image,font]
canonical_url: /en/2023/03/08/drawing-heart-in-console.html canonical_url: /en/2023/03/08/drawing-heart-in-console.html
url_translated: /ru/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, 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 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 we take the formulas for the circle and for the rhombus from it, and in this example, we add the
figure inside, in the formula instead of the *equals* sign we substitute the *less* sign, and to filling of the figure inside and outside instead of the *equal* sign in the formulas, we substitute
fill the outside, on the contrary, the *greater* sign. There will be many conditions, unlike the *less than* or *greater than* signs. There will be many conditions, unlike the previous example.
previous example.
Let's draw a picture for clarity. 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 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 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 we draw two half-circles and optionally paint over them inside and outside. In the lower part we draw
half-rhombus and also optionally paint over inside/outside. a half-rhombus and also optionally paint over inside and outside.
```java ```java
/** /**

View file

@ -2,7 +2,7 @@
title: Directory tree with links 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. 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] 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 canonical_url: /en/2023/08/04/directory-tree.html
url_translated: /ru/2023/08/03/directory-tree.html url_translated: /ru/2023/08/03/directory-tree.html
title_translated: Дерево каталогов со ссылками title_translated: Дерево каталогов со ссылками
@ -10,16 +10,17 @@ date: 2023.08.04
lang: en lang: en
--- ---
We write a Bash script for building a directory tree for a repository in the Markdown We write a Bash script for building a directory tree for a repository in
file. We use only Bash tools and basic Linux software — `ls`, `sed`, `tr` and `echo` the Markdown file. We use only Bash tools and basic Linux software — `ls`,
without additional programs. The obtained file `sed`, `tr` and `echo`without additional programs. The obtained file
[`DIRECTORY_TREE.md`]({{ site.homepage_url }} "{{ site.homepage_name }}") [`DIRECTORY_TREE.md`]({{ site.homepage_url }} "{{ site.homepage_name }}")
will be used in the web interface to navigate through the objects of the repository. 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, 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 excluding the list from `.gitignore` — we build a directory structure in the form of a tree. We
with one nested element into one line, place the tree in the container `<pre>` and add the title output the elements as links `<a>`, collapse folders with one nested element into one line, place
— as a result, we get a short and concise Markdown file with links. 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 ```bash
#!/bin/bash #!/bin/bash
@ -35,25 +36,21 @@ function directory_tree {
local head="$2" local head="$2"
local tail="$3" local tail="$3"
# prefix for current element # prefix for current element
if [ "one" == "$4" ]; then [ "one" == "$4" ] && printf '%s' "/" || printf '\n%s' "$head"
echo -n "/"
else
echo -ne "\n$head"
fi
# current element of the tree # current element of the tree
echo -n "<a href='${path#*/}'>${path##*/}</a>" printf '%s' "<a href='${path#*/}'>${path##*/}</a>"
# recursive calls for subdirectories # recursive calls for subdirectories
if [ -d "$path" ]; then if [ -d "$path" ]; then
local list # array of files and directories local list # array of files and directories
readarray -t list <<<"$(list_directory_contents "$path")" readarray -t list < <(list_directory_contents "$path")
local len=${#list[@]} # size of array local size=${#list[@]} # length of array
local i # counter local i # counter
for ((i = 0; i < len; i++)); do for ((i = 0; i < size; i++)); do
if [ -z "${list[$i]}" ]; then if [ -z "${list[$i]}" ]; then
continue # skip empty directory continue # skip empty directory
elif ((len == 1)); then elif ((size == 1)); then
directory_tree "$path/${list[$i]}" "$tail" "$tail" "one" 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" directory_tree "$path/${list[$i]}" "$tail├─ " "$tail"
else else
directory_tree "$path/${list[$i]}" "$tail└─ " "$tail " directory_tree "$path/${list[$i]}" "$tail└─ " "$tail "
@ -61,15 +58,11 @@ function directory_tree {
done done
fi fi
} }
# line of exclusions for 'ls' from '.gitignore' list — the untracked files # line of exclusions for "ls" from the list of untracked files ".gitignore"
exclusions="-I \".git\" $(sed 's/^/ -I "/;s/$/"/' .gitignore | tr -d '\n')" exclusions="-I'.git' $(sed -E "s|^(.*)$|-I'\1'|" .gitignore | tr '\n' ' ')"
# put the tree in a container, add a title and output to a file # place the tree in a container, add a header and output to a file
{ printf '%s\n' "## Directory tree" "" "<pre>" \
echo "## Directory tree" "$(directory_tree . | grep '\S')" "</pre>" >DIRECTORY_TREE.md
echo -ne "\n<pre>"
directory_tree .
echo -e "\n</pre>"
} >DIRECTORY_TREE.md
``` ```
Run the script in the root of the repository and save the obtained file. Run the script in the root of the repository and save the obtained file.

View file

@ -12,15 +12,16 @@ lang: en
{%- assign articles = "" | split: "" %} {%- assign articles = "" | split: "" %}
{%- assign articles = articles | push: "Directory tree with links" %} {%- assign articles = articles | push: "Directory tree with links" %}
{%- capture article_brief %} {%- capture article_brief %}
We write a Bash script for building a directory tree for a repository in the Markdown We write a Bash script for building a directory tree for a repository in the Markdown file.
file. We use only Bash tools and basic Linux software — `ls`, `sed`, `tr` and `echo` We use only Bash tools and basic Linux software — `ls`, `sed`, `tr` and `echo` without
without additional programs. The obtained file `DIRECTORY_TREE.md` will be used in the additional programs. The obtained file `DIRECTORY_TREE.md` will be used in the web interface
web interface to navigate through the objects of the repository. 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, 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 excluding the list from `.gitignore` — we build a directory structure in the form of a tree. We
with one nested element into one line, place the tree in the container `<pre>` and add the title output the elements as links `<a>`, collapse folders with one nested element into one line, place
— as a result, we get a short and concise Markdown file with links. 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 %} {%- endcapture %}
{%- assign articles = articles | push: article_brief %} {%- assign articles = articles | push: article_brief %}
{%- assign articles = articles | push: "Password generator" %} {%- 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 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. 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 We'll also 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 user to guess special characters with such a text decoration. For example, the plus `+` is still
to guess, but the minus `-` or the underscore `_` is already with difficulty, and even if you possible to guess, but the minus `-` or the underscore `_` is already with difficulty, and even if
guess right, then to find these buttons with difficulty, especially on the phone. Therefore, 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. for captcha we'll use a combination of only capital latin letters and digits.
{%- endcapture %} {%- endcapture %}
{%- assign articles = articles | push: article_brief %} {%- assign articles = articles | push: article_brief %}

View file

@ -15,11 +15,10 @@ date: 2023.01.03
{% include picture.html id="captcha.png" src="/img/captcha.png" alt="Рисуем простую капчу" %} {% 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 }}). Отрисовка спецсимволов моноширинным шрифтом: [Рисуем сердечко в консоли]({{ '/ru/2023/03/08/drawing-heart-in-console.html#text-as-picture-and-picture-as-text' | relative_url }}).

View file

@ -14,9 +14,9 @@ date: 2023.02.05
координат два вложенных цикла `for`. Нарисуем в консоли график окружности и графики вписанных координат два вложенных цикла `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)` из выводимого диапазона координат будем проверять на принадлежность графикам Каждую точку `(x,y)` из выводимого диапазона координат будем проверять на принадлежность графикам
функций и в соответствии с этим выводить. Параметры функций и выводимый диапазон определим заранее функций и в соответствии с этим выводить. Параметры функций и выводимый диапазон определим заранее
@ -48,7 +48,7 @@ alt="\sqrt{(x-a)^2+(y-b)^2}=r." %}
`c` половина стороны квадрата. `c` половина стороны квадрата.
{% include heading.html text="Математические операции" hash="mathematical-operations" type="3" %} {% include heading.html text="Математические операции" hash="mathematical-operations" %}
Для выполнения *базовых* математических операций в Java используется библиотека `FdLibm` Для выполнения *базовых* математических операций в Java используется библиотека `FdLibm`
*Свободно распространяемая математическая библиотека*. Большинство методов реализовано на уровне *Свободно распространяемая математическая библиотека*. Большинство методов реализовано на уровне
@ -66,7 +66,7 @@ alt="\sqrt{(x-a)^2+(y-b)^2}=r." %}
`floor(a)` округление аргумента `a` в ме́ньшую сторону. `floor(a)` округление аргумента `a` в ме́ньшую сторону.
{% include heading.html text="Описание алгоритма" hash="algorithm-description" type="3" %} {% include heading.html text="Описание алгоритма" hash="algorithm-description" %}
Берём диапазон координат на плоскости таким образом, чтобы выводимая фигура полностью помещалась Берём диапазон координат на плоскости таким образом, чтобы выводимая фигура полностью помещалась
в печатаемой области. Обходим выбранный диапазон двумя вложенными циклами `for`: сначала по оси в печатаемой области. Обходим выбранный диапазон двумя вложенными циклами `for`: сначала по оси

View file

@ -1,7 +1,7 @@
--- ---
title: Рисуем сердечко в консоли title: Рисуем сердечко в консоли
description: Напишем два варианта алгоритма на Java для вывода сердечка в консоль в форме текстового изображения поздравим женщин с восьмым марта. Нарисуем график... description: Напишем два варианта алгоритма на Java для вывода сердечка в консоль в форме текстового изображения поздравим женщин с восьмым марта. Нарисуем график...
sections: [Геометрические фигуры,Отрисовка шрифта,Текстовое изображение] sections: [Геометрические фигуры,Текстовое изображение,Отрисовка шрифта]
tags: [java,awt,консоль,ромб,окружность,круг,текст,изображение,шрифт] tags: [java,awt,консоль,ромб,окружность,круг,текст,изображение,шрифт]
canonical_url: /ru/2023/03/08/drawing-heart-in-console.html canonical_url: /ru/2023/03/08/drawing-heart-in-console.html
url_translated: /en/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 }}) [график функции в консоль]({{ '/ru/2023/02/05/function-graph-in-console.html' | relative_url }})
формулы для окружности и для ромба возьмём из него, а в этом примере для заполнения фигуры внутри, формулы для окружности и для ромба возьмём из него, а в этом примере добавим заполнение фигуры внутри и
в формуле вместо знака *равно* подставляем знак *меньше*, а для заполнения снаружи, наоборот, знак снаружи вместо знака *равно* в формулах подставляем знаки *меньше* или *больше*. Условий получится много,
*больше*. Условий получится много, в отличие от предыдущего примера. в отличие от предыдущего примера.
Нарисуем картинку для наглядности. Нарисуем картинку для наглядности.
@ -97,9 +97,10 @@ o o
{% endcapture %} {% endcapture %}
{%- include collapsed_block.html summary="Полный вывод" content=collapsed_md -%} {%- include collapsed_block.html summary="Полный вывод" content=collapsed_md -%}
Обходим диапазон координат двумя вложенными циклами `for`: сначала по оси `y` и затем по оси `x`. Каждую Обходим диапазон координат двумя вложенными циклами `for`: сначала по оси `y` и затем по оси `x`.
точку проверяем на соответствие условиям и выводим. В верхней части рисуем два полукруга и опционально Каждую точку проверяем на соответствие условиям и выводим. В верхней части рисуем два полукруга и
закрашиваем их внутри/снаружи. В нижней части рисуем полуромб и также опционально закрашиваем внутри/снаружи. опционально закрашиваем их внутри и снаружи. В нижней части рисуем полуромб и также опционально
закрашиваем внутри и снаружи.
```java ```java
/** /**

View file

@ -2,7 +2,7 @@
title: Дерево каталогов со ссылками title: Дерево каталогов со ссылками
description: Напишем скрипт Bash для построения дерева каталогов для репозитория в файле Markdown. Будем использовать только средства Bash и базовое ПО Linux без... description: Напишем скрипт Bash для построения дерева каталогов для репозитория в файле Markdown. Будем использовать только средства Bash и базовое ПО Linux без...
sections: [Рекурсия,Обработка файлов,Вёб-навигация] sections: [Рекурсия,Обработка файлов,Вёб-навигация]
tags: [linux,bash,markdown,html,каталоги,файлы,ссылки,сортировка] tags: [linux,bash,markdown,html,структура,каталоги,файлы,ссылки,сортировка]
canonical_url: /ru/2023/08/03/directory-tree.html canonical_url: /ru/2023/08/03/directory-tree.html
url_translated: /en/2023/08/04/directory-tree.html url_translated: /en/2023/08/04/directory-tree.html
title_translated: Directory tree with links title_translated: Directory tree with links
@ -15,10 +15,11 @@ date: 2023.08.03
[`DIRECTORY_TREE.md`]({{ site.homepage_url }} "{{ site.homepage_name }}") [`DIRECTORY_TREE.md`]({{ site.homepage_url }} "{{ site.homepage_name }}")
будем использовать в вёб-интерфейсе для навигации по объектам репозитория. будем использовать в вёб-интерфейсе для навигации по объектам репозитория.
Создаём рекурсивную функцию и с её помощью обходим все файлы и каталоги репозитория, Создаём рекурсивную функцию и с её помощью обходим все файлы и каталоги репозитория, за
за исключением списка из `.gitignore`. Выводим элементы дерева в виде ссылок `<a>`, исключением списка из `.gitignore` — строим структуру каталогов в форме дерева. Выводим
сворачиваем папки с одним вложенным элементом в одну строку, помещаем дерево в контейнер `<pre>` элементы в виде ссылок `<a>`, сворачиваем папки с одним вложенным элементом в одну строку,
и добавляем заголовок — в результате получаем краткий и лаконичный файл Markdown со ссылками. помещаем собранное дерево в контейнер `<pre>` и добавляем заголовок — в результате получаем
краткий и лаконичный файл Markdown со ссылками.
```bash ```bash
#!/bin/bash #!/bin/bash
@ -34,25 +35,21 @@ function directory_tree {
local head="$2" local head="$2"
local tail="$3" local tail="$3"
# префикс для текущего элемента # префикс для текущего элемента
if [ "one" == "$4" ]; then [ "one" == "$4" ] && printf '%s' "/" || printf '\n%s' "$head"
echo -n "/"
else
echo -ne "\n$head"
fi
# текущий элемент дерева # текущий элемент дерева
echo -n "<a href='${path#*/}'>${path##*/}</a>" printf '%s' "<a href='${path#*/}'>${path##*/}</a>"
# рекурсивные вызовы для подкаталогов # рекурсивные вызовы для подкаталогов
if [ -d "$path" ]; then if [ -d "$path" ]; then
local list # массив файлов и каталогов local list # массив файлов и каталогов
readarray -t list <<<"$(list_directory_contents "$path")" readarray -t list < <(list_directory_contents "$path")
local len=${#list[@]} # размер массива local size=${#list[@]} # длина массива
local i # счётчик local i # счётчик
for ((i = 0; i < len; i++)); do for ((i = 0; i < size; i++)); do
if [ -z "${list[$i]}" ]; then if [ -z "${list[$i]}" ]; then
continue # пропустить пустой каталог continue # пропустить пустой каталог
elif ((len == 1)); then elif ((size == 1)); then
directory_tree "$path/${list[$i]}" "$tail" "$tail" "one" 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" directory_tree "$path/${list[$i]}" "$tail├─ " "$tail"
else else
directory_tree "$path/${list[$i]}" "$tail└─ " "$tail " directory_tree "$path/${list[$i]}" "$tail└─ " "$tail "
@ -60,15 +57,11 @@ function directory_tree {
done done
fi fi
} }
# строка исключений для 'ls' из списка '.gitignore' — неотслеживаемые файлы # строка исключений для "ls" из списка неотслеживаемых файлов ".gitignore"
exclusions="-I \".git\" $(sed 's/^/ -I "/;s/$/"/' .gitignore | tr -d '\n')" exclusions="-I'.git' $(sed -E "s|^(.*)$|-I'\1'|" .gitignore | tr '\n' ' ')"
# помещаем дерево в контейнер, добавляем заголовок и выводим в файл # помещаем дерево в контейнер, добавляем заголовок и выводим в файл
{ printf '%s\n' "## Дерево каталогов" "" "<pre>" \
echo "## Дерево каталогов" "$(directory_tree . | grep '\S')" "</pre>" >DIRECTORY_TREE.md
echo -ne "\n<pre>"
directory_tree .
echo -e "\n</pre>"
} >DIRECTORY_TREE.md
``` ```
Запускаем скрипт в корне репозитория и сохраняем полученный файл. Запускаем скрипт в корне репозитория и сохраняем полученный файл.

View file

@ -16,10 +16,11 @@ title_translated: Code with comments
— без дополнительных программ. Полученный файл `DIRECTORY_TREE.md` будем использовать — без дополнительных программ. Полученный файл `DIRECTORY_TREE.md` будем использовать
в вёб-интерфейсе для навигации по объектам репозитория. в вёб-интерфейсе для навигации по объектам репозитория.
Создаём рекурсивную функцию и с её помощью обходим все файлы и каталоги репозитория, Создаём рекурсивную функцию и с её помощью обходим все файлы и каталоги репозитория, за
за исключением списка из `.gitignore`. Выводим элементы дерева в виде ссылок `<a>`, исключением списка из `.gitignore` — строим структуру каталогов в форме дерева. Выводим
сворачиваем папки с одним вложенным элементом в одну строку, помещаем дерево в контейнер `<pre>` элементы в виде ссылок `<a>`, сворачиваем папки с одним вложенным элементом в одну строку,
и добавляем заголовок — в результате получаем краткий и лаконичный файл Markdown со ссылками. помещаем собранное дерево в контейнер `<pre>` и добавляем заголовок — в результате получаем
краткий и лаконичный файл Markdown со ссылками.
{%- endcapture %} {%- endcapture %}
{%- assign articles = articles | push: article_brief %} {%- assign articles = articles | push: article_brief %}
{%- assign articles = articles | push: "Генератор паролей" %} {%- assign articles = articles | push: "Генератор паролей" %}
@ -55,11 +56,10 @@ JavaScript, чтобы далеко не ходить.
Символы и шрифт могут быть любыми, но для этого примера будем использовать комбинацию заглавных Символы и шрифт могут быть любыми, но для этого примера будем использовать комбинацию заглавных
латинских букв и цифр со шрифтом *Comic Sans* — будем рисовать простую капчу для сайта или блога. латинских букв и цифр со шрифтом *Comic Sans* — будем рисовать простую капчу для сайта или блога.
Спецсимволы рассмотрим, но пользоваться ими не будем, потому что угадать их с таким оформлением Спецсимволы тоже рассмотрим, но использовать их не будем, потому что угадать спецсимволы пользователю
текста пользователю будет сложно. Например, плюс `+` угадать ещё можно, а вот минус `-` или будет сложно с таким оформлением текста. Например, плюс `+` угадать ещё можно, а вот минус `-` или
нижнее подчёркивание `_` уже с трудом, и даже если угадаешь, тогда найти эти кнопки с трудом, нижнее подчёркивание `_` уже с трудом, и даже если угадаешь, тогда найти эти кнопки с трудом, особенно
особенно на телефоне. Поэтому для капчи будем использовать комбинацию только из заглавных на телефоне. Поэтому для капчи будем использовать комбинацию только из заглавных латинских букв и цифр.
латинских букв и цифр.
{%- endcapture %} {%- endcapture %}
{%- assign articles = articles | push: article_brief %} {%- assign articles = articles | push: article_brief %}
{%- include main_page.html articles = articles -%} {%- include main_page.html articles = articles -%}

View file

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
echo "Подготовка архива для последующего развёртывания." echo "Создание архива для последующего развёртывания."
cd _site || exit cd _site || exit
rm -rf ../pomodoro5.zip rm -rf ../pomodoro5.zip
7z a ../pomodoro5.zip ./* 7z a ../pomodoro5.zip . | grep -E '\S'

View file

@ -1,4 +1,4 @@
#!/bin/bash #!/bin/bash
echo "Локальное развёртывание для проверки корректности сборки." 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" echo "Адрес сервера: http://localhost:4000"