Архив рубрики: Блог

Мне нравится! в Octopress от vk.com

Из коробки Octopress умеет выдавать кнопки от google+, twitter и facebook. Для их размещения внизу каждой страницы достаточно прописать эти настройки в файле _config.yml:
123facebook_like: truegoogle_plus_one: truetwitter_tweet_button: true
А сейчас мы научим Octopress добавлять кнопку «Мне нравится!» от социальной сети «В контакте».

Вводим название своего сайта здесь, чтобы получить api Id — идентификатор контактовского виджета для Вашего сайта. Там и получаем код, который надо будет вставить. Код меняется в зависимости от того, какие параметры кнопки выбрать, так что мой код может Вам не подойти — тогда пользуйтесь тем кодом, который вам выдаст «В контакте».
Создаём файл source/_includes/vk_head.html с таким содержанием:
12345<script type=»text/javascript» src=»//vk.com/js/api/openapi.js?116″></script><script type=»text/javascript»>VK.init({apiId: Номер_Вашего_ID, onlyWidgets: true});</script>
Этот код пойдёт внутри <head>. Не забудьте вставить Ваше apiId. Затем добавьте в конец файла source/_includes/custom/head.html:
123{% if site.vk_like %}{% include head.html %}{% endif %}
Создавайте файл source/_includes/vk_sharing.html:
123<script type=»text/javascript»>VK.Widgets.Like(«vk_like», {type: «button»});</script>
Этот код пойдёт в том месте, где мы хотим нашу кнопку.
Добавляйте в конец файла source/_includes/post/sharing.html:
123{% if site.vk_like %}<div id=»vk_like»></div>{% endif %}
Добавьте в файл source/_includes/custom/after_footer.html:
123{% if site.vk_like %}{% include vk_sharing.html %}{% endif %}
Добавьте в файл _config.yml строку:
1vk_like: true
Почти готово. Осталось только расположить кнопку в нужном месте. Если у Вас есть кнопки от Twitter, Google+ и Facebook (с английским словом Like — по умолчанию Octopress и добавляет английскую кнопку), то подойдёт стиль со следующими цифрами, который можно записать в sass/custom/_styles.scss:
1234#vk_like {margin: 0 0 0 80px; padding: 25px 0 33px 0px;}@media screen and (min-width: 520px){ #vk_like {margin: -28px 0 0 320px; padding: 0 0 30px 0;}}
Так кнопка «Мне нравится» от «В контакте» стройно встанет в ряд с остальными кнопками. При ширине окна меньше 520 пикселей кнопка «Мне нравится» съедет во второй ряд и ровненько при этом займёт место посередине под этими тремя. Впрочем, если что-то Вас не устраивает, поменяйте цифры. Отключить кнопку можно, прописав в _config.yml параметр
1vk_like: false
Так что процесс автоматизирован. Будьте только внимательны при смене темы — файл source/_includes/post/sharing.html, скорее всего, будет переписан. Зато все файлы, которые мы создали, и все файлы из поддиректорий custom должны сохраниться. Впрочем, бэкапиться перед сменой темы всё равно необходимо.

Раскладка в Ubuntu 14.04

Для починки раскладки в Ubuntu + GNOME везде советуют это:
user $user $gsettings set org.gnome.settings-daemon.plugins.keyboard active false
setxkbmap -option «grp:alt_shift_toggle,grp_led:scroll,compose:ralt»

Первая команда отключает гномовский индикатор раскладки, так что он работать не будет. Зато вторая команда должна зажигать/гасить лампочку на Scroll Lock (при её наличии) в зависимости от выбранной раскладки. Также вторая команда вешает переключение раскладок на Alt+Shift, а Compose Key — на правый Alt. Читать

Align columns in vim

One may come across the table like this:

There are some utilities to align the columns in the table. But do you really need one, if you are already in vim? Have a look on the alignment process in gif animation or mp4 video.
The general idea is:

Paste enough spaces between the columns, so that the leftmost element from the second column will appear to the right relatively to rightmost element from the first column. In latex files like in the video/animation, & symbol serves as a delimiter between the columns, so I use :%s/&/          &/g to precede all the ampersands with bunch of spaces. How much exactly spaces you need depends on the cell length.

Select empty column in visual block mode via Ctrl + V. To move leftwards everything to the right of the selection, use <. Repeat the action as many times as you need with .. The video and the animation show this only for the first time, when second column is being aligned. It is not the shortest way, and it is shown only for better understanding of what’s going on.

Once you’ve selected an empty column, instead of <……. or so you may do 20<. This method is used to align the remainder of the table in the video/animation.

I started to learn vim about 5 years ago, when someone told me that vim knows how to work with columns. Since then this ability of vim is one of my favorites. I love vim!

Acestream on Ubuntu 16.04

Acestream (fork of the VLC player for video playback via torrents) was easy to install using apt-get on Ubuntu 14.04, but on Ubuntu 16.04 it is not in the repositories at the moment of writing (please let me know if it changes). One way is to install Acestream from source, but it could be difficult. The second way is was described here (Spanish, the link is dead already). I decided to gather all necessary files into an archive to make installation simpler.

To find out if your computer is running 32-bit or 64-bit version of Linux type uname -a in the terminal. If the output contains i686 or i386, then your Linux is 32-bit. If the output contains x86_64, then your Linux is 64-bit.
32-bit Linux

Download the appropriate archive: Acestream 32-bit.

Install the files as follows, using dpkg or gdebi:
user ~ $user ~ $unzip acestream-32.zip
cd acestream-32
root acestream-32 #root acestream-32 #root acestream-32 #root acestream-32 #root acestream-32 #dpkg -i 00-libgnutls-deb0-28_3.3.15-5ubuntu2_i386.deb
dpkg -i 01-acestream-engine_3.0.3-0.2_i386.deb
dpkg -i 02-acestream-player-compat_3.0.2-1.1_i386.deb
dpkg -i 03-acestream-player-data_3.0.2-1.1_i386.deb
dpkg -i 04-acestream-player_3.0.2-1.1_i386.deb

64-bit Linux

Download the appropriate archive: Acestream 64-bit.

Install the files as follows, using dpkg or gdebi:
user ~ $user ~ $unzip acestream-64.zip
cd acestream-64
root acestream-64 #root acestream-64 #root acestream-64 #root acestream-64 #root acestream-64 #dpkg -i 00-libgnutls-deb0-28_3.3.15-5ubuntu2_amd64.deb
dpkg -i 01-acestream-engine_3.0.5.1-0.2_amd64.deb
dpkg -i 02-acestream-player-compat_3.0.2-1.1_amd64.deb
dpkg -i 03-acestream-player-data_3.0.2-1.1_amd64.deb
dpkg -i 04-acestream-player_3.0.2-1.1_amd64.deb

Note
If you are running into the following issue: «trying to overwrite <filename> which is also in package <packagename>», you may want to add the flag —force-overwrite to your installation command. Attention: then the mentioned file will be overwritten and mentioned programs may fail.

Русификация Octopress

В интернете есть несколько записей о русификации дат в Octopress, например, на сегодня доступны Rinat’s Blog и maximmikheev.ru. Забавно, что оба они ссылаются на одного и того же немца. Просто повторяться я бы, конечно, не стал, однако упомянутые записи написаны более 3-х лет назад (24 мая и 13 июля 2012 соответственно), за это время время Jekyll обновился и перестал работать с некоторыми конструкциями из ruby. Мне удалось разобраться, как с этим бороться, о чём и расскажу.

Датами управляет плагин plugins/date.rb. Приведите его к такому виду:
date.rbСкачать# encoding: utf-8module Octopress module Date # Русская локализация: MONTHNAMES_RU = [nil, «Января», «Февраля», «Марта», «Апреля», «Мая», «Июня», «Июля», «Августа», «Сентября», «Октября», «Ноября», «Декабря» ] ABBR_MONTHNAMES_RU = [nil, «Янв», «Фев», «Мар», «Апр», «Май», «Июн», «Июл», «Авг», «Сен», «Окт», «Ноя», «Дек» ] DAYNAMES_RU = [ «Воскресенье», «Понедельник», «Вторник», «Среда», «Четверг», «Пятница», «Суббота» ] ABBR_DAYNAMES_RU = [ «Вс», «Пн», «Вт», «Ср», «Чт», «Пт», «Сб» ] # Returns a datetime if the input is a string def datetime(date) if date.class == String date = Time.parse(date) end date end # В _config.yml должно быть задано: date_format: ordinal def ordinalize(date) # Задаем наш формат выдачи даты format_date(date, «%d %b %Y») # 20 Авг 2019 end # Formats date either as ordinal or by given date format # Adds %o as ordinal representation of the day def format_date(date, format) date = datetime(date) if format.nil? || format.empty? || format == «ordinal» date_formatted = ordinalize(date) else format.gsub!(/%a/, ABBR_DAYNAMES_RU[date.wday]) format.gsub!(/%A/, DAYNAMES_RU[date.wday]) format.gsub!(/%b/, ABBR_MONTHNAMES_RU[date.mon]) format.gsub!(/%B/, MONTHNAMES_RU[date.mon]) date_formatted = date.strftime(format) end date_formatted end endendmodule Jekyll class Post include Octopress::Date def to_liquid(attrs = nil) date_format = self.site.config[‘date_format’] new_datas = { «title» => self.data[‘title’] || self.slug.split(‘-‘).select {|w| w.capitalize! || w }.join(‘ ‘), «url» => self.url, «date» => self.date, # Monkey patch «date_formatted» => format_date(self.date, date_format), «updated_formatted» => self.data.has_key?(‘updated’) ? format_date(self.data[‘updated’], date_format) : nil, «id» => self.id, «categories» => self.categories, «next» => self.next, «previous» => self.previous, «tags» => self.tags, «content» => self.content } Utils.deep_merge_hashes(self.data, new_datas) end end class Page include Octopress::Date # Initialize a new Page. # # site — The Site object. # base — The String path to the source. # dir — The String path between the source and the file. # name — The String filename of the file. def initialize(site, base, dir, name) @site = site @base = base @dir = dir @name = name self.process(name) self.read_yaml(File.join(base, dir), name) # Monkey patch date_format = self.site.config[‘date_format’] self.data[‘date_formatted’] = format_date(self.data[‘date’], date_format) if self.data.has_key?(‘date’) self.data[‘updated_formatted’] = format_date(self.data[‘updated’], date_format) if self.data.has_key?(‘updated’) end end module Filters include Octopress::Date def date_ru(date, format) format_date(date, format) end endend
Отличие от процитированных записей здесь в строках 48–65: там используется deep_merge, на который Jekyll старше 2.0 ругается. Оказалось, что его нужно заменить на Utils.deep_merge_hashes. Я так и не смог проделать это самостоятельно (обожаю ruby!), но мне ответили на stackoverflow.
В _config.yml укажите:
date_format: "ordinal"

Менять формат вывода даты надо в самом date.rb в строке №21. Подробнее о форматировании даты см. на ruby-doc.
Сразу же после изменения date.rb попробуйте собрать блог: rake generate. Даты пока не изменятся, просто проверьте, что всё собирается. Теперь нам осталось заменить в некоторых файлах date на date_ru. Переменная date может встречаться в разных файлах в зависимости от темы. Обычно она находится в source/_includes/archive_post.html. В теме Octostrap3, например, она встречается 7 раз в source/_includes/post/date.html. После замены файл выглядит так:
source/_includes/post/date.html{% capture date_ru %}{{ page.date }}{{ post.date }}{% endcapture %}{% capture date_formatted %}{% if page.date %}{{ page.date | date_ru: site.date_format }}{% endif %}{% if post.date %}{{ post.date | date_ru: site.date_format }}{% endif %}{% endcapture %}{% capture has_date %}{{ date_ru | size }}{% endcapture %}{% capture updated %}{{ page.updated }}{{ post.updated }}{% endcapture %}{% capture updated_formatted %}{% if page.updated %}{{ page.updated | date_ru: site.date_format }}{% endif %}{% if post.updated %}{{ post.updated | date_ru: site.date_format }}{% endif %}{% endcapture %}{% capture was_updated %}{{ updated | size }}{% endcapture %}{% if has_date != «0» %}{% capture time %}<span class=»glyphicon glyphicon-calendar»></span> <time datetime=»{{ date_ru | datetime | date_to_xmlschema }}» {% if updated %} data-updated=»true»{% endif %} itemprop=»datePublished dateCreated»>{{ date_formatted }}</time>{% endcapture %}{% endif %}{% if was_updated != «0» %} {% capture updated %}<span class=»glyphicon glyphicon-calendar»></span> <time datetime=»{{ updated | datetime | date_to_xmlschema }}» class=»updated» itemprop=»dateModified»>Updated {{ updated_formatted }}</time>{% endcapture %}{% else %}{% assign updated = false %}{% endif %}
В процитированных блогах указан такой вариант:
source/_includes/archive_post.html12345678{% capture category %}{{ post.categories | size }}{% endcapture %}<h1><a href=»{{ root_url }}{{ post.url }}»>{{post.title}}</a></h1><time datetime=»{{ post.date | datetime | date_to_xmlschema }}» pubdate>{{ post.date | date_ru: «<span class=’day’>%d</span> <span class=’month’>%b</span> <span class=’year’>%Y</span>»}}</time>{% if category != «0» %}<footer> <span class=»categories»>Опубликовано в {{ post.categories | category_links }}</span></footer>{% endif %}
Но ещё раз повторю, всё зависит от темы. Обратите внимание: менять на date_ru нужно только отдельно стоящее date, а post.date, например, трогать не надо.
А чтобы найти фразы типа «Posted by, Comments, Recent Posts, Categories, Previous post» и т.д., воспользуйтесь командой
grep -irl ‘posted by’ /path/to/octopress/source

Затем вручную редактируйте найденные файлы. Или можно делать замены с помощью потокового редактора sed, например (сделайте backup сначала):
find /path/to/octopress/source -type f -exec sed -i ‘s:recent posts:Последние записи:gI’ {} +

Флаг -i означает менять оригинальный файл, s — замена, далее через двоеточие что и на что менять, g — менять все вхождения в строке, I — нечувствительно к регистру.
Вот и всё, Октопресс локализован. Если что-то не сработало, обязательно дайте знать в комментариях.

Новые посты и временная смена приоритетов.


Рад снова приветствовать всех на страницах своего блога. Судя по комментариям, многих постоянных читателей начала волновать судьба ресурса, т.к. за последние полтора месяца в блоге действительно не появилось ни одного нового поста. Спешу вас заверить — ресурс будет продолжать жить, тем более что интересных тем, про которые я бы хотел написать — накопилось предостаточно (плюс еще остались незаконченные статьи). Наступившее временно затишье связано с небольшой сменой приоритетов. Как советуют некоторые, говорить о том что у тебя не хватает на что-то времени — не очень хорошо, поэтому, назовем это временной сменой приоритетов. Обстоятельства сложились так, что сейчас я занят работой в более крупных и интересных для меня проектах, поэтому та часть времени, которая раньше оставалась для моего небольшого хобби — ведения этого блога, теперь плотно занята другими вещами. Скорее всего подобная картина будет наблюдаться на протяжении всего оставшегося года, поэтому ожидать увидеть тут что-то новое раньше января 2018 г. скорее всего не стоит.

Тем не менее, я рад что судьба ресурса оказалась небезразличной для вас и, надеюсь, что в новом году у нас будет еще больше интересных и полезных статей, а также посетителей. Ну а пока, как говорится, stay tuned … и не забываем про поддержку проекта.



Источник: decker.su