Skip to content

April of 2022

Computer Science

GNULinux

Adjust external monitor brightness

  • New: Script to adjust external monitor brightness.

    If you want to adjust the external monitor brightness according to the main display, you can run the following script after every brightness change to the main monitor.

    xrandr -q | grep -q "DisplayPort-4 connected" || exit 0
    
    (
      # Wait for lock on /var/lock/adjust_external_monitors_brightness.exclusivelock (fd 200) for 20 seconds
      flock -x -w 20 200 || exit 1
    
      # main screen brightness (from 0 to 255)
      main=$(cat /sys/class/backlight/amdgpu_bl0/brightness)
    
      # external monitor
      l27_max=100 # max brightness
      l27_0=40 # equivalent brightness of main for l27 min brightness
      l27_100=255 # equivalent brightness of main for l27 max brightness
    
      # equivalent brightness for the external monitor
      l27=$(( 100 * ( (main > l27_0 ? main : l27_0) - l27_0 ) / (l27_100 - l27_0) ))
    
      # try to set it until success
      until ddccontrol -r 0x10 -w $l27 dev:/dev/i2c-11 | grep -q "Writing 0x10";
      do
        sleep 1;
      done
    
    ) 200>/var/lock/adjust_external_monitors_brightness.exclusivelock
    

    You will need to make a few adjustments:

    • Change DisplayPort-4 to whatever corresponds to your external monitor.
    • Change /sys/class/backlight/amdgpu_bl0/brightness if you use Intel.
    • Adjust the variables (l27_max, l27_0, l27_100).
    • Get the corresponding i2c device (change i2c-11) by running ddccontrol -p.

Alacritty

  • New: Setup remote shell automatically.

    An usefulzsh function is:

    s () {
        infocmp | ssh $@ 'tic -x /dev/stdin'
        ssh $@
    }
    

    Which will setup the shell always before connecting.

Bash

  • New: Get min or max from two variables.

    Use the ternary operator. For example, for MAX(10, $VAR) do:

    $((VAR > 10 ? VAR : 10))
    
  • New: Run a command until the ouptut contains some text.

    until somecommand | grep -q "Up to date";
    do
      sleep 1;
    done
    
  • New: Flcok.

    To ensure only one instance of the script runs some code, you can use flock as follows:

    (
      # Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds
      flock -x -w 10 200 || exit 1
    
      # Do stuff
    
    ) 200>/var/lock/.myscript.exclusivelock
    
  • New: Beep alert.

    You can generate a beep alert (if enabled in the system) and a window highlight with:

    echo -e "\a"
    

Basics

  • New: Get command output or default value if emtpy.

    echo | sed 's/^$/default value/'
    
  • New: Get the cursor position.

    Useful for recording part of the screen with (ffmpeg)[ffmpeg].

    watch -n 0.1 xdotool getmouselocation
    

dpkg

  • New: Most common commands.

    • dpkg -S (--search): Find package(s) owning file(s).

Git

  • New: Push tags.

    To push the local tags to the remote server:

    git push --tags
    
  • New: Move last n commits to a new branch.

    So you forgot to create a feature branch ah? No problem, let's move the last few unpushed commits to a new branch:

    git checkout -b new_branch # create a new branch from the current one
    git checkout old_branch # go back to the original branch
    git reset --hard HEAD~3 # undo the last 3 commits
    git checkout new_branch # go to the new branch and continue there
    
  • New: Modify specific commit message.

    git rebase --interactive '<commit-id>^'
    

    Then replace pick with r and save to modify the commit message.

  • New: Merge conflict style.

    Take the pain out of git conflict resolution: use diff3

    git config --global merge.conflictstyle diff3
    

    After running this command to turn on diff3, each new conflict will have a 3rd section, the merged common ancestor.

    <<<<<<< HEAD
    GreenMessage.send(include_signature: true)
    ||||||| merged common ancestor
    BlueMessage.send(include_signature: true)
    =======
    BlueMessage.send(include_signature: false)
    >>>>>>> merged-branch
    
  • New: View file evolution.

    You can use git log -L to view the evolution of a range of lines. Example:

    git log -L 15,23:filename.txt
    

    means trace the evolution of lines 15 to 23 in the file named filename.txt.

  • New: Compare file accross references.

    To compare a file accross references (branches, tags, commits...) do:

    git diff <reference1> <reference2> -- <file>
    
  • New: Revert file to specific commit.

    git checkout c5f567 -- file1/to/restore file2/to/restore
    

GPG

  • New: Generate a key.

    Use gpg --gen-key or gpg --full-gen-key for more options.

  • New: Export public key.

    gpg --output public.pgp --armor --export username@email
    

grep

  • New: Common options.

    • -r: recursively search a directory.
    • -i: ignore case.
    • -l: print only the path of the files that have at least one match.
  • New: Limit results line length.

    First 400 bytes of the line:

    grep "foobar" * | cut -b 1-400
    

    This might leave the match out, but it's simple to use and enough for most cases. The other option is:

    grep -rEo ".{0,10}wantedText.{0,10}" *
    

GTK

  • New: How to change themes.

    GTK is a free and open-source cross-platform widget toolkit for creating graphical user interfaces.

    To change the theme, either use lxapparence or manually edit ~/.config/gtk-3.0/settings.ini. You will be forced to do the second option if the theme is for gtk-3 only.

i3 window manager

  • New: Get pressed key name.

    Some key names are hard to guess, such as XF86AudioRaiseVolume, and you need their name to use them in bindings. You can use xev for that.

LibreOffice

  • New: LibreOffice Calc IF().

    Syntax: IF(Test, Then Value, Otherwise Value).

    Example:

    =IF(A2>500,"High","Low")
    

NeoMutt

  • New: Mailboxes commands.

    • c?<Tab>: (on top of a mailbox) Shows all subdirectories and allows to open them.

neovim

  • New: Edit remote files with SSH.

    Just run:

    nvim scp://user@host//tmp/file
    

    Notice the extra /. You can also specify just a directory to browse it interactively.

  • New: Cherry pick lines to commit.

    tpope/vim-fugitive: fugitive.vim: A Git wrapper so awesome, it should be illegal

    1. Open the git summary with :Git (or :G).
    2. Expand the file which contains the lines you want to stage with > (or = to toggle). This will only show the changed chunks plus some extra lines of context above and below the changed lines.
    3. V to start visual mode and select the lines you want to stage with hjkl.
    4. s to stage the visual selection (or - to toggle)
    5. Repeat 2-4 as needed
    6. cc to commit
  • New: Search for visual selection.

    vnoremap // y/\V<C-R>=escape(@",'/\')<CR><CR>
    
    To use the mapping, visually select the characters that are wanted in the search, then type // to search for the next occurrence of the selected text.

  • New: Marks.

    A mark allows you to record your current position so you can return to it later.

    Usage:

    • :marks: show existing marks.
    • ma: set mark a in current position of current file, accessible only from the current file.
    • mA: set mark A in current position of current file, accessible from anywhere.
    • 'a: Go to mark a.
    • ]': jump to next line with a lowercase mark.
  • New: Sed replace with newline.

  • New: Without RegEx.

    Use :sno instead of :s to disable magic.

OpenLDAP

  • New: Show special entries and attributes in search.

    ldapsearch [...] +
    

PostgreSQL

  • New: Stop remote connections.

    Some operations, like dropping a database, require that the database has no connections. To stop all remote connections and prevent them from connecting again, do:

    ALTER DATABASE somedatabase ALLOW_CONNECTIONS = OFF;
    
    SELECT pg_terminate_backend(pid)
    FROM pg_stat_activity
    WHERE datname = 'somedatabase';
    

    But if you are using PostgreSQL 13 or above, for dropping a table you can directly do:

    DROP DATABASE db_name WITH (FORCE);
    
  • New: List databases.

    \l
    

sed

  • New: Use matched pattern.

    echo "foobarbaz" | sed 's/^foo\(.*\)baz$/\1/'
    

    Returns bar.

Programming

basics

  • New: Pyhton AIOHTTP.

    Basic example:

    import aiohttp
    import asyncio
    
    async def main():
        async with aiohttp.ClientSession() as session:
            async with session.get('http://httpbin.org/get') as resp:
                print(resp.status)
                print(await resp.text())
    
    asyncio.run(main)
    

    Other methods:

    ``python session.put('http://httpbin.org/put', data=b'data') session.delete('http://httpbin.org/delete') session.head('http://httpbin.org/get') session.options('http://httpbin.org/get') session.patch('http://httpbin.org/patch', data=b'data')

  • New: Headers.

    headers = {
        'Accepts': 'application/json',
        'X-API_KEY': 'secret',
    }
    
    async with aiohttp.ClientSession(headers=headers) as session:
        ...
    
  • New: Types in the Closure Type System.

JSDoc

  • New: JSDoc @example.

    `javascript /** * Solves equations of the form a * x = b * @example * // returns 2 * globalNS.method1(5, 10); * @example * // returns 3 * globalNS.method(5, 15); * @returns {Number} Returns the value of x for the equation. */ globalNS.method1 = function (a, b) { return b / a; };

  • New: JSDoc @type.

    Reference: Use JSDoc: @type.

Basics

  • New: Enumerate().

    To iterate over a list keys and values use enumerate(). Example:

    some_list = ['a', 'b', 'c']
    for index, value in enumerate(some_list):
      ...
    
  • New: Enum.

    Example:

    from enum import Enum
    
    class Color(Enum):
      RED = 1
      GREEN = 2
      BLUE = 3
    
  • New: Enum examples.

    >>> Color(1)
    <Color.RED: 1>
    >>> Color(3)
    <Color.BLUE: 3>
    
    >>> Color['RED']
    <Color.RED: 1>
    >>> Color['GREEN']
    <Color.GREEN: 2>
    
    >>> member = Color.RED
    >>> member.name
    'RED'
    >>> member.value
    1
    
  • New: Datetime nstance methods.

    • isoformat(): ISO 8601 formatted string.
  • New: Check syntax without running.

    Try to compile it:

    python -m py_compile script.py
    

Logging

  • New: Python logging.

    Basic configuration:

    import logging
    
    logging.basicConfig(
        format='%(asctime)s %(levelname)s %(message)s',
        level=logging.INFO,
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    logging.info('Just a random string...')
    

pip

  • New: Install.

    Options:

    • --ignore-installed: Ignore the installed packages, overwriting them.

pydantic

  • New: Pydantic types.

    • pydantic.HttpUrl
    • pydantic.color.Color
  • New: Exporting.

    Options:

    • model.json(exclude_none=True)
    • model.dict(exclude_none=True)

Typing

  • New: Awaitable type.

    • Awaitable: Promise/Future.

Other

  • Reorganization: Renamed duplicated filenames.