10 янв. 2024 г.

MacOS: кто мешает спать?

 de1s-mbp:~ delayer$ pmset -g | grep -w sleep

 sleep                1 (sleep prevented by sharingd, useractivityd)


Кратенькая команда, которая покажет, кто в данный момент не дает макбуку уйти в сон (и в течение ночи пожрет к чертям всю батарейку). В моем случае это оказался включенный удаленный доступ к экрану. После отключения стало хорошо:

$ pmset -g | grep -w sleep

 sleep                1

Узнал о такой штуке отсюда 

15 окт. 2022 г.

АпТуДейт

Давно не заходил. 

А теперь зашел - да из забугра. Занесло, а вот надолго ли, непонятно.

15 мар. 2021 г.

Transmission remote

 Пара ссылок для конфигурации торрент-клиента transmission в клиент-серверном виде: демон на сервере, интерфейс управления - на клиентах.

7 окт. 2020 г.

Экспорт паролей из Яндекс.Браузера

Яндекс-браузер - таки бяка. Обиделся я на него после того, как не смог найти штатного способа забрать из него сохраненные пароли. Ребята не только написали свой менеджер паролей (который сам по себе вполне и норм), но выпилили штатные хромиумные возможности экспорт паролей. В итоге импортировать их можно практически откуда угодно, а вот экспортировать - никак. Совсем.

Однако нашелся таки умелец на просторах интернета, который смог. Более того, результаты своей деятельности он выложил на гитхабе (тут) и сопроводил инструкцией по использованию. Спасибо, Олег Правдин! Была бы спонсорская кнопка, обязательно отправил бы взнос на пиво.

А браузер - в топку, каким бы хорошим он в остальном не был.

3 сент. 2020 г.

Docker overlay deep dive

 Не передать словами насколько полезная нашлась серия статей про устройство overlay-сетей в Docker.

9 июн. 2020 г.

vscode - reenable settings when "exclude settings and ignore files are disabled"

Я полчаса глаза мозолил, прежде чем понять, о чем речь уже по готовым инструкциям. Это ж надо, а... Спасибо, Stephen Weiss, за картинки тут.
Поиск курильщика:
search with settings disabled

Поиск здорового человека:
search with settings enabled

19 мая 2020 г.

psycopg2 on MacOS

Споткнулся при создании нового virtualenv-а на установке пакета psycopg2 (нужен для работы ансибловых модулей с PostgreSQL). Для его установки требуется наличие бинарника pg_config, но найти его pip не может. Как полечить, нашел вот тут, спасибо автору.
Краткое содержание: взять предсобранный постгрес для макоси тут (на самом деле в оригинальной статье автор отправляет загружать постгрес неведомо куда, но по предложенной мной ссылке все проще и понятнее) и добавить в PATH 
export PATH="/Applications/Postgres.app/Contents/Versions/12/bin/:$PATH"
Далее можно собирать psycopg2.

11 апр. 2020 г.

Apple Magic Keyboard and tilde button

Пришел в редакцию вопрос, как в новой модной молодежной яблочной magic keyboard выковырять невнятную кнопку с символом параграфа и плюс-минуса (и кому они могли вовсе понадобиться?) и вернуть, как везде тильду с обратной кавычкой? 
Поиски привели к прекрасному человеку по имени Dimitar Chakarov и его заметке с решением проблемы и репозиторию со скриптиком и даже собранным приложением для макоси. Работает великолепно, коллеги довольны.

22 окт. 2019 г.

MacOS 10.15 Catalina: Abort trap: 6

Обновление до Каталины ломает питончик: 
Abort trap: 6 
Воркараунд:
$ brew install openssl
$ ln -s /usr/local/Cellar/openssl/1.0.2t/lib/libcrypto.1.0.0.dylib /usr/local/lib/libcrypto.dylib
Если версия openssl на момент выполнения команды уже иная, поменять.

Источник: https://someguys.blog/2019-10-09-python-abort-on-macos-catalina/

 

6 февр. 2019 г.

Openvpn\Tunnelblick hide `unrecognized option` window

Давненько ничего не приходилось записать, но вот...

На текущем рабочем месте доступ к ряду ресурсов организован через OpenVPN. Помимо прочих опций сервер выдает настройки DNS сервера, однако используются эти опции исключительно в win-среде, а мой macos-ный Tunnelblick на них ругается как на `unrecognized`:

Линуксовый openvpn-клиент сругнется ровно также:
2019-02-06 22:16:04 Options error: Unrecognized option or missing or extra parameter(s) in [PUSH-OPTIONS]:1: block-outside-dns (2.4.6)

2019-02-06 22:16:04 Options error: Unrecognized option or missing or extra parameter(s) in [PUSH-OPTIONS]:3: register-dns (2.4.6)
И если к сообщениям в логе можно отнестись спокойно (и не заметить), то всплывающее окно при каждом открытии крышки ноутбука напрягает.

Однако решение есть! В документации находим следующее:
--pull-filter accept|ignore|reject text
Filter options received from the server if the option starts with text. Runs on client. The action flag accept allows the option, ignore removes it and reject flags an error and triggers a SIGUSR1 restart. The filters may be specified multiple times, and each filter is applied in the order it is specified. The filtering of each option stops as soon as a match is found. Unmatched options are accepted by default.
Prefix comparison is used to match text against the received option so that
--pull-filter ignore "route"would remove all pushed options starting with route which would include, for example, route-gateway. Enclose text in quotes to embed spaces.
--pull-filter accept "route 192.168.1."--pull-filter ignore "route "would remove all routes that do not start with 192.168.1.
This option may be used only on clients. Note that reject may result in a repeated cycle of failure and reconnect, unless multiple remotes are specified and connection to the next remote succeeds. To silently ignore an option pushed by the server, use ignore.


 Добавив в конфигурационный файл нужные строки:
pull-filter ignore redister-dns
pull-filter ignore block-outside-dns
Получаем тишь и благодать:

2019-02-06 22:38:37 Pushed option removed by filter: 'block-outside-dns'
2019-02-06 22:38:37 Pushed option removed by filter: 'register-dns'
 

30 мая 2018 г.

Apple Notes -> Evernote

Так случилось, что появился у меня Evernote Premium, ввиду чего захотелось перенести накопленные за пару лет работы заметки из Apple Notes туда. Нашелся замечательный applescript-файл, позволяющий сделать это быстро и вкусно. Спасибо перечисленным в заголовке авторам и вообще всем участникам треда.
(*

    ====================================================

      [EN] Import Apple Notes into Evernote

    ====================================================

    

    DATE:    2013-10-24

    AUTHOR: d.b.walker

    

    REVISED BY:  JMichaelTX on 2016-03-28 to make BUG fix.

    

    REF:

      • Importing from Apple Mail.app's Notes - Mac Help - Evernote User Forum       

      • https://discussion.evernote.com/topic/4046-importing-from-apple-mailapps-notes/?do=findComment&comment=236445

    

    Posted 24 Oct 2013

    Modified this script to work with Mavericks Notes, which is no longer in the mail app.

    Added the original creation and modification dates

    Added multiple tags - replace with your own

    Did not add the long note name fix (I needed to preserve my note names)

    ====================================================

    

    FURTHER DEVELOPED BY: Nigel Garvey 2017-03-21/22/23, based on information in the Evernote fora, to allow a choice of Notes source folder(s) and to handle attachments.

    

    CAVEATS:

        1. I don't have Evernote and can't test that part of the code.

        2. (No longer relevant. Thanks to Yvan Koenig for the fix.)

        3. Any attachments are simply "appended" to the Evernote notes in the order they happen to be returned by Notes.

        4. The effect in Evernote of Notes's references to the attachments in the note HTML is unknown.

*)



main()



on main()
-- User choice of one or more Notes folders (by name).
tell application "Notes"
activate
set folderNames to name of folders
set chosenFolderNames to (choose from list folderNames with multiple selections allowed)
if (chosenFolderNames is false) then error number -128 -- Cancel button.
end tell
-- Preset HFS and POSIX versions of a path to a folder on the desktop for storing any attachments.
set tempFolderPath to (path to desktop as text) & "Attachments from Notes:"
set tempFolderPosix to quoted form of POSIX path of tempFolderPath
-- Repeat with each chosen folder name:
repeat with i from 1 to (count chosenFolderNames)
-- Get all the notes in the folder with this name.
set thisFolderName to item i of chosenFolderNames
tell application "Notes" to set theNotes to notes of folder thisFolderName
set quotedFolderName to quoted form of thisFolderName
-- Repeat with each note in the folder:
repeat with j from 1 to (count theNotes)
set thisNote to item j of theNotes
tell application "Notes"
-- Get the relevant note data.
set myTitle to the name of thisNote
set myText to the body of thisNote
set myCreateDate to the creation date of thisNote
set myModDate to the modification date of thisNote
set myAttachments to the attachments of thisNote
-- Any attachments will need to be extracted to the folder on the desktop and attached to the Evernote note from there.
-- To preserve the attachment names and avoid confusion in the case of duplicated names, each attachment is saved to a separate subfolder in a hierarchy based on the folder/note/attachment structure. 
set attachmentFiles to {}
set attachmentCount to (count myAttachments)
if (attachmentCount > 0) then
-- If this note has any attachments, create or add to the hierarchy of the folder on the desktop to accommodate each one.
do shell script ("mkdir -p " & tempFolderPosix & quotedFolderName & "/'Note '" & j & "/'Attachment '{1.." & attachmentCount & "}")
-- Repeat with each attachment:
repeat with k from 1 to attachmentCount
set thisAttachment to item k of myAttachments
-- Put together a specifier for a file in which to save this attachment.
set thisFile to (tempFolderPath & thisFolderName & ":Note " & j & ":Attachment " & k & ":" & thisAttachment's name) as «class furl»
-- Create the file before trying to save to it. (Suggested by Yvan Koenig.)
close access (open for access thisFile)
-- Save the attachment to it.
save thisAttachment in thisFile -- Now it works! Thanks, Yvan!
-- Store the file specifier for the retrieval of the attachment below.
set end of attachmentFiles to thisFile
end repeat
end if
end tell
tell application "Evernote"
set myNote to create note with text myTitle title myTitle notebook "Imported From Notes" tags ["imported_from_notes"]
set the HTML content of myNote to myText
repeat with thisFile in attachmentFiles
tell myNote to append attachment thisFile
end repeat
set the creation date of myNote to myCreateDate
set the modification date of myNote to myModDate
end tell
end repeat
end repeat
end main

27 апр. 2018 г.

SSH Agent auto add keys

Когда количество ssh-ключей начинает расти, жонглировать ими становится печально. Случайно на реддите нашелся замечательный лайфхак, как удобно работать с множеством ключей, не заморачиваясь ручным добавлением их в ssh-agent:
Host *
UseKeychain yes
AddKeysToAgent yes
IdentityFile ~/.ssh/id_rsa
IdentityFile ~/.ssh/id_25519
Один раз перечисляем все нужные ключи в начале ~/.ssh/config, и все. 

14 февр. 2018 г.

MacOS X High Sierra soft from unknown sources

В свежей макоси, которая High Sierra, из настроек безопасности (Системные настройки - Защита и безопасность - Основные - Разрешить использование программ, загруженных из:) убрали возможность установки ПО из неизвестных источников. Вернуть можно консольной командочкой: 
sudo spctl --master-disable

7 февр. 2018 г.

QEMU\KVM: virtio-blk vs virtio-scsi

Искал не так давно, а написали вот совсем недавно: отличная статейка по сабжу. Последний абзац процитирую:
Looking at the advantages of virtio-scsi, I believe it’s the correct choice as a default VM disk interface in oVirt. For optimized VMs, there is always the choice of manually switching to virtio-blk (or IDE, if you’re optimizing for slowness… or compatibility). For now, adding IO thread may cause more harm than good, therefore we’ll leave that for the future.

5 дек. 2017 г.

Openssl: самое-самое

Нечасто, но случается необходимость заглянуть внутрь openssl-сертификата, сгенерировать или подписать новый, сконвертировать из одного формата в другой. Отличная подборка самых частых команд.

20 нояб. 2017 г.

yum: a lot of duplicate packages

Пришел сегодня коллега с проблемой: в процессе обновления завис yum, а после рестарта виртуалки случился kernel panic на старте. И если рабочую систему мы получили, просто загрузившись с предыдушей версии ядра, то проблемы с менеджером пакетов решали еще некоторое время. А проблема оказалась такая: при попытке совершить любые действия с пакетами yum находил вагон и маленькую тележку пакетов в состоянии duplicate. Аналогичный результат выдавал и yum check. Выискивать и удалять полторы сотни дубликатов руками - не вариант.
После некоторого количества изысканий пришли к следующему решению:
# package-cleanup --cleandupes --skip-broken
# yum clean all
# yum update


27 окт. 2017 г.

github.com/de1ayer

Дошли руки выложить некоторые наработки за последние полгода, чтобы не забылись.

16 окт. 2017 г.

YUM: установка пакета конкретной версии

Посмотреть доступные версии пакета, причем с выводом в том виде, который скушает yum: 
[root@git03 gitlab]# repoquery --show-duplicates gitlab-ce | grep 9.5
gitlab-ce-0:8.9.5-ce.0.el7.x86_64
gitlab-ce-0:9.5.0-ce.0.el7.x86_64
gitlab-ce-0:9.5.1-ce.0.el7.x86_64
gitlab-ce-0:9.5.2-ce.0.el7.x86_64
gitlab-ce-0:9.5.3-ce.0.el7.x86_64
gitlab-ce-0:9.5.4-ce.0.el7.x86_64
gitlab-ce-0:9.5.5-ce.0.el7.x86_64
gitlab-ce-0:9.5.6-ce.0.el7.x86_64
gitlab-ce-0:9.5.7-ce.0.el7.x86_64
gitlab-ce-0:9.5.8-ce.0.el7.x86_64
Сам бы ни в жизнь не догадался так записать О_о, тем более что установленный пакет выглядит так:
[root@dpro-git03 gitlab]# yum -q list installed gitlab-ce
Installed Packages
gitlab-ce.x86_64           9.5.5-ce.0.el7           @gitlab_gitlab-ce

12 окт. 2017 г.

cURL + GitHub

Не достает времени заняться пополнением своих заметок. Оставлю пару ссылок на отличные сборники рецептов по использованию API GitHub (и любых других) с помощью cURL. Вот одна, вот вторая. Спасибо авторам, пешыте исчо.

15 сент. 2017 г.

Equivalent of update-grub for RHEL/Fedora/CentOS

Неведомо почему, но в RedHat-based дистрибутивах нет команды grub-update (update-grub). Приходится для регенерации конфигурационного файла загрузчика помнить вот такое:
grub2-mkconfig -o "$(readlink /etc/grub2.cfg)"