From 50ecff0115aec6cca176add179bb4343233411c3 Mon Sep 17 00:00:00 2001 From: eduardocerqueira <eduardomcerqueira@gmail.com> Date: Wed, 4 Dec 2024 17:13:54 +0000 Subject: [PATCH] 2024-12-04 17:13:54.644919 new snippets --- seeker/report.txt | 35 + .../AdditionalPropertiesExtractor.java | 52 ++ seeker/snippet/Main.java | 58 ++ seeker/snippet/SecurityEvent.java | 121 +++ seeker/snippet/amcrest.py | 115 --- seeker/snippet/build.sh | 115 --- seeker/snippet/class.py | 82 ++ seeker/snippet/code.java | 40 + seeker/snippet/create_flux_wireguard.sh | 71 ++ seeker/snippet/decorator_example.py | 15 + seeker/snippet/diamond.py | 37 - seeker/snippet/digitalioe9.py | 140 ---- seeker/snippet/headline.zsh | 715 ++++++++++++++++++ seeker/snippet/main.py | 17 + seeker/snippet/python_logging.py | 27 + seeker/snippet/quickstart.py | 28 - seeker/snippet/seeds.py | 82 ++ seeker/snippet/server_compare.py | 187 ----- seeker/snippet/test.java | 98 +++ seeker/snippet/tmux-sessionizer.sh | 53 -- seeker/snippet/tmux.conf | 49 ++ 21 files changed, 1462 insertions(+), 675 deletions(-) create mode 100644 seeker/snippet/AdditionalPropertiesExtractor.java create mode 100644 seeker/snippet/Main.java create mode 100644 seeker/snippet/SecurityEvent.java delete mode 100644 seeker/snippet/amcrest.py delete mode 100644 seeker/snippet/build.sh create mode 100644 seeker/snippet/class.py create mode 100644 seeker/snippet/code.java create mode 100644 seeker/snippet/create_flux_wireguard.sh create mode 100644 seeker/snippet/decorator_example.py delete mode 100644 seeker/snippet/diamond.py delete mode 100644 seeker/snippet/digitalioe9.py create mode 100644 seeker/snippet/headline.zsh create mode 100644 seeker/snippet/main.py create mode 100644 seeker/snippet/python_logging.py delete mode 100644 seeker/snippet/quickstart.py create mode 100644 seeker/snippet/seeds.py delete mode 100644 seeker/snippet/server_compare.py create mode 100644 seeker/snippet/test.java delete mode 100644 seeker/snippet/tmux-sessionizer.sh create mode 100644 seeker/snippet/tmux.conf diff --git a/seeker/report.txt b/seeker/report.txt index 74f00451..bb171027 100644 --- a/seeker/report.txt +++ b/seeker/report.txt @@ -1,3 +1,38 @@ +-------------------------------------------------------------------------------- + 2024-12-04 17:13:54.644919 +-------------------------------------------------------------------------------- + On branch main +Your branch is up to date with 'origin/main'. + +Changes not staged for commit: + (use "git add/rm <file>..." to update what will be committed) + (use "git restore <file>..." to discard changes in working directory) + deleted: snippet/amcrest.py + deleted: snippet/build.sh + deleted: snippet/diamond.py + deleted: snippet/digitalioe9.py + deleted: snippet/quickstart.py + deleted: snippet/server_compare.py + deleted: snippet/tmux-sessionizer.sh + +Untracked files: + (use "git add <file>..." to include in what will be committed) + snippet/AdditionalPropertiesExtractor.java + snippet/Main.java + snippet/SecurityEvent.java + snippet/class.py + snippet/code.java + snippet/create_flux_wireguard.sh + snippet/decorator_example.py + snippet/headline.zsh + snippet/main.py + snippet/python_logging.py + snippet/seeds.py + snippet/test.java + snippet/tmux.conf + +no changes added to commit (use "git add" and/or "git commit -a") + -------------------------------------------------------------------------------- 2024-12-03 17:14:56.419452 -------------------------------------------------------------------------------- diff --git a/seeker/snippet/AdditionalPropertiesExtractor.java b/seeker/snippet/AdditionalPropertiesExtractor.java new file mode 100644 index 00000000..d81ac04b --- /dev/null +++ b/seeker/snippet/AdditionalPropertiesExtractor.java @@ -0,0 +1,52 @@ +//date: 2024-12-04T16:51:06Z +//url: https://api.github.com/gists/cf0f9afbcf359df65846a760da64d230 +//owner: https://api.github.com/users/avishaybp81 + +package com.example.additionalproperties; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + + +public class AdditionalPropertiesExtractor { + + public static Map<String, String> extractAdditionalProperties(Object obj) { + Map<String, String> allProperties = new HashMap<>(); + processObject(obj, allProperties, ""); + return allProperties; + } + + private static void processObject(Object obj, Map<String, String> allProperties, String prefix) { + if (obj == null) { + return; + } + + if (obj instanceof Map) { + for (Map.Entry<String, Object> entry : ((Map<String, Object>) obj).entrySet()) { + allProperties.put(prefix + "." + entry.getKey(), entry.getValue().toString()); + } + + } else { + for (Field field : obj.getClass().getDeclaredFields()) { + if (field.getType().getPackage().equals(SecurityEvent.class.getPackage()) || field.getType().equals(Map.class)) { + try { + field.setAccessible(true); + } catch (Exception ignored) { + continue; + } + try { + Object fieldValue = field.get(obj); + System.out.println("--->: " + fieldValue.getClass().getSimpleName() + " : " + fieldValue); + processObject(fieldValue, allProperties, obj.getClass().getSimpleName()); + } catch (IllegalAccessException e) { + // Handle exception, e.g., log the error + e.printStackTrace(); + } + + } + + } + } + } +} \ No newline at end of file diff --git a/seeker/snippet/Main.java b/seeker/snippet/Main.java new file mode 100644 index 00000000..fa31e16f --- /dev/null +++ b/seeker/snippet/Main.java @@ -0,0 +1,58 @@ +//date: 2024-12-04T16:51:06Z +//url: https://api.github.com/gists/cf0f9afbcf359df65846a760da64d230 +//owner: https://api.github.com/users/avishaybp81 + +package com.example.additionalproperties; + +import com.example.additionalproperties.SecurityEvent; +import com.example.additionalproperties.AdditionalPropertiesExtractor; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + public static void main(String[] args) { + SecurityEvent event = new SecurityEvent(); + event.setEventId("event123"); + event.setEventType("security_event"); + + // Set top-level additional properties + Map<String, String> topLevelProps = new HashMap<>(); + topLevelProps.put("prop1", "value1"); + topLevelProps.put("prop2", "value2"); + event.setAdditionalProperties(topLevelProps); + + // Create nested event + SecurityEvent.NestedSecurityEvent nestedEvent = new SecurityEvent.NestedSecurityEvent(); + nestedEvent.setNestedId("nested123"); + nestedEvent.setNestedType("nested_event"); + + // Set nested additional properties + Map<String, String> nestedProps = new HashMap<>(); + nestedProps.put("nestedProp1", "nestedValue1"); + nestedProps.put("nestedProp2", "nestedValue2"); + nestedEvent.setAdditionalProperties(nestedProps); + + // Create deeply nested event + SecurityEvent.NestedSecurityEvent.DeeplyNestedSecurityEvent deeplyNestedEvent = new SecurityEvent.NestedSecurityEvent.DeeplyNestedSecurityEvent(); + deeplyNestedEvent.setDeeplyNestedId("deeplyNested123"); + deeplyNestedEvent.setDeeplyNestedType("deeplyNested_event"); + + // Set deeply nested additional properties + Map<String, String> deeplyNestedProps = new HashMap<>(); + deeplyNestedProps.put("deeplyNestedProp1", "deeplyNestedValue1"); + deeplyNestedProps.put("deeplyNestedProp2", "deeplyNestedValue2"); + deeplyNestedEvent.setAdditionalProperties(deeplyNestedProps); + + nestedEvent.setDeeplyNestedEvent(deeplyNestedEvent); + event.setNestedEvent(nestedEvent); + + // Extract additional properties + Map<String, String> extractedProps = AdditionalPropertiesExtractor.extractAdditionalProperties(event); + + // Print extracted properties + + System.out.println("Result below:"); + extractedProps.forEach((key, value) -> System.out.println("\t" + key + ": " + value)); + } +} \ No newline at end of file diff --git a/seeker/snippet/SecurityEvent.java b/seeker/snippet/SecurityEvent.java new file mode 100644 index 00000000..eb7e4e72 --- /dev/null +++ b/seeker/snippet/SecurityEvent.java @@ -0,0 +1,121 @@ +//date: 2024-12-04T16:51:06Z +//url: https://api.github.com/gists/cf0f9afbcf359df65846a760da64d230 +//owner: https://api.github.com/users/avishaybp81 + +package com.example.additionalproperties; + +import java.util.Map; + +public class SecurityEvent { + private String eventId; + private String eventType; + private Map<String, String> additionalProperties; + private NestedSecurityEvent nestedEvent; + + // Getters and Setters + public String getEventId() { + return eventId; + } + + public void setEventId(String eventId) { + this.eventId = eventId; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public Map<String, String> getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(Map<String, String> additionalProperties) { + this.additionalProperties = additionalProperties; + } + + public NestedSecurityEvent getNestedEvent() { + return nestedEvent; + } + + public void setNestedEvent(NestedSecurityEvent nestedEvent) { + this.nestedEvent = nestedEvent; + } + + // NestedSecurityEvent Class + public static class NestedSecurityEvent { + private String nestedId; + private String nestedType; + private Map<String, String> additionalProperties; + private DeeplyNestedSecurityEvent deeplyNestedEvent; + + // Getters and Setters + public String getNestedId() { + return nestedId; + } + + public void setNestedId(String nestedId) { + this.nestedId = nestedId; + } + + public String getNestedType() { + return nestedType; + } + + public void setNestedType(String nestedType) { + this.nestedType = nestedType; + } + + public Map<String, String> getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(Map<String, String> additionalProperties) { + this.additionalProperties = additionalProperties; + } + + public DeeplyNestedSecurityEvent getDeeplyNestedEvent() { + return deeplyNestedEvent; + } + + public void setDeeplyNestedEvent(DeeplyNestedSecurityEvent deeplyNestedEvent) { + this.deeplyNestedEvent = deeplyNestedEvent; + } + + // DeeplyNestedSecurityEvent Class + public static class DeeplyNestedSecurityEvent { + private String deeplyNestedId; + private String deeplyNestedType; + private Map<String, String> additionalProperties; + + // Getters and Setters + public String getDeeplyNestedId() { + return deeplyNestedId; + } + + public void setDeeplyNestedId(String deeplyNestedId) { + this.deeplyNestedId = deeplyNestedId; + } + + public String getDeeplyNestedType() { + return deeplyNestedType; + } + + public void setDeeplyNestedType(String deeplyNestedType) { + this.deeplyNestedType = deeplyNestedType; + } + + public Map<String, String> getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(Map<String, String> additionalProperties) { + this.additionalProperties = additionalProperties; + } + } + } +} + diff --git a/seeker/snippet/amcrest.py b/seeker/snippet/amcrest.py deleted file mode 100644 index a596549e..00000000 --- a/seeker/snippet/amcrest.py +++ /dev/null @@ -1,115 +0,0 @@ -#date: 2024-12-02T17:11:07Z -#url: https://api.github.com/gists/be7cff34e2ccdd8fda90637aea05fc24 -#owner: https://api.github.com/users/adamkornafeld - -import requests -import hashlib -import time -import logging - -# Constants -LOGIN_METHOD = "global.login" -LOGOUT_METHOD = "global.logout" -CONTROL_METHOD = "CoaxialControlIO.control" -CLIENT_TYPE = "Web3.0" -AUTHORITY_TYPE = "Default" -ENCRYPTION_TYPE = "Default" -IO_TYPE_ON = 1 -IO_TYPE_OFF = 2 - -# Configuration -id = 1 -user = "admin" -password = "**********" -camera_ip = "CAMERA_IP_HERE" - -loginURL = f"http://{camera_ip}/RPC2_Login" -rpcURL = f"http://{camera_ip}/RPC2" - -# Setup logging -logging.basicConfig(level=logging.INFO) - -def make_request(url, payload): - response = requests.post(url, json=payload) - if response.status_code != 200: - logging.error(f"Request failed with status code: {response.status_code}") - raise Exception("Request failed") - return response.json() - -def login(): - global id - first = { - "method": LOGIN_METHOD, - "params": "**********": user, "password": "", "clientType": CLIENT_TYPE, "loginType": "Direct"}, - "id": id - } - resp = make_request(loginURL, first) - session = resp['session'] - params = resp['params'] - random = params['random'] - realm = params['realm'] - encryption = params['encryption'] - - if encryption != ENCRYPTION_TYPE: - logging.error(f"Expected '{ENCRYPTION_TYPE}' encryption, got: {encryption}") - raise Exception("Unexpected encryption type") - - id += 1 - m = hashlib.md5() - h1 = f"{user}: "**********":{password}" - m.update(h1.encode('UTF-8')) - h1md5 = m.hexdigest().upper() - - m = hashlib.md5() - h2 = f"{user}:{random}:{h1md5}" - m.update(h2.encode('UTF-8')) - h2md5 = m.hexdigest().upper() - - second = { - "method": LOGIN_METHOD, - "params": "**********": user, "password": h2md5, "clientType": CLIENT_TYPE, "loginType": "Direct", "authorityType": AUTHORITY_TYPE}, - "id": id, - "session": session, - } - resp = make_request(loginURL, second) - if not resp['result']: - logging.error("Login failed") - raise Exception("Login failed") - - return session - -def control_light(session, io_type): - global id - id += 1 - control = { - "method": CONTROL_METHOD, - "params": {"channel": 0, "info": [{"Type": 1, "IO": io_type, "TriggerMode": 2}]}, - "id": id, - "session": session - } - make_request(rpcURL, control) - -def logout(session): - global id - id += 1 - logout = {"method": LOGOUT_METHOD, "params": None, "id": id, "session": session} - make_request(rpcURL, logout) - logging.info("Logged out") - -def main(): - try: - session = login() - logging.info(f"Logged in with session: {session}") - control_light(session, IO_TYPE_ON) # Turn light on - logging.info(f"Camera light is on") - time.sleep(3) - control_light(session, IO_TYPE_OFF) # Turn light off - logging.info(f"Camera light is off") - except Exception as e: - logging.error(f"An error occurred: {e}") - finally: - logout(session) - -if __name__ == "__main__": - main() -) diff --git a/seeker/snippet/build.sh b/seeker/snippet/build.sh deleted file mode 100644 index dd9e85a2..00000000 --- a/seeker/snippet/build.sh +++ /dev/null @@ -1,115 +0,0 @@ -#date: 2024-12-02T16:47:43Z -#url: https://api.github.com/gists/56cf05f5d9c781eda599ae1e80f7b691 -#owner: https://api.github.com/users/BaoZhuhan - -#!/bin/bash -export ROOT_DIR=$(pwd) -export MODULE_DIR=/etc/profile.d -# export PATH=~/env/cmake/bin:$PATH -# export oneAPI_DIR= !the correct path for oneAPI! - -# source $MODULE_DIR/module.sh -# source $oneAPI_DIR/setvars.sh -# module load cmake - -mkdir Build -ROOT_DIR/Build -# Unzip all the files -tar -zxvf $ROOT_DIR/lapack-3.11.tar.gz -C $ROOT_DIR/Build/ -tar -zxvf $ROOT_DIR/parmetis-4.0.3.tar.gz -C $ROOT_DIR/Build/ -tar -zxvf $ROOT_DIR/hypre-2.28.0.tar.gz -C $ROOT_DIR/Build/ -tar -zxvf $ROOT_DIR/petsc-3.19.3.tar.gz -C $ROOT_DIR/Build/ -tar -zxvf $ROOT_DIR/petsc_solver.tar.gz -C $ROOT_DIR/Build/ -tar -zxvf $ROOT_DIR/OpenCAEPoro.tar.gz -C $ROOT_DIR/Build/ - -# Build LAPACK - -cd $ROOT_DIR/Build/lapack-3.11 - -make blaslib -make cblaslib -make lapacklib -make lapackelib - -# Build ParMETIS -cd $ROOT_DIR/Build/parmetis-4.0.3 - -make config cc=mpiicx cxx=mpiicpx prefix=$ROOT_DIR/Build/parmetis-4.0.3/parmetis-install -make -j 16 -make install - -# Build Hypre - -cd $ROOT_DIR/Build/hypre-2.28.0/ - -cd src/ -make clean -./configure cc=mpiicx cxx=mpiicpx --prefix="$ROOT_DIR/Build/hypre-2.28.0/install" --with-MPI --enable-shared -make -j 16 -make install - -# Build PETSc - -cd $ROOT_DIR/Build/petsc-3.19.3 - -export PETSC_DIR=$ROOT_DIR/Build/petsc-3.19.3 -export PETSC_ARCH=petsc_install - -./configure cc=mpiicx cxx=mpiicpx \ - --with-fortran-bindings=0 \ - --with-hypre-dir=$ROOT_DIR/Build/hypre-2.28.0/install \ - --with-debugging=0 \ - COPTFLAGS="-O3" \ - CXXOPTFLAGS="-O3" \ - -make -j 20 PETSC_DIR=$ROOT_DIR/Build/petsc-3.19.3 PETSC_ARCH=petsc_install all -make all check - -# Build PETSc Solver - -cd $ROOT_DIR/Build/petsc_solver - -export CC=mpiicx -export CXX=mpiicpx - -export CPATH=$ROOT_DIR/Build/lapack-3.11/CBLAS/include:$ROOT_DIR/Build/lapack-3.11/LAPACKE/include:$CPATH -export LD_LIBRARY_PATH=$ROOT_DIR/Build/lapack-3.11:$LD_LIBRARY_PATH - -rm -rf build -mkdir build -cd build -cmake .. -make -mv libpetsc_solver.a ../lib/ - -# Build OpenCAEPoro - -cd $ROOT_DIR/Build/OpenCAEPoro - -export PARMETIS_DIR=$ROOT_DIR/Build/parmetis-4.0.3 -export PARMETIS_BUILD_DIR=$ROOT_DIR/Build/parmetis-4.0.3/build/Linux-x86_64 -export METIS_DIR=$ROOT_DIR/Build/parmetis-4.0.3/metis -export METIS_BUILD_DIR=$ROOT_DIR/Build/parmetis-4.0.3/build/Linux-x86_64 -export PETSC_DIR=$ROOT_DIR/Build/petsc-3.19.3 -export PETSC_ARCH=petsc_install -export PETSCSOLVER_DIR=$ROOT_DIR/Build/petsc_solver -export CPATH=$ROOT_DIR/Build/petsc-3.19.3/include/:$CPATH -export CPATH=$ROOT_DIR/Build/petsc-3.19.3/petsc_install/include/:$ROOT_DIR/Build/parmetis-4.0.3/metis/include:$ROOT_DIR/Build/parmetis-4.0.3/include:$CPATH -export CPATH=$ROOT_DIR/Build/lapack-3.11/CBLAS/include/:$CPATH - - -rm -fr build; mkdir build; cd build; - -echo "cmake -DUSE_PETSCSOLVER=ON -DUSE_PARMETIS=ON -DUSE_METIS=ON -DCMAKE_VERBOSE_MAKEFILE=OFF -DCMAKE_BUILD_TYPE=Release .." -cmake -DUSE_PETSCSOLVER=ON -DUSE_PARMETIS=ON -DUSE_METIS=ON -DCMAKE_VERBOSE_MAKEFILE=OFF -DCMAKE_BUILD_TYPE=Release .. - -echo "make -j 32" -make -j 32 - -echo "make install" -make install - -# Run the test -cd $ROOT_DIR/Build/ - -mpirun -n 4 ./testOpenCAEPoro ./data/test/test.data \ No newline at end of file diff --git a/seeker/snippet/class.py b/seeker/snippet/class.py new file mode 100644 index 00000000..07c6b530 --- /dev/null +++ b/seeker/snippet/class.py @@ -0,0 +1,82 @@ +#date: 2024-12-04T16:55:56Z +#url: https://api.github.com/gists/5cb49fe01fc22d81f1c274e53bf6c116 +#owner: https://api.github.com/users/TerskikhAndrey + +class House: + def __init__(self, name, number): + self.name = str(name) + self.number_of_floors = number + + def __len__(self): + return self.number_of_floors + + def __str__(self): + return f'Название: {self.name}, количество этажей: {self.number_of_floors}' + + def __eq__(self, other): + if isinstance(other.number_of_floors, int) and isinstance(other, House): + return self.number_of_floors == other.number_of_floors + def __lt__(self, other): + if isinstance(other.number_of_floors, int) and isinstance(other, House): + return self.number_of_floors < other.number_of_floors + def __le__(self, other): + if isinstance(other.number_of_floors, int): + if isinstance(other, House): + return self.number_of_floors <= other.number_of_floors + def __gt__(self, other): + if isinstance(other.number_of_floors, int): + if isinstance(other, House): + return self.number_of_floors > other.number_of_floors + def __ge__(self, other): + if isinstance(other.number_of_floors, int) and isinstance(other, House): + return self.number_of_floors >= other.number_of_floors + def __ne__(self, other): + if isinstance(other.number_of_floors, int): + if isinstance(other, House): + return self.number_of_floors != other.number_of_floors + def __add__(self, value): + if isinstance(value, int): + self.number_of_floors = self.number_of_floors + value + return self + def __radd__(self, value): + return self.__add__(value) + def __iadd__(self, value): + if isinstance(value, int): + self.number_of_floors += value + return self + + + + + def go_to(self, new_floor): + floor = 0 + if new_floor < 1 or new_floor > self.number_of_floors: + print('Такого экажа не существует') + else: + for floor in range(new_floor): + print(floor + 1) +h1 = House('ЖК Горский', 10) + + + +h2 = House('Домик в деревне', 20) + + +print(h1) +print(h2) +print(h1 == h2) +h1 = h1 + 10 +print(h1) +print(h1 == h2) +h1 += 10 +print(h1) +h2 = 10 + h2 +print(h2) + +print(h1 > h2) +print(h1 >= h2) +print(h1 < h2) +print(h1 <= h2) +print(h1 != h2) + + diff --git a/seeker/snippet/code.java b/seeker/snippet/code.java new file mode 100644 index 00000000..634fa5da --- /dev/null +++ b/seeker/snippet/code.java @@ -0,0 +1,40 @@ +//date: 2024-12-04T17:09:52Z +//url: https://api.github.com/gists/3b3fb1487c2b2bba023de8f929030509 +//owner: https://api.github.com/users/MichalBrylka + +import java.time.LocalDate; +import java.util.stream.Stream; + +public class BusinessDayCalculator { + + public static LocalDate previousBusinessDay(LocalDate date) { + LocalDate previous = date.minusDays(1); + while (isHoliday(previous)) { + previous = previous.minusDays(1); + } + return previous; + } + + public static Stream<LocalDate> previousBusinessDays(LocalDate date) { + return Stream.iterate(date.minusDays(1), d -> d.minusDays(1)) + .filter(d -> !isHoliday(d)); + } + + public static LocalDate nextBusinessDay(LocalDate date) { + LocalDate next = date.plusDays(1); + while (isHoliday(next)) { + next = next.plusDays(1); + } + return next; + } + + public static Stream<LocalDate> nextBusinessDays(LocalDate date) { + return Stream.iterate(date.plusDays(1), d -> d.plusDays(1)) + .filter(d -> !isHoliday(d)); + } + + public static boolean isHoliday(LocalDate date) { + // Example: weekends are holidays + return date.getDayOfWeek().getValue() >= 6; + } +} diff --git a/seeker/snippet/create_flux_wireguard.sh b/seeker/snippet/create_flux_wireguard.sh new file mode 100644 index 00000000..2abadd5b --- /dev/null +++ b/seeker/snippet/create_flux_wireguard.sh @@ -0,0 +1,71 @@ +#date: 2024-12-04T17:13:34Z +#url: https://api.github.com/gists/027b894cf5d6eadcf9bc6406fd9a9dba +#owner: https://api.github.com/users/MorningLightMountain713 + +#!/bin/bash + +umask 077 + +if [[ "$EUID" -ne 0 ]]; then + echo "Please run as root / with sudo" + exit +fi + +! dpkg -s wireguard 2>&1 >/dev/null && apt get install wireguard + +sed -i "s/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/" /etc/sysctl.conf +sysctl -p >/dev/null + +local_ip=10.11.12.1/31 +peer_ip=10.11.12.0/31 +vpn_port=51001 + +user=$(who am i | awk '{print $1}') +wan_int=$(ip route show default | awk '/default/ {print $5}') +wan_ip=$(curl -4 -s -L ipshow.me) + +local_private=$(wg genkey) +local_public=$(echo $local_private | wg pubkey) +peer_private=$(wg genkey) +peer_public=$(echo $peer_private | wg pubkey) +psk=$(wg genpsk) + +echo $peer_private >opnsense_private +echo $local_public >vps_public +echo $psk >opnsense_psk + +chown "$user:$user" opnsense_private vps_public opnsense_psk + +cat <<EOF >/etc/wireguard/wg_flux.conf +[Interface] +Address = $local_ip +PrivateKey = $local_private +ListenPort = $vpn_port +PostUp = /etc/wireguard/action_script up +PostDown = /etc/wireguard/action_script down + +[Peer] +PublicKey = $peer_public +PreSharedKey = $psk +AllowedIPs = $peer_ip +EOF + +cat <<EOF >/etc/wireguard/action_script +#!/bin/bash + +state=\$1 + +[[ "\$state" = "up" ]] && action="-I" || action="-D" + +iptables \$action INPUT -p udp -m udp --dport $vpn_port -j ACCEPT +iptables -t nat \$action PREROUTING -i $wan_int -p udp -m udp ! --dport $vpn_port -j DNAT --to-destination ${peer_ip%%/*} +iptables -t nat \$action PREROUTING -i $wan_int -p tcp -m tcp ! --dport 22 -j DNAT --to-destination ${peer_ip%%/*} +iptables -t nat \$action POSTROUTING -o $wan_int -j SNAT --to-source $wan_ip +EOF + +chmod +x /etc/wireguard/action_script + +systemctl enable wg-quick@wg_flux +systemctl daemon-reload + +systemctl start wg-quick@wg_flux diff --git a/seeker/snippet/decorator_example.py b/seeker/snippet/decorator_example.py new file mode 100644 index 00000000..6ab962ce --- /dev/null +++ b/seeker/snippet/decorator_example.py @@ -0,0 +1,15 @@ +#date: 2024-12-04T16:57:45Z +#url: https://api.github.com/gists/b8e271643dc0108d83daa26388915895 +#owner: https://api.github.com/users/ozzloy + +def decorator_func(func): + def manipulated_func(fruit): + return "manipulated " + func(fruit) + return manipulated_func + +@decorator_func +def return_fruit(fruit): + return "your fruit is " + fruit + +print(return_fruit("pear")) +# manipulated your fruit is pear \ No newline at end of file diff --git a/seeker/snippet/diamond.py b/seeker/snippet/diamond.py deleted file mode 100644 index ae429651..00000000 --- a/seeker/snippet/diamond.py +++ /dev/null @@ -1,37 +0,0 @@ -#date: 2024-12-02T17:06:52Z -#url: https://api.github.com/gists/1148009e518ca01a63e4bf13d2f02769 -#owner: https://api.github.com/users/Fuanyi-237 - -#Code to create a Diaamond with a letter starting from "A"(to that letter and back) -def rows(letter): - #collecting the number of rows from the alpha-numeric correspondant - row = int(ord(letter)) - 64 - result = [] - n = 0 - spaces = row - 2 #front spaces - space_btw = 2*n + 1 #spaces in between the letter - if row > 1: #I wish to do a logic from the second row to the last - # firstly, I secure the first letter in the list(result) - first_letter = " " * (row-1) + "A" + " " * (row-1) - result.append(first_letter) - #Collect from 'B' to last letter - for i in range(ord('B'), ord(letter) + 1): - #logic behind collecting the letters in a row - row_letter = " "*(spaces) + chr(i) + " "*(space_btw) + chr(i) + " "*(spaces) - result.append(row_letter) - space_btw += 2 - spaces -= 1 - space_btw -= 2 - spaces += 1 - #Collect from second to last letter to B - for k in range(ord(letter)-1, ord('A'), -1): - spaces += 1 - space_btw -= 2 - row_letter = " "*(spaces) + chr(k) + " "*(space_btw) + chr(k) + " "*(spaces) - result.append(row_letter) - #secure my last letter, which is same as first - last_letter = " " * (row-1) + "A" + " " * (row-1) - result.append(last_letter) - return result - else: - return [chr(ord(letter))] \ No newline at end of file diff --git a/seeker/snippet/digitalioe9.py b/seeker/snippet/digitalioe9.py deleted file mode 100644 index 55bf3108..00000000 --- a/seeker/snippet/digitalioe9.py +++ /dev/null @@ -1,140 +0,0 @@ -#date: 2024-12-02T16:51:34Z -#url: https://api.github.com/gists/81eef2bab4bb130bd2034d95f9c22b1d -#owner: https://api.github.com/users/jepler - -# SPDX-FileCopyrightText: Copyright (c) 2024 Jeff Epler for Adafruit Industries LLC -# -# SPDX-License-Identifier: MIT - -"""Work around the RP2350 E9 erratum by turning off input buffer - -A silicon bug in the RP2350 "A2" stepping (the latest and only available version in -December 2024) prevents input pull-downs larger than about 8.2kOhm from working -properly, including the built-in pull down resistors. - -A workaround is proposed (keep the input buffer disabled except when actually -reading the input pin value). For various reasons, CircuitPython chose not to -implement this workaround in the core. This workaround slows access to digital -pins and can't work with peripherals like SPI and PIO. - -However, in limited circumstances, it is useful to be able to slowly read a digital -pin with a weak pull-down that is affected by the "E9 Erratum" (search for -"RP2350-E9" in https://datasheets.raspberrypi.com/rp2350/rp2350-datasheet.pdf for more -details) - -This class implements the workaround in pure Python, using the memorymap module to -directly access the "input enable" bit in the pad control registers. - -Typical usage, Feather RP2350 with nothing connected to D5: - -.. code-block:: python - >>> import digitalioe9 - >>> import digitalio - >>> import board - >>> - >>> d = digitalioe9.DigitalInOutE9(board.D5) - >>> d.switch_to_input(digitalio.Pull.UP) - >>> print(d.value) - True - >>> d.switch_to_input(digitalio.Pull.DOWN) - >>> print(d.value) - False - -""" - -import os -import struct -import microcontroller.pin -import digitalio -import memorymap - -if not os.uname().nodename.startswith("rp2350"): - raise RuntimeError( - "This module is only compatible with rp2350, not {os.uname().nodename}" - ) - -_RP2350_PADS_BANK0_BASE = const(0x40038000) -_ATOMIC_SET_OFFSET = const(0x2000) -_ATOMIC_CLEAR_OFFSET = const(0x3000) - -_input_enable_bit = struct.pack("I", 1 << 6) - - -def _pin_number(p): - for i in range(48): - a = getattr(microcontroller.pin, f"GPIO{i}", None) - if p is a: - return i - raise ValueError("{p!r} is not a GPIO pin") - - -def _get_reg(offset): - return memorymap.AddressRange(start=_RP2350_PADS_BANK0_BASE + offset, length=4) - - -class DigitalInOutE9: - """A class that functions similar to DigitalInOut, but implements the E9 workaround - - See `digitalio.DigitalInOut` for documentation. - """ - def __init__(self, pin): - self._dio = digitalio.DigitalInOut(pin) - pin_number = _pin_number(pin) - ctrl_offset = 4 + 4 * pin_number - self._set_reg = _get_reg(_ATOMIC_SET_OFFSET | ctrl_offset) - self._clear_reg = _get_reg(_ATOMIC_CLEAR_OFFSET | ctrl_offset) - self._disable_buffer() - - def _enable_buffer(self): - self._set_reg[:] = _input_enable_bit - - def _disable_buffer(self): - self._clear_reg[:] = _input_enable_bit - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.deinit() - - def deinit(self): - self._dio.deinit() - - def switch_to_input(self, pull=None): - self._dio.switch_to_input(pull) - self._disable_buffer() - - def switch_to_output(self, value=False, drive_mode=digitalio.DriveMode.PUSH_PULL): - self._dio.switch_to_output(value, drive_mode) - self._disable_buffer() - - @property - def direction(self): - return self._dio.direction - - @direction.setter - def direction(self, value): - self._dio.direction = direction - self._disable_buffer() - - @property - def pull(self): - return self._dio.pull - - @pull.setter - def pull(self, value): - self._dio.pull = pull - self._disable_buffer() - - @property - def value(self): - self._dio.value # side effect: checks for deinit - self._enable_buffer() - result = self._dio.value - self._disable_buffer() - return result - - @value.setter - def value(self, value): - self._dio.value = value - self._disable_buffer() diff --git a/seeker/snippet/headline.zsh b/seeker/snippet/headline.zsh new file mode 100644 index 00000000..cf95406b --- /dev/null +++ b/seeker/snippet/headline.zsh @@ -0,0 +1,715 @@ +#date: 2024-12-04T16:51:07Z +#url: https://api.github.com/gists/76adb48bb7b05f9fed95cbc4c09a9345 +#owner: https://api.github.com/users/covertivy + +#!/bin/zsh + +# Headline ZSH Prompt +# Copyright (c) 2024 Moarram under the MIT License + +# To install, source this file from your ~/.zshrc +# Customization variables begin around line 80 + + +# Formatting aliases +# (add more if you need) +reset=$'\e[0m' +bold=$'\e[1m' +faint=$'\e[2m'; no_faint_bold=$'\e[22m' +italic=$'\e[3m'; no_italic=$'\e[23m' +underline=$'\e[4m'; no_underline=$'\e[24m' +invert=$'\e[7m'; no_invert=$'\e[27m' +# ... + +# Foreground color aliases +black=$'\e[30m' +red=$'\e[31m' +green=$'\e[32m' +yellow=$'\e[33m' +blue=$'\e[34m' +magenta=$'\e[35m' +cyan=$'\e[36m' +white=$'\e[37m' +light_black=$'\e[90m' +light_red=$'\e[91m' +light_green=$'\e[92m' +light_yellow=$'\e[93m' +light_blue=$'\e[94m' +light_magenta=$'\e[95m' +light_cyan=$'\e[96m' +light_white=$'\e[97m' +default_fg=$'\e[39m' + +# Background color aliases +black_bg=$'\e[40m' +red_bg=$'\e[41m' +green_bg=$'\e[42m' +yellow_bg=$'\e[43m' +blue_bg=$'\e[44m' +magenta_bg=$'\e[45m' +cyan_bg=$'\e[46m' +white_bg=$'\e[47m' +light_black_bg=$'\e[100m' +light_red_bg=$'\e[101m' +light_green_bg=$'\e[102m' +light_yellow_bg=$'\e[103m' +light_blue_bg=$'\e[104m' +light_magenta_bg=$'\e[105m' +light_cyan_bg=$'\e[106m' +light_white_bg=$'\e[107m' +default_bg=$'\e[49m' + +# Custom colors +# Ref: https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters +# orange_yellow=$'\e[38;5;214m' # example 8-bit color (n=214) +# orange_brown=$'\e[38;2;191;116;46m' # example rgb color (r=119, g=116, b=46) +# ... + +# Terminal control aliases +cursor_up=$'\e[1F' +cursor_show=$'\e[?25h' +cursor_hide=$'\e[?25l' +cursor_to_top_left_corner=$'\e[H' +clear_entire_screen=$'\e[2J' +# ... + +# Flags +[ ! -z "$SSH_TTY$SSH_CONNECTION$SSH_CLIENT" ] && IS_SSH='true' + + + +# ------------------------------------------------------------------------------ +# Customization +# Use the following variables to customize the theme. +# If you're setting them in ~/.zshrc, source the theme, THEN set the variables. +# To insert styles (ANSI SGR codes defined above) use syntax: "%{$style%}" + + +# Print separator and information line with precmd hook or in PROMPT +HL_PRINT_MODE='precmd' # precmd|prompt + +# Print the separator line always, when not following clear screen, or don't print +HL_SEP_MODE='on' # on|auto|off + +# Print the information line always, when it has changed, or don't print +HL_INFO_MODE='on' # on|auto|off + +# Press <enter> with no commands to overwrite previous prompt +HL_OVERWRITE='on' # on|off + + +# Style applied to separator line, after other styles +HL_SEP_STYLE="%{$default_bg%}" + +# Segments of the separator line +declare -A HL_SEP=( + _PRE '' + _LINE '▁' # repeated char to create separator line, consider '▁' + _POST '' +) + + +# Style applied to all segments, before other styles +HL_BASE_STYLE="" + +# Style of segment layout template +HL_LAYOUT_STYLE="%{$faint%}" + +# Order of segments +declare -a HL_LAYOUT_ORDER=( + _PRE USER HOST VENV PATH _SPACER BRANCH STATUS _POST # ... +) + +# Template for each segment's layout +declare -A HL_LAYOUT_TEMPLATE=( + # _PRE "${IS_SSH+=> }" # shows "=> " if this is an ssh session + _PRE "" + USER '...' + HOST ' @ ...' + VENV ' (...)' + PATH ': ...' + _SPACER ' | ' # special, only shows when compact, otherwise fill with space + BRANCH '...' + STATUS ' [...]' + _POST '' + # ... +) + +# Template for first segment's layout (when prior segments removed) +declare -A HL_LAYOUT_FIRST=( + VENV '(...)' + PATH '...' + _SPACER '' + # ... +) + +# The character used by _SPACER segment to fill space +HL_SPACE_CHAR=' ' + + +# Template for each segment's content +declare -A HL_CONTENT_TEMPLATE=( + USER "%{$bold$green%} ..." # consider ' ' or ' ' + HOST "%{$bold$cyan%} ..." # consider ' ' or ' ' + VENV "%{$bold$green%} ..." # consider ' ' or ' ' + PATH "%{$bold$yellow%} ..." # consider ' ' or ' ' + BRANCH "%{$bold$cyan%} ..." # consider ' ' or ' ' + STATUS "%{$bold$magenta%}..." + # ... +) + +# Commands to produce each segment's content +declare -A HL_CONTENT_SOURCE=( + USER 'echo $USER' + HOST 'hostname -s' + VENV 'basename "$VIRTUAL_ENV"' + PATH 'print -rP "%~"' + BRANCH 'headline-git-branch' + STATUS 'headline-git-status' + # ... +) + + +# Show count of each status always, only when greater than one, or don't show +HL_GIT_COUNT_MODE='off' # on|auto|off + +# Symbol to join each status +HL_GIT_SEP_SYMBOL='' + +# Order of statuses +declare -a HL_GIT_STATUS_ORDER=( + STAGED CHANGED UNTRACKED BEHIND AHEAD DIVERGED STASHED CONFLICTS CLEAN +) + +# Symbol for each status +declare -A HL_GIT_STATUS_SYMBOLS=( + STAGED '+' + CHANGED '!' + UNTRACKED '?' + BEHIND '↓' + AHEAD '↑' + DIVERGED '↕' + STASHED '*' + CONFLICTS "%{$red%}✘" # consider "%{$red%}✘" + CLEAN "%{$green%}✔" # consider '✓' or "%{$green%}✔" +) + + +# Minimum screen width to show segment +declare -A HL_COLS_REMOVAL=( + USER 50 + HOST 70 + VENV 30 + # ... +) + +# Order to truncate & remove segments +declare -a HL_TRUNC_ORDER=( + HOST USER VENV PATH BRANCH # ... +) + +# Symbol to insert when truncating a segment +HL_TRUNC_SYMBOL='…' # consider '…' + +# Minimum segment length for initial truncation +HL_TRUNC_INITIAL=16 + +# Minimum segment length before removal +HL_TRUNC_REMOVAL=2 + + +# Prompt +# HL_PROMPT='%(#.#.%(!.!.$)) ' # consider '%#' +HL_PROMPT='~> ' # consider '%#' + +# Right prompt +HL_RPROMPT='' + + +# Show the clock, or don't show +HL_CLOCK_MODE='on' # on|off + +# Template for the clock +HL_CLOCK_TEMPLATE="%{$faint%}..." + +# Command which outputs clock content +HL_CLOCK_SOURCE='date +%+' # consider 'date +%+' for full date + + +# Show non-zero exit code, include a guessed meaning too, or don't show +HL_ERR_MODE='off' # on|detail|off + +# Template for the exit code +HL_ERR_TEMPLATE="%{$faint$italic%}→ ..." + +# Template for the optional detail +HL_ERR_DETAIL_TEMPLATE=' (...)' + + +# The string to replace in templates +HL_TEMPLATE_TOKEN= "**********" + +# ------------------------------------------------------------------------------ + + + +# Output variables +HL_OUTPUT_SEP='' # printed separator line +HL_OUTPUT_INFO='' # printed information line + +# Local variables +_HL_SEP='' # computed separator line +_HL_INFO='' # computed information line +_HL_AT_TOP='true' # whether prompt is at top of the screen +_HL_CMD_NUM=0 # number of commands entered +_HL_CMD_NUM_PREV=-1 # previous number of commands entered, no command if same + +# Zsh configuration +setopt PROMPT_SP # always start prompt on new line +setopt PROMPT_SUBST # enable substitutions +autoload -U add-zsh-hook +PROMPT_EOL_MARK='' # remove weird % symbol +ZLE_RPROMPT_INDENT=0 # remove extra space + + +# Calculate length of string, excluding formatting characters +headline-prompt-len() { # (str, num?) + # Ref: https://old.reddit.com/r/zsh/comments/cgbm24/multiline_prompt_the_missing_ingredient/ + emulate -L zsh + local -i COLUMNS=${2:-COLUMNS} + local -i x y=${#1} m + if (( y )); then + while (( ${${(%):-$1%$y(l.1.0)}[-1]} )); do + x=y + (( y *= 2 )) + done + while (( y > x + 1 )); do + (( m = x + (y - x) / 2 )) + (( ${${(%):-$1%$m(l.x.y)}[-1]} = m )) + done + fi + echo $x +} + +# Repeat character a number of times +headline-repeat-char() { # (char, num) + # Note: This replaces the "${(pl:$num::$char:)}" expansion + local result='' + for (( i = 0; i < $2; i++ )); do + result+=$1 + done + echo $result +} + +# Guess the exit code meaning +headline-exit-meaning() { # (num) + # Ref: https://tldp.org/LDP/abs/html/exitcodes.html + # Ref: https://man7.org/linux/man-pages/man7/signal.7.html + # Note: These meanings are not standardized + case $1 in + 126) echo 'Command cannot execute';; + 127) echo 'Command not found';; + 129) echo 'Hangup';; + 130) echo 'Interrupted';; + 131) echo 'Quit';; + 132) echo 'Illegal instruction';; + 133) echo 'Trapped';; + 134) echo 'Aborted';; + 135) echo 'Bus error';; + 136) echo 'Arithmetic error';; + 137) echo 'Killed';; + 138) echo 'User signal 1';; + 139) echo 'Segmentation fault';; + 140) echo 'User signal 2';; + 141) echo 'Pipe error';; + 142) echo 'Alarm';; + 143) echo 'Terminated';; + *) ;; + esac +} + +# Git command wrapper +headline-git() { + # TODO is this necessary? + GIT_OPTIONAL_LOCKS=0 command git "$@" +} + +# Get git branch (or hash) +headline-git-branch() { + local ref + ref=$(headline-git symbolic-ref --quiet HEAD 2> /dev/null) + local err=$? + if [[ $err == 0 ]]; then + echo ${ref#refs/heads/} # remove "refs/heads/" to get branch + else # not on a branch + [[ $err == 128 ]] && return # not a git repo + ref=$(headline-git rev-parse --short HEAD 2> /dev/null) || return + echo ":${ref}" # hash prefixed to distingush from branch + fi +} + +# Get the quantity of each git status +headline-git-status-counts() { + local -A counts=( + 'STAGED' 0 # staged changes + 'CHANGED' 0 # unstaged changes + 'UNTRACKED' 0 # untracked files + 'BEHIND' 0 # commits behind + 'AHEAD' 0 # commits ahead + 'DIVERGED' 0 # commits diverged + 'STASHED' 0 # stashed files + 'CONFLICTS' 0 # conflicts + 'CLEAN' 1 # clean branch 1=true 0=false + ) + + # Retrieve status + local raw lines + raw="$(headline-git status --porcelain -b 2> /dev/null)" + if [[ $? == 128 ]]; then + return 1 # catastrophic failure, abort + fi + lines=(${(@f)raw}) + + # Process tracking line + if [[ ${lines[1]} =~ '^## [^ ]+ \[(.*)\]' ]]; then + local items=("${(@s/,/)match}") + for item in $items; do + if [[ $item =~ '(behind|ahead|diverged) ([0-9]+)?' ]]; then + case $match[1] in + 'behind') counts[BEHIND]=$match[2];; + 'ahead') counts[AHEAD]=$match[2];; + 'diverged') counts[DIVERGED]=$match[2];; + esac + fi + done + fi + + # Process status lines + for line in $lines; do + if [[ $line =~ '^##|^!!' ]]; then + continue + elif [[ $line =~ '^U[ADU]|^[AD]U|^AA|^DD' ]]; then + counts[CONFLICTS]=$(( ${counts[CONFLICTS]} + 1 )) + elif [[ $line =~ '^\?\?' ]]; then + counts[UNTRACKED]=$(( ${counts[UNTRACKED]} + 1 )) + elif [[ $line =~ '^[MTADRC] ' ]]; then + counts[STAGED]=$(( ${counts[STAGED]} + 1 )) + elif [[ $line =~ '^[MTARC][MTD]' ]]; then + counts[STAGED]=$(( ${counts[STAGED]} + 1 )) + counts[CHANGED]=$(( ${counts[CHANGED]} + 1 )) + elif [[ $line =~ '^ [MTADRC]' ]]; then + counts[CHANGED]=$(( ${counts[CHANGED]} + 1 )) + fi + done + + # Check for stashes + if $(headline-git rev-parse --verify refs/stash &> /dev/null); then + counts[STASHED]=$(headline-git rev-list --walk-reflogs --count refs/stash 2> /dev/null) + fi + + # Update clean flag + for key val in ${(@kv)counts}; do + [[ $key == 'CLEAN' ]] && continue + (( $val > 0 )) && counts[CLEAN]=0 + done + + echo ${(@kv)counts} # key1 val1 key2 val2 ... +} + +# Get git status +headline-git-status() { + local parts=( ${(ps: "**********":)HL_CONTENT_TEMPLATE[STATUS]} ) # split on template token + local style=${${parts[1]##*%\{}%%%\}*} # regex for "%{...%}" + local -A counts=( $(headline-git-status-counts) ) + (( ${#counts} == 0 )) && return # not a git repo + local result='' + for key in $HL_GIT_STATUS_ORDER; do + if (( ${counts[$key]} > 0 )); then + if (( ${#HL_GIT_SEP_SYMBOL} != 0 && ${#result} != 0 )); then + result+="%{$reset%}$HL_BASE_STYLE$HL_LAYOUT_STYLE$HL_GIT_SEP_SYMBOL%{$reset%}$HL_BASE_STYLE%{$style%}" + fi + if [[ $key != 'CLEAN' && $HL_GIT_COUNT_MODE == 'on' || ( $HL_GIT_COUNT_MODE == 'auto' && ${counts[$key]} != 1 ) ]]; then + result+="${counts[$key]}${HL_GIT_STATUS_SYMBOLS[$key]}" + else + result+="${HL_GIT_STATUS_SYMBOLS[$key]}" + fi + fi + done + echo $result +} + +# Transfer styles to another string +headline-transfer-styles() { # (str, str) + local -a src=( ${(@s::)1} ) # source char array + local -a dest=( ${(@s::)2} ) # destination char array + local result='' + local prev='' + local is_style='false' + local index=0 + for char in $src; do + if [[ $prev == '{' || $prev == '}' ]]; then + prev=$char + continue + elif [[ $prev == '%' && $char == '{' ]]; then + [[ $is_style != 'true' ]] && result+='%{' + is_style='true' + elif [[ $prev == '%' && $char == '}' ]]; then + [[ $is_style == 'true' ]] && result+='%}' + is_style='false' + elif [[ $is_style == 'true' ]]; then + result+=$prev + else + result+=${dest[$index]} + (( index += 1 )) + fi + prev=$char + done + result+=${dest[$index]} + echo $result + + # TODO use regex... why does this suck so much? can't match multiple? + # if [[ $1 =~ '%{([^%]*)%}' ]]; then + # echo $MBEGIN $MEND $MATCH + # echo $mbegin $mend $match # expect arrays? + # fi +} + + +# Handle Ctrl+L press +zle -N headline-clear-screen +bindkey '^L' headline-clear-screen +headline-clear-screen() { + _HL_AT_TOP='true' + _HL_INFO='' # ensure info line will print + + # Hide cursor and clear screen + print -nr "$cursor_hide$cursor_to_top_left_corner$clear_entire_screen" + + # Update and print + for function in $precmd_functions; do + $function + done + zle .reset-prompt # re-print $PROMPT and $RPROMPT + + # Show cursor + print -nr "$cursor_show" +} + +# Before executing command +add-zsh-hook preexec headline-preexec +headline-preexec() { + (( _HL_CMD_NUM++ )) + # TODO better way of knowing the prompt is at the top of the terminal ? + if [[ $2 == 'clear' ]]; then + _HL_AT_TOP='true' + _HL_INFO='' # ensure info line will print + fi +} + +# Before prompting +add-zsh-hook precmd headline-precmd +headline-precmd() { + local -i err=$? + local -i trunc_initial_length=$(( $HL_TRUNC_INITIAL + ${#HL_TRUNC_SYMBOL} )) + local -i trunc_removal_length=$(( $HL_TRUNC_REMOVAL + ${#HL_TRUNC_SYMBOL} )) + + # Acquire contents + local -A contents + local -A content_lengths # length of each content (without style) + local -i content_length=0 # total length of content + for key val in "${(@kv)HL_CONTENT_SOURCE}"; do + content_lengths[$key]=0 + (( $COLUMNS < ${HL_COLS_REMOVAL[$key]:-0} )) && continue # omit segment + contents[$key]=$(eval ${=val}) + local -i length=$(headline-prompt-len ${contents[$key]:-''} 999) + (( content_length += $length )); content_lengths[$key]=$length + done + + # Compute layout lengths + local -A layouts + local -A layout_lengths # length of each layout (without style) + local -i layout_length=0 # total length of layout + local -A first_layout_lengths # length of each first layout (without style) + for key val in "${(@kv)HL_LAYOUT_TEMPLATE}"; do + layout_lengths[$key]=0 + local -i length=$(headline-prompt-len "$val$HL_CONTENT_TEMPLATE[$key]" 999) + local -i first_length=$(headline-prompt-len "$HL_LAYOUT_FIRST[$key]$HL_CONTENT_TEMPLATE[$key]" 999) + if [[ ${key[1]} != '_' ]]; then + (( content_lengths[$key] <= 0 )) && continue # skip omitted segment + (( length -= "**********" + (( first_length -= "**********" + fi + layouts[$key]=$val + (( layout_length += $length )); layout_lengths[$key]=$length + (( ${+HL_LAYOUT_FIRST[$key]} )) && first_layout_lengths[$key]=$first_length + done + + # Compute target truncation length + local -i target_length=$content_length + for key in $HL_LAYOUT_ORDER; do + (( ! $HL_TRUNC_ORDER[(Ie)$key] )) && continue # no truncation specified + (( $trunc_initial_length >= $content_lengths[$key] )) && continue # already short enough + (( target_length -= $content_lengths[$key] - $trunc_initial_length )) + done + + # Update first segment + for key in $HL_LAYOUT_ORDER; do + [[ $key == '_PRE' ]] && continue # skip special segment + (( content_lengths[$key] <= 0 && layout_lengths[$key] <= 0 )) && continue # skip omitted segment + if (( ${+HL_LAYOUT_FIRST[$key]} )); then + layouts[$key]=$HL_LAYOUT_FIRST[$key] + (( layout_length -= $layout_lengths[$key] - $first_layout_lengths[$key] )) + layout_lengths[$key]=$first_layout_lengths[$key] + fi + break + done + + # Remove segments as needed + for key in $HL_TRUNC_ORDER; do + (( content_lengths[$key] <= 0 )) && continue # already removed + local -i remove=$(( $content_lengths[$key] < $trunc_initial_length ? $content_lengths[$key] : $trunc_initial_length )) + local -i offset=$(( $remove < $trunc_removal_length ? 0 : $remove - $trunc_removal_length )) + (( $target_length + $layout_length - $offset <= $COLUMNS )) && break # done removing + (( target_length -= $remove )) + contents[$key]=''; (( content_length -= $content_lengths[$key] )); content_lengths[$key]=0 + layouts[$key]=''; (( layout_length -= $layout_lengths[$key] )); layout_lengths[$key]=0 + + # Update first segment + for key in $HL_LAYOUT_ORDER; do + [[ $key == '_PRE' ]] && continue # skip special segment + (( content_lengths[$key] <= 0 && layout_lengths[$key] <= 0 )) && continue # skip omitted segment + if (( ${+HL_LAYOUT_FIRST[$key]} )); then + layouts[$key]=$HL_LAYOUT_FIRST[$key] + (( layout_length -= $layout_lengths[$key] - $first_layout_lengths[$key] )) + layout_lengths[$key]=$first_layout_lengths[$key] + fi + break + done + done + + # Truncate segments to initial length + for key in $HL_TRUNC_ORDER; do + (( content_lengths[$key] <= 0 )) && continue # segment removed + local -i excess=$(( $content_length + $layout_length - $COLUMNS )) + (( $excess <= 0 )) && break # done truncating + local -i removeable=$(( $content_lengths[$key] - $trunc_initial_length )) + (( $removeable <= 0 )) && continue # already short enough + local -i remove=$(( ( $excess < $removeable ? $excess : $removeable ) )) + (( content_length -= $remove )) + content_lengths[$key]=$(( $content_lengths[$key] - $remove )) + contents[$key]="$HL_TRUNC_SYMBOL${contents[$key]:$(( $remove + ${#HL_TRUNC_SYMBOL} ))}" + done + + # Truncate segment to minimum length + for key in $HL_TRUNC_ORDER; do + (( content_lengths[$key] <= 0 )) && continue # segment removed + local -i excess=$(( $content_length + $layout_length - $COLUMNS )) + (( $excess <= 0 )) && break # done truncating + (( content_length -= $excess )) + content_lengths[$key]=$(( $content_lengths[$key] - $excess )) + contents[$key]="$HL_TRUNC_SYMBOL${contents[$key]:$(( excess + ${#HL_TRUNC_SYMBOL} ))}" + done + + # Build spacer + local -i remainder=$(( $COLUMNS - $content_length - $layout_length )) + if (( $remainder > 0 )); then + contents[_SPACER]="$(headline-repeat-char "$HL_SPACE_CHAR" $(( $remainder + $layout_lengths[_SPACER] )) )" + fi + + # Assemble segments + local information='' # the styled information line + for key in $HL_LAYOUT_ORDER; do + local segment=''; local segment_sep='' + if [[ ${key[1]} == '_' && ${#contents[$key]} == 0 ]]; then # special segment without content (ex: _PRE, _POST) + segment="${layouts[$key]}"; segment_sep=$segment + elif [[ ${key[1]} == '_' && ${#contents[$key]} != 0 ]]; then # special segment with generated content (ex: _SPACER) + segment="${contents[$key]}"; segment_sep=$segment + elif [[ ${key[1]} != '_' && ${#contents[$key]} != 0 ]]; then # normal segment with content + segment= "**********" + segment="%{$reset%}$HL_BASE_STYLE$segment%{$reset%}$HL_BASE_STYLE$HL_LAYOUT_STYLE" + segment= "**********" + else # normal segment without content + continue + fi + information+="$HL_BASE_STYLE$HL_LAYOUT_STYLE$segment%{$reset%}" + done + + # Assemble separator + local separator=$(headline-repeat-char "${HL_SEP[_LINE]}" $(( $COLUMNS - ${#HL_SEP[_PRE]} - ${#HL_SEP[_POST]} )) ) + separator=$(headline-transfer-styles "$information" "${HL_SEP[_PRE]}$separator${HL_SEP[_POST]}") + separator="${separator//"%}"/"%}$HL_SEP_STYLE"}" + + # Prepare cursor + local overwrite='false' + if [[ $HL_OVERWRITE == 'on' && $_HL_CMD_NUM == $_HL_CMD_NUM_PREV ]]; then + overwrite='true' + print -nr "$cursor_hide" + print -nr "$cursor_up" # to prompt line + (( ${#HL_OUTPUT_INFO} )) && print -nr "$cursor_up" # to info line + (( ${#HL_OUTPUT_SEP} )) && print -nr "$cursor_up" # to separator line + if [[ $HL_SEP_MODE == 'auto' && ! $HL_OUTPUT_SEP ]]; then + _HL_AT_TOP='true' # deduce that we were at top last time + fi + print -nr "$cursor_show" + fi + + # Error line + if [[ $err != 0 && ($HL_ERR_MODE == 'on' || $HL_ERR_MODE == 'detail') && $overwrite != 'true' ]]; then + local message=$err + if [[ $HL_ERR_MODE == 'detail' ]]; then + local meaning=$(headline-exit-meaning $err) + (( ${#meaning} > 0 )) && message+= "**********" + fi + print -rP "${HL_ERR_TEMPLATE/$HL_TEMPLATE_TOKEN/$message}%{$reset%}" + fi + + # Separator line + if [[ $HL_SEP_MODE == 'on' || ($HL_SEP_MODE == 'auto' && $_HL_AT_TOP != 'true') ]]; then + HL_OUTPUT_SEP=$separator + [[ $HL_PRINT_MODE == 'precmd' ]] && print -rP "$HL_OUTPUT_SEP" + else + HL_OUTPUT_SEP='' + fi + _HL_SEP=$separator + + # Information line + if [[ $HL_INFO_MODE == 'on' || ($HL_INFO_MODE == 'auto' && $information != $_HL_INFO) || $overwrite == 'true' ]]; then + HL_OUTPUT_INFO=$information + [[ $HL_PRINT_MODE == 'precmd' ]] && print -rP "$HL_OUTPUT_INFO" + else + HL_OUTPUT_INFO='' + fi + _HL_INFO=$information + + # Prompt + if [[ $HL_PRINT_MODE == 'prompt' ]]; then + PROMPT='$(' + (( ${#HL_OUTPUT_SEP} )) && PROMPT+='print -rP "$HL_OUTPUT_SEP"; ' + (( ${#HL_OUTPUT_INFO} )) && PROMPT+='print -rP "$HL_OUTPUT_INFO"; ' + PROMPT+='print -rP "$HL_PROMPT")' + else + PROMPT=$HL_PROMPT + fi + + # Right prompt + if [[ $HL_CLOCK_MODE == 'on' ]]; then + RPROMPT= "**********"=HL_CLOCK_SOURCE})}%{$reset%}$HL_RPROMPT' + else + RPROMPT=$HL_RPROMPT + fi + + _HL_CMD_NUM_PREV=$_HL_CMD_NUM + _HL_AT_TOP='false' +} + fi + + # Right prompt + if [[ $HL_CLOCK_MODE == 'on' ]]; then + RPROMPT='${HL_CLOCK_TEMPLATE/$HL_TEMPLATE_TOKEN/$(eval ${=HL_CLOCK_SOURCE})}%{$reset%}$HL_RPROMPT' + else + RPROMPT=$HL_RPROMPT + fi + + _HL_CMD_NUM_PREV=$_HL_CMD_NUM + _HL_AT_TOP='false' +} diff --git a/seeker/snippet/main.py b/seeker/snippet/main.py new file mode 100644 index 00000000..55668a77 --- /dev/null +++ b/seeker/snippet/main.py @@ -0,0 +1,17 @@ +#date: 2024-12-04T16:56:44Z +#url: https://api.github.com/gists/2e782bb6132502e0c5dffd6bb06ac6cb +#owner: https://api.github.com/users/mypy-play + +from typing import Callable, Sequence, Any, MutableSequence + +def f(x: list[int]) -> None: + x[0] / 10 + +def g(x: list[str]) -> None: + x[0].startswith("a") + +def do_it(fn: Callable[[list[Any]], None]) -> None: + fn([1]) + +do_it(f) +do_it(g) diff --git a/seeker/snippet/python_logging.py b/seeker/snippet/python_logging.py new file mode 100644 index 00000000..adb31042 --- /dev/null +++ b/seeker/snippet/python_logging.py @@ -0,0 +1,27 @@ +#date: 2024-12-04T16:50:44Z +#url: https://api.github.com/gists/fb4ab07058187be34f6cbf7f9fef6c5a +#owner: https://api.github.com/users/tsonntag + +import logging + +# basic +logging.basicConfig(level=logging.ERROR) +logging.info("This is an INFO message.") + +# formatting +logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', +) + +# file +logging.basicConfig( + filename='app.log', +) + +# complex: +logger = logging.getLogger("my_logger") +handler = logging.StreamHandler() +formatter = logging.Formatter('%(levelname)s - %(message)s') +handler.setFormatter(formatter) +handler.setLevel(logging.DEBUG) +logger.addHandler(handler) \ No newline at end of file diff --git a/seeker/snippet/quickstart.py b/seeker/snippet/quickstart.py deleted file mode 100644 index 6e639f9c..00000000 --- a/seeker/snippet/quickstart.py +++ /dev/null @@ -1,28 +0,0 @@ -#date: 2024-12-02T16:58:17Z -#url: https://api.github.com/gists/81ef5bca642ce98b6014ff87f0bbc11a -#owner: https://api.github.com/users/RobSpectre - - -import ldclient -from ldclient.config import Config -from ldclient import Context - -from yourapp import App - -app = App() - -ldclient.set_config(Config('sdk-copy-your-key-here')) - -client = ldclient.get() - -@app.route("/") -def root(): - context = Context.builder('user-id-123abc').kind('user').name('Sandy').set('email', 'sandy@testcorp.com').build() - - flag_value = client.variation("my-first-feature-flag", context, False) - - # If the flag is true, user gets new template. If not, fallback to previous template. - if flag_value == True: - return "new_template.html" - else: - return "old_template.html" \ No newline at end of file diff --git a/seeker/snippet/seeds.py b/seeker/snippet/seeds.py new file mode 100644 index 00000000..82059f91 --- /dev/null +++ b/seeker/snippet/seeds.py @@ -0,0 +1,82 @@ +#date: 2024-12-04T17:00:01Z +#url: https://api.github.com/gists/1a077b9daa4d4c98ac75877466433861 +#owner: https://api.github.com/users/riga + +# coding: utf-8 + +""" +Pseudo code for generating deterministic event and jet seeds, +to be used in random number generators with consistent output. + +The seeds use the entire uint64 space and are proven to be +uniformly distributed using bijective hashing. + +It requires a list of the first 200 primes plus some event +and object level integer (!) quantities. Floats are not used +as any algorithm based on them is intrinsically non-deterministic. +""" + +# first 200 primes, starting at 2 +primes = [...] + +# singular hash function converting int to uint64 +def create_seed(val: int, n_hex: int = 16) -> int: + return int(hashlib.sha256(bytes(str(val), "utf-8")).hexdigest()[:-(n_hex + 1):-1], base=16) + +# +# event seed calculation +# + +# inputs to identifiy the event (order matters!) +# (get() is a placeholder for a retrieval function) +index_inputs = [ + get("event"), get("run"), get("luminosityBlock"), +] + +# event-level inputs, i.e, one number per event (order matters!) +event_inputs = [ + get("Pileup.nPU"), + get("nJet"), get("nFatJet"), get("nSubJet"), + get("nPhoton"), get("nMuon"), get("nElectron"), get("nTau"), + get("nSV"), get("nGenJet"), +] + +# object-level inputs, i.e., one number per object (order matters!) +# (here, each get() would return a list of numbers) +object_inputs = [ + get("Electron.jetIdx"), get("Electron.seediPhiOriY"), + get("Muon.jetIdx"), get("Muon.nStations"), + get("Tau.jetIdx"), get("Tau.decayMode"), + get("Jet.nConstituents"), get("Jet.nElectrons"), get("Jet.nMuons"), +] + +# start by creating a short seed from index inputs +event_seed = create_seed( + index_input[0] * primes[7] + index_input[1] * primes[5] + index_input[2] * primes[3], +) + +# fold with event level info +value_offset = 3 +prime_offset = 15 +for i, inp in enumerate(event_inputs): + inp += i + value_offset + event_seed += primes[(inp + prime_offset) % len(primes)] * inp + +# fold with object level info +for i, inps in enumerate(object_inputs): + inp_sum = 0 + for j, inp in enumerate(inps): + inp += i + value_offset + inp_sum += inp + inp * (j + 1) + inp**2 * (j + 1) + event_seed += primes[(inp_sum + prime_offset) % len(primes)] * inp_sum + +# final seed +event_seed = create_seed(event_seed) # done + +# +# jet seed calculation +# + +for i, jet in enumerate(jets): + jet_seed = event_seed + primes[event_seed % len(primes)] * (i + primes[50]) + jet_seed = create_seed(jet_seed) # done diff --git a/seeker/snippet/server_compare.py b/seeker/snippet/server_compare.py deleted file mode 100644 index d0316e5c..00000000 --- a/seeker/snippet/server_compare.py +++ /dev/null @@ -1,187 +0,0 @@ -#date: 2024-12-02T17:00:26Z -#url: https://api.github.com/gists/62003ca810543ec9d57a8dcecbe1d789 -#owner: https://api.github.com/users/PandeCode - -#!/bin/env python3 -import os -import re - -from fire import Fire -import json5 as json -import matplotlib.pyplot as plt -from numpy import Infinity -from typing import Iterable - -defaultServers: set[str] = { - "1.1.1.1", # Cloudflare - "1.0.0.1", # Cloudflare - "208.67.222.222", # OpenDNS - "208.67.220.220", # OpenDNS - "8.8.4.4", # Google Public DNS ipv4 - "8.8.8.8", # Google Public DNS ipv4 - "9.9.9.11", # Quad9 ECS enabled - "149.112.112.11", # Quad9 ECS enabled - "9.9.9.10", # Quad9 Unsecured: No Malware blocking, no DNSSEC validation - "149.112.112.10", # Quad9 Unsecured: No Malware blocking, no DNSSEC validation - "9.9.9.9", # Quad9 - "149.112.112.112", # Quad9 - "185.228.168.9", # CleanBrowsing - "185.228.169.9", # CleanBrowsing - "185.228.168.168", # CleanBrowsing - "76.76.19.19", # Alternate DNS - "76.223.122.150", # Alternate DNS - "94.140.14.14", # AdGuard DNS - "94.140.15.15", # AdGuard DNS - "176.103.130.130", # AdGuard DNS - "91.239.100.100", # UncensoredDNS - "89.233.43.71", # UncensoredDNS - "84.200.69.80", # DNS.WATCH - "84.200.70.40", # DNS.WATCH - "8.26.56.26", # ComodoSecureDNS - "8.20.247.20", # ComodoSecureDNS - "77.88.8.8", # Yandex.DNS - "77.88.8.7", # Yandex DNS - "77.88.8.1", # Yandex.DNS - "13.239.157.177", # OpenNIC - "172.98.193.42", # OpenNIC - "66.70.228.164", # OpenNIC - "205.171.3.66", # CenturyLink(Level3) - "205.171.202.166", # CenturyLink(Level3) - "195.46.39.39", # SafeDNS - "195.46.39.40", # SafeDNS - "198.101.242.72", # Alternate DNS - "64.6.65.6", # Verisign Public DNS - "74.82.42.42", # HurricaneElectric - "109.69.8.51", # puntCAT - "216.146.35.35", # Dyn - "216.146.36.36", # Dyn - "45.33.97.5", # FreeDNS - "37.235.1.177", # FreeDNS - "64.6.64.6", # Neustar - "64.6.65.6", # Neustar - "45.77.165.194", # FourthEstate - "45.32.36.36", # FourthEstate -} -defaultServers = { "filemoon.sx","streamtape.com","www.mp4upload.com","mcloud.to","vidstream.pro" } - -def main( - old: bool = False, - iterations: int = 10, - servers: Iterable[str] | str = defaultServers, - flash: bool = False, -) -> None: - if type(servers) == str: - servers = servers.split(",") - - output: dict[str, str] = dict() - - if old: - try: - with open(r"./output.json", "r") as f: - output = json.load(f) # type: ignore - except Exception as e: - print("Error: ", e) - output = getData(iterations, writeToFile=True, servers=servers, flash=flash) - - else: - output = getData(iterations, writeToFile=True, servers=servers, flash=flash) - showData(output) - - -def getData( - iterations: int, - servers: Iterable[str] = defaultServers, - writeToFile: bool = False, - flash: bool = False, -) -> dict[str, str]: - - output = dict() - for server in servers: - command = f"ping -A -c {iterations} -i {'0' if flash else '0.2'} {server}" - print(command) - output[server] = os.popen( command).read() - - if writeToFile: - with open("output.json", "w") as file: - json.dump(output, file) - - return output - - -def showData(output: dict[str, str]): - - maxPing = -Infinity - minPing = Infinity - - maxPingHolder = "" - minPingHolder = "" - - maxAveragePing = -Infinity - minAveragePing = Infinity - - maxAveragePingHolder = "" - minAveragePingHolder = "" - - averages: dict[str, float] = {} - mins: dict[str, float] = {} - maxes: dict[str, float] = {} - - for key, value in output.items(): - if not value: - print(key) - data = value.split() - pings: list[float] = [] - - for i in data: - if i.startswith("time="): - pings.append(float(i[5:])) - - byNl = value.split("\n") - maxAvgMinLine = byNl[len(byNl) - 2] - - if not maxAvgMinLine: - continue - thisMax, thisAvg, thisMin, *_ = list( - map(float, re.findall(r"(\d+\.\d+)", maxAvgMinLine)) - ) - - averages[key] = thisAvg - maxes[key] = thisMax - mins[key] = thisMin - - if thisMax > maxPing: - maxPing = thisMax - maxPingHolder = key - if thisMin < minPing: - minPing = thisMin - minPingHolder = key - - if thisAvg > maxAveragePing: - maxAveragePing = thisAvg - maxAveragePingHolder = key - if thisAvg < minAveragePing: - minAveragePing = thisMin - minAveragePingHolder = key - - print(f"{key} {thisAvg} {thisMax} {thisMin}") - - plt.plot( - [i for i in range(1, len(pings) + 1)], pings, label=key, marker="o", - ) - - print(f"Max ping: {maxPing} by {maxPingHolder}") - print(f"Min ping: {minPing} by {minPingHolder}") - print(f"Max Average ping: {maxAveragePing} by {maxAveragePingHolder}") - print(f"Min Average ping: {minAveragePing} by {minAveragePingHolder}") - - plt.xlabel("Run") - plt.ylabel("Ping") - plt.title("Ping against runs") - plt.grid(True) - plt.legend() - - plt.show() - - -if __name__ == "__main__": - Fire(main) diff --git a/seeker/snippet/test.java b/seeker/snippet/test.java new file mode 100644 index 00000000..d86485ed --- /dev/null +++ b/seeker/snippet/test.java @@ -0,0 +1,98 @@ +//date: 2024-12-04T17:09:52Z +//url: https://api.github.com/gists/3b3fb1487c2b2bba023de8f929030509 +//owner: https://api.github.com/users/MichalBrylka + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.time.LocalDate; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BusinessDayCalculatorTest { + + static Stream<Arguments> previousBusinessDayTestData() { + return Stream.of( + Arguments.of(LocalDate.of(2024, 12, 2), LocalDate.of(2024, 11, 29)), // Monday -> Friday + Arguments.of(LocalDate.of(2024, 12, 9), LocalDate.of(2024, 12, 6)), // Monday -> Friday + Arguments.of(LocalDate.of(2024, 12, 5), LocalDate.of(2024, 12, 4)) // Thursday -> Wednesday + ); + } + + static Stream<Arguments> nextBusinessDayTestData() { + return Stream.of( + Arguments.of(LocalDate.of(2024, 11, 29), LocalDate.of(2024, 12, 2)), // Friday -> Monday + Arguments.of(LocalDate.of(2024, 12, 6), LocalDate.of(2024, 12, 9)), // Friday -> Monday + Arguments.of(LocalDate.of(2024, 12, 4), LocalDate.of(2024, 12, 5)) // Wednesday -> Thursday + ); + } + + static Stream<Arguments> previousBusinessDaysTestData() { + return Stream.of( + Arguments.of(LocalDate.of(2024, 12, 6), Stream.of( + LocalDate.of(2024, 12, 5), + LocalDate.of(2024, 12, 4), + LocalDate.of(2024, 12, 3), + LocalDate.of(2024, 12, 2), + LocalDate.of(2024, 11, 29) + )), + Arguments.of(LocalDate.of(2024, 12, 9), Stream.of( + LocalDate.of(2024, 12, 6), + LocalDate.of(2024, 12, 5), + LocalDate.of(2024, 12, 4), + LocalDate.of(2024, 12, 3), + LocalDate.of(2024, 12, 2) + )) + ); + } + + static Stream<Arguments> nextBusinessDaysTestData() { + return Stream.of( + Arguments.of(LocalDate.of(2024, 12, 6), Stream.of( + LocalDate.of(2024, 12, 9), + LocalDate.of(2024, 12, 10), + LocalDate.of(2024, 12, 11), + LocalDate.of(2024, 12, 12), + LocalDate.of(2024, 12, 13) + )), + Arguments.of(LocalDate.of(2024, 12, 4), Stream.of( + LocalDate.of(2024, 12, 5), + LocalDate.of(2024, 12, 6), + LocalDate.of(2024, 12, 9), + LocalDate.of(2024, 12, 10), + LocalDate.of(2024, 12, 11) + )) + ); + } + + @ParameterizedTest + @MethodSource("previousBusinessDayTestData") + @DisplayName("Test previousBusinessDay method") + void testPreviousBusinessDay(LocalDate input, LocalDate expected) { + assertEquals(expected, BusinessDayCalculator.previousBusinessDay(input)); + } + + @ParameterizedTest + @MethodSource("nextBusinessDayTestData") + @DisplayName("Test nextBusinessDay method") + void testNextBusinessDay(LocalDate input, LocalDate expected) { + assertEquals(expected, BusinessDayCalculator.nextBusinessDay(input)); + } + + @ParameterizedTest + @MethodSource("previousBusinessDaysTestData") + @DisplayName("Test previousBusinessDays method") + void testPreviousBusinessDays(LocalDate input, Stream<LocalDate> expectedStream) { + assertEquals(expectedStream.toList(), BusinessDayCalculator.previousBusinessDays(input).limit(5).toList()); + } + + @ParameterizedTest + @MethodSource("nextBusinessDaysTestData") + @DisplayName("Test nextBusinessDays method") + void testNextBusinessDays(LocalDate input, Stream<LocalDate> expectedStream) { + assertEquals(expectedStream.toList(), BusinessDayCalculator.nextBusinessDays(input).limit(5).toList()); + } +} diff --git a/seeker/snippet/tmux-sessionizer.sh b/seeker/snippet/tmux-sessionizer.sh deleted file mode 100644 index 8f27da01..00000000 --- a/seeker/snippet/tmux-sessionizer.sh +++ /dev/null @@ -1,53 +0,0 @@ -#date: 2024-12-02T16:52:02Z -#url: https://api.github.com/gists/24f0703c321706710d1b46b1ae71713b -#owner: https://api.github.com/users/vivalchemy - -#!/usr/bin/env bash - -include_dirs=( - "$HOME/dotfiles" - "$HOME/dotfiles/roles/" - "$HOME/.local/bin" -) - -tmuxifier_sessions=$(tmuxifier list-sessions) - -if command -v fd &> /dev/null; then - search_cmd="fd . --type=directory --max-depth=1 " -else - search_cmd="find -mindepth 1 -maxdepth 1 -type d" -fi - -if [[ $# -eq 1 ]]; then - selected=$1 -else - selected=$($search_cmd ~/Projects ~/Public | cat - <(echo -e "${include_dirs[@]} ${tmuxifier_sessions}" | tr " " "\n") | fzf --tmux center,50%,40%) -fi - -if [[ -z $selected ]]; then - exit 0 -fi - -tmuxifier_file_template="${TMUXIFIER_LAYOUT_PATH:-$(which tmuxifier)/layouts}/${selected}.session.sh" -tmux_running=$(pgrep tmux) - -if [[ -e $tmuxifier_file_template ]]; then - tmuxifier load-session ${selected} -fi - -selected_name=$(basename "$selected" | tr . _) - -if [[ -z $TMUX ]] && [[ -z $tmux_running ]]; then - tmux new-session -s $selected_name -c $selected - exit 0 -fi - -if ! tmux has-session -t=$selected_name 2> /dev/null; then - tmux new-session -ds $selected_name -c $selected -fi - -if [[ -z $TMUX ]]; then - tmux attach -t $selected_name -else - tmux switch-client -t $selected_name -fi diff --git a/seeker/snippet/tmux.conf b/seeker/snippet/tmux.conf new file mode 100644 index 00000000..790f172f --- /dev/null +++ b/seeker/snippet/tmux.conf @@ -0,0 +1,49 @@ +#date: 2024-12-04T16:54:06Z +#url: https://api.github.com/gists/f629097db1c9092f1a9a0c8dcc42bafa +#owner: https://api.github.com/users/covertivy + +# Fix shitty copy mode +set-option -g mouse on +set-option -g mode-keys vi +set-option -s set-clipboard off + +bind P paste-buffer +bind-key -T copy-mode-vi v send-keys -X begin-selection +bind-key -T copy-mode-vi y send-keys -X rectangle-toggle + +unbind -T copy-mode-vi Enter +bind-key -T copy-mode-vi Enter send-keys -X copy-pipe-and-cancel 'xclip -se c -i' +bind-key -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel 'xclip -se c -i' + +# Set new panes to open in current directory +bind c new-window -c "#{pane_current_path}" +bind '"' split-window -c "#{pane_current_path}" +bind % split-window -h -c "#{pane_current_path}" + +# Set up tmux plugins +set -g @plugin 'tmux-plugins/tpm' +set -g @plugin 'tmux-plugins/tmux-sensible' +set -g @plugin 'tmux-plugins/tmux-resurrect' +set -g @plugin 'catppuccin/tmux#latest' + +## Catppuccin Settings +set -g @catppuccin_window_left_separator "" +set -g @catppuccin_window_right_separator " " +set -g @catppuccin_window_middle_separator " █" +set -g @catppuccin_window_number_position "right" + +set -g @catppuccin_window_default_fill "number" +set -g @catppuccin_window_default_text "#W" + +set -g @catppuccin_window_current_fill "number" +set -g @catppuccin_window_current_text "#W" + +set -g @catppuccin_status_modules_right "directory user host session" +set -g @catppuccin_status_left_separator " " +set -g @catppuccin_status_right_separator "" +set -g @catppuccin_status_fill "icon" +set -g @catppuccin_status_connect_separator "no" + +set -g @catppuccin_directory_text "#{pane_current_path}" + +run '~/.tmux/plugins/tpm/tpm' \ No newline at end of file