20 September 2025

Python - List, set and dictionary

A list is an ordered collection of items. The items can be approached with their index.
a = [3, 0, 5]
a:list[int] = [3, 0, 5]
A set is an unordered collection of unique items. You can assign the same item as many times as you want without error. It will appear just once in the set.
a = {3, 0, 5}
a:set[int] = {3, 0, 5}
A dictionary is an unordered collection of key-value pairs.
a = {3: 'E'}
a:dict[int, str] = {3: 'E', 0: 'G', 5: 'S'}
The :list[] etc. are just datatype suggestions for the IDE. They don't mean anything to the actual program, and you can still assign whatever you want to the variable.

16 August 2025

Python - Execute a query with pyodbc

To work with a database via ODBC, first install the PyOdbc package and import it. The following simple query shows how to execute a select query and return data:
import pyodbc

def get_user(username) -> int:   
    with pyodbc.connect("Server=(LocalDB)\Test; Integrated Security=true; Driver={ODBC Driver 17 for SQL Server}") as conn:
        with conn.execute("SELECT id FROM Users WHERE username=?", username) as cursor:
            rows = cursor.fetchall()
    
    if len(rows) <= 0:
        return
    
    return rows[0].id

print(f"user ID: {get_user("EGS")}")

24 June 2025

.NET - Read/write a binary file line by line

To read a text file, you can use a StreamReader, but to read a binary file, you need a BinaryReader.This is how you use it:

if (File.Exists(FILENAME))
{
    using (var stream = new FileStream(FILENAME, FileMode.Open))
    using (var reader = new BinaryReader(stream))
    {
        if (stream.Length <= 0) return; //The file is empty.
        int i = reader.ReadInt32();
        string s = reader.ReadString();
    }
}

Writing is similar:

using (var stream = new FileStream(SaveFilePath, FileMode.Create))
using (var writer = new BinaryWriter(stream))
{
    writer.Write(305);
    writer.Write("EGS");
}

The file will be automatically created if it doesn't exist yet.