Skip to content

Instantly share code, notes, and snippets.

@nessalc
Last active July 28, 2022 12:55
Show Gist options
  • Save nessalc/b39044b583fc2474a69a3170d56cef2e to your computer and use it in GitHub Desktop.
Save nessalc/b39044b583fc2474a69a3170d56cef2e to your computer and use it in GitHub Desktop.
Code Snippets: How do I do that again?

Python

Inverse of zip()

lst1, lst2 = zip(*zipped_list)

Unix Timestamp from datetime object

dt.timestamp()

Parse date/time string

from dateutil.parser import parse
d = parse(datetime_string)

Assign "the rest" to another variable

v, *rest = [0, 1, 2, 3, 4, 5, 6]

# result:
# v = 0
# rest = [1, 2, 3, 4, 5, 6]

Unpack to Arguments

image_size = (800, 600)
resize_image(filename, *image_size)
# this is like calling `resize_image(filename, 800, 600)`

Flatten list

from collections.abc import Iterable

def flatten(l):
    for el in l:
        if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el

Pretty Printing

Signature: pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)

import pprint
pprint.pprint(object)
pp=pprint.PrettyPrinter(sort_dicts=False).pprint
pp(object)

Parameter slots

Keyword Only

def compare(a, b, *, key=None):
    ...

key in this function must be specified with a keyword, and cannot be supplied positionally. I.e., compare(a,b,None) will raise an error.

Positional Only

def greet(name, /, greeting="Hello"):
    return f'{greeting}, {name}'

name in this function is positional only, and cannot be specified by name. I.e., greet(name='James', greeting='Bonjour') will raise an error.

Both

def headline(text, /, border="~", *, width=50):
    return f' {text} '.center(width, border)

text is positional only, border is a "regular" argurment (positional or named), and width is keyword only.

Type Hinting

# simple example
def greeting(name: str) -> str:
    return f'Hello {name}'

# a type alias: `Vector` is interchangable with `list[float]`
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# Complex signatures
ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

# Distinct (custom) types
from typing import NewType

UserId = NewType('UserId', int)
def get_user_name(user_id: UserId) -> str:
    ...

# The above will be able to use UserId where int is expected, but prevents
# accidentally messing with UserIds in an invalid way, e.g.

UserId(25) + UserId(97) # will throw an error

Other valid (special) types: NoReturn (for functions that return nothing); Any (any type); Union[int, str] (means either int or str); Optional[int] is equivalent to Union[int, None]; Callable[[int], str] is a function that takes an int as a parameter and returns a str; Literal['r', 'rb', 'w', 'wb'] is one of the literal values included

@typing.overload allows describing functions supporting multiple combinations of argument types. Must be followed by a non-@overload decorated definition, as this last one will be used by the actual program. These decorated functions are used by the type checker.

Ternary

Like

a ? b : c
b if a else c

(where a, b, and c are all valid one-line statements in the associated language)

f-strings

a, b = 100, 'Hello'
c = {'test1': 42, 'test2': 'parrot'}
d = datetime.datetime.now()
print(f'{a} {b}')
# results in "100 Hello"
print(f'{a=} {b=}')
# results in "a=100 b='Hello'"
print(f'{b:<10} {a:04x}')
# results in "Hello      0064"
print(f'{c}')
# results in "{'test1': 42, 'test2': 'parrot'}"
print(f'{c["test1"]}')
# results in "42"
print(f'{d}')
# results in "2019-12-09 12:59:25.268219"
print(f'{d!r}') # output is __repr__ instead of __str__
# results in "datetime.datetime(2019, 12, 9, 12, 59, 25, 268219)"
print(f'{d:%d/%m/%Y}') # if custom format method is defined, will use that instead
# results in "09/12/2019"

sort/min/max dict by value

import operator

# returns a list of (key,value) tuples
sorted(dictionary.items(), key = operator.itemgetter(1))
#reutnrs a (key,value) tuple
max(dictionary.items(), key = operator.itemgetter(1))
#reutnrs a (key,value) tuple
min(dictionary.items(), key = operator.itemgetter(1))

__slots__

Slots greatly improve memory usage and speed of accessing attributes, though their use can cause issues with inheritance trees if care is not exercised.

class Thing:
  __slots__ = 'foo', 'bar'

obj = Thing()
obj.foo = 5 # assigns 5 to obj.foo in obj.__slots__
obj.foo # returns 5
obj.bar # raises "AttributeError: bar"
obj.x = 10 #raises "AttributeError: 'Thing' object has no attribute 'x'"

dataclasses

Dataclasses automatically generate __init__, __repr__, and can also create __lt__, __le__, __eq__, __ge__, __gt__, functions as well, which compare the class as if they are tuples of their fields in the defined order.

from dataclasses import dataclass, field

@dataclass
class Thing:
  x: int
  y: str
  z: complex = field(repr = False, default = 42)
  c: float = 0
  # init would become
  # def __init__(self, x: int, y: str, z: complex, c: float = 0):
  #   ...
  # repr would become
  # def __repr__(self):
  #   return <Thing(x=*value_of_x*, y=*value_of_y*, c=*value_of_c*)>
  # Note that z is not shown.

See here for additional details.

VBA

Open Excel file and disable macros

Dim secAutomation As MsoAutomationSecurity
secAutomation = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityForceDisable
With Workbooks.Open(basepath & fileName, UpdateLinks:=0, ReadOnly:=False, IgnoreReadOnlyRecommended:=True, AddToMru:=False)
  'do stuff
  .Close SaveChanges:=True 'yes, you have to close even when using a With statement
End With
Application.AutomationSecurity = secAutomation

Time a piece of code

Dim startTime as Double, elapsedTime as Double
startTime = Timer
'do stuff
elapsedTime = Round(Timer - startTime, 2)

Excel

  • A space  is the "intersection" operator for ranges of cells.
  • A comma , is the "union" operator for ranges of cells.
  • A plus + is the "or" operator for conditions in array formulas.
  • An asterisk * is the "and" operator for conditions in array formulas.

PowerShell

Shortcuts

Command Shortcut
Add-Content ac
Get-Content gc
cat
type
Clear-Host clear
cls
Set-Location cd
chdir
sl
Copy-Item cp
copy
cpi
Invoke-WebRequest curl
iwr
wget
Remove-Item del
erase
rm
rd
ri
rmdir
Get-ChildItem dir
ls
gci
Get-Location pwd
gl
Get-Item gi
Get-Member gm
Get-History ghy
h
history
Invoke-History ihy
r
Get-ItemProperty gp
Stop-Process kill
Measure-Object measure

Comments

# This is a single-line comment
<#
This is a
block
or
multiline comment
#>

Tail

# show last three lines
Get-Content filename.log -Tail 3

# tail follow
Get-Content filename.log -Tail 1 -Wait

Ranges

# print numbers 16 through 24
16..24

Run history commands

# Run most recent command
Invoke-History

# Run command with a specific ID
Invoke-History -Id 132

# Run command with the most recent starting pattern
# (pattern matching is case-insensitive, but must be at beginning of line)
Invoke-History -Id get-pr

# Run a sequence of commands
16..24 | ForEach {Invoke-History -Id $_}

# Run the seven commands ending with Id 255
Get-History -Id 255 -Count 7 | ForEach {Invoke-History -Id $_.Id}

C#

Array size

array.Length; //returns number of elements in an array
array.Rank; //returns number of dimensions in an array
array.GetLength(n); //returns number of elements in dimension n

Interpolation String

string name = "James";
Console.WriteLine($"Hello {name}!")
// prints pi with default formatting
Console.WriteLine($"Pi is approximately equal to {Math.PI})
// prints pi with 3 decimal places, right-aligned in a field 20 characters wide
Console.WriteLine($"Pi is approximately equal to {Math.PI,20:F3}) 

Verbatim String

string filename = @"C:\Users\James\logfile.log";

Interpolated/Verbatim String

From C# 8.0, the above can be combined in either order. Earlier versions must be combined $@"..."

Console.WriteLine($@"He asked, ""Is your name {name}?"", but didn't wait for a reply :-{{");

Excel-Dna / C#

Excel UDFs created using ExcelDna (install ExcelDna.AddIn, ExcelDna.Integration with NuGet after creating a library project in Visual Studio). Arguments are one of the following types:

  • double Any number
  • string Any text
  • bool TRUE or FALSE
  • ExcelError Any Excel Error
    • ExcelError.ExcelErrorDiv0
    • ExcelError.ExcelErrorGettingData
    • ExcelError.ExcelErrorNA
    • ExcelError.ExcelErrorName
    • ExcelError.ExcelErrorNull
    • ExcelError.ExcelErrorNum
    • ExcelError.ExcelErrorRef
    • ExcelError.ExcelErrorValue
  • ExcelMissing An argument was not provided
  • object[,] Any array (there are no one-dimensional arrays; I don't know how or if three-dimensional arrays are handled)
  • ExcelReference must declare argument attribute AllowReference=True

Sample Function

using ExcelDna.Integration;
using System.Text.RegularExpressions;
using System;

public static class MyFunctions
{
    [ExcelFunction(Description = "ARINC BNR Decoder", Category = "ARINC Helper Functions")]
    public static object ArincBnrDecode(
        [ExcelArgument(Name = "ARINC Data", Description = "The data bits of an ARINC word or field")] object arinc_data,
        [ExcelArgument(Name = "LSB", Description = "The value of the least-significant bit of the field (default 1)")] object lsb,
        [ExcelArgument(Name = "Signed", Description = "Whether or not the value is signed (default TRUE)")] object signed,
        [ExcelArgument(Name = "Bits", Description = "Number of bits in the field (default 19)")] object bits)
    {
        Regex binary = new Regex("^[01]{1,64}$", RegexOptions.Compiled);
        Regex octal = new Regex("^[01]?[0-7]{1,21}$", RegexOptions.Compiled);
        Regex hex = new Regex("^[0-9A-Fa-f]{1,16}$", RegexOptions.Compiled);
        long raw_val;
        if (lsb is ExcelMissing)
            lsb = 1.0;
        else
            lsb = (double)lsb;
        if (signed is ExcelMissing)
            signed = true;
        else
            signed = (bool)signed;
        if (bits is ExcelMissing)
            bits = 19;
        else if (bits is double && ((double)bits < 1))
            return ExcelError.ExcelErrorValue;
        else if (bits is double)
            bits = Convert.ToInt32((double)bits);
        if (arinc_data is string)
        {
            if (binary.IsMatch((string)arinc_data))
                raw_val = Convert.ToInt64((string)arinc_data, 2);
            else if (octal.IsMatch((string)arinc_data))
                raw_val = Convert.ToInt64((string)arinc_data, 8);
            else if (hex.IsMatch((string)arinc_data))
                raw_val = Convert.ToInt64((string)arinc_data, 16);
            else
                return ExcelError.ExcelErrorValue;
        }
        else if (arinc_data is double)
            raw_val = Convert.ToInt64(arinc_data);
        else
            return ExcelError.ExcelErrorValue;
        if ((bool)signed && raw_val > (1 << ((int)bits - 1)))
            raw_val -= 1 << ((int)bits);
        return raw_val * (double)lsb;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment