Things that live here:

  1. Work log, where I note things I feel I'll have to Google later.
  2. Journal, very similar but about non-IT topics.
  3. Blog for rare longer-form posts (last one below).
  4. Links blog, formerly my personal wiki.

Feel free to look at what you can find here and enjoy yourself.


~17% of my country is occupied by Russia, and horrible things are happening there. You can help stop this! If you can donate - I contribute to (and fully trust) Come Back Alive and Hospitallers, but there are also other ways to help.

If you're in Germany, DHL sends packets with humanitarian help for free!

Latest posts from the Work log

Day 1744 / Quick-access links

I’ll keep here important links for my own easy access. 1

Masterarbeit index


  1. The irony of having two separate high-level things named “master” is not lost on me. ↩︎

Day 1022 / Day 1021

Obsidian for zettelkasten-type notes

.. is probably my new obsession, along with getting it to play nicely with Hugo. It’s a closed non-open-source system but files are saved as markdown, has an awesome Android app - everything I’ve ever wanted except openness, basically.

So:

Template to create hugo-compatible front matter in Obsidian:

Templater1 is a community plugin for template stuff, but supports neat things like getting clipboard data, creating files, etc. Additionally supports automatically using templates when creating notes in a folder or in general and a lot of other excellent stuff.

This template gets run manually after I create and name a note. When I run it, it autogenerates Hugo front matter, gets the title from the filename, and puts the cursor in the first tag. The second tag is created from the folder name where the note is located, currently I defined two: it and rl.

---
title: "<% tp.file.title %>"
tags:
  - "zc"
  - "zc/<% tp.file.folder() %>"
  - "<% tp.file.cursor() %>"
fulldate: <% tp.date.now("YYYY-MM-DDTHH:MM:SSZZ") %>
date: <% tp.date.now("YYYY-MM-DD") %>
hidden: false
draft: true
---

Obsidian to Hugo Conversion

I looked at zoni/obsidian-export: Rust library and CLI to export an Obsidian vault to regular Markdown and khalednassar/obyde: A minimal tool to convert a standardly configured Obsidian vault to a Jekyll or Hugo blog., found the latter to be a bit clearer in how it handles assets etc. It requires a date in frontmatter in YYYY-MM-DD format, which I provided.

Day 1019 / Day 1018

Python math.isclose() to check for “almost equal”

Had an issue with checking whether a sum of floats sums up to a number, remembering that python floats are ‘special’:

>>> 0.1 + 0.2
0.30000000000000004

Stack overflow1 told me about math.isclose(), works as you’d expect:

assert math.isclose(sum(floats), needed_sum)

Day 1016 / Day 1015

unittest skip test based on condition

From unittest documentation 1

class MyTestCase(unittest.TestCase):

    @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

Day 1010 / Day 1009

Google Meet

You can minimize your own video, and then make the entire window much smaller!

Python strings formatting

Obvious, but: you can declare strings and format them in separate places!

constants.py:

my_string = "Hello my name is {0}"

other_file.py:

from constants import my_string
print(my_string.format("Serhii"))

Pycharm run current unittest binding

<C-S-F10> runs the unittest where the cursor is currently located. Or all of them if located anywhere else in the file.

TODO: set binding to do the same, but debugging.

python - run only some tests from a test suite

I wanted to run only some test files, all except the ones where I needed a GPU. Wrote this:

import subprocess

# Parts of filenames to exclude
large_tests = ['component', 'test_temp']

test_folder = Path(__file__).parent.absolute()
test_files = list(test_folder.glob("test_*.py"))
test_files = [x.name for x in test_files]

for l in large_tests:
  test_files = list(filter(lambda x: l not in x, test_files))

commands = ["python3", "-m", "unittest"] + test_files

subprocess.run(commands, cwd=test_folder)

Notes:

  • Thought this would be a security nightmare, but it’s not1 - unless shell=True is explicitly passed, no shell is called, ergo no shell-command-injection stuff is possible.
  • os.chdir() is nicely replaced by the cwd= parameter, much nicer than what I’d have done previously!

Day 1009 / Day 1008

Python typing annotating second-order functions

def my_function(other_function: Callable) -> Callable:
  return other_function

Pycharm run all unit tests in a folder

What I’d do as

cd tests
python3 -m unittest

in Pycharm is right-clicking on a directory in Project view and “Run unittests”

OOP principles

Open/Closed principle: you should be able to open a module/class to add stuff easily, but otherwise you shouldn’t need to touch it for existing stuff.

Python dir

Wrote a line like if dir is not None .., but dir is a builtin! It returns all the names in the current scope.

Pycharm debugging

You can add Watches, values that will be shown and tracked! Nice for debugging stuff that needs values that are deep in other variables

Python unittests run at the end of the class/module

  • class-level:

    • setUpClass(cls) gets called before tests from one class get run, not once per test
    • tearDownClass(cls) gets called before tests from one class get run, not once per test
    • Both need to be class methods, a la:1
        class Test(unittest.TestCase):
            @classmethod
            def setUpClass(cls):
                cls._connection = createExpensiveConnectionObject()
      
  • module-level

    • setUpModule(), tearDownModule()
    • should be implemented as normal functions

    Aaanad if you set any class variables, you can still access them as self.xxx from within the tests!

Python or in arguments

Neat thing seen in detectron default_argument_parser:

def argparser(epilog=None):
  ...
  x = epilog or "here's some text"

Where “here’s some text” is a long string that doesn’t really belong in the function signature.

A really nice pattern, much better than my usual

if x is None:
  x = ...

Day 1008 / Day 1007

vim open list of files from cli

vim -p `ag -l whatever`

opens each file returned by ag. (ag -l lists only the files with matches and nothing else)

Replacing jekyll-style highlight tags with standard markdown ones

In some posts I had code blocks like {% highlight html %} etc. The html/js got parsed, and some “here’s how to redirect using javascript” code got executed in the master page.

Here’s how I replaced all that syntax with the standard markdown one:

for f in `ag -l "endhighlight"`;
do cat $f | sed "s/{% highlight \(.*\) %}/\`\`\`\1/" | sed "s/{% endhighlight %}/\`\`\`/g" > $f;
done

Python dataclasses and classmethods

@dataclass
class MyClass:
  x: int = 4

@classmethod
def init_whatever(number: int)
  return cls(x=number)

Python exceptions and unittests

unittest’s self.assertRaisesRegex() is nice but couldn’t get it to work with my custom exception class.

with self.assertRaisesRegex(CustomException, "No trained model"):

It expects the message to be in e.args1. args also gets used by the Exception class for __str__() etc, so it’s a nice thing.

Set it up easily:

class CustomException(Exception):
    def __init__(self, detailed_message: str = None):
        if detailed_message:
          self.detailed_message = detailed_message
          self.args = (self.detailed_message, )

Catching python regex exceptions

try:
  re.search("DataLoader worker(.*is killed by signal: Bus error", text)
except re.error:
  whatever()

TODO I really like this regex tutorial: Regular Expressions: Regexes in Python (Part 2) – Real Python

Day 1007 / Day 1006

Hugo indexes and layouts

I think that:

  • Placing an _index.md in the root of the section makes it listable with a list.html template.
  • Placing an index.md (no underscore!) makes that file’s content the real index of that section.

The best way to use a custom layout is to specify it explicitly in the front matter as layout: newlayout. For example for the custom list template in pages (formerly /ntb/pages), I put the layout file in ./layouts/ntb/ntblist.html and put in ./content/ntb/pages/_index.md’s front matter this:

title: "Pages"
[...]
layout: ntblist

Day 1004 / Day 1003

Pycharm presentation mode and font size

Previously, I had to manually increase font sizes in Pycharm when presenting stuff in meeting, and couldn’t automate it.

Today I realized that I can change the script resolution to a lower one, giving the same results, and easily automatable through randr and a shell script!

Pycharm moving functions

“Right click -> Refactor” works not just for renaming files/folders, but also for moving functions to different files!

Miroboard moving

Holding <space> makes the mouse move the view, not the content

Logging in Python

logging — Logging facility for Python — Python 3.9.7 documentation

logger.exception() exists! Exception info is written as given by the exception handler.

Exceptions handling in Python

Was looking for a strategy to handle errors in a complex-ish applications, with logging, different levels etc.

  • Three options how to deal with exceptions:1

    • Swallow it quietly (handle it and keep running).
    • Do something like logging, but re-raise the same exception to let higher levels handle.
    • Raise a different exception instead of the original.
  • Defining your custom exception1

    class SuperError(Exception):
        def __init__(self, message):
            Exception.__init__(message)
            self.when = datetime.now()
    
    raise SuperError('Something went wrong')
    
  • Re-raising the same exception after handling it 1

    def invoke_function(func, *args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print type(e)
            raise
    
  • Ways to clean stuff up in try..catch blocks:2

    • try: - execute this
    • except: execute this if there’s an exception
    • else: - execute if no exceptions
    • finally: - always run this code
  • Context managers

    • Alternative to finally, standard with ... syntax
  • Logging best practice1

    import logging
    logger = logging.getLogger()
    def f():
        try:
            flaky_func()
        except Exception:
            logger.exception()
            raise
    

    If you re-raise, make you sure you don’t log the same exception over and over again at different levels.1

    The simplest way to do it is to let all exceptions propagate (unless they can be handled confidently and swallowed earlier) and then do the logging close to the top level of your application/system.1

  • Error logger decorator for the above1

    def log_error(logger)
        def decorated(f):
            @functools.wraps(f)
            def wrapped(*args, **kwargs):
                try:
                    return f(*args, **kwargs)
                except Exception as e:
                    if logger:
                        logger.exception(e)
                    raise
            return wrapped
        return decorated
    

    And usage:

    import logging
    logger = logging.getLogger()
    
    @log_error(logger)
    def f():
        raise Exception('I am exceptional')
    
  • If there are multiple decorators, that one should be the immediate next one to the function! When I did it wrong, I got an exception (ha) about “‘staticmethod’ object is not callable”.

    The correct way is:

    @staticmethod
    @return_trainer_exception(logger=None)
    

Day 1003 / Day 1002

Cherry-picking commits from pycharm

Messed up merging/rebasing branches from branches from branches, but needed to merge literally a couple of commits.

So I created a clean branch from master. Then:

  • Check out the target branch, the one you’re cherry-picking to
  • Open the git log
  • Select the commits you want to cherry-pick, right click, “cherry-pick”
  • Done!

As usual, docs exist1 and are quite readable.

PEP8 max line width of 80 characters

… is the best thing since sliced bread, I was skeptical at first but makes editing code in multiple windows so much better!

Installing python3.8 on Ubuntu 18.04 LTS

  • Needed a third-party PPA2 that has all the newer python versions:
      sudo add-apt-repository ppa:deadsnakes/ppa
      sudo apt install python3.8
      sudo apt install python3.8-dev
    
  • Needed sudo apt-get install python3.8-venv3
  • Needing to reinstall all packages for it, haha.
    • Set up locally a venv38 for this; if I source venv38/bin/activate python3 becomes python3.8 by default.
  • Needed to install

python3.8-dev was added after an error I had4 when installing pycocotools, it didn’t find python.h when building.

Installing python locally

This describes the process well: Install python3.6+ for local user on remote machine without root access - ~/web/logs

The official documentation: 2. Using Python on Unix platforms — Python 3.9.7 documentation

Basically make altinstall is a safer version that doesn’t overwrite system-wide stuff:

make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix/bin/pythonversion.

TL;DR:

  • Download the source tarball
  • Then:
    ./configure --prefix=whatever
    make
    make altinstall
    
  • Add the prefix to $PATH:
    export PATH=$PATH:/data/sh/tools/python3.8/bin
    

Hugo auto-reload and CSS

Just now remembered that when doing CSS stuff it’s sometimes cached, and one needs to <Shift-R> or sth similar. Hugo’s automatic reloading reloads the content/templates/…, but not the CSS!

Explains a lot of what happened the last two days.

Hugo Templating

Copypasting from the docu5:

  • Parameters for functions are separated using spaces
  • Dot-notations for methods and fields ({{ .Params.bar }})
  • Things can be grouped via parentheses:
    • {{ if or (isset .Params "alt") (isset .Params "caption") }} Caption {{ end }}
  • A Single Statement Can be Split over Multiple Lines:
    {{ if or 
      (isset .Params "alt") 
      (isset .Params "caption")
    }}
    

Setting directory-specific settings in vim

Given that Hugo’s markdown considers code as part of a bullet-point if it’s indented two spaces more than the *-bulletpoint’s level, and that I have a tabwidth of 4 and tabs everywhere else and two spaces were a pain…

To apply settings only within a specific directory, add this to ~/.vimrc6:

autocmd BufNewFile,BufRead /home/me/ntb/* set tabstop=4 softtabstop=4 shiftwidth=4 expandtab foldmethod=marker

Notably, for me it didn’t work when the path contained a symlink, had to write it explicitly.

Another option from that SO questiont was placing a ~/.vimrc in that directory7, allowing vim to use it by default, and sourcing the usual global one from the first line. Has security implications, may lead to issues with paths/plugins, didn’t try it.

vim tabs and spaces and indentation settings

Looking for indentation stuff for the above lead me here: Tab settings in Vim. Summary: | by Ari Sweedler | Medium

It has this description, copying verbatim:

  • tabstop: display-only, how many spaces does one \t equal visually?
  • shiftwidth: how many spaces does one level of indentation equal? (shifting commands, formatting, behaviour).
  • softtabstop: how much whitespace to add/remove when pressing tab/backspace?
    • Disabled by default; if using tabs - we create as much whitespace as needed to get to the next tabstop
    • but when using spaces for indentation, we don’t want backspace to delete one space, then this is needed
  • expandtab: should pressing <Tab> on the keyboard create spaces or a tab character?

highlight indentation levels in vim, if indentation is done with spaces

Highlighting tab-indents is easy, and I had these settings for that:

set listchars=tab:\:\ 
set listchars+=trail:◦

For spaces it’s harder.

Tried the indentLine plugin8, due to it using the conceal setting I couldn’t see my json-quotes and _ underscores anymore. Setting conceallevel to 1 from 2 helped only for the latter. May get fixed by colorscheme/syntax files with less concealed stuff?

Setting let g:indentLine_concealcursor = '' (by default inc) helps - text is not concealed at all in the cursor line in any of the modes. I see all concealed text and don’t see the guides. I can kinda live with that.

In any case replacing the 's in json is ugly.

Then found this excellent SO answer. set cursorcolumn cursorline highlight the entire column/row where the cursor is. Which is why I want indentation highlighting 99% of the time!

With my newfound vim knowledge, added this to ~/.vimrc:

autocmd filetype python set cursorcolumn cursorline

But this didn’t satisfy me for the dtb and I kept looking.

Then I found vim-indent-guides9 that changes just the background color. Settings I ended up using:

let g:indent_guides_enable_on_vim_startup = 1
let g:indent_guides_auto_colors = 0
let g:indent_guides_start_level = 2
let g:indent_guides_guide_size = 4
" autocmd VimEnter,Colorscheme * :hi IndentGuidesOdd  guibg=darkgrey  ctermbg=233
autocmd VimEnter,Colorscheme * :hi IndentGuidesEven guibg=blue ctermbg=233

ctermbg=233is one of the darkest black-like vim colors, there’s a nice vim colors reference10 online.

At the end, wrapped everything related to DTB and indentst in one nice startup function:

fun! SetDTB()
	set tabstop=4  shiftwidth=2 expandtab 
	foldmethod=marker
	set nocursorline nocursorcolumn 
	let g:indent_guides_auto_colors = 0
	let g:indent_guides_start_level = 1
	let g:indent_guides_guide_size = 1
	autocmd VimEnter,Colorscheme * :hi IndentGuidesEven guibg=blue ctermbg=236
endfu

autocmd BufNewFile,BufRead /home/me/ntb/* :call SetDTB()

Latest post from Blog

'The Hacker Manifesto', переклад українською

Оригінал: .:: Phrack Magazine ::.
Контекст: Маніфест хакера — Вікіпедія / Hacker Manifesto - Wikipedia
Існуючий дуже класний переклад, не відкривав, поки не закінчив свій: Маніфест хакера | Hacker’s Manifesto | webKnjaZ: be a LifeHacker

                               ==Phrack Inc.==

                    Том I, випуск 7, Ph-айл[0] 3 з 10

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Наступне було написано невдовзі після мого арешту...

	                        \/\Совість хакера/\/

	                               автор:

	                          +++The Mentor+++

	                           8 січня 1986р.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

	Сьогодні ще одного спіймали, пишуть у всіх газетах. "Кібер-скандал:
підлітку повідомили про підозру", "Кіберзлочинця затримали після
проникнення в систему банку".
	Тупа школота[1], вони всі однакові.

	Та чи ви, з вашою трафаретною ментальністю[2] та знаннями 
інформатики зразка першої половини пʼятидесятих[3], коли-небудь дивилися 
в душу хакера?[4] Чи вас колись цікавило, що є причиною його поведінки[5], 
які сили на нього впливали, що його сформувало?
	Я хакер, ласкаво прошу у мій світ...
	Мій світ почався ще зі школи... Я розумніший за більшість інших
дітей, і дурниці, які нам викладають, мені набридають.
	Тупий відстаючий[6], вони всі однакові.

	Восьмий, девʼятий, десятий, одинадцятий клас[7]. В пʼятнадцятий
раз слухаю, як вчителька пояснює, як скорочувати дроби. Мені все ясно. "Ні, 
Вікторія Миколаївна[8], я не написав проміжні кроки, я розвʼязав все усно..."
	Тупий підліток. Мабуть списав. Всі вони такі.

	Сьогодні я зробив відкриття. Я знайшов компʼютер. Ха, почекай-но,
це круто. Він робить те, що я від нього хочу. І якщо він помиляється,
це тому, що помилився я. А не тому що він мене не любить...
                         Або відчуває від мене загрозу...
                         Або думає що я тіпа самий умний[9]...
                         Або не любить викладати[10] і йому тут не місце...
	Тупий підліток. Він постійно тільки грає в свої ігри. Всі вони такі...

	Потім це відбулось... відчинились двері в світ... несучись телефонною 
лінією як героїн венами наркомана, надсилається електронний пульс,
шукається спасіння від невігластва навколо...[11] Знаходиться борд.[12]
	"Це воно... це те, до чого я належу..."
	Я з усіма тут знайомий... попри те, що я з ними ніколи не 
зустрічався, не розмовляв, і колись можливо більше нічого не чутиму про 
них... Я їх всіх знаю...
	Тупий підліток. Знову займає телефонну лінію... Вони всі однакові.

	Та можете не сумніватись,[13] що ми всі однакові... Нас годували
дитячими сумішами з ложки, коли ми хотіли стейк... а ті куски мʼяса, які 
до нас все ж потрапляли, були вже пережовані і без смаку. Над нами
панували садисти, або нас ігнорували байдужі. Для тих, хто хотіли чомусь 
нас навчити, ми були вдячними учнями, але їх було як краплин дощу в
пустелі.

	Цей світ зараз наш... світ електрона і комутатора, світ краси
бода[14]. Ми користуємося існуючою послугою не платячи за те, що могло б 
бути дуже дешевим, якби ним не завідували ненажерливі бариги[15], і ви 
називаєте нас злочинцями. Ми досліджуємо... і ви називаєте нас 
злочинцями. Ми шукаємо знання... і ви називаєте нас злочинцями. Ми 
існуємо без кольору шкіри, без національності і без релігійної 
нетерпимості... і ви називаєте нас злочинцями. Ви будуєте атомні бомби, 
ви ведете війни, ви вбиваєте, обманюєте, і брешете нам, намагаючись 
заставити нас повірити, що ви це робите для нашого блага, і попри все - 
це ми тут злочинці.

	Так, я злочинець. Мій злочин - моя допитливість. Мій злочин - 
оцінювати людей по тому, що вони кажуть і думають, а не по тому, як 
вони виглядають. Мій злочин в тому, що я вас перехитрив, і ви мене 
ніколи не пробачите за це.

	Я хакер, і це мій маніфест. Можливо ви зупините мене як особу, але ви 
ніколи не зупините нас всіх... зрештою, ми всі однакові.
	

Замітки:

  1. Ph-айл: worst of both worlds between phile and файл
  2. Damn kids: тупі/кляті/грьобані діти/школота1/малолітки2? Дякую цьому твіту Букви, який дає мені моральне право використовувати слово “школота”, бо нічого інше не клеїлося (“Окаяні дітлахи!")
  3. three-piece-psychology: інтерпретую як невисоку оцінку розвитку внутрішнього світу. Тому: пересічним/шаблонним/банальним/трафаретним3/примітивним/нехитрим/безхитрим; psychology: ‘інтелект’ але не зовсім, мені подобається ‘ментальність’
  4. and 1950’s technobrain: Німецький переклад, який сподобався англіцизмами та дав ідею перекласти technobrain в значенні “знання про компʼютери”, а не слово в слово: Berühmte Manifeste 2 – openPunk
  5. хакер/гакер: Вікіпедія вважає обидва допустимими; сам Авраменко ссилаючись на ті самі правила українського правопису теж вважає обидва допустимими, але все ж любить “г” більше (Хакер чи гакер - експрес-урок - YouTube). А я не можу і не буду. Хакер. I will die on this hill.
  6. what makes him tick: TODO, нічого не подобається. Що його рухає/надихає, що у нього в середині, …
  7. underachiever: хай буде “відстаючий”. Хоча пригадую з ЗНО, що суфікси уч/юч обмежені у вживанні, правильніше ВІДСТАЛИЙ мені не подобається.
  8. junior high or high school: тут додаю драми замість дослівності, тому що все ближче до оригіналу, що я можу придумати, занадто канцеляристично: “я закінчую базову чи повну загальну середню освіту”..?
  9. Ms. Smith:
  10. I’m a smart ass
  11. doesn’t like teaching: оплакую невикористаний варіант від душі “ненавидить себе, дітей, і педагогіку”. Дуже оплакую.
  12. a refuge from the day-to-day incompetencies is sought
  13. a board is found: мається на увазі електронна дошка оголошень (BBS — Вікіпедія), дід форумів і прадід іміджбордів. Найцікавіше слово для перекладу. Якщо буде “борд” то збережеться драматизм оригіналу, але є шанси, що хтось спутає з іміджбордами. Коли вони були популярні, нормальні люди в Україні їх не називали ніяк, російською були варіанти “доска”, “бибиэска”4. “BBS” був би найпростішим виходом; “електронна дошка оголошень” знову ж таки канцеляризм. По контексту далі очевидно, що мова йде про якесь спілкування, тому хай буде “борд”, принесу в жертву однозначність і зрозумілість милозвучності.
  14. you bet your ass we’re all alike: як же складно підбирати такі речі. Умовні embeddings з ML тут були б в тему. “Дай мені щось на кшталт ‘авжеж’ тільки більш emphatical”. Попередня версія “Авжеж ми всі однакові!”
    1. You bet – phrases: базара нет, по любому, я вас умоляю
    2. Будьте певні5
    3. ЩЕ Б ПАК — СИНОНІМІЯ | Горох — українські словники
      1. Авжеж?6
  15. the beauty of the baud: Бод — Вікіпедія Нехай мій (і єдиний можливий) переклад буде всім настільки ж зрозумілим, наскільки мені був зрозумілий оригінал, коли я його читав вперше.
  16. profitteering gluttons

Hat tip to:

Random: