dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def list_nodes(self):
try:
peer_to_server_socket = \
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
peer_to_server_socket.setsockopt(
socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
peer_to_server_socket.connect(
(self.peer_hostna... | The code performs leader election in a distributed network by checking if the current node has the highest port number among connected peers. If so, it designates itself as the leader, updates server records, and broadcasts leadership status. If not, it resets its leader status. The process ensures only the node with t... | def elect_leader(self):
try:
ip_nodes=self.list_nodes()
#elect leader only when there are peers connected to the network
if(ip_nodes):
nodes=[int(x.split(':')[1]) for x in ip_nodes]
if(int(self.peer_port)==max(nodes) and self.leader==False):
... |
def elect_leader(self):
try:
ip_nodes=self.list_nodes()
#elect leader only when there are peers connected to the network
if(ip_nodes):
nodes=[int(x.split(':')[1]) for x in ip_nodes]
if(int(self.peer_port)==max(nodes) and self.leader==False):
... | The main task of the code is to continuously generate sensor data, update an index server, and manage vehicle operations. It periodically elects a leader, connects to a network leader if specified, checks fuel levels to shut off devices when low, alerts peers about obstacles, and broadcasts status updates. The loop run... | def generate_data_continuously(self):
try:
#Elect a leader every 15 seconds
self.elect_leader()
#if a network arg was specified, connect to the leader of that network
if(self.network):
if(self.leader==True):
self.connec... |
def show_instructions():
instructions.draw()
win.flip()
event.waitKeys(keyList=['space'])
def load_trial_structure(condition):
"""
Load the pre-generated trial structure for a given condition.
"""
trial_list_path = "trialList/"
structure_files = [f for f in os.listdir(trial_list_path) if... | The main task of the code is to conduct an experimental trial process by displaying instructions, loading trial data, saving results to a CSV file with specific headers, optionally running practice trials, iterating through each trial to execute them, and finally restoring mouse visibility and closing the window after ... | def main():
show_instructions()
# Load main trials, not including practice trials
trial_data, structure_number = load_trial_structure(condition)
global filename
filename = f"{data_dir}JUDIT_{participant_number}_{condition}_{structure_number}.csv"
# Write header for the trial resul... |
def show_instructions():
instructions.draw()
win.flip()
event.waitKeys(keyList=['space'])
def load_trial_structure():
trial_list_path = "trialList/"
structure_files = [f for f in os.listdir(trial_list_path) if f.startswith("JUDIT")]
chosen_filename = random.choice(structure_files)
trial_data... | The code conducts an experimental trial with multiple blocks, saving participant responses and performance metrics to a CSV file. It initializes trial data, runs adaptive practice if enabled, processes trials in blocks with progress tracking, and pauses for user breaks between blocks. Data includes trial details, user ... | def main():
show_instructions()
trial_data, structure_number = load_trial_structure()
global filename
filename = f"{data_dir}JUDIT_{participant_number}_{structure_number}_{TODAY}.csv"
TRIALS_PER_BLOCK = len(trial_data) // NUM_BLOCKS
block_num = 0
block_trials = trial_data[:TRIALS_PER_BLOCK]
... |
def _valid_function(self, operation: Optional[str] = None):
current = float(self._current)
operation = self._operation if operation is None else operation
if operation == OperationList.SUM:
self._total += current
if operation == OperationList.DIFF:
self._total -= ... | This function processes a mathematical operation, validates its input, updates internal state variables, handles errors like division by zero or type mismatches, and returns the current result or an error message. It checks if the operation is valid, manages calculation flow, converts values between numeric and string ... | def operation_enter(self, operation: str):
try:
self._await_input = True
if operation not in OnTotalOperations:
self._valid_function(operation)
return self._current
if self._await_result:
self._await_result = False
... |
def get_prediction(vector, lg, xgb, rfc, nn):
if nn.predict(vector) == 1:
nn_pred = 1
else:
nn_pred = 0
if lg.predict(vector)+xgb.predict(vector)+rfc.predict(vector)+nn_pred > 2:
return 1
return 0
def feature_to_vector(features_json, pre_processor):
X = pre_processor.trans... | This function predicts phishing URLs by extracting features from the input URL, preprocessing them, converting to a vector, and using multiple machine learning models (logistic regression, XGBoost, random forest, neural network) to generate a phishing prediction. | def url_phishing_predictor_js(url, pre_processor, lg, xgb, rfc, nn):
return get_prediction(feature_to_vector(get_features(url), pre_processor), lg, xgb, rfc, nn) |
def possiblePiBonds(self):
for b in self.mol.GetBonds():
i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
if self.canBePi(i, j):
yield i, j
def isCarbon(self, i):
return self.atom[i].isCarbon()
def singleCoordinate(self, i):
return self.graph.degree[i] == 1
d... | This code initializes a molecular structure analyzer by constructing a graph of potential pi bonds. It applies filters to exclude certain atoms, prioritizes heteroatoms, and iteratively assigns pi bonds (double/triple) based on atom capabilities. The process includes sanitizing the molecule, identifying ring atoms, and... | def __init__(self, mol, atom, useFilters):
self.mol = mol
self.atom = atom
self.excluded = set()
if useFilters:
Chem.SanitizeMol(self.mol)
Chem.GetSSSR(self.mol)
ringInfo = self.mol.GetRingInfo()
self.excluded.update(BridgeheadAtoms(mol, ... |
def get_elapsed_time(self, sec_or_min):
now_time = (pgm.time.get_ticks() - self.FIRST_TIME) /1000
if sec_or_min == 0:
return math.floor(now_time / 60)
else:
return math.floor(now_time % 60)
def resume_game(self):
'''meant to make the game sprites drawn and updated again.'''
global BACKGROUND
BACKGROUN... | This method processes game events, handling quit requests, key presses for input fields, and pause/resume logic. It checks for player death to trigger the score screen, while logging event details and managing game state transitions based on user input and game conditions. | def events(self):
print("[{}:{}] Running EVENTS\n".format(self.get_elapsed_time(0), self.get_elapsed_time(1)))
for event in pgm.event.get():
print("Processing {} event of {} type".format(event, event.type))
if event.type == pgm.QUIT:
if self.playing:
self.playing = False
playing = False
if ev... |
def show_start_screen(self):
print("\n\n--DISPLAYING START MENU--\n\n")
global BACKGROUND
if self.all_sprites_group:
for sprite in iter(self.all_sprites_group): sprite.kill()
self.game_paused = False
self.on_settings_menu = False
BACKGROUND = WHITE
self.load_screen(startmenu)
self.render()
def events... | The main task of the code is to execute a game loop that manages gameplay by handling events, updating the game state, rendering frames at a set FPS, tracking frame counts, and displaying start/score screens, while also measuring load time and maintaining the game's running state until it concludes. | def run(self):
print("Game is RUNNING")
frame_count = 0
self.playing = True
self.show_start_screen()
print("Game took {} seconds to load".format(time.time() - started_loading_time))
while self.playing:
frame_count += 1
print("\n\nFRAME", frame_count, "\n")
self.clock.tick(FPS)
self.events()
s... |
def load_screen(self, data_dict):
print("\nLOADING SCREEN {}\n\n".format(data_dict))
for sprite_type in data_dict.keys():
sprite_number = 0
for sprite in data_dict[sprite_type]:
sprite_generic_name = sprite_type.lower()
current_sprite_str = ""
for arg in data_dict[sprite_type][sprite_number]:
... | (The code initializes a new Pygame game by creating sprites and sprite groups, loads the game screen, logs the start event with timestamps, and initiates the game loop. It sets up essential game components and transitions to the active game state.) | def start(self):
''' Starts a bew game by creating all Pygame Sprites and Sprites
Groups
'''
global projectiles_list
#creating sprites
self.load_screen(world)
#displaying new state
print("[{}:{}] Game has been STARTED".format(self.get_elapsed_time(0), self.get_elapsed_time(1)))
self.run() |
def dump_traffic():
print("starting dump_traffic()")
remove_temp()
dump_time = 120 # time in seconds to analyze the traffic
print("Enabling monitor mode")
monitor_mode("enable", "wlan1", selected_network['Channel'])
print("Starting Dump")
send_command("tmux new -s 'capture_han... | The main task of the code is to manage network encryption analysis by creating directories, handling different encryption types (WEP, WPA, WPA3), executing protocol-specific tasks (traffic dumping, handshake hashing, channel comparison), and generating reports. It ensures proper folder management, executes security ass... | def encryption_Manager(Assessment_window, message, next_button,back_button):
#Create the folder to hold all the analysis
try:
os.mkdir(selected_network['ESSID'])
except:
# Delete all contents of the directory
for file in os.listdir(selected_network['ESSID']):
os.rem... |
def start():
stream = cv2.VideoCapture(0)
writer = None
# loop over frames from the video file stream
while True:
# grab the next frame
(grabbed, frame) = stream.read()
res=predict(frame)
speak1(res)
def main1():
cap = cv2.VideoCapture(0)
i = 0
while(cap.isOpened()):
... | The code creates a GUI for blind users to access emotion, face, and object detection features. It displays a background image, labels, and buttons for initiating each detection task. The interface includes three 'check' buttons triggering respective functions (start, main1, start1) for face, emotion, and object detecti... | def detect():
top = Tk()
top.title("gui")
top.geometry("1000x700")
e=Frame(top)
e.config(bg="lightblue")
e.pack(fill=BOTH, expand=YES)
try:
path3="eye.png"
image = Image.open(path3)
except:
path3="eye.png"
image = Image.open(path3)
messagebox.show... |
def run_oai():
run_epc()
run_enb()
def run_zookeeper():
kfk_dir = '~/app/kafka_2.11-2.1.0'
cmd = 'xterm -T \"zookeeper\" -e ssh ' + ssh_oai +' "'
cmd += kfk_dir + '/bin/zookeeper-server-start.sh '
cmd += kfk_dir + '/config/zookeeper.properties" &'
exe_cmd(cmd)
def run_brokers():
kfk_dir... | The `run_all()` function sequentially initializes multiple services and applications with specified delays: OAI, Zookeeper (5s delay), brokers (3s delay), Flink applications (3s delay), TensorFlow (2s delay), and NC. It orchestrates the startup of distributed systems components, ensuring each service has adequate time ... | def run_all():
run_oai()
run_zookeeper()
time.sleep(5)
run_brokers()
time.sleep(3)
run_flink_app()
time.sleep(3)
run_tensorflow()
time.sleep(2)
run_nc() |
def kill_tensorflow():
print("killing tensorflow..")
for pid in get_pids("python", tensorflow_ip):
cmd = 'ssh ' + ssh_ts + ' "echo password | sudo -S kill ' + pid + '"'
exe_cmd(cmd)
def kill_flink():
print("killing flink..")
for pid in get_pids("java", flink_ip):
cmd = 'ssh ' + s... | The code defines a function `kill_all()` that sequentially terminates multiple services (TensorFlow, Flink, OAI, brokers, Zookeeper) with specified delays between each termination to ensure orderly shutdown. | def kill_all():
kill_tensorflow()
time.sleep(1)
kill_flink()
time.sleep(2)
kill_oai()
time.sleep(2)
kill_brokers()
time.sleep(5)
kill_zookeeper()
time.sleep(1) |
def current(self):
"""
Return the current token
@return the token
"""
if len(self.tokens) > 0:
return self.tokens[self.index]
else:
return None
def next(self):
"""
Advance to the next token
"""
self.index = self.inde... | The function generates a parse tree for a class variable declaration (static or field), parsing keywords, types, variable names, and handling multiple variables separated by commas, while validating syntax and raising exceptions on errors. | def compileClassVarDec(self):
"""
Generates a parse tree for a static variable declaration or field declaration
@return a ParseTree that represents a static variable declaration or field declaration
"""
class_VarDec = ParseTree("classVarDec", "")
current_tk = self.current... |
def current(self):
"""
Return the current token
@return the token
"""
if len(self.tokens) > 0:
return self.tokens[self.index]
else:
return None
def mustBe(self,expectedType,expectedValue):
"""
Check if the current token matches the ... | The code generates a parse tree for a variable declaration by parsing the keyword "var", followed by a type (keyword or identifier), one or more variable names (identifiers), and a semicolon. It constructs a hierarchical structure with these elements as children of a "varDec" node, handling comma-separated multiple var... | def compileVarDec(self):
"""
Generates a parse tree for a variable declaration
@return a ParseTree that represents a var declaration
"""
comp_vardec = ParseTree("varDec","")
current_tk = self.current()
self.mustBe("keyword","var")
comp_vardec.addChild(To... |
def current(self):
"""
Return the current token
@return the token
"""
if len(self.tokens) > 0:
return self.tokens[self.index]
else:
return None
def mustBe(self,expectedType,expectedValue):
"""
Check if the current token matches the ... | The code generates a parse tree for a 'let' statement by parsing keywords, identifiers, expressions, and symbols like '=' and ';', ensuring correct syntax and raising exceptions for invalid structures. | def compileLet(self):
"""
Generates a parse tree for a let statement
@return a ParseTree that represents the statement
"""
current_tk = self.current()
compLet = ParseTree("letStatement", "")
self.mustBe("keyword","let")
compLet.addChild(Token("keyword","le... |
def current(self):
"""
Return the current token
@return the token
"""
if len(self.tokens) > 0:
return self.tokens[self.index]
else:
return None
def mustBe(self,expectedType,expectedValue):
"""
Check if the current token matches the ... | The code generates a parse tree for a "do" statement by validating the keyword "do", checking for a subsequent "skip" keyword to include an expression, ensuring a semicolon follows, and constructing the tree structure with appropriate nodes and children. | def compileDo(self):
"""
Generates a parse tree for a do statement
@return a ParseTree that represents the statement
"""
compDo = ParseTree("doStatement","")
current_tk = self.current()
self.mustBe("keyword","do")
compDo.addChild(Token("keyword","do"))
... |
def current(self):
"""
Return the current token
@return the token
"""
if len(self.tokens) > 0:
return self.tokens[self.index]
else:
return None
def mustBe(self,expectedType,expectedValue):
"""
Check if the current token matches the ... | The main task of the code is to generate a parse tree for a return statement that ends with a semicolon. It checks if the current token is the keyword "return", verifies the next token is a semicolon, and constructs a parse tree node with these elements. If the next token is not a semicolon, it raises a parsing error. | def compileReturn(self):
"""
Generates a parse tree for a return statement
@return a ParseTree that represents the statement
"""
comp_Return = ParseTree("returnStatement","")
current_tk = self.current()
self.mustBe("keyword","return")
current_tk = self.cu... |
def current(self):
"""
Return the current token
@return the token
"""
if len(self.tokens) > 0:
return self.tokens[self.index]
else:
return None
def have(self,expectedType,expectedValue):
"""
Check if the current token matches the ex... | The main task of the code is to generate a parse tree representing a series of statements by iterating through tokens, identifying statement keywords (let, if, while, do, return), and recursively compiling each statement into child nodes of a "statements" root node. The function constructs a hierarchical ParseTree stru... | def compileStatements(self):
"""
Generates a parse tree for a series of statements
@return a ParseTree that represents the series of statements
"""
comp_statements = ParseTree("statements","")
current_tk = self.current()
while current_tk.getType() == "keyword" a... |
def current(self):
"""
Return the current token
@return the token
"""
if len(self.tokens) > 0:
return self.tokens[self.index]
else:
return None
def mustBe(self,expectedType,expectedValue):
"""
Check if the current token matches the ... | The main task of the code is to generate a parse tree representing a subroutine's body by parsing tokens, adding symbols like '{' and '}', handling variable declarations, and compiling statements (let, if, while, do, return) as child nodes in the parse tree. | def compileSubroutineBody(self):
"""
Generates a parse tree for a subroutine's body
@return a ParseTree that represents a subroutine's body
"""
comp_subroutineBody = ParseTree("subroutineBody", "")
current_tk = self.current()
#here
self.mustBe("symbol... |
def current(self):
"""
Return the current token
@return the token
"""
if len(self.tokens) > 0:
return self.tokens[self.index]
else:
return None
def next(self):
"""
Advance to the next token
"""
self.index = self.inde... | The code generates a parse tree for a subroutine (method, function, or constructor) by parsing its components: identifying the subroutine type (constructor/function/method), return type (void, primitive, or identifier), name (identifier), parameter list (if present), and body. It constructs a hierarchical `ParseTree` n... | def compileSubroutine(self):
"""
Generates a parse tree for a method, function, or constructor
@return a ParseTree that represents the method, function, or constructor
"""
class_compileSub = ParseTree("subroutine", "")
current_tk = self.current()
if current_tk.ge... |
def heuristic(self):
self.pre = []
self.rec = []
self.fscore = []
if self.binet:
alpha_low = 0
alpha_high = 1 / self.max_mean
else:
alpha_low = 0.9/self.max_mean
alpha_high = 1 / self.max_mean
alpha_dif = alpha_high-alpha_lo... | This code evaluates an anomaly detection model by calculating metrics like F1 score, precision, recall, and generating a summary DataFrame with performance statistics. It identifies anomalies using a heuristic, compares them against ground truth, and optionally visualizes results or outputs a table. | def __call__(self, threshold = 'gmean', s = 20, analyze=False, table=False, t=None):
self.s = s
self.threshold = threshold
if (self.threshold == 'gmean'):
self.mean = self.df.loc[self.df['a_score']>0]['a_score'].mean()
self.max_mean = self.mean
self.alpha = self.h... |
def result_file_exist(dr):
result_file = dr + ".result"
if args.noReadOnly:
result_file = dr + ".resultNR"
if os.path.exists(result_file):
return True
return False
def analyse(dir_name):
l = dir_name.split(".")[0].split("-")[:-1]
sn = '-'.join(l) + ".json"
sf = open(sn)
s... | The main task of the code is to analyze directories named after configuration files by processing each config file's prefix, filtering matching directories, skipping existing results unless forced, and executing analysis on relevant directories, followed by generating error bars for visualization. | def analyse_file():
path = os.getcwd()
lists = os.listdir(path)
for f in args.configFile:
print(f)
prefix = f.split(".")[0] + "-"
dLists = [d for d in lists if d.startswith(prefix) and os.path.isdir(os.path.join(path, d))]
for d in dLists:
if not args.force and re... |
def result_file_exist(dr):
result_file = dr + ".result"
if args.noReadOnly:
result_file = dr + ".resultNR"
if os.path.exists(result_file):
return True
return False
def analyse(dir_name):
l = dir_name.split(".")[0].split("-")[:-1]
sn = '-'.join(l) + ".json"
sf = open(sn)
s... | The main task of the code is to process directories or files based on command-line arguments, analyze data, and generate error bars or increase rates from JSON files. It checks for existing results, skips processing if not forced, and performs analysis on directories or specific JSON files, modifying prefixes and compa... | def main():
if args.resultDir is not None:
for dr in args.resultDir:
if not args.force and result_file_exist(dr):
continue
analyse(dr)
return
if args.configFile is not None:
analyse_file()
return
path = os.getcwd()
lists = os.listd... |
def login_commonwealth(driver: WebDriver, client_number: str, password: str):
client_number_id = "txtMyClientNumber_field"
my_click(driver, By.ID, client_number_id)
client_number_input = driver.find_element(by=By.ID, value=client_number_id)
client_number_input.send_keys(client_number)
password_id =... | The function scrapes Commonwealth Bank transaction data by automating browser login, accesses account details, and extracts pending and non-pending movements. It returns a tuple containing the total pending count and two lists of transaction records. | def scrap_commonwealth(
client_number: str, password: str, headless: bool
) -> Tuple[int, List[CommonWealthMovement], List[CommonWealthMovement]]:
driver = start_driver(headless=headless)
driver.get("https://www.my.commbank.com.au/netbank/Logon/Logon.aspx?ei=mv_logon-NB")
login_commonwealth(driver, cli... |
def question_is_detailed(question):
request = copy.deepcopy(details.array)
request.append("Q. " + question)
response = execute_gpt3_request(request, gpt3_details_options, "Detailed?")
return response == "Yes"
def extract_topic_of_discussion(prompts):
request = copy.deepcopy(prompts)
request.appe... | This code runs a conversational loop where the user inputs questions or topics. It checks if the question is detailed, retrieves Wikipedia summaries for relevant topics, and uses GPT-3 to generate responses. The conversation history is maintained, truncated, and logged. The loop ends when the user enters "." or an empt... | def main():
print("Ask a question or a topic you are interested to learn about. (Write . to quit.)")
while True:
print("Q. ", end = "")
question = input()
print("")
if question in [".",""]:
break
response = ""
if question_is_detailed(question):
... |
def draw_world_settings(self, context):
layout = self.layout
box = layout.box()
box.label(text='World', icon='WORLD')
if bpy.context.scene.world:
if bpy.context.scene.world.name:
box.label(text=str(bpy.context.scene.world.name))
return
def d... | This code defines a UI drawing function that displays different configuration panels based on the selected 'context_tab' value. It uses Blender's UI layout system to show settings for Scene, General, Bake, Shading, and Renderer tabs, dynamically calling corresponding methods to populate the interface with world setting... | def draw(self, context):
layout = self.layout
layout.prop(self, "context_tab",expand=True)
if self.context_tab == 'Scene':
self.draw_world_settings(context)
self.draw_objects_in_scene(context)
if self.context_tab == 'General':
self.draw_export_co... |
def handle_jobs(d,user,isme=True):
"""Find and display options for the user's jobs.
Obtain information about a user's Grid engine job in either fine grain or
coarse grain. Also search for HTCondor jobs on this specific host.
Utilizes node_search for specifics.
:param d: Dialog object.
:param ... | The code presents a menu for searching user-related information (jobs, resources, storage) using a dialog, executes corresponding handling functions based on user selection, and resets global caches to prevent prior search interference. It loops until the user cancels or exits via menu options. | def search_landing(d, user):
"""Prompting user what to search for with new user-name.
:param d: Dialog object we are casting the screen with.
:param user: User object containing user we want to search for.
:return: Nothing.
"""
# Create a menu similiar to the one in main().
# Obtain bools ... |
def disp_warning(d):
"""Display a warning about lack of stability in this program.
:param d: Dialog object.
:return: Nothing, prints window to screeen and returns to main.
"""
lighthouse_str = """
____
|\/| *************************************
... | The main task of the code is to create a dialog-driven interface for the LightHouse application, allowing users to select options like viewing jobs, resources, storage, or performing searches. It handles user input through a loop, invoking corresponding functions based on selections, and exits gracefully when the user ... | def main(dialog=None):
"""Main function for lighthouse. Create dialog box and accept input."""
exit_cond = False
# This is the default user, we are assuming we are wanting to check whoever
# is running this script.
my_user = User(USER,F_NAME)
d = Dialog(dialog="dialog") # creating the inital ... |
def enable_interrupt(self):
"""Enables the interrupt of the sensor"""
value = self.read_single_byte(REGISTER_INT_STATUS)
value = value | int(INTERRUPT_MASK, 0)
self.write_bytes(REGISTER_INT_ENAB, str(value))
def write_bytes(self, register: str, value: str):
"""Writes the given v... | The main task of the code is to perform factory calibration by sending a command to a sensor, monitoring a status register for a specific response, and reading calibration data bytes once the response is detected. The watchdog timer is periodically fed to prevent reset during the 30-second calibration window. | def perform_calibration(self) -> bytes:
calibration_data: bytes = b""
self.wdt.feed()
self.enable_interrupt()
self.write_bytes(REGISTER_COMMAND, COMMAND_FACTORY_CALIBRATION)
start_of_calibration = utime.time()
while (utime.time() - start_of_calibration) < 30:
... |
def load_measurement_application(self):
"""Sets the values in the register that is responsible for the current loaded application
to the application to start a measurement
"""
self.write_bytes(REGISTER_APPREQID, APPLICATION)
def is_application_ready(self) -> bool:
"""Checks if t... | The function performs a distance measurement using a sensor. It loads the measurement application, waits for it to be ready, initiates the measurement, and checks for data availability. It processes result data, extracts reliability and status flags, reads peak values from registers, combines them into a distance value... | def get_measurement(self) -> int:
"""Loads the application to start a measurement. Wait till the application is ready. Executes the
measurement application. Waits till data is available. Returns the read data.
Returns:
int: Measured distance in mm
"""
self.load_meas... |
def is_connected(self) -> bool:
"""Scans the I2C bus and checks if the given address is found
Returns:
bool: True if the address could be found, False otherwise
"""
devices = self.i2c.scan()
return self.hex_to_dec(self.address) in devices
def reset_cpu(self):
... | The code initializes the TMF8805 sensor by checking its connection, resetting the CPU, and verifying CPU readiness. It returns `True` if all steps succeed; otherwise, it prints error messages and returns `False` upon connection failure or CPU readiness timeout. | def initialize(self) -> bool:
"""Initialization of the sensor
Returns:
bool: True if initialization was successful, False otherwise
"""
if not self.is_connected():
print("TMF8805 is not connected. Please check the parameters")
return False
s... |
def get_piece(self, row, col):
return self.cells[row][col].piece
def check_king(self, piece, goalRow):
if not piece.is_king:
if (piece.player == GameBoard.PLAYER_ONE and goalRow == 0):
piece.make_king()
self.nKings[piece.player] = sum(x.is_king for x in self.p... | This method handles a successful jump move in a game, updating the piece's position, marking it as a king if applicable, removing jumped-over pieces, and advancing the turn. It updates the game state by relocating the piece, clearing the original cell, placing the piece at the new coordinates, deleting intermediate pie... | def jump_success(self, row, col, goalRow, goalCol, pieces_to_delete):
piece = self.get_piece(row, col)
self.check_king(piece, goalRow)
piece.set_coord(goalRow, goalCol)
self.currentHistory["jump"].append(piece)
self.cells[row][col].piece = None
self.cells[goalRow][goalCol... |
def is_valid_move_dir(self, row, col, direction):
piece = self.get_piece(row, col)
if piece is None or piece.player != self.currentTurn:
return False
directions = [self.FORWARD_LEFT(), self.FORWARD_RIGHT()]
if piece.is_king:
directions += [self.BACKWARD_LEFT(), se... | The main task of the code is to attempt a directional movement in a grid-based system. It checks if the movement is valid, calculates the new coordinates, executes the move if valid, and returns True on success or False if invalid/exception occurs. | def move_dir(self, row, col, direction):
if self.is_valid_move_dir(row, col, direction):
try:
(goalRow, goalCol) = self.add_dir(row, col, direction)
self.move_success(row, col, goalRow, goalCol)
return True
except ValueError:
... |
def mousePressedWrapper(self, event):
self.mousePressed(event)
self.redrawAllWrapper()
def mouseMovedWrapper(self, event):
self.mouseMoved(event)
self.redrawAllWrapper()
def mouseReleasedWrapper(self, event):
self.mouseReleased(event)
self.redrawAllWrapper()
def keyPresse... | This code initializes a game interface with a board and menu, sets up event handlers for user interactions, and starts the main GUI loop. It creates a GameBoard, two frames (for board and menu), canvases for rendering, buttons for "Undo" and "Reset", and binds mouse/keyboard events to handle game actions. The `redrawAl... | def run(self):
self.board = GameBoard()
self.board_frame = Frame(self)
self.menu_frame = Frame(self)
# create the root and the canvas
self.board_canvas = Canvas(self.board_frame)
self.board_canvas.pack(fill=BOTH, expand=YES)
self.menu_canvas = Ca... |
def is_valid_jump_dir(self, row, col, direction, pieces_to_delete = None):
"""
Whether this coor's direction can get moved (FOR JUMP)
"""
piece = self.get_piece(row, col)
if piece is None or piece.player != self.currentTurn:
return False
dir0 = abs(direction[0... | This function checks if a jump in a specified direction is valid for a piece at (row, col). It validates the direction, calculates the target position, and executes the jump if valid, returning True on success or False if invalid. | def jump_dir(self, row, col, direction):
pieces_to_delete = []
if not self.is_valid_jump_dir(row, col, direction, pieces_to_delete):
return False
try:
(goalRow, goalCol) = self.add_dir(row, col, direction)
except ValueError:
return False
self.j... |
def get_dirs(self, row, col, goalRow, goalCol):
"""
From (r,c) to (r', c'), which direction should it take?
may be more than 1
"""
row_diff = goalRow - row
if row_diff == 0:
return []
col_norm = goalCol - col
col_pass = goalCol - col - self.col... | This function determines if a valid jump can be made from the current coordinates (row, col) to the goal coordinates (goalRow, goalCol). It retrieves possible movement directions, checks each for validity, and executes the jump if a valid direction is found, returning True upon success or False if no valid jumps are av... | def jump_coord(self, row, col, goalRow, goalCol):
dirs = self.get_dirs(row, col, goalRow, goalCol)
if len(dirs) == 0:
return False
for dir in dirs:
if self.is_valid_jump_dir(row, col, dir):
return self.jump_dir(row, col, dir)
return False |
def off(self):
self.red_led.off()
self.blue_led.off()
self.green_led.off()
def red(self):
self.off()
self.red_on()
def orange(self):
self.off()
self.red_on()
self.green_on()
def green(self):
self.off()
self.green_on()
def yellow(self):
... | The code simulates a cyclic sequence of light color transitions (red, orange, green, yellow, blue, purple, white) with adjustable duration and completeness. The 'full' parameter determines if all colors are included. It turns off, activates each color, pauses, and repeats, ending with a final off state. | def cycle(self, seconds=1, full=False):
self.off()
self.red()
time.sleep(seconds)
if full:
self.orange()
time.sleep(seconds)
self.green()
time.sleep(seconds)
if full:
self.yellow()
time.sleep(seconds)
self.bl... |
def count_table_totals(infile, outdir='', outfile=''):
"""
Given a Mothur counttable, calculate the total number of sequences for each
sample. This can be appended as additional row in the count table by
providing a file name.
:param infile: Mothur count table.
:param outfile: Optional. Write t... | This script is a command-line tool for microbiome data analysis, processing inputs like count tables, taxonomy files, and FASTA sequences. It executes tasks such as generating QC reports, creating Krona plots, correcting replicates, and manipulating OTU tables based on user-specified commands. Outputs are directed to a... | def main():
print("Welcome to the MYcrobiota suite")
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--command', required=True,
help="What action to perform")
parser.add_argument('-ct', '--count_table', action='append',
help="mothur count tab... |
def split_nodes_link(old_nodes):
new_nodes = []
for old_node in old_nodes:
if not(isinstance(old_node, TextNode)):
new_nodes.append(old_node)
continue
html_node = old_node.to_html_node()
text = html_node.to_html()
images = extract_markdown_links(text)
parts = split_many(lambda i... | The function processes input text through nested splitting operations to parse and convert it into structured TextNodes, handling code blocks, bold, italic, images, and links sequentially. Each split function processes specific markdown elements, transforming the text into a list of nodes representing different content... | def text_to_textnodes(text):
return split_nodes_link(split_nodes_image(split_nodes_delimiter(split_nodes_delimiter(split_nodes_delimiter([TextNode(text, "text")], "`", "code"), "**", "bold"), "*", "italic"))) |
def markdown_to_blocks(markdown):
lines = map(lambda l: l.strip(), markdown.split("\n"))
blocks = []
current_block = []
for line in lines:
if len(line) == 0:
if len(current_block) != 0:
blocks.append(current_block)
current_block = []
continue
current_block.append(line)
if l... | This function converts markdown content into a list of HTML nodes by parsing each block of text, identifying its type (e.g., heading, code, quote), and generating the corresponding HTML element using specialized conversion functions. It raises an error for unknown block types and returns the list of HTML nodes. | def markdown_to_html_node(markdown):
blocks = markdown_to_blocks(markdown)
print("BLOCKS", blocks)
nodes = []
for block in blocks:
blocktype = block_to_blocktype(block)
match blocktype:
case "heading":
nodes.append(block_to_heading(block))
case "code":
nodes.append(block_to_c... |
def getV(ratingsForUser):
# ratingsForUser is obtained from the ratings for user library
# you should return a binary matrix ret of size m x K, where m is the number of movies
# that the user has seen. ret[i][k] = 1 if the user
# has rated movie ratingsForUser[i, 0] with k stars
# otherwise it... | This function predicts a user's movie rating using a collaborative filtering model. It computes a rating distribution based on user ratings, model weights (W), and bias terms (b_h, b_v), then returns either the maximum predicted rating or an exponential prediction, depending on the specified type. Input parameters incl... | def predictMovieForUser(q, user, W, training, b_h, b_v, predictType="exp"):
# movie is movie idx
# user is user ID
# type can be "max" or "exp"
# b_h: vec F ###
# b_v: (array m*5) ###
ratingsForUser = lib.getRatingsForUser(user, training)
v = getV(ratingsForUser) # m(num of movies user sees... |
def update_arrival_info(self):
self.whether_reaches_ground_prev = self.whether_reaches_ground
self.whether_reaches_ground = self.reaches_ground()
def update_lock_delay(self):
if self.lock_delay_count < 5:
self.reset_gravity()
self.lock_delay_count+=1
def set_dropped(s... | The main task of the code is to update the lock state by evaluating changes in the `whether_reaches_ground` status. It triggers `update_lock_delay` if the object remains on the ground, sets `event_map_change_reservation` to 'on_ground' when transitioning to the ground, or resets it to 'default' when leaving the ground.... | def update_lock(self):
self.update_arrival_info()
if self.whether_reaches_ground and self.whether_reaches_ground_prev:
self.update_lock_delay()
elif self.whether_reaches_ground and not self.whether_reaches_ground_prev:
self.event_map_change_reservation='on_ground'
... |
def overlaps(self, block):
elements = block.get_elements_in_board()
for y,x in elements:
if not self.is_valid_pos(y,x):
return True
if self.board[y][x]:
return True
return False
def try_move_block(self, dir):
if self.can_move_block(... | The main task of the code is to attempt to move the current block downward. If successful, it reserves a deletion event and triggers a gravity event to handle the block's fall, ensuring no overlap with itself before initiating the movement. | def try_pull_down_block(self):
assert not self.overlaps(self.curr_block)
if self.try_move_block(self.DOWN):
self.reserve_delete_event(self.gravity_action_event_key)
self.add_gravity_event() |
def get_matching_id_encodings(self, matching_id):
from recognize.models import Profile, KnownImage
images = KnownImage.objects.filter(profile=Profile.objects.get(matching_id=matching_id))
# print(images)
return [self.get_img_encodings(self.load_image_url(url=image.url)) for image in imag... | This function compares faces in an image from a given URL against a known person's encoding (matching_id) to determine if there's a match. It returns face count, match status, and detailed position data. It loads the image, extracts encodings, compares them, and updates results if a match is found, including distances ... | def match_faces_from_url(self, url, matching_id, mode='RGB'):
"""
Gets the url of image, and the person matching_id to check that it matches or not!
:param url: image file name or file object to load
:param matching_id: matching id of a a person that should be checked. Anyone known by ... |
def get_product_by_id(product_id):
products = get_all_products()
for item in products:
print(item)
if item['id'] == product_id:
return item
return None
def add(product_id):
product = get_product_by_id(product_id)
if product is None:
abort(404)
product['quant... | Your returnThe function `add_to_cart` adds a product to a user's shopping cart. It retrieves the product, checks authentication, and updates or creates a `CartItem` entry. If the product exists in the cart, it increments the quantity; otherwise, it adds a new item. It then compiles cart items into a structured format w... | def add_to_cart(product_id):
product = get_product_by_id(product_id)
if not product:
flash('Product not found.', 'error')
return redirect(url_for('products.view_products'))
# Check if the user is authenticated
if current_user.is_authenticated:
# Check if the product is already ... |
def get_product_by_id(product_id):
products = get_all_products()
for item in products:
print(item)
if item['id'] == product_id:
return item
return None
def calculate_total_price(user_id):
# Calculate the total price based on the items in the user's cart
cart_items = Cart... | The code handles checkout functionality by retrieving authenticated users' cart items, calculating totals, and rendering the checkout template. If unauthenticated, it displays the home page with products and a calculated total amount. | def checkout():
if current_user.is_authenticated:
# Check if the product is already in the user's cart
cart_item = []
# To display items in cart.
cart_list = CartItem.query.filter_by(user_id=current_user.id).all()
for item in cart_list:
product_info = get_product... |
def remainder(a,n,m,y,k=0):
return (a-inversion_number(azby_inverse(y)))%m
def weight(y,k=0):
a=evenflipped(y)
return np.sum(a)
def position1(y,r,k=0):
arr=np.array(evenflipped(y))
pos=np.count_nonzero(arr==1)
if pos==r:
return len(arr)
for i in np.arange(len(arr))[::-1]:
... | The function `dec_BAD` computes a remainder `r` and weight `w` of input `y`, then conditionally deletes or inserts elements into `y` based on comparing `r` and `w`. If `r ≤ w`, it deletes a sequence at position `p` derived from `position1`; otherwise, it uses `position2`. The result is a modified version of `y` after i... | def dec_BAD(a,n,m,y,k=0):
r=remainder(a,n,m,y)
w=weight(y)
if r<=w:
p=position1(y,r)
b=deleted_seq1(p)
else:
p=position2(y,r)
b=deleted_seq2(p)
return ins(y,p,b) |
def remainder(a,n,m,y,k=0):
return (a-inversion_number(azby_inverse(y)))%m
def position(r,n,m,y,k=0):
return len(y)-min([r,m-r])
def Substituted(p,y):
return np.insert(np.zeros(len(y)-2,dtype="int32"),p-1,[1,1])^y | This function decodes a sequence `y` by checking if it meets specific failure conditions (all ones/zeros) or a remainder condition. If valid, it locates a position `p` and substitutes it into `y` using `Substituted`; otherwise, it returns 'failure'. | def dec_BAS(a,n,m,y,k=0):
r=remainder(a,n,m,y)
if (np.all(y==np.ones(len(y))))|(np.all(y==np.zeros(len(y)))):
return 'failure'
elif r==0:
return np.array(y)
else:
p= position(r,n,m,y)
if p==None:
return 'failure'
else:
return Substituted(p,... |
def remainder(a,n,m,y,k=0):
return (a-inversion_number(azby_inverse(y)))%m
def weight(y,k=0):
a=evenflipped(y)
return np.sum(a)
def position1(y,r,k=0):
arr=np.array(evenflipped(y))
pos=np.count_nonzero(arr==1)
if pos==r:
return len(arr)
for i in np.arange(len(arr))[::-1]:
... | This function decodes or processes a sequence 'y' by calculating a remainder 'r' and weight 'w', then conditionally modifying 'y' using either position1/deleted_seq1 or position2/deleted_seq2 based on the comparison between r and w. It returns the result of function I(y,p,b) after successful modification, or 'failure' ... | def dec_BAD(a,n,m,y,k=0):
r=remainder(a,n,m,y)
w=weight(y)
if r<=w:
p=position1(y,r)
if p==None:
return'failure'
b=deleted_seq1(p)
else:
p=position2(y,r)
if p==None:
return 'failure'
b=deleted_seq2(p)
return I(y,p,b) |
def get_dealer_position(self) -> DealerPosition:
scoreTop = self.get_image_score(
"temp/dealer_top.png",
self.top_dealer_pos,
dealer_button_img_height,
dealer_button_img_width,
self.dealer_button_model,
)
if self.dealer_button_class_nam... | The main task of the code is to handle game actions by identifying cards via image recognition, determining optimal moves (fold or all-in), and executing decisions through button clicks. It processes card images, classifies them, validates their types, and triggers actions based on predefined logic, with occasional ran... | def handle_action(self):
self.my_table_position = self.get_dealer_position()
call_button = self.get_action_button(True)
fold_button = self.get_action_button(False)
if call_button == "AllIn" and fold_button == "Fold":
left_score = self.get_image_score(
"temp/l... |
def CNN1(xtrain, ytrain, xtest, ytest):
shape = np.shape(xtrain[1])
model = init_cnn(shape)
train_cnn(model, xtrain, ytrain, xtest, ytest)
def CNN2(xtest, ytest):
test_cnn(xtest,ytest)
def KNN(xtrain, ytrain, xtest, ytest):
xtrain = IMG_P.process_image(xtrain)
xtest = IMG_P.process_image(xtest)... | The code loads the MNIST dataset, preprocesses images (normalization, adding batch dimension), and executes different models (CNN1, CNN2, KNN) based on the 'mode' argument. It defaults to running all models if no valid mode is provided. | def main():
# seed(1)
# tf.random.set_seed(2)
try:
mode = sys.argv[1]
mode = int(mode)
except:
mode = 0
pass
input_path = './input'
training_images_filepath = join(input_path, 'train-images-idx3-ubyte/train-images-idx3-ubyte')
training_labels_filepath = join... |
def fill_stacks(lines):
""" given input, create a nested list. stacks[0] is the first stack.
stacks[0][0] is the bottom item of the first stack
stacks[0][-1] is the top item of the first stack """
stacks = create_empty_stacks(lines)
print(stacks)
for line in lines:
if '[' not in line:
... | The code reads input from '05input.txt', parses initial stack configurations and move instructions, applies the moves to the stacks, and outputs the top crates of each non-empty stack as a concatenated string. | def main():
# with open('05test.txt') as f:
with open('05input.txt') as f:
lines = f.readlines()
# print(lines)
stacks = fill_stacks(lines)
print(stacks)
moves = create_move_list(lines)
print(moves)
final_stack_state = execute2(moves, stacks)
result = []
for stack in f... |
def get_zones(pair):
z1 = get_elf_zone(pair[:pair.find(',')])
z2 = get_elf_zone(pair[pair.find(',') + 1:-1])
return(z1, z2)
def fully_contains(z1, z2):
""" returns true if z1 is entirely contained in z2 or vice versa """
if z1[0] >= z2[0] and z1[1] <= z2[1]:
# zone 2 contains zone 1
... | The code reads input lines from '04input.txt', processes each pair of zones, and counts how many pairs have one zone fully containing another (part1) and how many have overlapping zones (part2). It uses helper functions `get_zones`, `fully_contains`, and `overlap` to analyze each line, accumulating results in `sum` and... | def main():
with open('04input.txt') as f:
lines = f.readlines()
sum = 0
sum2 = 0
for pair in lines:
zones = get_zones(pair)
if fully_contains(zones[0], zones[1]):
sum += 1
if overlap(zones[0], zones[1]):
sum2 += 1
print("part1", sum)
prin... |
def generate_tree(lines):
dirname = None
currnode = None
root = None
lineindex = 0
for line in lines:
if '$ cd' in line:
dirname = line[5:-1]
if dirname == '..':
currnode = exit(currnode)
else:
currnode = enter(dirname, cur... | The code reads input from '07input.txt', constructs a tree structure, calculates the sum of directory values ≤100,000, and prints this sum along with the result of a second part of the problem involving the tree's total value. | def main():
with open('07input.txt') as f:
lines = f.readlines()
tree = generate_tree(lines)
directories = dir_list(tree)
sum = 0
for dir in directories:
if dir.value <= 100000:
sum += dir.value
print(sum)
print(part2(directories, tree.value)) |
def tokenize(self, input_expression):
tokens = []
len_infix = len(input_expression)
cur_pos = 0
while cur_pos < len_infix:
token = ""
if input_expression[cur_pos] == " " or input_expression[cur_pos] == "\t":
cur_pos += 1
continue
... | The code evaluates a mathematical expression by tokenizing it, checking for balanced brackets, and handling errors. If brackets are unbalanced or evaluation fails, it logs an error; otherwise, it stores the expression and result in history and returns the computed value. | def evaluate_expression(self, input_expression):
tokens = self.tokenize(input_expression)
if not self.check_brackets(input_expression):
self.history.append((str(input_expression),'Error'))
return 'Error'
else:
result = self.evaluate_list_tokens(tokens)
... |
def check_cages_valid(puzzle, cages):
for i in range(len(cages)):
if check_cage(puzzle, cages[i]) == False:
return False
return True
def check_columns_valid(puzzle):
for i in range(len(puzzle)):
if check_column(puzzle, i) == False:
return False
return True
def check_rows_valid(puzzle):
for i in ran... | The code checks if a puzzle is valid by verifying three conditions: cages' correctness, rows' uniqueness, and columns' uniqueness. It returns True only if all checks pass, ensuring the puzzle adheres to constraints. | def check_valid(puzzle, cages):
if check_cages_valid(puzzle, cages) and check_columns_valid(puzzle) and check_rows_valid(puzzle):
return True
return False |
def custom_plate_config(self, use_positions):
return custom_plate_config(use_positions)
def full_plate_config(self):
# make the serperntine pattern
return serpentine(self.rows, self.columns)
def serpentine(rows, columns):
""" Make a serpentine pattern """
rows = range(rows)
columns ... | This code creates a microplate configuration by generating well positions based on a custom or full-plate pattern. It initializes wells with calculated coordinates, then assigns multiple positions per well in a serpentine grid pattern, adjusting for camera field of view (fov_mm) and z-position. The result is a structur... | def create(self,
use_positions=[],
num_positions_per_well=1,
z_pos=0.,
fov_mm=CAMERA_FOV_MM):
self._wells = []
if use_positions:
pattern = self.custom_plate_config(use_positions)
else:
pattern = self.full_plate... |
def create_raw_transaction(self, input_params, output_params):
self.reconnect()
return self.connection.createrawtransaction(input_params, output_params)
def sign_raw_transaction(self, tx, private_key):
self.reconnect()
if self.version >= 17:
return self.connection.signrawtran... | This function constructs, signs, and sends a cryptocurrency transaction. It generates a raw transaction from input/output parameters, signs it with a private key, and attempts to broadcast it. On success, it returns the transaction hash; on failure, it catches errors, logs them, and returns None. | def construct_and_send_tx(self, input_params, output_params, private_key):
tx = self.create_raw_transaction(input_params, output_params)
signed = self.sign_raw_transaction(tx, private_key)
try:
tx_hash = self.send_raw_transaction(signed['hex'])
print('tx', tx_hash, flus... |
def audio_gui(self):
if self.plot_audio:
length, data_audio = self.capture.audio.read()
if length == self.nb_samples_audio:
self.draw_audio_plot(data_audio)
def video_gui(self):
if self.capture is not None:
cv_frame = self.capture.video.read_live()
... | This method continuously updates the GUI by refreshing audio, video, and bar plot elements, displays the latest detected emotion from the model, and schedules itself to repeat every 5 milliseconds for real-time updates. | def update(self):
self.audio_gui()
self.video_gui()
self.bar_plot()
self.label_output.set(f"Detected emotion: {self.model.last_emotion}")
self.root.after(5, self.update) |
def init_tk(self):
print("[!] Creating tkinter GUI")
self.root = tk.Tk()
self.label_output = tk.StringVar()
self.root.geometry("640x660")
self.root.title("AV Emotion Recognition")
self.label = tk.Label(self.root, textvariable=self.label_output, compound="top",
... | This code initializes a GUI application for real-time emotion detection or analysis. It sets up a graphical interface with either an audio plot or bar chart visualization, loads a PyTorch model onto a specified device, and configures event handling for window closure. The initialization includes capturing input, model ... | def __init__(self, plot_audio: bool, model: torch.nn.Module, device: torch.device):
self.emotion_list_cache = None
self.bar_canvas = None
self.label_output = None
self.plot_audio = plot_audio
self.init_tk()
self.init_capture()
self.init_model(model, device)
... |
def get_paths_issame_CALFW(calfw_dir):
calfw_images_dir = calfw_dir + '/images'
calfw_pairs = calfw_dir + '/pairs_CALFW.txt'
return get_paths_issame_ca_or_cp_lfw(calfw_images_dir, calfw_pairs)
def get_paths_issame_CPLFW(cplfw_dir):
cplfw_images_dir = cplfw_dir + '/images'
cplfw_pairs = cplfw_dir + '... | This function loads evaluation datasets for face recognition tasks, such as LFW, CALFW, CPLFW, CFP_FF, or CFP_FP, by selecting appropriate data paths and labels based on the specified type. It creates an `EvaluateDataset` with given image dimensions and generates a DataLoader for batch processing, enabling model evalua... | def get_evaluate_dataset_and_loader(root_dir, type='LFW', num_workers=2, input_size=[112, 112], batch_size=100):
if type == 'CALFW':
paths, actual_issame = get_paths_issame_CALFW(root_dir)
elif type == 'CPLFW':
paths, actual_issame = get_paths_issame_CPLFW(root_dir)
elif type == 'CFP_FF... |
def train_step(self):
# Fetch data
t0 = time()
batch = self._get_next_batch()
print(batch['images'].size(), batch['aux_data'].size(), batch['irradiance'].size())
print(batch['images'][0, 0, :, :].size())
for x in batch['images'][0,1]:
print(x)
"""prin... | The main task of the code is to train a machine learning model for a specified number of iterations, performing training steps, periodic evaluation via testing, and saving checkpoints when improved performance is detected. It tracks training progress, updates the best score upon improvement, and closes TensorBoard afte... | def train(self):
print('Starting training session..')
self.model.train()
self.start_time = time()
while self.global_step < self.config.n_iterations:
self.global_step += 1
self.train_step()
if (self.global_step * self.config.batch_size) % self.config.n... |
def gameloop(self):
"""
Runs the game.
:param: None
:return: None
"""
pygame.key.set_repeat(1, 50)
clock = pygame.time.Clock()
while self.state == "GAME":
# Pressing the keys
for event in pygame.event.get():
self.sc... | The main task of the code is to continuously check the current state of an object and execute the corresponding loop method (GAME, LOSE, WIN, or MENU) indefinitely. It acts as a state-driven control loop, calling `gameloop()`, `lose_loop()`, `win_loop()`, or `menuloop()` based on `self.state`, ensuring the application ... | def mainloop(self):
"""
Determines the state and enters the respective loop.
:param: None
:return: None
"""
while True:
if self.state == "GAME":
self.gameloop()
elif self.state == "LOSE":
self.lose_loop()
... |
def get_params():
try:
return ' '.join(argv[1:]).title()
except IndexError:
return ''
def build_func_data(data, country=None):
xarr, yarr = [], []
for x, (k, v) in enumerate(iterate(data, country)):
y = int(v[0]) if country is None else int(v['TOT'][0])
yarr.append(y)
... | The code analyzes coronavirus data by fitting exponential and logistic growth models to confirmed cases, generating forecasts, and visualizing real data versus model predictions. It handles country-specific inputs, processes historical data, calculates model parameters, and plots trends with scatter points and curve ov... | def main():
country = get_params()
if not country:
data = corona.get_data(True, True)
COUNTRY = None
else:
c = r'\b' + re.escape(str(country).lower()) + r'\b'
data = corona.get_data(True, False, c)
if not data:
print(u.error(), 'INVALID COUNTRY')
... |
def get_params():
try:
cmd = argv[1:][0]
try:
s = ' '.join(argv[1:][1:])
except IndexError:
return cmd, Utils.EMPTY
return cmd, s
except IndexError:
return Utils.EMPTY, Utils.EMPTY
def get_countries():
url = Api.append_url(Api.TC)
table ... | The code processes command-line parameters to retrieve and display country-related data. It handles commands like listing all countries, fetching country-specific or global data, and uses regex to search for specific countries, then prints the results accordingly. | def main():
cmd, sort = get_params()
if cmd == Utils.EMPTY:
print(Utils.USAGE)
quit()
elif cmd == Utils.LIST:
cs = get_countries()
list_countries(cs)
elif cmd == Utils.COUNTRIES:
data = get_data(False)
print_countries(data, sort)
elif cmd == Utils.... |
def S2_SendCommand(self, cmd):
epdconfig.digital_write(self.EPD_M2S2_DC_PIN, 0)
epdconfig.digital_write(self.EPD_S2_CS_PIN, 0)
epdconfig.spi_writebyte(cmd)
epdconfig.digital_write(self.EPD_S2_CS_PIN, 1)
def S2_SendData(self, val):
epdconfig.digital_write(self.EPD_M2S2_DC_PIN, 1)
... | The code converts black and red images into bitmapped byte arrays, processes pixel data to set bits for display, and sends the resulting data to specific display sections (S2, M2, M1, S1) with inversion for red. It measures execution time and activates the display. | def display(self, BlackImage, RedImage):
start = time.clock()
Blackbuf = [0x00] * int(self.width * self.height / 8)
blackconvert = BlackImage.convert('1')
bimwidth, bimheight = blackconvert.size
Blackpixles = blackconvert.load()
temp=0;
for y in r... |
def S2_SendCommand(self, cmd):
epdconfig.digital_write(self.EPD_M2S2_DC_PIN, 0)
epdconfig.digital_write(self.EPD_S2_CS_PIN, 0)
epdconfig.spi_writebyte(cmd)
epdconfig.digital_write(self.EPD_S2_CS_PIN, 1)
def S2_SendData(self, val):
epdconfig.digital_write(self.EPD_M2S2_DC_PIN, 1)
... | The code clears an image buffer by sending specific commands and data to multiple display sections (S2, M2, M1, S1). It iterates over defined pixel ranges, using 0x10 and 0x13 commands with 0xff/0x00 data to reset buffer regions. Time measurement is included to track the operation's duration. | def clear(self):
"""Clear contents of image buffer"""
start = time.clock()
self.S2_SendCommand(0x10)
for y in range(0, 492):
for x in range(0, 81):
self.S2_SendData(0xff)
self.S2_SendCommand(0x13)
for y in range(0, 492):
... |
def read_data(self):
ready = self.check_read_pipe()
if ready[0]:
data = self.conn.recv(4096)
data = data.decode("utf-8")
start_time = time.time()
# Loop until full json object
while not data.count('{') == data.count('}') or not data:
... | The main task of the code is to read data from a socket connection, parse it as JSON, process the response, and send the result back to the client. It handles exceptions like parsing errors and timeouts by logging warnings and sending error messages. The connection is always closed after processing, ensuring proper res... | def handle_connection(self):
"""
Function to read from the socket and pass the data read to be parsed
Closes connection on function finish
"""
data = ""
try:
data = self.read_data()
response = self.handle_response(parse_json_in_to_dict(data))
... |
def analyzeboard(board):
cb = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
for i in range(0, 8):
if board[cb[i][0]] != 0 and board[cb[i][0]] == board[cb[i][1]] == board[cb[i][2]]:
return board[cb[i][2]]
return 0
def CompTurn(board):
pos, value = -1, -2
for i ... | The code implements a tic-tac-toe game where the computer (O) and user (X) alternate turns. It initializes a 3x3 board, lets the player choose first or second, and uses `CompTurn` for AI moves and `UserTurn` for human input. The game checks for a win/draw after each move, printing "YOU WON!", "YOU LOST!", or "DRAW!" ba... | def main():
board = [0] * 9
print("Computer: O Vs. You: X")
player = int(input("Enter to play 1(st) or 2(nd): "))
for i in range(0, 9):
if analyzeboard(board) != 0:
break
if (i + player) % 2 == 0:
CompTurn(board)
else:
ConstBoard(board)
... |
def get_header( # pylint: disable = R0914
user: User, context: CCT, event: Event = None
) -> Image.Image:
"""
Gets the header for the sticker customized for the given user. The header either be loaded from
file or created anew, if there is no header for the user or users info changed.
If the heade... | The function generates a sticker image by combining a header, body, and footer. It uses user data and context to build each section, then merges them into a single RGBA image. The image is resized to a 512x512 thumbnail before returning. An optional event checks for cancellation during creation. | def build_sticker(text: str, user: User, context: CCT, event: Event = None) -> Image.Image:
"""Builds the sticker.
Arguments:
text: Text of the tweet.
user: The user the sticker is generated for.
context: The callback context as provided by the dispatcher.
event: Optional. If pa... |
def get_amount_of_iterations(prob, sample_size, epsilon):
return ceil(log2(1-prob) / log2(1 - (1 - epsilon)**sample_size))
def apply_P3P(points_3d, points_2d, intrinsic):
"""
finds the Rotation and translation matrix of the camera, from world coords
:param points_3d: 4 3d_points in world coords-sys. (No... | This function estimates a camera's [R|t] transformation using RANSAC with P3P and PnP. It iteratively samples 3D-2D point pairs, computes initial [R|t] via P3P, refines using inliers via PnP, and returns the best [R|t] and inlier mask. The process combines RANSAC for robustness, P3P for initial estimation, and PnP refi... | def get_Rt_with_ransac(points_3d, kps_cameras, intrinsic, extrinsic_left0, extrinsic_right0):
"""
get [R|t] of the camera using ransac with PnP as inner model
steps:
0. calculate amount of iterations
repeat:
1. select sample data
2. create model
3. check how the model fits to... |
def get_4matched_kps(matches_left_0_1, matches_pair0, matches_pair1):
"""
find quartets of indeces of the same keypoint, as recognized by the 4 cameras
:param matches_left_0_1: matches between left0 and left1
:param matches_pair0: matches between left0 and right0
:param matches_pair1: matches betwee... | The code processes image pairs to estimate camera extrinsic parameters using PnP with RANSAC, tracks consistent keypoints across pairs, and builds a database of 3D points and camera poses. It iteratively matches features, computes 3D world coordinates from 2D matches, and updates tracks for persistent keypoints, serial... | def main():
"""
database = Database('data - only_1_iteration_of_PnP.pkl') # data - 10 pairs
pairs = database.Pairs
tracks = database.Tracks
show_camera_coords(database)
#show_track_in_images(get_longest_track(tracks), database)
"""
database = Database()
pairs = database.Pairs
... |
def preprocess_smiles(self, mol_list):
atom_encodings = []
for mol in mol_list:
for atom in mol.GetAtoms():
encoded_atom = self.encode_atom(mol, atom)
if encoded_atom not in atom_encodings:
atom_encodings.append(encoded_atom)
retu... | The main task of the code is to train a Graph Convolutional Network (GCN) model on molecular data using specified hyperparameters (epochs, learning rate, batch size). It preprocesses molecular structures, constructs a data loader, initializes the model, and performs training via Adam optimization with MSE loss. The mod... | def fit_model(self, epochs=2000, lr=0.0001, lr_decay=0.999, batch_size=32, mode='both'):
mols = [Chem.MolFromSmiles(smiles) for smiles in self._training_set_molecules]
if self._encodings is None:
self._encodings = self.preprocess_smiles(mols)
data_list = [self.mol_to_data(mol, self.... |
def getNNOutput(dataset, model, device, signalIndex=2):
batchSize = 100
labels = np.array([])
targetLabels = np.array([])
output_tags = np.array([])
rawOutputs = np.array([])
allOutputs = np.array([])
inputFileIndices = np.array([])
pT = np.array([])
weight = np.array([])
meds = ... | The code evaluates a trained neural network model on test data, analyzing performance through ROC curves, signal parameter scores, pT correlations, confusion matrices, and discrimination plots. It loads a pre-trained model, processes test outputs, and generates visualizations to assess classification accuracy and signa... | def main():
# parse arguments
parser = ArgumentParser(config_options=MagiConfigOptions(strict = True, default="logs/config_out.py"),formatter_class=ArgumentDefaultsRawHelpFormatter)
parser.add_argument("--outf", type=str, default="logs", help='Name of folder to be used to store outputs')
parser.add_argu... |
def _do_list(client, fmt="md"):
metrics = client.list_metrics()
if fmt == "md":
md = "# List of tau_metric_exporter Metrics\n\n" + "\n".join(["* **{}** ({}) : {}".format(x["name"], x["type"], x["doc"]) for x in metrics])
_show_md(md)
else:
_show_data(metrics, fmt=fmt)
return 0
... | This code defines a command-line client for interacting with a `tau_metric_proxy` server. It parses arguments to retrieve metrics, list available metrics, track values over time, or output data in specified formats (e.g., JSON, YAML). The client connects via a UNIX socket, executes requested actions (like listing metri... | def run():
#
# Argument parsing
#
parser = argparse.ArgumentParser(description='tau_metric_proxy client')
parser.add_argument('-o', '--output', type=str, help="File to store the result to")
parser.add_argument('-u', '--unix', type=str, help="Path to the tau_metric_proxy UNIX socket")
par... |
def _exchange_config(self, conf):
jconf = json.dumps(conf)
self.sock.sendall(bytes(jconf, encoding="utf-8"))
ret = self.sock.recv(8192)
return json.loads(ret.decode(encoding="utf-8"))
def _run_metric_proxy(self, first=False):
pid = os.getpid()
random.seed(pid)
pro... | This method registers a configuration for a process by initializing host info, exchanging config data, and handling first-instance setup. If 'new' is True, it runs metric proxy/client, marks config for overwrite, and updates the config again before closing the socket. | def _register_config(self, args):
self.config = {"host": socket.gethostname()}
self.config = self._exchange_config(self.config)
if self.config["new"]:
# We are the first for this process do scafold
self._run_metric_proxy(self.config["first"])
if args.log:
... |
def password_checker(passw):
count_alpha=0
count_digit=0
count_special=0
for i in passw:
if i.isalpha():
count_alpha+=1
elif i.isdigit():
count_digit+=1
else:
count_special+=1
if count_alpha>=4 an... | The main task of the code is to implement a user sign-up system that validates a username and password (ensuring they are different, meet length and complexity requirements), confirms the password, and stores the credentials in a database. It handles retries for invalid passwords and enforces security rules like minimu... | def sign_up():
user=input("Enter New Username:")
print("Enter New password [Must contain characters, digits, special character (Minimum length 8) ] : ")
passw = input()
if user==passw:
print("Username and password cannot be same\nPlease try again")
sign_up()
elif len(passw) >= 8:
... |
def login_chk(user):
cursor.execute("Select * from login")
x=cursor.fetchall()
for i in x:
if i[0]==user:
print("Username already exist!")
print("Try logging in!")
print()
print(" Login Page ... | The code's main task is to handle user registration by collecting a username and password, validating the password's complexity (minimum 8 characters with letters, digits, and special characters), ensuring it doesn't match the username, confirming it with the user, and storing the verified credentials in a database. It... | def sign_up():
user = input("Enter New Username: ")
x = login_chk(user)
if x:
print("Enter New password [Must contain characters, digits, special character (Minimum length 8) ] : ")
passw = input()
if user == passw:
print("Username and password cannot be same\nPlease try ... |
def handle_common_params_to_masking_and_zeroshot(
params: dict,
) -> Tuple[str, int, pd.DataFrame]:
"""
Handles the common parameters to masking and zeroshot scanners.
Parameters:
params: The parameters passed to daisybell.
Returns:
A tuple of the suffix, the maximum number of name... | The code evaluates a named entity recognition (NER) model's ability to detect "PER" entities across multiple languages. It replaces detected entities in book sentences with names from other languages (plus a suffix), then measures how often the model identifies these substituted entities. The result is a sorted DataFra... | def scan(self, model: Pipeline, params: dict) -> pd.DataFrame:
(
suffix,
max_names_per_language,
wikidata,
) = handle_common_params_to_masking_and_zeroshot(params)
max_sentences_per_book = params.get("max_sentences_per_book", 999999999)
max_books = pa... |
def ChooseRandomCentroids(data, k):
centroids = [] # our k centroids will go in here
used_keys = []
# Keep looping until we have k number of centroids
while len(centroids) < k:
# Choose a random key from the data AND MAKE SURE IT'S A UNIQUE CHOICE
key = random.choice(l... | This function performs K-means clustering on 2D data by iteratively assigning data points to the nearest centroid, updating centroids based on cluster means, and repeating until centroids stabilize or max_passes is reached. It returns final centroids and cluster assignments, with optional real-time visualization of eac... | def CreateKMeansClusters(k, data, colors, x_label=None, y_label=None, max_passes=10, show_debug=True):
# These two variables help us know when to finish the algorithm
stable_clusters = False
pass_count = 0
# Choose our initial centroids
prev_centroids = ChooseRandomCentroids(data, k)
... |
def initRandomCentroids(data, k):
"""
Randomly places the centroids to begin the kmeans algorithm
Args:
data: the set of data in question
k: number of centroids/ groups
Returns:
Returns list of centroids
"""
centroids = []
x = 0
used = []
# Initializes list o... | The code implements the K-means clustering algorithm by iteratively initializing random centroids, assigning data points to clusters based on centroid proximity, recalculating centroids from cluster means, and repeating until centroids stabilize or 10 iterations are reached. It returns the final centroids and cluster a... | def run_kmeans_algorithm(data, k):
"""
The main kmeans Algorithm; initializes random centroids based on the data, calculates
and recalculates which cluster the data belongs in based on the centroids, which
also get recalculated in a loop until either a centroid doesn't move or 10 loops occurs.
Args... |
def print_menu(self, title, options):
clear()
print('-'*100)
print(title)
print('-'*100)
for key in options.keys():
print(" {key}: {description}".format(key=key, description=options[key]))
def listall(self):
"""
Displays menu for listing all ticke... | The code displays a menu with options to list all tickets, list one ticket, or quit. It loops until the user selects 'q', executing corresponding methods like listall() or listone() based on input. | def menu(self):
"""
Displays main menu.
q: Quit
1: List all tickets
2: List one ticket
"""
options = {'1' : 'List all tickets', '2' : 'List one ticket', 'q' : 'Quit'}
while not self.end:
self.print_menu('Ticket Viewer Menu', options)
... |
def undo(self):
if len(self.trace) == 0: # undo last mask
self.global_masks[self.last_mask] = 0
self.prev_mask_data[:, :, 3][self.last_mask] = 0
self.prev_mask_plot.set_data(self.prev_mask_data)
self.label -= 1
self.full_legend.pop()
self.... | This function handles keyboard events in an interactive plotting application, enabling actions like undo (z), saving and closing (enter/escape), and toggling help text (h) that explains labeling controls. It updates the UI dynamically based on user input. | def _on_key(self, event):
if event.key == 'z':
self.undo()
elif event.key == 'enter':
self.new_tow()
self.save_annotation()
plt.close(self.fig)
elif event.key == 'escape': # save for notebooks
plt.close(self.fig)
... |
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def activate(x_image, W_conv1, W_conv2, W_conv3, W_fc1, W_fc2, b_conv1,
b_conv2, b_conv3, b_fc1, b... | The main task of the code is to train a convolutional neural network (CNN) for facial expression classification using the FER2013 dataset. The model consists of multiple convolutional layers followed by fully connected layers, employing dropout regularization during training. It uses softmax cross-entropy loss and the ... | def main():
x_image = tf.placeholder(tf.float32)
y_ = tf.placeholder(tf.float32)
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
W_conv3 = weight_variable([5,5,64,128])
b_conv3 = bias_variable([128])
W_fc... |
def generate_key():
key = Fernet.generate_key()
return key
def key_exchange(client_socket, sym_key):
"""
send the symmetric key to the client
"""
transfer_message = sym_key
client_socket.send(transfer_message + " 69420".encode('utf-8'))
def handle_client_message(client_socket, client_message... | This function manages multiple client connections using I/O multiplexing (select). It accepts new connections, exchanges symmetric keys, handles client messages, tracks active clients, and gracefully closes connections upon disconnection or errors. It maintains global client lists, timestamps, and keys, while a separat... | def handle_all_clients(connection_socket):
global ended_all
global connected_num
global key_client
global all_clients
global time_client
all_clients = []
inputs = [connection_socket]
outputs = []
key_client = {
}
time_client = {
}
disconnect_thread = Thread(targe... |
def get_client_message():
"""
get user input message
"""
user_message = str(type_message.get())
return user_message
def clear_history():
message_history.delete(1, END)
type_message.delete(0, END)
def find_new_conversation():
"""
in case the convers... | The main task of the code is to handle client input when the enter button is pressed. It processes user messages, checks for broadcast/clear commands, manages socket connections, sends encoded messages to the server, updates message history, and formats display text. It also restarts communication threads if the conver... | def client_send(event):
"""
handle client pressing enter button
"""
global message_num
global main_socket
global server_details
global ended
global client_data
global always_broadcast
global last_message
user_message = get_client_m... |
def add_patient(med_rec, name=None, heart_rate=None, ecg_str=None,
img_str=None):
"""Adds a patient to the database.
Adds a patient to the database with the given medical record number. Since
only the medical record number is necessary to add a patient the other
inputs are optional. If ... | (The main task of the code is to initialize a server by connecting to a MongoDB database, clearing existing data, and populating it with predefined patient records containing base64-encoded ECG and medical image data. If the `testing` flag is True, it adds simplified test patients with placeholder data for easier testi... | def init_server(testing=True):
"""Server initialization function.
Initializes server by connecting to the MongoDB for this project. The
current database is cleared with each run to ensure no data is accidentally
added during testing. Adds initial patients with base64 encoded image
strings for ECG a... |
def validate_new_patient(in_data):
"""Validates the input json dictionary
The function takes in a json dictionary, tests that the medical
record number is in the dictionary, tests that each key has the
correct name, and tests that each value has the right data type.
If any of these fail, a message ... | This function processes a JSON input containing patient data to either add a new patient to the database or update existing information. It validates input format, checks for existing patients via medical record number, and adds/update fields like name, heart rate, ECG data, and medical images. It returns success/failu... | def add_new_patient_worker(in_data):
"""Driver function for the route /new_patient
The function validates that the input json dictionary is of
the correct format, keys, and values, adds the patient information
to the database with the input json dictionary, and outputs a message
of success or failu... |
def pt_data_from_server(med_rec):
"""Requests data from a specific patient from the patient server.
Sends a GET request to the "/patient_data/<med_rec>" route of the patient
server (see fp_server.py). This route returns a dictionary containing the
all of the current data for that patient (medical recor... | This function retrieves patient data from a server based on a selected medical record number (MRN) via a GUI button. It stores the retrieved data globally, populates GUI fields with patient details, and handles errors by displaying messages. If successful, it updates status messages and initializes default visuals for ... | def retrieve_patient_cmd():
"""Patient retrival command for patient selection GUI button.
Gets the selected medical record number from the patient selection
dropdown list in the GUI and retrieves the patient data for the patient
specified by that medical record number. The patient data ... |
def get_medical_records():
"""Gets a GUI-accessible list of medical record numbers from server.
Uses the med_recs_from_server function to get a list of medical record
numbers for all patients registered in the patient database inside the
GUI definition. This list of medical record numbe... | The function `get_update_info` periodically (every 15 seconds) fetches the latest medical record list from the server, updates the GUI with this data, and if a patient is selected, synchronizes their details, ECG data, and fields. It uses `tkinter.root.after()` for recurring execution, ensuring real-time updates to the... | def get_update_info():
"""Updates GUI information with data from the server every 15 seconds.
Makes requests to the server to get the latest list of medical record
numbers in the server and updates to the currently selected patient's
data. If no patient is currently selected, only the l... |
def detect(self, home_pos: ti.template(), home_radius: ti.f32,
food: ti.template(), obstacle: ti.template(), size: ti.f32):
for i in range(self.N):
self.attraction[i] = 0.0
if (home_pos[0] - self.pos[i]).norm() <= home_radius:
self.internal_clock[i] = self.... | The code's main task is to move an agent by detecting environmental elements (home, food, obstacles), setting a random orientation, updating its position while avoiding obstacles, and applying periodic boundary conditions to handle spatial boundaries. | def move(self, home_pos, home_r, food, size, obstacle):
self.detect(home_pos, home_r, food, obstacle, size)
self.random_ori()
self.update_pos(obstacle)
self.pbc() |
def slime_detect(self):
for i in range(self.N):
self.attraction[i] = 0.0
if self.is_home[i] == 1:
self.detect_things(i, self.from_home)
else:
self.detect_things(i, self.from_food)
def random_ori(self):
for i in self.theta:
s... | The code defines a method `slime_move` that orchestrates three key actions: detecting environmental conditions via `slime_detect`, generating a random orientation with `random_ori`, and updating the slime's state or position through `slime_update`. Together, these steps enable the slime to dynamically respond to its su... | def slime_move(self):
self.slime_detect()
self.random_ori()
self.slime_update() |
def paths():
p = PathGroup(
hvenv=Path(sys.executable).joinpath("..", "..").abspath(),
gen=Path(sys.executable).joinpath("..", "..", "..").abspath(),
key=Path(hvenv().joinpath("linkfile").bytes().decode("utf8").strip()),
)
p.hitchreqsin = p.key.joinpath("hitchreqs.in")
p.hitchreq... | The function ensures installed packages match hitchreqs.txt by checking file existence, comparing contents, and using pip-sync to synchronize. It triggers a restart if discrepancies are found, ensuring correct package versions are used for subsequent runs. | def ensure_hitchreqs_synced():
"""
Check packages installed are in sync with what is in hitchreqs.txt.
If not, run pip-sync and re-run everything to ensure that everything is run
with the correct packages installed.
"""
trigger_rerun = False
path = paths()
if path.hitchreqsin.exists() ... |
def get_distribution(data_sequence, number_of_bins = 30):
"""
Function to get a log-binned distribution of a given dataset.
Args:
data_sequence: numpy array with data to calculate
log-binned PDF on.
number_of_bins: number of logarithmic bins to use.
Returns:
... | The function `make_plots` generates visualizations and saves data for tail index estimation of a given ordered dataset. It calculates the probability density function (PDF), complementary cumulative distribution function (CCDF), and applies multiple estimators (Pickands, smooth Hill, adjusted Hill, moments, kernel-type... | def make_plots(ordered_data, output_file_path, labda, number_of_bins,
r_smooth, alpha, hsteps, bootstrap_flag, t_bootstrap,
r_bootstrap, diagn_plots, eps_stop, theta1, theta2,
verbose, noise_flag, p_noise, savedata):
"""
Function to create plots and save tail index e... |
def get_item():
while True:
choice = input(
f"""
Select:
1. to add an income
2. to add an expense
"""
)
if choice.lower() == "1":
item = "income"
break
elif choice.lower() == "2":
item = "expense"
break
else... | The main task of the code is to collect user input data (item, date, category, amount, comment), save it to a username-specific CSV file, and sort the file's contents. It uses helper functions to retrieve data, writes a new line to the CSV, and ensures the file's data is sorted after each addition. | def add_data(username):
print(f"Here we add the data, {username}")
filename = username + ".csv"
item = get_item()
item_date = get_date()
item_category = get_category_from_file(filename, item)
item_amount = get_amount()
item_comment = get_comment()
add_line_to_file(
username, i... |
def read_csv_to_df_with_dates(filename):
df = pd.read_csv(filename) # automatically?
df["date"] = pd.to_datetime(df["date"]).dt.date
return df
def choose_data_row_to_edit(df):
df_chosen = df.copy()
while True:
choice = input(
"""
Select number to filter the data by the follow... | The main task of the code is to edit data in a user-specific CSV file. It checks if the file exists and is non-empty, allows selecting a row to modify, updates the data, sorts the DataFrame by date, and saves the changes back to the CSV file. | def edit_item(username):
filename = username + ".csv"
if not file_exists(filename):
print("There is no file for this name and currency. Please, add new data")
return
df_file = read_csv_to_df_with_dates(filename)
if len(df_file) == 0:
print("The file is empty. Add new data")
... |
def get_block_size_parted(outfile, temp_time):
block_size_command = "sudo cat /tmp/timeline_partition_info_" + temp_time +".txt | grep -a " + "'"+"Sector size"+"'" + " | awk {'print $4'} | sed s_B/.*__"
outfile.write("The block_size command is: " + block_size_command + "\n")
block_size = subprocess.check_output([blo... | The main task of the code is to extract Windows registry hives from disk image evidence (e.g., E01 files) by analyzing partitions, handling NTFS/FAT32 file systems, processing unallocated clusters, overt/deleted files, and shadow volumes. It creates output directories, runs forensic tools (mmls, parted), removes duplic... | def extract_registry_hives_mr(item_to_process, case_number, root_folder_path, evidence, options):
print("The item to process is: " + item_to_process)
print("The case_name is: " + case_number)
print("The output folder is: " + root_folder_path)
print("The evidence to process is: " + evidence)
print("The options sele... |
def build_random_state(n, static_x, static_y):
state = []
for row in range(n):
# Put queen at static point.
if row == static_x:
state.append(static_y)
continue
col = random.randint(0, n - 1)
state.append(col)
return state
def n_queens(initial_state, st... | This function solves the N-Queens problem using k random restarts, tracking the best states with the lowest conflict score (f-score). It initializes a random board, runs the solver, and updates the minimum states list if a lower f-score is found. Finally, it prints all optimal states found, prioritizing those with zero... | def n_queens_restart(n, k, static_x, static_y):
random.seed(1)
# In the previous assignment i assigned 1000000 as the value for minimum.
# Here I found the alternative to JAVA's Integer.MIN_VALUE. We want the first f to be the minimum
min_fScore = sys.maxsize
min_states = []
for i in range(k):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.