Preparation Materials ‐ week 1 - LCAS/RBT1001 GitHub Wiki

Index:

  1. Bash Commands Refresher
  2. Python Programming Refresher

Bash Commands Refresher

Command History

!!            # Run the last command

touch foo.sh
chmod +x !$   # !$ is the last argument of the last command i.e. foo.sh

Navigating Directories

pwd                       # Print current directory path
ls                        # List directories
ls -a|--all               # List directories including hidden
ls -l                     # List directories in long form
ls -l -h|--human-readable # List directories in long form with human readable sizes
ls -t                     # List directories by modification time, newest first
stat foo.txt              # List size, created and modified timestamps for a file
stat foo                  # List size, created and modified timestamps for a directory
tree                      # List directory and file tree
tree -a                   # List directory and file tree including hidden
tree -d                   # List directory tree
cd foo                    # Go to foo sub-directory
cd                        # Go to home directory
cd ~                      # Go to home directory
cd -                      # Go to last directory

Creating Directories

mkdir foo                        # Create a directory
mkdir foo bar                    # Create multiple directories

Moving Directories

cp -r foo bar                               # Copy directory
mv foo bar                                              # Move directory

Deleting Directories

rmdir foo                        # Delete empty directory
rm -r foo            # Delete directory including contents

Creating Files

touch foo.txt          # Create file or update existing files modified timestamp
touch foo.txt bar.txt  # Create multiple files

Moving Files

cp foo.txt bar.txt                                # Copy file
mv foo.txt bar.txt                                # Move file

Deleting Files

rm foo.txt            # Delete file
rm -f foo.txt    # Delete file, ignore nonexistent files and never prompt

Reading Files

cat foo.txt            # Print all contents
less foo.txt           # Print some contents at a time (g - go to top of file, SHIFT+g, go to bottom of file, /foo to search for 'foo')
head foo.txt           # Print top 10 lines of file
tail foo.txt           # Print bottom 10 lines of file
open foo.txt           # Open file in the default editor
wc foo.txt             # List number of lines words and characters in the file

Packages

apt update                   # Refreshes repository index
apt search wget              # Search for a package
apt show wget                # List information about the wget package
apt list --all-versions wget # List all versions of the package
apt install wget             # Install the latest version of the wget package
apt install wget=1.2.3       # Install a specific version of the wget package
apt remove wget              # Removes the wget package
apt upgrade                  # Upgrades all upgradable packages

Shutdown and Reboot

shutdown                     # Shutdown in 1 minute

shutdown -c                  # Cancel a shutdown or reboot

reboot                       # Reboot now
reboot -f                    # Force a reboot

Identifying Processes

top                    # List all processes interactively
htop                   # List all processes interactively
ps all                 # List all processes
pidof foo              # Return the PID of all foo processes

CTRL+Z                 # Suspend a process running in the foreground
bg                     # Resume a suspended process and run in the background
fg                     # Bring the last background process to the foreground

Killing Processes

CTRL+C                 # Kill a process running in the foreground
kill PID               # Shut down process by PID gracefully. Sends TERM signal.
kill -9 PID            # Force shut down of process by PID. Sends SIGKILL signal.

Python Programming Refresher

Main

if __name__ == '__main__':      # Runs main() if file wasn't imported.
    main()

List

<list> = <list>[<slice>]        # Or: <list>[from_inclusive : to_exclusive : ±step]
<list>.append(<el>)             # Or: <list> += [<el>]
<list>.extend(<collection>)     # Or: <list> += <collection>
<list>.sort()                   # Sorts in ascending order.
<list>.reverse()                # Reverses the list in-place.
<list> = sorted(<collection>)   # Returns a new sorted list.
<iter> = reversed(<list>)       # Returns reversed iterator.
sum_of_elements  = sum(<collection>)
elementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both   = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list     = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, el: out * el, <collection>)
list_of_chars    = list(<str>)
<list>.insert(<int>, <el>)      # Inserts item at index and moves the rest to the right.
<el>  = <list>.pop([<int>])     # Removes and returns item at index or from the end.
<int> = <list>.count(<el>)      # Returns number of occurrences. Also works on strings.
<int> = <list>.index(<el>)      # Returns index of the first occurrence or raises ValueError.
<list>.remove(<el>)             # Removes first occurrence of the item or raises ValueError.
<list>.clear()                  # Removes all items. Also works on dictionary and set.

Dictionary

<view> = <dict>.keys()                          # Coll. of keys that reflects changes.
<view> = <dict>.values()                        # Coll. of values that reflects changes.
<view> = <dict>.items()                         # Coll. of key-value tuples that reflects chgs.
value  = <dict>.get(key, default=None)          # Returns default if key is missing.
value  = <dict>.setdefault(key, default=None)   # Returns and writes default if key is missing.
<dict> = collections.defaultdict(<type>)        # Returns a dict with default value `<type>()`.
<dict> = collections.defaultdict(lambda: 1)     # Returns a dict with default value 1.
<dict> = dict(<collection>)                     # Creates a dict from coll. of key-value pairs.
<dict> = dict(zip(keys, values))                # Creates a dict from two collections.
<dict> = dict.fromkeys(keys [, value])          # Creates a dict from collection of keys.
<dict>.update(<dict>)                           # Adds items. Replaces ones with matching keys.
value = <dict>.pop(key)                         # Removes item or raises KeyError if missing.
{k for k, v in <dict>.items() if v == value}    # Returns set of keys that point to the value.
{k: v for k, v in <dict>.items() if k in keys}  # Returns a dictionary, filtered by keys.

Tuple

Tuple is an immutable and hashable list.

<tuple> = ()                               # Empty tuple.
<tuple> = (<el>,)                          # Or: <el>,
<tuple> = (<el_1>, <el_2> [, ...])         # Or: <el_1>, <el_2> [, ...]

Range

Immutable and hashable sequence of integers.

<range> = range(stop)                      # range(to_exclusive)
<range> = range(start, stop)               # range(from_inclusive, to_exclusive)
<range> = range(start, stop, ±step)        # range(from_inclusive, to_exclusive, ±step_size)
>>> [i for i in range(3)]
[0, 1, 2]

Enumerate

for i, el in enumerate(<collection> [, i_start]):
    ...

Type

  • Everything is an object.
  • Every object has a type.
  • Type and class are synonymous.
<type> = type(<el>)                          # Or: <el>.__class__
<bool> = isinstance(<el>, <type>)            # Or: issubclass(type(<el>), <type>)
>>> type('a'), 'a'.__class__, str
(<class 'str'>, <class 'str'>, <class 'str'>)

String

Immutable sequence of characters.

<str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
<str>  = <str>.strip('<chars>')              # Strips passed characters. Also lstrip/rstrip().
<list> = <str>.split()                       # Splits on one or more whitespace characters.
<list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.splitlines(keepends=False)    # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
<str>  = <str>.join(<coll_of_strings>)       # Joins elements using string as a separator.
<bool> = <sub_str> in <str>                  # Checks if string contains the substring.
<bool> = <str>.startswith(<sub_str>)         # Pass tuple of strings for multiple options.
<int>  = <str>.find(<sub_str>)               # Returns start index of the first match or -1.
<int>  = <str>.index(<sub_str>)              # Same, but raises ValueError if missing.

Numbers

<int>      = int(<float/str/bool>)                # Or: math.floor(<float>)
<float>    = float(<int/str/bool>)                # Or: <int/float>e±<int>
<complex>  = complex(real=0, imag=0)              # Or: <int/float> ± <int/float>j
<Fraction> = fractions.Fraction(0, 1)             # Or: Fraction(numerator=0, denominator=1)
<Decimal>  = decimal.Decimal(<str/int>)           # Or: Decimal((sign, digits, exponent))
  • 'int(<str>)' and 'float(<str>)' raise ValueError on malformed strings.
  • Decimal numbers are stored exactly, unlike most floats where '1.1 + 2.2 != 3.3'.
  • Floats can be compared with: 'math.isclose(<float>, <float>)'.
  • Precision of decimal operations is set with: 'decimal.getcontext().prec = <int>'.

Basic Functions

<num> = pow(<num>, <num>)                         # Or: <num> ** <num>
<num> = abs(<num>)                                # <float> = abs(<complex>)
<num> = round(<num> [, ±ndigits])                 # `round(126, -1) == 130`

Math

from math import e, pi, inf, nan, isinf, isnan    # `<el> == nan` is always False.
from math import sin, cos, tan, asin, acos, atan  # Also: degrees, radians.
from math import log, log10, log2                 # Log can accept base as second arg.

Random

from random import random, randint, choice        # Also: shuffle, gauss, triangular, seed.
<float> = random()                                # A float inside [0, 1).
<int>   = randint(from_inc, to_inc)               # An int inside [from_inc, to_inc].
<el>    = choice(<sequence>)                      # Keeps the sequence intact.

Class

class <name>:
    def __init__(self, a):
        self.a = a
    def __repr__(self):
        class_name = self.__class__.__name__
        return f'{class_name}({self.a!r})'
    def __str__(self):
        return str(self.a)

    @classmethod
    def get_class_name(cls):
        return cls.__name__
  • Return value of repr() should be unambiguous and of str() readable.
  • If only repr() is defined, it will also be used for str().
  • Methods decorated with '@staticmethod' do not receive 'self' nor 'cls' as their first arg.

Expressions that call the str() method:

print(<el>)
f'{<el>}'
logging.warning(<el>)
csv.writer(<file>).writerow([<el>])
raise Exception(<el>)

Expressions that call the repr() method:

print/str/repr([<el>])
print/str/repr({<el>: <el>})
f'{<el>!r}'
Z = dataclasses.make_dataclass('Z', ['a']); print/str/repr(Z(<el>))
>>> <el>

Constructor Overloading

class <name>:
    def __init__(self, a=None):
        self.a = a

Inheritance

class Person:
    def __init__(self, name):
        self.name = name

class Employee(Person):
    def __init__(self, name, staff_num):
        super().__init__(name)
        self.staff_num = staff_num

Multiple Inheritance

class A: pass
class B: pass
class C(A, B): pass
⚠️ **GitHub.com Fallback** ⚠️