From df694999879315997f35ae6d6b659079a6186bf7 Mon Sep 17 00:00:00 2001 From: eduardocerqueira Date: Tue, 20 Aug 2024 17:12:29 +0000 Subject: [PATCH] 2024-08-20 17:12:29.821398 new snippets --- seeker/report.txt | 23 +++ seeker/snippet/dedup_roaster.py | 55 ++++++ seeker/snippet/file_to_env.sh | 5 + seeker/snippet/hw_m4_fake_math.py | 9 + seeker/snippet/hw_m4_true_math.py | 9 + seeker/snippet/hw_module_4_1.py | 15 ++ seeker/snippet/install-java.command | 38 ++++ seeker/snippet/lab2.py | 32 ++++ seeker/snippet/lem2gtif.py | 140 ++++++++++++++ seeker/snippet/lulu.py | 92 +++++++++ seeker/snippet/new_PD.py | 157 +++++++++++++++ seeker/snippet/rockpaperscissors_infinite.py | 180 ++++++++++++++++++ .../sagemaker_studio_lifecycle_config.sh | 122 ++++++++++++ 13 files changed, 877 insertions(+) create mode 100644 seeker/snippet/dedup_roaster.py create mode 100644 seeker/snippet/file_to_env.sh create mode 100644 seeker/snippet/hw_m4_fake_math.py create mode 100644 seeker/snippet/hw_m4_true_math.py create mode 100644 seeker/snippet/hw_module_4_1.py create mode 100644 seeker/snippet/install-java.command create mode 100644 seeker/snippet/lab2.py create mode 100644 seeker/snippet/lem2gtif.py create mode 100644 seeker/snippet/lulu.py create mode 100644 seeker/snippet/new_PD.py create mode 100644 seeker/snippet/rockpaperscissors_infinite.py create mode 100644 seeker/snippet/sagemaker_studio_lifecycle_config.sh diff --git a/seeker/report.txt b/seeker/report.txt index 40d8526f..d1459ab3 100644 --- a/seeker/report.txt +++ b/seeker/report.txt @@ -1,3 +1,26 @@ +-------------------------------------------------------------------------------- + 2024-08-20 17:12:29.821398 +-------------------------------------------------------------------------------- + On branch main +Your branch is up to date with 'origin/main'. + +Untracked files: + (use "git add ..." to include in what will be committed) + snippet/dedup_roaster.py + snippet/file_to_env.sh + snippet/hw_m4_fake_math.py + snippet/hw_m4_true_math.py + snippet/hw_module_4_1.py + snippet/install-java.command + snippet/lab2.py + snippet/lem2gtif.py + snippet/lulu.py + snippet/new_PD.py + snippet/rockpaperscissors_infinite.py + snippet/sagemaker_studio_lifecycle_config.sh + +nothing added to commit but untracked files present (use "git add" to track) + -------------------------------------------------------------------------------- 2024-08-19 17:13:16.613524 -------------------------------------------------------------------------------- diff --git a/seeker/snippet/dedup_roaster.py b/seeker/snippet/dedup_roaster.py new file mode 100644 index 00000000..cda6e491 --- /dev/null +++ b/seeker/snippet/dedup_roaster.py @@ -0,0 +1,55 @@ +#date: 2024-08-20T16:46:29Z +#url: https://api.github.com/gists/5ad11d4d71544e6eeb18901f262328ca +#owner: https://api.github.com/users/datageek19 + +import pandas as pd +import glob +import os + +# Step 1: List all relevant CSV files +files = glob.glob("UHCCS-1-z-*.csv") # Adjust the pattern to match your files + +# Step 2: Create a dictionary to group files by month +file_groups = {} +for file in files: + # Extract the date part from the filename + date_part = os.path.basename(file).split('-')[-3:] # Extract the '01-03-2024' part + month_year = '-'.join(date_part[1:]) # Extract '03-2024' + + # Group files by month-year + if month_year not in file_groups: + file_groups[month_year] = [] + file_groups[month_year].append(file) + +# Step 3: Process each group of files +for month_year, file_list in file_groups.items(): + # Read all files for the given month into a DataFrame + month_df_list = [pd.read_csv(f) for f in file_list] + combined_df = pd.concat(month_df_list, ignore_index=True) + + # Step 4: Check for duplicates based on First_Name, Last_Name, Birthdate + duplicates = combined_df.duplicated(subset=['First_Name', 'Last_Name', 'Birthdate'], keep=False) + duplicates_df = combined_df[duplicates] + + # Print or save the duplicates found for this month + print(f"Duplicates for {month_year}:") + print(duplicates_df) + + # Optional: Save duplicates to a CSV file + # duplicates_df.to_csv(f'duplicates_{month_year}.csv', index=False) +# +++++++++++++++++++++++++++ +import dask.dataframe as dd + +combined_df = dd.concat([dd.read_csv(f) for f in file_list]) +duplicates_df = combined_df[combined_df.duplicated(subset=['First_Name', 'Last_Name', 'Birthdate'], keep=False)].compute() + +import dask.dataframe as dd + +combined_df = dd.concat([dd.read_csv(f) for f in file_list]) +duplicates_df = combined_df[combined_df.duplicated(subset=['First_Name', 'Last_Name', 'Birthdate'], keep=False)].compute() + + +writer = pd.ExcelWriter('duplicate_report.xlsx', engine='xlsxwriter') +for month_year, duplicates_df in all_duplicates.items(): + duplicates_df.to_excel(writer, sheet_name=month_year, index=False) +writer.save() diff --git a/seeker/snippet/file_to_env.sh b/seeker/snippet/file_to_env.sh new file mode 100644 index 00000000..d4be4d3e --- /dev/null +++ b/seeker/snippet/file_to_env.sh @@ -0,0 +1,5 @@ +#date: 2024-08-20T17:11:25Z +#url: https://api.github.com/gists/f8c8885b6c29d8968184402b47914f5c +#owner: https://api.github.com/users/kaedonkers + +API_KEY=`cat ~/path/to/apikey_file` && export API_KEY \ No newline at end of file diff --git a/seeker/snippet/hw_m4_fake_math.py b/seeker/snippet/hw_m4_fake_math.py new file mode 100644 index 00000000..b45fd718 --- /dev/null +++ b/seeker/snippet/hw_m4_fake_math.py @@ -0,0 +1,9 @@ +#date: 2024-08-20T16:51:02Z +#url: https://api.github.com/gists/84b82cfd4ac148cd130e16cffe06af02 +#owner: https://api.github.com/users/PavelYar-1 + +def divide(first, second): + if second == 0: + return 'Ошибка' + else: + return first / second \ No newline at end of file diff --git a/seeker/snippet/hw_m4_true_math.py b/seeker/snippet/hw_m4_true_math.py new file mode 100644 index 00000000..82e9d6cc --- /dev/null +++ b/seeker/snippet/hw_m4_true_math.py @@ -0,0 +1,9 @@ +#date: 2024-08-20T16:51:02Z +#url: https://api.github.com/gists/84b82cfd4ac148cd130e16cffe06af02 +#owner: https://api.github.com/users/PavelYar-1 + +def divide (first, second): + if second == 0: + return 'inf' + else: + return first / second \ No newline at end of file diff --git a/seeker/snippet/hw_module_4_1.py b/seeker/snippet/hw_module_4_1.py new file mode 100644 index 00000000..e4c573b8 --- /dev/null +++ b/seeker/snippet/hw_module_4_1.py @@ -0,0 +1,15 @@ +#date: 2024-08-20T16:49:51Z +#url: https://api.github.com/gists/57c4aae920934d9c7d78a2b1df6de13c +#owner: https://api.github.com/users/PavelYar-1 + +from hw_m4_fake_math import divide as fake +from hw_m4_true_math import divide as true + +result1 = fake(69, 3) +result2 = fake(3, 0) +result3 = true(49, 7) +result4 = true(15, 0) +print(result1) +print(result2) +print(result3) +print(result4) \ No newline at end of file diff --git a/seeker/snippet/install-java.command b/seeker/snippet/install-java.command new file mode 100644 index 00000000..ba232acb --- /dev/null +++ b/seeker/snippet/install-java.command @@ -0,0 +1,38 @@ +#date: 2024-08-20T16:45:31Z +#url: https://api.github.com/gists/ff44e7ad3f67fc5b59a5fde56ba0f1ef +#owner: https://api.github.com/users/ankitahuja0508 + +# Function to check if a value is an integer +is_integer() { + [ "$1" -eq "$1" ] 2>/dev/null +} + +# Remove any existing JAVA_HOME entries in .zshrc +echo "Removing old JAVA_HOME if any..." +sed -i '' '/export JAVA_HOME=/d' ~/.zshrc + +# Check if an argument is passed (the Java version) +if [ -n "$1" ]; then + # Check if the argument is an integer + if is_integer "$1"; then + echo "Installing Oracle JDK version $1..." + brew install oracle-jdk@$1 --cask + echo "setting JAVA_HOME for version $1..." + echo export "JAVA_HOME=\$(/usr/libexec/java_home -v $1)" >> ~/.zshrc + else + echo "Error: The argument '$1' is not an integer. Please provide a valid Java version number." >&2 + exit 1 + fi +else + echo "Installing the latest Oracle JDK..." + brew install oracle-jdk --cask + echo "setting JAVA_HOME for the latest version..." + echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.zshrc +fi + +# Apply changes to .zshrc +source ~/.zshrc + +# Check Java version +echo "checking java version" +java -version \ No newline at end of file diff --git a/seeker/snippet/lab2.py b/seeker/snippet/lab2.py new file mode 100644 index 00000000..b456dccc --- /dev/null +++ b/seeker/snippet/lab2.py @@ -0,0 +1,32 @@ +#date: 2024-08-20T16:54:43Z +#url: https://api.github.com/gists/b65cd558432b4ceb4707b9180c09ca7e +#owner: https://api.github.com/users/sydseats + +#Class :CSE 1321L +#Term: fall semester +#Instructor: +#Name: Sydney Green +#Lab: 2a +name =input('enter a name:') +name2=input('enter another name:') +verb =input('enter a verb:') +adverb=input('enter an adverb:') +print ('Once upon a time, there was a person named ' + name + ' and they had a friend named ' + name2 +'.' + ' This friend would ' + verb + " " + adverb + ' while complaining to other people.') + +#lab2b +print('___*___') +print('__*_*__') +print('_*_*_*_') +print('*_*_*_*') +print('_*_*_*_') +print('__*_*__') +print('___*___') + + + +width = float (input( "Enter a width: ")) +height = float (input("Enter a height: ")) +area = (height * width ) +perimeter = (width + height) * 2 +print ("The area is",area) +print ("The perimeter is",perimeter) diff --git a/seeker/snippet/lem2gtif.py b/seeker/snippet/lem2gtif.py new file mode 100644 index 00000000..c12d3075 --- /dev/null +++ b/seeker/snippet/lem2gtif.py @@ -0,0 +1,140 @@ +#date: 2024-08-20T16:46:10Z +#url: https://api.github.com/gists/e418fe42d33f953ac4a0d0cea933b18d +#owner: https://api.github.com/users/todashuta + +import os +import re +import glob +import time +from osgeo import (gdal, osr) +import numpy as np + + +""" +lem ファイルを GeoTIFF に変換するスクリプトです。 + +lem ファイルの仕様 +https://www.gsi.go.jp/MAP/CD-ROM/dem5m/doc/info5m1.htm + + +(現時点では) lem2gtif.py が存在するフォルダ内の lem ファイルを +GeoTIFF に変換するようになっているので、このファイルを対象の +フォルダにコピーし、実行してください。 +""" + + + +def main(): + # lem2gtif.py と同じフォルダ内に存在する lem ファイルを走査 + basedir = os.path.dirname(os.path.abspath(__file__)) + for lem_filepath in glob.glob(os.path.join(basedir, '*.lem')): + try: + # lem ファイルを GeoTIFF に変換 + lem_to_gtif(lem_filepath) + except (ValueError, FileNotFoundError) as err: + print(f"Error: {err}") + print() + + + +def lem_to_gtif(lem_filepath): + if not re.search(r'\.lem$', lem_filepath): + raise ValueError("lem ファイル以外が指定されました。") + + # lem ファイルと同じ場所に csv 形式のヘッダファイルがあるはず + csv_filepath = re.sub(r'\.lem$', '.csv', lem_filepath) + # lem ファイルと同じ場所に変換した TIFF ファイルを出力する + tif_filepath = re.sub(r'\.lem$', '.tif', lem_filepath) + + lem_filename = os.path.basename(lem_filepath) + csv_filename = os.path.basename(csv_filepath) + tif_filename = os.path.basename(tif_filepath) + + now = time.strftime('%H:%M:%S', time.localtime()) + print(f"[{now}] convert to {tif_filename}") + + # ファイルが存在しているかチェック + if not os.path.exists(lem_filepath): + raise FileNotFoundError(f"{lem_filename} がみつかりません。") + if not os.path.exists(csv_filepath): + raise FileNotFoundError(f"{csv_filename} がみつかりません。") + + # ヘッダファイルを読み取る + header = read_header_file(csv_filepath) + if header is None: + raise ValueError(f"{csv_filename} のパースに失敗しました。") + + # GeoTIFF ファイル作成 + srs = osr.SpatialReference() + srs.ImportFromEPSG(header['crs']) + driver = gdal.GetDriverByName('GTiff') + raster = driver.Create(tif_filepath, header['cols'], header['rows'], 1, gdal.GDT_Float32) + raster.SetGeoTransform((header['left'], header['xres'], 0, header['top'], 0, -header['yres'])) + raster.SetProjection(srs.ExportToWkt()) + band = raster.GetRasterBand(1) + band.SetNoDataValue(-9999.0) + + with open(lem_filepath) as lem_f: + row = 0 + # lem ファイルから1行読み取り、 GeoTIFF ファイルに1行書き込む + for line in lem_f: + line = line.replace('-1111', '-9999') + array = np.array([[-9999.0 if line[5*i+10:5*i+15] == '-9999' else int(line[5*i+10:5*i+15])/10 for i in range(header['cols'])]]) + band.WriteArray(array, yoff=row) + row += 1 + band.FlushCache() + + + +def read_header_file(csv_filepath): + csv_filename = os.path.basename(csv_filepath) + header = {} + + # ヘッダファイルを読み込む + with open(csv_filepath, 'r', encoding='cp932') as f: + for line in f: + k, v = line.strip().split(',') + if k == '東西方向の点数': + header['cols'] = int(v) + elif k == '南北方向の点数': + header['rows'] = int(v) + elif k == '東西方向のデータ間隔': + header['xres'] = float(v) + elif k == '南北方向のデータ間隔': + header['yres'] = float(v) + elif k == '平面直角座標系番号' or k == '座標系番号': + header['crs'] = int(v) + 6668 + elif k == '区画左下X座標' or k == '区画左下X座標': + header['bottom'] = int(v) / 100 + elif k == '区画左下Y座標' or k == '区画左下Y座標': + header['left'] = int(v) / 100 + elif k == '区画右上X座標' or k == '区画右上X座標': + header['top'] = int(v) / 100 + elif k == '区画右上Y座標' or k == '区画右上Y座標': + header['right'] = int(v) / 100 + + # 必要な情報が読み取れなかったら例外を投げる + if 'cols' not in header: + raise ValueError(f"{csv_filename} に「東西方向の点数」がありません。") + if 'rows' not in header: + raise ValueError(f"{csv_filename} に「南北方向の点数」がありません。") + if 'xres' not in header: + raise ValueError(f"{csv_filename} に「東西方向のデータ間隔」がありません。") + if 'yres' not in header: + raise ValueError(f"{csv_filename} に「南北方向のデータ間隔」がありません。") + if 'crs' not in header: + raise ValueError(f"{csv_filename} に「座標系番号」がありません。") + if 'bottom' not in header: + raise ValueError(f"{csv_filename} に「区画左下X座標」がありません。") + if 'left' not in header: + raise ValueError(f"{csv_filename} に「区画左下Y座標」がありません。") + if 'top' not in header: + raise ValueError(f"{csv_filename} に「区画右上X座標」がありません。") + if 'right' not in header: + raise ValueError(f"{csv_filename} に「区画右上Y座標」がありません。") + + return header + + + +main() \ No newline at end of file diff --git a/seeker/snippet/lulu.py b/seeker/snippet/lulu.py new file mode 100644 index 00000000..9a3b1657 --- /dev/null +++ b/seeker/snippet/lulu.py @@ -0,0 +1,92 @@ +#date: 2024-08-20T17:06:22Z +#url: https://api.github.com/gists/a1eabdbf295b1a69733f86d5f3c52e20 +#owner: https://api.github.com/users/eduluzufop + +import json +import torch +from tqdm import tqdm +import pandas as pd +from datasets import Dataset +from transformers import AutoTokenizer, AutoModelForMaskedLM +from transformers import Trainer, TrainingArguments + +# Verificar se GPU está disponível +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +paragrafos_espiritas = [] + +# Carregar o arquivo 'paragrafos_livrosKardec.json' +with open('paragrafos_livrosKardec.json', 'r', encoding='utf-8') as f: + paragrafos = json.load(f) + +# Atualizar cada parágrafo com a propriedade 'textoOriginal' +for par_id, par_data in tqdm(paragrafos.items(), desc="Atualizando parágrafos", unit="parágrafo"): + text = par_data['textoOriginal'] + categoriaDoTexto = par_data['categoriaDoTexto'] + if categoriaDoTexto in ['nota', 'item', 'texto']: + paragrafos_espiritas.append(text) + +# Criar um DataFrame com os parágrafos +df = pd.DataFrame(paragrafos_espiritas, columns=['text']) +df.to_csv('dataFrameKardec.csv', index=False) +dataset = Dataset.from_pandas(df) + +# Carregar o tokenizer e modelo BERT +tokenizer = "**********" +model = AutoModelForMaskedLM.from_pretrained('neuralmind/bert-large-portuguese-cased').to(device) + +# Função de tokenização e aplicação de máscara + "**********"d "**********"e "**********"f "**********" "**********"t "**********"o "**********"k "**********"e "**********"n "**********"i "**********"z "**********"e "**********"_ "**********"f "**********"u "**********"n "**********"c "**********"t "**********"i "**********"o "**********"n "**********"( "**********"e "**********"x "**********"a "**********"m "**********"p "**********"l "**********"e "**********"s "**********") "**********": "**********" + outputs = "**********"="max_length", truncation=True, max_length=512, return_tensors="pt") + + # Movendo os tensores para a GPU + outputs = {key: value.to(device) for key, value in outputs.items()} + + # Garantir que 'labels' seja uma cópia de 'input_ids' + outputs["labels"] = outputs["input_ids"].clone() + + # Criar máscaras aleatórias para a tarefa de MLM + probability_matrix = torch.full(outputs["labels"].shape, 0.15, device=device) + special_tokens_mask = "**********" + tokenizer.get_special_tokens_mask(val, already_has_special_tokens= "**********" + ] + special_tokens_mask = "**********"=torch.bool, device=device) + probability_matrix.masked_fill_(special_tokens_mask, value= "**********" + masked_indices = torch.bernoulli(probability_matrix).bool() + outputs["labels"][~masked_indices] = "**********" + + # Máscara os tokens que foram marcados + outputs["input_ids"][masked_indices] = "**********" + + return {key: value.cpu().numpy() for key, value in outputs.items()} # Retorna os dados para CPU para evitar problemas de incompatibilidade + +# Aplicar a tokenização com as máscaras +tokenized_dataset = "**********"=True) + +# Configurar os argumentos de treinamento +training_args = TrainingArguments( + output_dir="./bert-finetuned-espirita", + overwrite_output_dir=True, + num_train_epochs=5, + per_device_train_batch_size=8, + per_device_eval_batch_size=8, + save_steps=500, + evaluation_strategy="steps", + eval_steps=500, + save_total_limit=3, + logging_dir='./logs', + logging_steps=100, + load_best_model_at_end=True, + resume_from_checkpoint=True, +) + +# Configurar o trainer +trainer = Trainer( + model=model, + args=training_args, + train_dataset= "**********" + eval_dataset= "**********" +) + +# Iniciar o treinamento +trainer.train() diff --git a/seeker/snippet/new_PD.py b/seeker/snippet/new_PD.py new file mode 100644 index 00000000..1bb799d9 --- /dev/null +++ b/seeker/snippet/new_PD.py @@ -0,0 +1,157 @@ +#date: 2024-08-20T17:09:41Z +#url: https://api.github.com/gists/e86d825d0afb42eaae80163ee40a858d +#owner: https://api.github.com/users/beccajek + +import cv2 +import numpy as np +import tflite_runtime.interpreter as tflite +from picamera2 import Picamera2 +import RPi.GPIO as GPIO +import time +import logging +from flask import Flask, render_template, Response + +# Initialize Flask app +app = Flask(__name__) + +logging.basicConfig(filename='/home/beccajekogian/person_detection_good.log', level=logging.INFO, + format='%(asctime)s:%(levelname)s:%(message)s') + +# Load the TFLite model +interpreter = tflite.Interpreter(model_path="detect.tflite", num_threads=4) +interpreter.allocate_tensors() + +# Get input and output tensors +input_details = interpreter.get_input_details() +output_details = interpreter.get_output_details() + +# Initialize camera +cap = cv2.VideoCapture(0) # 0 is usually the default for the first USB camera +cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) +cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) + +# Allow time for camera to initialize +time.sleep(2) + +# GPIO setup +GPIO.setmode(GPIO.BCM) +door1Out = 14 +GPIO.setup(door1Out, GPIO.OUT, initial=GPIO.HIGH) +door2Out = 24 +GPIO.setup(door2Out, GPIO.OUT, initial=GPIO.HIGH) +detectionOut = 18 +GPIO.setup(detectionOut, GPIO.OUT, initial=GPIO.HIGH) + +doorOne_check = False +doorTwo_check = False + +door1In = 15 +door2In = 23 + +def Door1Trigger(channel): + global doorOne_check + global door_1_start_time + GPIO.output(door1Out, GPIO.HIGH) + door_1_start_time = time.time() + print("Door 1 opened! Checking for people...") + logging.info("Door 1 opened! Checking for people...") + doorOne_check = True + +GPIO.setup(door1In, GPIO.IN, pull_up_down=GPIO.PUD_UP) +GPIO.add_event_detect(door1In, GPIO.FALLING, callback=Door1Trigger, bouncetime=200) + +def Door2Trigger(channel): + global doorTwo_check + global door_2_start_time + GPIO.output(door2Out, GPIO.HIGH) + door_2_start_time = time.time() + print("Door 2 opened! Checking for people...") + logging.info("Door 2 opened! Checking for people...") + doorTwo_check = True + +GPIO.setup(door2In, GPIO.IN, pull_up_down=GPIO.PUD_UP) +GPIO.add_event_detect(door2In, GPIO.FALLING, callback=Door2Trigger, bouncetime=200) + +def detect_person(image): + image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + input_shape = input_details[0]['shape'] + input_data = cv2.resize(image, (input_shape[1], input_shape[2])) + input_data = np.expand_dims(input_data, axis=0) + if input_details[0]['dtype'] == np.uint8: + input_data = input_data.astype(np.uint8) + else: + input_data = (np.float32(input_data) - 127.5) / 127.5 + interpreter.set_tensor(input_details[0]['index'], input_data) + interpreter.invoke() + boxes = interpreter.get_tensor(output_details[0]['index'])[0] + classes = interpreter.get_tensor(output_details[1]['index'])[0] + scores = interpreter.get_tensor(output_details[2]['index'])[0] + person_detections = [(box, score) for box, class_id, score in zip(boxes, classes, scores) + if class_id == 0 and score > 0.3] + return person_detections + +def generate_frames(): + while True: + ret, frame = cap.read() + if not ret: + logging.info("Failed to grab frame") + continue + + detections = detect_person(frame) + + if detections: + GPIO.output(detectionOut, GPIO.LOW) + logging.info("Person detected!") + for box, score in detections: + ymin, xmin, ymax, xmax = box + (left, right, top, bottom) = (xmin * 640, xmax * 640, ymin * 480, ymax * 480) + frame = cv2.rectangle(frame, (int(left), int(top)), (int(right), int(bottom)), (0, 255, 0), 2) + + else: + GPIO.output(detectionOut, GPIO.HIGH) + logging.info("No one detected.") + + ret, buffer = cv2.imencode('.jpg', frame) + frame = buffer.tobytes() + yield (b'--frame\r\n' + b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') + + if doorOne_check: + if (time.time() - door_1_start_time) > 0.25: + if detections: + GPIO.output(door1Out, GPIO.LOW) + logging.info("Person detected in one! Door1out LOW.") + else: + logging.info("No one in one! Door1out HIGH.") + GPIO.output(door1Out, GPIO.HIGH) + doorOne_check = False + + if doorTwo_check: + if (time.time() - door_2_start_time) > 0.25: + if detections: + GPIO.output(door2Out, GPIO.LOW) + logging.info("Person detected in two! Door2out LOW.") + else: + logging.info("No one in two! Door2out HIGH.") + GPIO.output(door2Out, GPIO.HIGH) + doorTwo_check = False + +@app.route('/video_feed') +def video_feed(): + return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') + +@app.route('/') +def index(): + return render_template('index.html') + +if __name__ == '__main__': + try: + app.run(host='0.0.0.0', port=5000) + except KeyboardInterrupt: + logging.info("Program stopped by user") + except Exception as e: + logging.error(f"An error occurred: {e}") + time.sleep(10) + finally: + cap.release() + GPIO.cleanup() \ No newline at end of file diff --git a/seeker/snippet/rockpaperscissors_infinite.py b/seeker/snippet/rockpaperscissors_infinite.py new file mode 100644 index 00000000..1f4b733f --- /dev/null +++ b/seeker/snippet/rockpaperscissors_infinite.py @@ -0,0 +1,180 @@ +#date: 2024-08-20T17:06:04Z +#url: https://api.github.com/gists/a85000e3c4e4d20d491aa5baf55522bb +#owner: https://api.github.com/users/blockchain200 + +import random + +def invalid_item(): + print("Invalid item. Terminating...") + +items = { + 'A': "asteroid", + 'B': "ball", + 'C': "cake", + 'D': "door", + 'E': "elephant", + 'F': "finger", + 'G': "gun", + 'H': "hacker", + 'I': "igloo", + 'J': "janitor", + 'K': "knowledge", + 'L': "lol", + 'M': "mettaton", + 'N': "null", + 'O': "opp", + 'P': "paper", + 'Q': "croissant", + 'R': "rock", + 'S': "scissors", + 'T': "taxonomy", + 'U': "ukelele", + 'V': "vigilant", + 'W': "wash-your-hands", + 'X': "x? what kinda word starts with the letter x?", + 'Y': "yes", + 'Z': "zebra" +} + +print("\n".join(f"{k} - {v}" for k, v in items.items())) + +current_item_rand = random.choice(["ROCK", "PAPER", "SCISSORS"]) + +print(f"{current_item_rand} vs: ", end="") + +input_char = input().strip().upper() + +match input_char: + case 'R': + match current_item_rand: + case "ROCK": + print("ROCK and ROCK... They both got a rock-er.") + case "PAPER": + print("PAPER suffocates the soul out of ROCK!") + case "SCISSORS": + print("ROCK smashes the shit out of SCISSORS!") + + case 'P': + match current_item_rand: + case "ROCK": + print("PAPER suffocates the soul out of ROCK!") + case "PAPER": + print("PAPER and PAPER... They kiss.") + case "SCISSORS": + print("SCISSORS slice up PAPER into bits.") + + case 'S': + match current_item_rand: + case "ROCK": + print("ROCK smashes the shit out of SCISSORS!") + case "PAPER": + print("SCISSORS slice up PAPER into bits.") + case "SCISSORS": + print("SCISSORS and SCISSORS... They made out.") + + case 'A': + match current_item_rand: + case "ROCK": + print("ASTEROID crushes ROCK with its mighty force!") + case "PAPER": + print("PAPER summons Death By A Thousand Cuts and cuts ASTEROID to death!") + case "SCISSORS": + print("SCISSORS cut ASTEROID in half, but got shattered in the process. It's a tie.") + + case 'B': + match current_item_rand: + case "ROCK": + print("BALL bounced up and down, making ROCK vomit from the nausea.") + case "PAPER": + print("PAPER was able to catch BALL while it was bouncing!") + case "SCISSORS": + print("SCISSORS popped BALL like a balloon!") + + case 'C': + match current_item_rand: + case "ROCK": + print("ROCK destroys the CAKE!") + case "PAPER": + print("PAPER covers the CAKE, but it's too delicious to resist!") + case "SCISSORS": + print("SCISSORS slice the CAKE into perfect pieces!") + + case 'D': + match current_item_rand: + case "ROCK": + print("DOOR made a squeaky sound when it opened and ruptured ROCK's ears!") + case "PAPER": + print("PAPER slid under the DOOR and escaped!") + case "SCISSORS": + print("SCISSORS drew (scratched) a smiley face on the DOOR, and DOOR got embarrassed!") + + case 'E': + match current_item_rand: + case "ROCK": + print("ELEPHANT turned ROCK into dust by stepping on it!") + case "PAPER": + print("PAPER got lost in the ELEPHANT's hair molecules!") + case "SCISSORS": + print("ELEPHANT's nails were groomed by SCISSORS!") + + case 'F': + match current_item_rand: + case "ROCK": + print("FINGER went into ROCK's ass!") + case "PAPER": + print("FINGER stabbed PAPER and left a big hole!") + case "SCISSORS": + print("SCISSORS cut off FINGER's head like a carrot!") + + case 'G': + match current_item_rand: + case "ROCK": + print("ROCK destroys the gun!") + case "PAPER": + print("GUN shoots through the PAPER!") + case "SCISSORS": + print("SCISSORS deflected the GUN's bullet!") + + case 'H': + match current_item_rand: + case "ROCK": + print("ROCK destroyed HACKER's computer!") + case "PAPER": + print("PAPER climbed into HACKER's USB drive!") + case "SCISSORS": + print("HACKER hacked SCISSORS and made it go ballistic!") + + case 'I': + match current_item_rand: + case "ROCK": + print("ROCK isn't used to cold weather, so it got frozen by IGLOO!") + case "PAPER": + print("PAPER rode the icy cold winds, escaping from IGLOO!") + case "SCISSORS": + print("IGLOO trapped SCISSORS inside his territory!") + + case 'J': + match current_item_rand: + case "ROCK": + print("JANITOR cleaned the dust off of ROCK, leaving ROCK embarrassed.") + case "PAPER": + print("PAPER cleaned JANITOR, leaving his self-esteem at an all-time low.") + case "SCISSORS": + print("SCISSORS sliced JANITOR's mop, making him go cry in the corner.") + + case 'K': + match current_item_rand: + case "ROCK": + print("KNOWLEDGE outsmarted ROCK's dumb brain!") + case "PAPER": + print("PAPER modeled a 3D diagram of the 4th dimension and outsmarted KNOWLEDGE!") + case "SCISSORS": + print("SCISSORS cut through KNOWLEDGE's brain cells!") + + case 'M': + match current_item_rand: + case _: + print("Mettaton.") + + case _: + invalid_item() diff --git a/seeker/snippet/sagemaker_studio_lifecycle_config.sh b/seeker/snippet/sagemaker_studio_lifecycle_config.sh new file mode 100644 index 00000000..7b9f984a --- /dev/null +++ b/seeker/snippet/sagemaker_studio_lifecycle_config.sh @@ -0,0 +1,122 @@ +#date: 2024-08-20T16:44:38Z +#url: https://api.github.com/gists/97b994f6766f4fe6b66e84c97104ebe5 +#owner: https://api.github.com/users/tuliocasagrande + +#!/bin/bash + +# -e Exit immediately if a command exits with a non-zero status. +# -u Treat unset variables as an error when substituting. +# -x Print commands and their arguments as they are executed. +set -eux + +# Install extensions and depending libraries +pip install -U \ + jupyterlab-spellchecker \ + jupyterlab-code-formatter \ + jupyterlab-notifications \ + black flake8 isort + +# Configurations +# I prefer flake8 over pylint and the others. Also, setting max line to 100 and ignoring a few errors +CONFIG_DIR=.jupyter/lab/user-settings/@jupyter-lsp/jupyterlab-lsp +CONFIG_FILE=plugin.jupyterlab-settings +CONFIG_PATH="$CONFIG_DIR/$CONFIG_FILE" +if test -f $CONFIG_PATH; then + echo "$CONFIG_PATH already exists. Skipping..." +else + echo "Creating $CONFIG_PATH" + mkdir -p $CONFIG_DIR + cat >$CONFIG_PATH <$CONFIG_PATH <$CONFIG_PATH <$CONFIG_PATH <