dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def extract_orcid_info(orcid_dir):
# First check if there is an ORCID.json file
if os.path.isfile(os.path.join(orcid_dir, 'ORCID.json')):
print('Loading ORCID dict from local json.')
with open(os.path.join(orcid_dir, 'ORCID.json')) as f:
return json.load(f)
# Personal info
... | The code generates a CV document from ORCID data. It extracts information from an ORCID directory, configures document settings based on a specified style, creates a PDF with sections like personal details, employment, education, publications, talks, and preprints, then builds and saves the formatted CV as a file. | def quick_build(orcid_dir, output_fname, style = 'greenspon-default'):
orcid_dict = extract_orcid_info(orcid_dir)
config = make_document_config(style)
doc_title = orcid_dict['personal']['fullname'] + ' - CV'
doc = SimpleDocTemplate(output_fname,
pagesize = letter,
... |
def generate_file_tree(commands: list[str]):
"""Iterate over the commands, and keep track of where we are by
using a list of visited folders."""
ret = {}
path_stack = []
for command in commands:
if command.startswith("$"):
command_segments = command.split(" ")
if comm... | The function `solver_2star` identifies the smallest folder size that, when deleted, reduces the total disk usage to meet a required minimum. It calculates the current disk size, determines the target minimum, and iterates through sorted folders to find the smallest valid candidate. The goal is to free up at least 30,00... | def solver_2star(data):
tree = generate_file_tree(data)
max_disk_size = 70000000
needed_disk_size = 30000000
minimum_disk_size = max_disk_size - needed_disk_size
current_size = calculate_tree_size(tree)
flat_size = flatten_tree_and_get_sizes(tree)
folders = {
key: value for key, valu... |
def data_parser(filepath):
"""Parse the data by splitting each line."""
with open(filepath, "r") as file:
# split into lines
return [[int(y) for y in x.removesuffix("\n")] for x in file.readlines()]
def solver_1star(data):
height, width = forrest_dimensions(data)
# Test all trees, and co... | The main task of the code is to execute a program that processes input data from a file, parses it, and returns solutions for two star problems based on the `solve` parameter. If `solve=0`, it returns both solutions; if `solve=1`, only the first star's solution; if `solve=2`, only the second star's solution. Invalid `s... | def main(solve=0):
"""Run the program by itself, return a tuple of star1 and star2.
solve: set what stars we want, 0 returns both
"""
dirname = os.path.dirname(__file__)
input_source = os.path.join(dirname, "..", "input1.txt")
# Make list, since the generator has to be used multiple times
d... |
def data_parser(filepath):
"""Parse the data by splitting each line."""
with open(filepath, "r") as file:
# split into lines
return [x.removesuffix("\n") for x in file.readlines()]
def solver_1star(data):
tree = generate_file_tree(data)
flat_size = flatten_tree_and_get_sizes(tree)
# ... | The main task of the code is to execute a program that processes input data from a file, applies two distinct solvers (`solver_1star` and `solver_2star`), and returns their results in a tuple based on the `solve` parameter. If `solve=0` (default), both solvers are executed; if `solve=1`, only the first solver's result ... | def main(solve=0):
"""Run the program by itself, return a tuple of star1 and star2.
solve: set what stars we want, 0 returns both
"""
dirname = os.path.dirname(__file__)
input_source = os.path.join(dirname, "..", "input1.txt")
# Make list, since the generator has to be used multiple times
d... |
def display_board_init():
print('1' + '|' + '2' + '|' + '3')
print('-' * 5)
print('4' + '|' + '5' + '|' + '6')
print('-' * 5)
print('7' + '|' + '8' + '|' + '9')
def init():
players_data = {
'Player1': {
'name': '',
... | The code implements a tic-tac-toe game where two players take turns selecting positions on a board. It initializes game data, determines the starting player via a coin flip, and alternates turns. After each move, it checks for a win or tie, displays results, and offers replay. The game loop continues until a player win... | def game_start():
game_on = True
print("initial board data")
display_board_init()
while True:
# Initialize the data for players and game
players_data, game_data = init()
# Flip the coin, and select the player
current_player = turn_flipper(players_data)
print(f"{... |
def full_setup():
"""This function gets the baseline vehicle and creates modifications for different
configurations, as well as the mission and analyses to go with those configurations."""
# Collect baseline vehicle data and changes when using different configuration settings
vehicle = vehicle_setup(... | The main task of the code is to configure and analyze vehicle settings through sizing and finalization, compute weight breakdowns, execute a mission analysis, and visualize results like altitude profiles and L/D ratios. It orchestrates setup, evaluation, and plotting of aerospace vehicle performance data in a structure... | def main():
"""This function gets the vehicle configuration, analysis settings, and then runs the mission.
Once the mission is complete, the results are plotted."""
# Extract vehicle configurations and the analysis settings that go with them
configs, analyses = full_setup()
# Size each of the ... |
def imgs2arr(img_names, img_dir, version = 1):
""" convert images to mutli-dimensional array
Args:
@img_names: image names (e.g. [pic001.png])
@img_dir: directory of the images (e.g. ./tmp)
@version: for vggface model preprocessing
Return:
np.array
"""
imgs = []
f... | The code evaluates a model's performance on validation data by predicting BMI, age, and sex from image arrays. It calculates metrics: MAE for BMI and age, and AUC for sex, comparing predictions with true values in `valid_data`. Results are returned as a dictionary of error and correlation scores. | def evaulate(self, valid_data):
imgs = valid_data['index'].values
arr = imgs2arr(imgs, self.img_dir, self.version)
bmi, age, sex = self.model.predict(arr)
metrics = {'bmi_mae':mae(bmi[:,0], valid_data.bmi.values),
'bmi_cor':cor(bmi[:,0], valid_data.bmi.values),
... |
def parse_files(root):
global document_count
for filename in os.listdir(root): #opens the root directory
for json_files in os.listdir(os.path.join(root, filename)): #opens each file within the root directory
... | The main task of the code is to initialize storage directories, process files in the 'DEV' directory, save document ID mappings to a JSON file, load data into memory, and compute TF-IDF scores for text analysis. | def start():
if not os.path.exists('storage'):
os.mkdir('storage')
if not os.path.exists('storage/partial'):
os.mkdir('storage/partial')
parse_files('DEV')
with open("storage/docID_mappings.json", "w+") as output_file: #writes docID mappings to a file
json.dump(doc_id_dict,... |
def __prepare_resources(self, questions):
questions_per_resources = {}
for question in questions:
fields_for_translation = {}
if not self.__check_resources_for_category(settings.TRANSIFEX_ORGANIZATION, settings.TRANSIFEX_PROJECT, question.category.name):
self.cr... | The code processes a list of questions by grouping them into resources, converting resource paths to strings, uploading corresponding files, and verifying each uploaded source's string representation. | def manage_source_uploading(self, questions_list):
questions_per_resources = self.__prepare_resources(questions_list)
resources_strings = self.__convert_paths(questions_per_resources)
uploaded_ids = self.__upload_files(self.__create_resource_files(resources_strings))
if len(uploaded_ids... |
def OnCloseWindow (self):
# Close this window
self.preserve_data()
self.Close(True)
def OnAboutWindow(self):
dlg = AboutDialog(self, self)
dlg.ShowModal()
dlg.Destroy()
def OnLoginWindow(self):
self.dlg = login.LogIn(self, self)
self.dlg.Show() | The code defines a MenuHandler method that processes menu item selections by checking the event's ID and invoking corresponding actions: closing a window, displaying about information, or handling login functionality based on the selected menu option. | def MenuHandler(self, e):
id = e.GetId()
if(id == ID_MENU_FILE_CLOSE):
self.OnCloseWindow()
elif(id == ID_MENU_HELP_ABOUT):
self.OnAboutWindow()
elif(id == ID_MENU_LOGIN):
self.OnLoginWindow() |
def imgs2arr(img_names, img_dir, version = 1):
""" convert images to mutli-dimensional array
Args:
@img_names: image names (e.g. [pic001.png])
@img_dir: directory of the images (e.g. ./tmp)
@version: for vggface model preprocessing
Return:
np.array
"""
imgs = []
f... | The code evaluates a model's performance on validation data by predicting BMI, age, and sex from image indices, then calculating metrics like MAE for BMI/age and AUC for sex against true values in `valid_data`, returning these metrics in a dictionary. | def evaulate(self, valid_data):
imgs = valid_data['index'].values
arr = imgs2arr(imgs, self.img_dir, self.version)
bmi, age, sex = self.model.predict(arr)
metrics = {'bmi_mae':mae(bmi[:,0], valid_data.bmi.values),
'bmi_cor':cor(bmi[:,0], valid_data.bmi.values),
... |
def whyAction(AnswerSet, ASPprogram, timestep,i):
sorted_actions = planDescription(AnswerSet)
if sorted_actions == []:
return [],[]
action = sorted_actions[i]
action_query = action
action = re.sub(" ","",action)
action = re.sub("\(","\(",action)
action = re.sub("\)","\)",action)
pri... | The code generates explanations for actions and their negations in a planning scenario by reading input files, processing time steps, and logging results into a CSV file. It combines data from multiple sources, analyzes actions using ASP logic, and records plans, explanations, and decision trees for each step. | def explain(AS1, ASP, step, length, j):
#reading the files
file_names = [AS1, "Explanations/next_dir", "Explanations/next_to_terms.txt", "Explanations/not_next"]
#file_names2 = ["history2", "Explanations/next_to_terms.txt", "Explanations/not_next","Explanations/next_dir"]
AnswerSet = ""
# Iterate through the fil... |
def get_pieces(self, colour):
pieces = [x for x in self.__pieces if x.colour == colour]
return pieces
def get_piece_at(self, location):
pieces = self.pieces_at(location)
if len(pieces) == 0:
return None
return pieces[0]
def is_move_possible(self, piece, die_roll):
... | This function checks if any piece of the given colour can make a move with the provided dice roll. It retrieves unique piece locations, iterates through each die in the roll, and tests if any piece can move using that die. If no valid moves are found, it returns True; otherwise, it returns False. | def no_moves_possible(self, colour, dice_roll):
piece_locations = [x.location for x in self.get_pieces(colour)]
piece_locations = list(set(piece_locations))
dice_roll = list(set(dice_roll))
pieces = []
for piece_location in piece_locations:
pieces.append(self.get_piec... |
def is_move_possible(self, piece, die_roll):
# Check if there is a piece at the taken location and prevent the move if necessary
if piece is not None and len(self.pieces_at(self.__taken_location(piece.colour))) > 0:
if piece.location != self.__taken_location(piece.colour):
re... | This function moves a game piece according to a die roll, checks if the move is valid, adjusts direction for black pieces, removes the piece if it exits the board, captures opponent's pieces at the new location by moving them to a "taken" position, and updates the piece's location. | def move_piece(self, piece, die_roll):
# if not self.__pieces.__contains__(piece):
# raise Exception('This piece does not belong to this board')
if not self.is_move_possible(piece, die_roll):
raise Exception('You cannot make this move')
if piece.colour == Colour.BLACK:
... |
def load_cropped ():
global ref_rects
ref_rects = road['cropped_rects']
print('Loaded ref_rects from settings.json!')
def process_frame(frame_number, frame, bg_subtractor, car_counter):
processed = frame.copy()
gray = cv2.cvtColor(processed, cv2.COLOR_BGR2GRAY)
# remove specified cropped regions
cropped, pro... | This code performs real-time vehicle counting using OpenCV's KNN background subtraction. It captures video from a stream, processes frames to detect moving vehicles, and tracks them with a VehicleCounter. The program displays original and processed frames, allows saving cropped regions, and exits on 'q' or ESC. It hand... | def main ():
bg_subtractor = cv2.createBackgroundSubtractorKNN(detectShadows=True)
car_counter = None
load_cropped()
cap = cv2.VideoCapture(road['stream_url'])
#cap=cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 2)
cv2.namedWindow('Source Image')
cv2.setMouseCallback('Source... |
def readByte(self) -> int:
return int.from_bytes(self.file.read(1), byteorder='little')
def readBool(self) -> bool:
return bool.from_bytes(self.file.read(1), byteorder='little')
def readNumber(self) -> float:
# IEEE 754 double-precision binary floating-point format
return struct.unpack('<d', self.file.r... | The method reads a dictionary structure from a data stream by interpreting type codes. It returns parsed values (bool, number, string, etc.) or recursively builds a Python dictionary by reading key-value pairs, using indexes as keys. Unsupported types raise errors. | def readDictionary(self, dictName:str="") -> Union[bool, float, str, dict]:
treeType = self.readByte()
treeBool = self.readBool()
if treeType == 0: # None
raise NotImplementedError
elif treeType == 1: # Bool
return self.readBool()
elif treeType == 2: # Number
return self.readNumber... |
def writePropertyType(self, type:str) -> None:
self.writeByte(self.types.get(type))
self.writeBool(False)
def writeUnsignedInteger(self, value:int, spaceOptimised:bool=False) -> None:
if spaceOptimised:
self.writeByte(min(value, 255))
if value >= 255:
self.writeUnsignedInteger(value, spa... | This function serializes a dictionary by writing its type, size, and each key-value pair with appropriate type handling. It writes the dictionary's size, iterates through key-value pairs, and processes values as booleans, floats, or strings, raising errors for unsupported types like lists or nested dictionaries. | def writeDictionary(self, value:dict) -> None:
self.writePropertyType('dictionary')
dictSize = len(value.keys())
self.writeUnsignedInteger(dictSize)
for dictIndex in range(dictSize):
dictKey, dictValue = value.get(dictIndex)
self.writeString(dictKey)
if type(dictValue) is None:
... |
def make_freqvaluency_dict(self, text):
freqvaluency = {}
for char in text:
if not char in freqvaluency:
freqvaluency[char] = 0
freqvaluency[char] += 1
return freqvaluency
def min_heapify_dict(self, freqvaluency):
heap = []
for key in freqv... | The code implements Huffman encoding by building a frequency dictionary, constructing a min-heap, merging nodes into a binary tree, generating binary codes from the tree, and encoding the input text using these codes. It returns the compressed binary string and the Huffman tree for decoding. | def huffman_encoding(self, text):
if text == "":
return "", None
freqvaluency_dict = self.make_freqvaluency_dict(text)
min_heap = self.min_heapify_dict(freqvaluency_dict)
merged_heap = self.merge_nodes(min_heap)
tree = heapq.heappop(merged_heap)
codes = self.c... |
def encrypt(string, key):
ciphertext = ""
for ch in list(string):
if 'A' <= ch <= 'Z':
ciphertext += chr((ord(ch) - ord('A') + key) % 26 + ord('A'))
elif 'a' <= ch <= 'z':
ciphertext += chr((ord(ch) - ord('a') + key) % 26 + ord('a'))
elif '0' <= ch <= '9':
... | The code implements a Caesar cipher tool that encrypts, decrypts, or analyzes text based on command-line arguments. It parses input text, a key (integer), and a mode ('enc' for encryption, 'dec' for decryption, 'anl' for analysis). Depending on the mode, it applies the Caesar cipher algorithm to transform or analyze th... | def main():
parser = argparse.ArgumentParser(description='Caesar cipher')
parser.add_argument('text', help='data string')
parser.add_argument('key', type=int, help='key (integer)')
parser.add_argument('mode', choices=['enc', 'dec', 'anl'], nargs='?',default='enc', help="mode")
args = parser.parse_a... |
def _clear_canvas(self, canvas: Optional[ctk.CTkCanvas] = None):
"""
Clears the canvas by destroying all widgets and clearing the canvas itself.
Args:
canvas (Optional[ctk.CTkCanvas]): The canvas to be cleared. If not provided, all widgets will be destroyed but the canvas will not b... | The code defines a method to initialize and display the game menu. It selects a starting player, clears the canvas, draws the game grid, creates a "Menu" button to return to the main menu, positions the button, and binds a mouse click event to the game grid for interaction. | def _game_menu(self):
"""
Displays the game menu and starts a new game.
"""
self.current_player = self.choose_starting_player(
[self.Player_one, self.Player_two]
)
self._clear_canvas()
self._draw_game_grid()
self.menu_button = self._create_but... |
def _update_label(self, label: ctk.CTkLabel, text: str, **kwargs) -> ctk.CTkLabel:
"""
Updates the given label with the specified text and optional keyword arguments.
Args:
label (ctk.CTkLabel): The label to be updated.
text (str): The new text for the label.
... | The main task of the code is to execute a move in the specified column, update the UI to indicate the current player's turn, handle game-over scenarios (draw or win) by triggering a menu, display error messages for invalid moves, and render the game state. It manages game flow, visual feedback, and exception handling t... | def make_move(self, column: int) -> str | None:
"""
Makes a move in the specified column and handles game events.
Args:
- column (int): The column in which to make the move.
Returns:
- str | None: The game over message if the game is over, otherwise None.
... |
def debug_verbose(msg, o_gui, b_verbose):
"""Verbose cmd or gui if b_verbose is ON"""
if not b_verbose:
return False
if o_gui:
o_gui.display_debug(msg)
else:
lg.debug(msg)
return True
def dtnt():
"""Return current date and time"""
return datetime.now().time()
def a... | The function `launch_analysis` analyzes a given path or file (script/project) by checking its validity, performing recursive or detailed analysis, and formatting results. It handles GUI or command-line output, cancels analysis if needed, and returns formatted results or errors. The core task is to validate input, execu... | def launch_analysis(pof, o_gui, b_verbose, b_detail, b_byfile, b_recur, b_exem,
ex_fo, ex_fi, sort):
"""Check if pof (path or file) is a good argument and start analysis"""
lg.basicConfig(level=lg.DEBUG)
pof_error = f"Invalid argument 'path_or_file': '{pof}'"
pof_is = ""
result ... |
def drivetrainValueSelection(_callback=None):
CURRENT_VALUE = 0
while True:
if left():
CURRENT_VALUE -= 1
update(CURRENT_VALUE)
dt.drive(DEFAULT_POWER, -1)
elif right():
CURRENT_VALUE += 1
update(CURRENT_VALUE)
dt.drive(DEF... | The code defines a callback function `actionSelectCallback` that handles different action types by printing the action and invoking corresponding selection functions with their own callbacks, enabling user input for drivetrain, waiting, turning, or motor operations. | def actionSelectCallback(actionType):
print(actionType)
if actionType == 'Move':
drivetrainValueSelection(drivetrainValueSelectionCallback)
elif actionType == 'Wait':
waitValueSelection(waitValueSelectionCallback)
elif actionType == 'Turn':
turnValueSelection(turnValueSelectionC... |
def select_action():
available_actions = ['Move', 'Turn', 'Wait', 'Run Motor']
action = available_actions[0]
while True:
vexiq.lcd_write('Action select (' + action + ')')
if joystick.bLup():
action = available_actions[(available_actions.index(action) - 1) % len(available_action... | The code defines a recursive function `run()` that repeatedly selects user actions (Move, Turn, Wait, Run Motor), captures associated parameters (e.g., movement values, motor names), and appends them to a global `actions` list. It uses sleep delays between operations and handles motor availability checks for "Run Motor... | def run():
action = select_action()
sleep(0.2)
if action == 'Move':
value = select_integer_value(-100, 100, moveOnDecrease, moveOnIncrease, 0)
sleep(0.1)
actions.append({ 'type': 'move', 'value': value })
print('Saved move action')
elif action == 'Turn':
valu... |
def _parse_config(self, conf):
config = ConfigParser.ConfigParser()
config.read(conf)
KEY_TRAINING = ['trainer','tester','solver']
config_dict = {s: {k:v for k,v in config.items(s)} for s in config.sections()}
if 'fine_tuning' in config_dict.keys():
KEY_TRAINING.appen... | The code initializes a class to manage data preparation, model training, and testing processes by parsing a configuration file, creating necessary directories, and generating prototxt files for workflow management. | def __init__(self, conf_file):
"""
[conf_file]
This class manages all processes (data preparation, model training, model testing)
based on input configuration file
'workspace' means directory consisting of data and training trials...
"""
self._conf... |
def connect_db():
client_db = MongoClient('mongodb://localhost:27017/')
db = client_db['trader_bot']
return db
def get_last_buy(db):
collection = db[TRADE_SYMBOL]
last_buy = collection.find().sort("date", -1).limit(1)[0]
if last_buy and last_buy['side'] == 'BUY':
return last_buy
retu... | The code processes real-time candlestick data to execute trading decisions based on RSI and MACD indicators. It checks if the market is overbought (RSI ≥ RSI_OVERBOUGHT) or oversold (RSI ≤ RSI_OVERSOLD), combined with MACD thresholds, to trigger sell or buy orders. It maintains position status, calculates gains, and in... | def on_message(ws, message):
# import pdb; pdb.set_trace()
global closes, in_position, bought
try:
db = connect_db()
last_buy = get_last_buy(db)
except Exception as e:
print(f"an exception occured - {e}")
last_buy = ""
if last_buy:
in_position = True
... |
def reset(self, agent = (0,0), keepQ=None):
self.agent = agent
self.mazeCopy = np.copy(self.maze)
nrow, ncols = self.mazeCopy.shape
row, col = agent
self.maze[row, col] = agent_mark
self.state = (row, col)
self.min_reward = -0.5*self.maze.size
self.total_r... | This code implements a Q-learning algorithm to train an agent in an environment by updating Q-values using the Bellman equation, tracking the best episode reward, and employing epsilon-greedy exploration to balance exploration and exploitation. It iterates over episodes, selects actions, updates the Q-table based on re... | def qlearning(self):
breakplz = False
times_won = 0
for episode in range(EPISODES):
self.reset(keepQ=True)
episode_reward = 0
SHOW_EVERY = 1
done = False
while not done:
if np.random.random() > self.epsilon:
... |
def reset(self, agent = (0,0), keepQ=None):
self.agent = agent
self.mazeCopy = np.copy(self.maze)
nrow, ncols = self.mazeCopy.shape
row, col = agent
self.maze[row, col] = agent_mark
self.state = (row, col)
self.min_reward = -0.5*self.maze.size
self.total_r... | This code implements the SARSA algorithm for reinforcement learning, updating Q-values using on-policy experience. It trains an agent by selecting actions via epsilon-greedy exploration, updating Q-table entries based on current and next state-action pairs, and tracking the best-performing episodes. The agent learns to... | def sarsa(self):
breakplz = False
times_won = 0
for episode in range(EPISODES):
self.reset(keepQ=True)
episode_reward = 0
SHOW_EVERY = 1
done = False
if np.random.random() > self.epsilon:
action = max(self.q_table[self... |
def reset(self, agent = (0,0), keepQ=None):
self.agent = agent
self.mazeCopy = np.copy(self.maze)
nrow, ncols = self.mazeCopy.shape
row, col = agent
self.maze[row, col] = agent_mark
self.state = (row, col)
self.min_reward = -0.5*self.maze.size
self.total_r... | The main task of the code is to implement a Q-learning algorithm for training an agent in a maze environment. It uses an epsilon-greedy strategy to explore/exploit actions, updates the Q-table with the Bellman equation when the episode continues, and tracks the best-performing episodes (highest reward) when the agent s... | def qlearning(self):
breakplz = False
times_won = 0
self.episode_print = 249
for episode in range(EPISODES):
self.reset(keepQ=True)
episode_reward = 0
SHOW_EVERY = 1
done = False
# print(episode)
self.episode = epis... |
def reset(self, agent = (0,0), keepQ=None):
self.agent = agent
self.mazeCopy = np.copy(self.maze)
nrow, ncols = self.mazeCopy.shape
row, col = agent
self.maze[row, col] = agent_mark
self.state = (row, col)
self.min_reward = -0.5*self.maze.size
self.total_r... | The code implements the SARSA reinforcement learning algorithm to train an agent by updating its Q-table using experience from each episode. It uses an epsilon-greedy strategy to choose actions, updates Q-values based on the SARSA formula (current Q + learning rate * (reward + discount * future Q)), tracks episode rewa... | def sarsa(self):
breakplz = False
times_won = 0
for episode in range(EPISODES):
self.reset(keepQ=True)
episode_reward = 0
SHOW_EVERY = 1
done = False
# print(episode)
if np.random.random() > self.epsilon:
ac... |
def reset(self, agent = (0,0), keepQ=None):
self.agent = agent
self.mazeCopy = np.copy(self.maze)
nrow, ncols = self.mazeCopy.shape
row, col = agent
self.maze[row, col] = agent_mark
self.state = (row, col)
self.min_reward = -0.5*self.maze.size
self.total_r... | The code initializes a reinforcement learning agent for a maze navigation task. It sets up the maze environment, defines the target and free blocks, validates the agent's starting position, and initializes a Q-table for learning. Depending on the specified algorithm (SARSA or Q-learning), it prepares to execute the cho... | def __init__(self, alg, maze, agent = (0,0)):
self.epsilon = EPSILON
self.maze = np.array(maze) #MAZE 10x10
nrows, ncols = self.maze.shape #nrows = 10, ncols = 10 (10, 10)
self.target = (nrows-1, ncols-1) # terminal block where the target is (9, 9)
self.freeblocks = [(r,c) for ... |
def reset(self, agent = (0,0), keepQ=None):
self.agent = agent
self.mazeCopy = np.copy(self.maze)
nrow, ncols = self.mazeCopy.shape
row, col = agent
self.maze[row, col] = agent_mark
self.state = (row, col)
self.min_reward = -0.5*self.maze.size
self.total_r... | This code initializes a reinforcement learning agent for maze navigation, setting up the environment, Q-table, target position, free blocks, and villains. It validates maze parameters, initializes the agent's position, and prepares for either Sarsa or Q-learning algorithms based on the specified algorithm. The setup in... | def __init__(self, alg, maze, villains, agent = (0,0)):
self.epsilon = EPSILON
self.maze = np.array(maze) #MAZE 10x10
nrows, ncols = self.maze.shape #nrows = 10, ncols = 10 (10, 10)
self.target = (nrows-1, ncols-1) # terminal block where the target is (9, 9)
self.villains = []
... |
def huffmanCode(text): # generates and returns the huffman tree of the text encoding
charOccurrences = {}
minHeap = []
for char in text: # Compute Frequencies
if char in charOccurrences:
charOccurrences[char] += 1
else:
charOccurrences[char] = 1
for char in cha... | The code implements the LZSS compression algorithm by encoding the input text using a sliding window and buffer size. It generates Huffman codes for symbols, builds an encoded header, and iteratively processes the text to encode repeated patterns. The output combines the header, Elias code for format fields count, and ... | def lzss(text, windowSize, bufferSize):
startPos = 0
endPos = len(text) - 1
huffmanCodeDict = huffmanCode(text)
encodeHeader = buildEncodedHeader(huffmanCodeDict)
numberOfFormatFields = 0
encodeData = bitarray()
while startPos <= endPos:
numberOfFormatFields += 1
output, next... |
def genZernikeCoeff(num_zern, D_r0):
'''
Just a simple function to generate random coefficients as needed, conforms to Zernike's Theory. The nollCovMat()
function is at the heart of this function.
A note about the function call of nollCovMat in this function. The input (..., 1, 1) is done for the sake ... | The code generates a blurred image by applying multiple point spread functions (PSFs) derived from Zernike coefficients to patches of the input image. It calculates patch sizes, generates PSFs, convolves them with image patches, and accumulates results to produce a final blurred image. The process involves iterative co... | def genBlurImage(p_obj, img):
smax = p_obj['delta0'] / p_obj['D'] * p_obj['N']
temp_line = np.arange(1,101)
patchN = temp_line[np.argmin((smax*np.ones(100)/temp_line - 2)**2)]
patch_size = int(round(1.0*p_obj['N'] / patchN))
xtemp = np.round_(p_obj['N']/(2*patchN) + np.linspace(0, p_obj['N'] - p_obj... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--epochs", type=int, default=3)
parser.add_argument("--train-batch-size", type=int, default=32)
parser.add_argument("--eval-batch-size", type=int, default=64)
parser.add_argument("--warmup_steps", type=int, default=500)
p... | The main task of the code is to train a DistilBERT model for sequence classification using synthetic text data. It loads and preprocesses training/ validation data, tokenizes texts, converts labels to numerical format, creates custom datasets, configures training parameters, initializes the model, trains it, evaluates ... | def main():
args = parse_args()
logger = setup_logger()
train_source = args.training_dir + "/synthetic.train.txt"
val_source = args.valid_dir + "/synthetic.validation.txt"
train_labels, train_texts = load_labels_and_texts(train_source)
val_labels, val_texts = load_labels_and_texts(val_... |
def compute_gradient(gradient_f,values):
grad = []
for derivative in gradient_f:
gradient = derivative(*values)
grad.append(gradient)
return np.array(grad)
def set_gradient_direction(function, gradient, hessian, values):
dk = []
grad = compute_gradient(gradient, values)
hess = co... | This code implements the globalized Newton method for optimization. It iteratively computes a search direction using the Hessian and gradient, determines a step size via the Armijo rule, and updates the solution until the gradient's norm falls below a threshold or max iterations are reached. The method aims to find a l... | def globalized_newton_method(function,gradient,hessian,initial,stopping_creiterion,max_iteration):
xk = initial
counter = 0
xk1 = 0
delta = 10**(-4)
while LA.norm(compute_gradient(gradient,xk)) > 0.01:
dk = set_gradient_direction(function,gradient,hessian,xk)
step_size = armijo_step_... |
def globalized_newton_method(function,gradient,hessian,initial,stopping_creiterion,max_iteration):
xk = initial
counter = 0
xk1 = 0
delta = 10**(-4)
while LA.norm(compute_gradient(gradient,xk)) > 0.01:
dk = set_gradient_direction(function,gradient,hessian,xk)
step_size = armijo_step_... | This function performs gradient descent or Newton's method for optimization, depending on the 'use_newton_direction' flag. It iteratively updates the solution using Armijo line search for step size determination, stopping when the gradient norm falls below 0.01 or max iterations are reached. The Newton direction varian... | def general_descent(function,gradient_f,initial,use_newton_direction,stopping_creiterion,max_iteration):
xk = initial
counter = 0
xk1 = 0
delta = 10**(-4)
if use_newton_direction:
xk1 = globalized_newton_method(function,gradient,hessian,initial,stopping_creiterion,max_iteration)
else:
... |
def _strip_bad_chars(self, text: str) -> str:
"""Remove chars that don't work well in filenames"""
return re.sub('[^0-9a-zA-Z@.?_:\'" ()]+', '_', text)
def _is_tweet(self) -> bool:
"""Return true if the text looks like a tweet."""
return TWEET_REGEX.search(self.text) is not None and '@cr... | The main task of the code is to generate an appropriate filename based on the content of `self.text`. It checks for specific patterns (e.g., Dune Analytics, tweets, Reddit, Reveddit) and constructs filenames by combining extracted titles, platform-specific identifiers, and the original image file's basename, with fallb... | def filename(self) -> str:
"""Examine self.text and decide on an appropriate filename."""
if self.text is None:
return self.image_file.basename
elif DUNE_ANALYTICS_REGEX.search(self.text):
dune_match = DUNE_ANALYTICS_REGEX.search(self.text)
query_title = self.... |
def _build_cors_preflight_response():
print("making response")
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add('Access-Control-Allow-Headers', "*")
response.headers.add('Access-Control-Allow-Methods', "*")
return response
def findShortestP... | The code generates a travel plan with the shortest path between two cities (source and destination) using graph algorithms, considering both time and cost. It handles CORS preflight requests, retrieves city and flight data from a database, constructs graphs, computes shortest paths via time and cost, and returns the re... | def generate_plan():
if request.method == "OPTIONS": # CORS preflight
return _build_cors_preflight_response()
print('inside plan')
#dat=request.data
args=request.args
#print(type())
source=args.to_dict()['source']
dest=args.to_dict()['dest']
src=City.query.filter_by(name=sourc... |
def vocabulary(self):
"""Check if vocabulary tokens exists else generate the file."""
if os.path.exists("data/vocabulary.txt"):
with open("data/vocabulary.txt", "r") as file:
return eval(file.readline())
else:
self.load_vocabulary()
def generate_query_vect... | This function computes cosine similarity between a query vector and documents in trained_data, returning top-k similar documents with summaries, IDs, and optional query/author metadata. | def compute_similarity(self, trained_data, q_df, k, author=False, query=None):
d_cosines = []
tfidf = TfidfVectorizer(vocabulary=self.vocabulary(), dtype=np.float32)
tfidf.fit(q_df)
query_vector = self.generate_query_vector(q_df, tfidf)
for d in trained_data:
d_cosine... |
def create_tree(chars: str) -> Optional[HuffmanNode]:
if len(chars) == 0:
return None
if len(chars) == 1:
tree = HuffmanNode(chars, 1, None, None)
return tree
frequency_list = count_frequency(chars, ascii_count=[])
trees = convert_into_nodes(frequency_list, new=[])
trees = so... | The main task of the code is to build a Huffman tree from initial characters, then repeatedly encode user-input strings using the tree, verify decoding accuracy, and print the encoded result. It handles errors like encoding/decoding mismatches and exits on EOF, ensuring the Huffman tree's correctness through validation... | def main() -> None:
chars = input("Treeify: ") # initial chars used to create Huffman tree
root = create_tree(chars)
while True:
try:
chars = input(">>> ") # chars to encode
code = encode(chars, root)
assert decode(code, root) == chars
print(code)
... |
def sequential_search(a_list, item):
start_time = time.time()
pos = 0
found = False
while pos < len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos + 1
return found, time.time() - start_time
def ordered_sequential_search(a_list, ite... | The main task of the code is to benchmark and compare the average execution times of four search algorithms—sequential search, ordered sequential search, iterative binary search, and recursive binary search—when searching for a specific value (-1) in a sorted list of 10,000 randomly generated integers. The code runs ea... | def main():
a_time = 0.0
b_time = 0.0
c_time = 0.0
d_time = 0.0
for number in range(100):
my_randoms = random.sample(range(50000), 10000)
my_randoms.sort()
a = sequential_search(my_randoms,-1)
a_time = a_time + a[1]
b = ordered_sequential_search(my_randoms, -1... |
def get_code_length():
with open('hidden/hidden-json.json', 'r') as json_file:
data = json.load(json_file)
return data.get('code-length')
def code_exists(code):
client = get_connection_client()
db = client['shorturl']
collection = db['urls']
doc = collection.find({"url_code": code}, {'... | The main task of the code is to generate a unique random code of variable length by selecting characters from a predefined set (CODE_ALLOWED). It recursively generates codes until one that does not already exist (checked via code_exists()) is produced, ensuring uniqueness. | def generate_code():
LENGTH = get_code_length()
code = ''
for i in range(LENGTH):
code += choice(CODE_ALLOWED)
if not code_exists(code):
return code
return generate_code() |
def get_connection_client():
connection_string = get_database_connection_string()
client = pymongo.MongoClient(connection_string)
return client
def calc_expiry_date(days=5):
time_now = datetime.datetime.now()
expiry = time_now + datetime.timedelta(days=days)
return expiry
def generate_code():
... | The code inserts a new URL entry into a MongoDB collection, generating a unique code and expiry date for the provided full URL. | def insert_into(full_url):
client = get_connection_client()
db = client['shorturl']
collection = db['urls']
insertion_data = {
"expiry_date": calc_expiry_date(),
"full_url": full_url,
"url_code": generate_code()
}
collection.insert_one(insertion_data)
return insert... |
def KMeans(K, dp):
# pick k random points
random_k = random.sample(list(dp), K)
centroids, clusters = dict(), dict()
centroids_ori_idx = dict()
for idx,key in enumerate(random_k):
centroids[idx] = dp[key]
centroids_ori_idx[idx] = key
# print(centroids)
i = 0
while Tr... | The code implements the BFR (Batting for Results) clustering algorithm using Apache Spark. It processes multiple data files incrementally, performing K-means on sampled data (DS), compressing clusters (CS), and retaining outliers (RS). The algorithm merges clusters, tracks intermediate results, and outputs final cluste... | def main(argv):
input_dir_path = "./test2"
K = int("10")
out_cluster_file = "myout1"
out_intermediate_file = "myout1_"
input_dir_path = argv[0]
K = int(argv[1])
out_cluster_file = argv[2]
out_intermediate_file = argv[3]
intermediate_results = list()
files = sorted(os.listdir(i... |
def find_exam(col_exams, course, start, minutes_margin):
begin_margin, end_margin = get_margin_limits(start, minutes_margin)
return col_exams.find_one({'course':course, 'start' : {'$gte': begin_margin, '$lt': end_margin}})
def is_same_person(image1, image2):
result = DeepFace.verify([[image1, image2]],
... | The code processes an attendee's attendance data by verifying their identity against a student record, checking exam details, determining attendance status (present/late), updating the student's attendance history, and removing the processed attendance entry. If verification fails, it logs discrepancies and deletes the... | def process_attendee(not_verified, attendee):
col_attendances = db["attendances"]
col_students = db["students"]
col_exams = db["exams"]
student = col_students.find_one({'email':attendee['email']})
if not student:
return
exam = find_exam(col_exams, attendee['course'], attendee['date... |
def log_message(message: dict, received: bool):
logged = message.copy()
logged.update({"timestamp": time.time()})
if received:
logged.update({"received": True})
LOGS.append(logged)
def respond(
msg_type: str,
msg_id: int,
msg_forwarder: int,
msg_originator: int,
... | The main task of the code is to handle incoming messages by parsing received JSON data, extracting message parameters, and forwarding them to the `respond` function for processing. It logs the receipt of messages and handles exceptions by logging errors, ultimately returning "OK" to confirm successful reception and for... | def receive():
'''
Entry-point when the node receives a message from another node.
Parses the request and forwards it along to `respond`.
You should not need to modify this function.
'''
req_data = request.get_json()
log_message(message=req_data, received=True)
msg_type = req_data["msg_... |
def crawl(svn_root_path, omit=""):
print("CRAWLING STARTED")
print('')
import os
from os.path import join, getsize
paths = []
txtfiles = []
for root, dirs, files in os.walk(svn_root_path):
if files != []:
paths.append(root.strip(omit))
txtfiles.append(files)
... | The main task of the code is to generate structured tree data from file paths, creating multiple tree instances (including randomized versions) and converting them into JSON format with class mappings for training/test purposes. It processes input directories, constructs tree hierarchies, duplicates trees, introduces r... | def createData(path = cwd + '/input/test_oss/', omitpath = cwd + '/input/', test_train = True, createRandomData = True, Randomsamples = 100, realsamples = 1):
import copy
crawl_Res = crawl(path, omitpath)
allPaths = completeallPaths(crawl_Res[0],crawl_Res[1]) # remove random paths to create test data
ro... |
def remove_null(self):
if self.cards.count(None) != 0:
for i in range(self.cards.count(None)):
self.cards.remove(None)
if self.discards.count(None) != 0:
for i in range(self.discards.count(None)):
self.discards.remove(None)
def cards_left(self):
... | This method draws cards from a deck, handling three cases: (1) when drawing 1 card, it checks if the deck is empty and discards are available, then reshuffles and draws; (2) when drawing all cards, it returns a copy and empties the deck; (3) for other quantities, it recursively draws 'x' cards. It also removes null car... | def draw(self,x=1):
self.remove_null()
if x == 1:
if self.cards_left() == 0 and self.cards_discarded() > 0:
self.insert_cards(self.draw_discarded(self.cards_discarded()))
self.shuffle()
return self.cards.pop(0)
elif x == len(self.cards):
... |
def remove_null(self):
if self.cards.count(None) != 0:
for i in range(self.cards.count(None)):
self.cards.remove(None)
if self.discards.count(None) != 0:
for i in range(self.discards.count(None)):
self.discards.remove(None)
def cards_left(self):
... | The main task of the code is to either draw a single card or a list of cards by recursively calling `check()`. When `x=1`, it replenishes the deck from discarded cards if empty, shuffles, and returns the top card. For `x>1`, it recursively draws `x` cards and returns them as a list. | def check(self,x=1):
self.remove_null()
if x == 1:
if self.cards_left() == 0 and self.cards_discarded() > 0:
self.insert_cards(self.draw_discarded(self.cards_discarded()))
self.shuffle()
return self.cards[0]
else:
return_list = ... |
def loadDataSet(filename):
dataMat = []
labelMat = []
fr = open(filename)
for line in fr.readlines():
lineArr = line.strip().split('\t')
dataMat.append([float(lineArr[0]), float(lineArr[1])])
labelMat.append(float(lineArr[2]))
return dataMat, labelMat
def smoP(dataMatIn, clas... | This code implements a Support Vector Machine (SVM) with an RBF kernel to classify data. It trains the model on 'testSetRBF.txt', computes training error, then evaluates the model on a separate test dataset 'testSetRBF2.txt', reporting both training and test error rates. The RBF kernel parameter k1 is adjustable, and t... | def testRbf(k1 = 1.3):
dataArr,labelArr = loadDataSet('original/testSetRBF.txt')
b,alphas = smoP(dataArr, labelArr, 200, 0.0001, 10000, ('rbf', k1)) # C=200 important
datMat = mat(dataArr)
labelMat = mat(labelArr).transpose()
svInd = nonzero(alphas.A > 0)[0]
sVs = datMat[svInd] #get matrix of on... |
def loadImages(dirName):
from os import listdir
hwLabels = []
trainingFileList = listdir(dirName) # load the training set
m = len(trainingFileList)
trainingMat = zeros((m,1024))
for i in range(m):
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0] # take off .t... | The main task of the code is to train a Support Vector Machine (SVM) using the Sequential Minimal Optimization (SMO) algorithm with an RBF kernel on digit training data, evaluate its training error rate, and test its performance on separate test digit data, outputting both error rates. It calculates predictions using s... | def testDigits(kTup=('rbf', 10)):
dataArr,labelArr = loadImages('original/trainingDigits')
b,alphas = smoP(dataArr, labelArr, 200, 0.0001, 10000, kTup)
datMat=mat(dataArr); labelMat = mat(labelArr).transpose()
svInd=nonzero(alphas.A>0)[0]
sVs=datMat[svInd]
labelSV = labelMat[svInd]
print("t... |
def AND(x1, x2):
return perceptron(np.array([x1, x2]), np.array([0.5, 0.5]), -0.7)
def NAND(x1, x2):
return perceptron(np.array([x1, x2]), np.array([-0.5, -0.5]), 0.7)
def OR(x1, x2):
return perceptron(np.array([x1, x2]), np.array([0.5, 0.5]), -0.2)
def XOR(x1, x2):
return AND(NAND(x1, x2), OR(x1, x2)) | The main task of the code is to test and display the outputs of four logic gates (AND, NAND, OR, XOR) implemented via a perceptron model. It evaluates all possible input combinations (0,0), (1,0), (0,1), (1,1) for each gate, printing results to verify their correctness. This serves as a validation step for the perceptr... | def perceptron_test():
print('AND---------')
print('0, 0|' + str(AND(0, 0)))
print('1, 0|' + str(AND(1, 0)))
print('0, 1|' + str(AND(0, 1)))
print('1, 1|' + str(AND(1, 1)))
print('NAND---------')
print('0, 0|' + str(NAND(0, 0)))
print('1, 0|' + str(NAND(1, 0)))
print('0, 1|' + str(NA... |
def create_seq(parts):
samples = []
curT = 0
for part in parts:
curT = add_sample(samples, part[0], part[1], curT, part[3], part[4])
return samples, curT
def download_audio(samples, duration, filename, transcript_id=None):
if transcript_id:
if not os.path.exists(os.path.join(config['... | The function generates audio files from a list of parts. If `combine` is True and a `name` is provided, it combines all parts into a single audio file and downloads it with the specified name. Otherwise, it creates individual audio files for each part using the provided name. | def get_audio(parts, combine=False, name=None):
if combine and name:
print("Creating combined file with",len(parts),"parts")
samples, duration = create_seq(parts)
download_audio(samples, duration, name)
else:
print("Creating",len(parts),"audio files")
for part in parts:
... |
def nabla2(f, dx=1, pad_sign=(1,1,1),scale=(1,1,1)):
wx, wy, wz = scale
kernel = torch.cuda.FloatTensor(
[
[[0, 0, 0],
[0, wx, 0],
[0, 0, 0]],
[[0, wy, 0],
[wz, -2*(wx + wy + wz), wz],
[0, wy, 0]],
[[0, 0, 0],
[0, wx, 0],
[0, ... | This code simulates a dynamic system by updating state variables w and v over time steps. It computes second-order spatial derivatives (D2w) using tanh, applies nonlinear dynamics involving w³ terms, and incorporates damping. After multiple time steps, it smooths the final w state with a Gaussian filter before returnin... | def update(self, dt=0):
w = self.w
v = self.v
t = self.t
dx = self.dx
max_dt = 0.02
scale = (1, 1, 1)
step = int(dt / max_dt) + 1
dt = dt / step
# regist = torch.exp(-t/30)
for _ in range(step):
w = w + dt * v
D2w =... |
def _log_setup(self, event, context):
if self._json_logging:
log_helper.setup(self._log_level, boto_level=self._boto_level, RequestType=event['RequestType'],
StackId=event['StackId'], RequestId=event['RequestId'],
LogicalResourceId=event['Log... | This code handles AWS Lambda events for CloudFormation custom resources, initializing logging, checking polling status, and determining whether to send a response. It processes events, manages error handling, and ensures proper cleanup by canceling timers, while supporting both polling and direct invocation scenarios. | def __call__(self, event, context):
try:
self._log_setup(event, context)
logger.debug(event)
if not self._crhelper_init(event, context):
return
# Check for polling functions
if self._poll_enabled() and self._sam_local:
l... |
def format_feilds(fields):
'Format a list of fields `fields` as a header of a html table.'
fmt = '<thead><tr>{fields}</tr></thead>'
return fmt.format(fields=join('', [format_field(field)
for field in fields]))
def format_matches(matches):
'''Format a list of match ... | The main task of the code is to generate an HTML table from a list of match dictionaries, handling empty cases by displaying "No matches found," while escaping content for safety and formatting table structure. | def format_html(matches):
'Format a list of match dictionaries `matches` as a html table.'
fields = ['', 'Activity', 'Name', 'Matching time slot']
text = '' if matches else 'No matches found.'
html = '''
<table class="table">
{fields}
{matches}
</table>
{text}
'''.format(fields=format_feilds(fields)... |
def __print_options(self):
print("")
for idx in range(0, len(self.__menu_options)): self.__print_option(idx)
print("")
def __input_option(self):
while True:
self.__current_opt = HelperClass.input_int(
message = "Insert option: ",
requ... | The main task of the code is to execute a command-line interface workflow by printing available options, capturing user input, running the selected operation, and returning its result if non-None. | def start(self):
self.__print_options()
self.__input_option()
result = self.__run_option()
if not result == None:
return result |
def wait_for_memory_threshold(threshold, check_interval=1):
"""
Continuously check the total free memory across all CUDA devices.
Only exits the loop when the cumulative free memory exceeds 'threshold' (in bytes),
checking every 'check_interval' seconds.
"""
while True:
total_free_memory... | The main task of the code is to evaluate and compare the performance of multiple sentence transformer models and a central LLM (gtr-t5-xl) for reranking search results across various benchmark datasets (e.g., MS MARCO, BEIR, TREC). It uses Pyserini for initial retrieval, processes results with transformer-based similar... | def main():
THE_INDEX = {
'dl19': 'msmarco-v1-passage',
'dl20': 'msmarco-v1-passage',
'covid': 'beir-v1.0.0-trec-covid.flat',
'arguana': 'beir-v1.0.0-arguana.flat',
'touche': 'beir-v1.0.0-webis-touche2020.flat',
'news': 'beir-v1.0.0-trec-news.flat',
'scifact':... |
def Search_Node(root_node,value_tosearch):
if root_node is None:
print("Value not found!")
return False
elif value_tosearch>root_node.value:
return Search_Node(root_node.right,value_tosearch)
elif value_tosearch<root_node.value:
return Search_Node(root_node.left,valu... | The code implements a deletion operation in a binary search tree (BST). It locates the node with the given value, then handles three cases: removing a node with no left child, no right child, or both. For nodes with two children, it finds the successor, transplants it, and adjusts parent-child links to maintain BST pro... | def Deletion(tree,value):
root_node=tree.root_node
if Search_Node(root_node,value):
value_node=root_node
while value_node.value!=value:
if value_node.value>value:
value_node=value_node.left
elif value_node.value<value:
value_node=value_node... |
def main():
getInstalledProgramList()
repeat() # add programs at definite interval
#for k,v in onOff.items(): print(k,v)
time.sleep(30)
main()
def getInstalledProgramList():
psutil.process_iter(attrs=None, ad_value=None)
for proc in psutil.process_iter():
try:
processName... | This function checks if the software is being used for the first time by reading a JSON log file. If the log is empty, it prompts the user to choose between first-time setup (0) or reusing existing settings (1). It then retrieves running processes, allows user input to control process states, and updates the log with t... | def checkFirstTime():
with open(logDirectory, "r+") as f: d = json.load(f)
if len(d)!=0 : main()
else :
print(f"{LCYAN}This is the first time you used this software.")
print(f"{LGREEN}Press 0 for not using it for second time.")
print(f"{LMAGENTA}Press 1 for reusing it.")
get... |
def load_csv(filename):
lines = csv.reader(open(filename, "r"))
dataset = list(lines)
headers = dataset.pop(0)
# Convert string value to float
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
return dataset, headers
def split_data(dataset, split):
train = l... | The code loads a diabetes dataset, splits it into training (67%) and test sets, trains a Naive Bayes classifier on the training data, makes predictions on the test set, calculates accuracy by comparing predictions to actual labels, and prints the accuracy metric. | def run_naive_bayes():
dataset, headers = load_csv("data/diabetes.csv")
split = 0.67
train, test = split_data(dataset, split)
predictions = train_naive_bayes(train, test)
accuracy = get_accuracy(test, predictions)
print("Accuracy: ", accuracy) |
def get_worker_id(self):
"""Extract the worker id"""
worker_id = "default"
if hasattr(self.config, "workerinput"):
worker_id = self.config.workerinput["workerid"]
if (
not hasattr(self.config, "workerinput")
and getattr(self.config.option, "dist", "no"... | The code processes a pytest test report to generate structured result data for broadcasting. It checks the worker ID, handles test outcomes (passed, failed, skipped), and constructs appropriate report entries using helper methods. Results are aggregated into a dictionary and returned, excluding non-master workers. | def __call__(self, report: pytest.TestReport):
"""Prepare result report for broadcasting."""
# pylint: disable=too-many-branches
results: typing.Dict[typing.Any, typing.Any] = {}
worker_id = self.get_worker_id()
# wait until workers are senting back their results.
# See ... |
def _set_session_uid(
self, id: typing.Optional[typing.Union[str, uuid.UUID]] = None
) -> None:
"""Set or create a session ID."""
if id is None:
self._session_uuid = create_unique_identifier()
elif isinstance(id, str):
self._session_uuid = uuid.UUID(id)
... | This code initializes a logging reporter by configuring session parameters, retrieving Fluentd settings from the config, and setting up log transmission to a Fluentd server. It patches Python's logging module to integrate with the reporter, enabling structured logging with optional features like docstring inclusion and... | def __init__(self, config):
self._session_uuid = None
self._session_start_time = None
self._test_uuid = None
self.config = config
self._set_session_uid(self.config.getoption("--session-uuid"))
self._host = config.getoption("--fluentd-host")
self._port = config.get... |
def check_username(displayname: str):
"""
Checks the validity of a display name.
Args:
displayname (str): The display name to be checked.
Raises:
TypeError: If the display name is not a string.
ValueError: If the display name length exceeds 14 characters.
"""
if not isi... | The code creates a new user by validating the display name, generating a unique ID, populating a user template with the display name and ID, and saving the data to an encrypted or unencrypted JSON file. It returns True upon successful creation. | def create_user(displayname: str, encryption=ENCRYPTION_STATE) -> bool:
"""
Creates a new user with the provided display name.
Args:
displayname (str): The display name of the user.
Returns:
bool: True if the user is successfully created.
Calls:
check_username: checks vali... |
def GetPositiveMutations(data, upto, X, PocketYs):
# Prepare data
Xs = []
Ys = []
for i in range(0,13):
Xs.append([])
Ys.append([])
# Structure of the csv at this point
i_pre_model = i_agent+1
i_pre_fitness = i_agent+2
i_pre_error = i_agent+3
i_post_model = i_agent+... | The code generates a generational summary GIF visualizing agent behaviors (mutations, bubble-ups, local searches) over time. It filters 'PopulationBestFitnessPocket' data, creates per-generation plots, and compiles them into an animated GIF showing evolutionary trends in agent performance and strategy changes. | def GenerationalSummary(orig_data, filename):
# !!! WORKGING HERE, need to make the Agent grid showing Pocket Values
# !!! Then
finished_file = filename.replace(replace_str,".Master.GenerationSummary.gif")
# Structure of the csv at this point
i_fitness = i_agent+2
data = orig_data[ orig_data[... |
def extract_order_id(user_input):
# Regular expression to find a sequence of digits that may represent an order ID
#order_id_pattern = r'\d+'
order_id_pattern = r'O\d{3,}' # Matches sequences of four or more digits
# Search for the order ID pattern in the user's input
match = re.search(order_id_pa... | The function processes user text to determine the appropriate database query: extracts order/product IDs for direct lookups, handles "Find me [category]" requests for category-based products, retrieves promotions for "Discount for [product]" queries, and defaults to a prediction model for other inputs. | def chatbot_response(text, db_connection):
order_id = extract_order_id(text)
product_id = extract_product_id(text)
if order_id:
order_data = get_order_by_id(order_id, db_connection)
return order_data
if text.startswith("Find me"):
catergories_name = text.split()[-1]
categ... |
def epsilon(e):
# exploitation
if random.uniform(0, 1) > e:
return False
# exploration
else:
return True
def explore(state):
action = game.ACTIONS[random.randint(0,7)]
next_state = game.transition(state, action)
update_Matrix(state, action, next_state)
return next_state
def exploit(state):
sta... | The main task of the code is to simulate a 3-round learning episode in a reinforcement learning context. It initializes a random dice state, then iteratively updates the state by either exploring (random action) or exploiting (optimal action) based on an epsilon-greedy strategy. The function returns the final state aft... | def learn_episode():
# an episode is composed of 3 rounds
# first round where we roll every dices
current_state = sorted([random.randint(1,6), random.randint(1,6), random.randint(1,6)])
# two more rounds
for i in range(0, 2):
if (epsilon(epsilon)):
current_state = sorted(explore(current_state))
... |
def set_sessions_dict_from_xml(self) -> None | dict:
"""Read SecureCRT export (self._sessions_xml) and set self._sessions_dict.
Returns:
None | dict: Ordered dict (self._sessions_dict) or None.
"""
if self._xml_sessions is None:
return None
base_root = ... | The main task of the code is to parse a SecureCRT XML session file, validate its existence, and populate three dictionaries (`_sessions_dict`, `_credentials_dict`, `_firewalls_dict`) by extracting data from the XML content. It ensures the XML data is properly loaded before processing and populating the structured dicti... | def build_dict_from_xml(self):
"""Read SecureCRT XML session file and set all dictionaries.
Read XML file, set sessions_xml attribute and set:
- self._sessions_dict
- self._credentials_dict
- self._firewalls_dict
"""
# get XML element/content from XM... |
def __xml_tpl_get_root(self):
"""Return root template Element object"""
xml_obj = SMXml()
return xml_obj.parse_xml_file(self._settings["scrt"]["template"]["root"])
def __sessions_dict_to_xml(self) -> ET.Element:
"""Read self._sessions_dict and return firewalls hierarchy as XML object.
... | The code constructs an XML structure for SecureCRT by merging a base template with session, credential, and firewall data converted from dictionaries. It appends these elements to the base XML's designated sections and stores the final XML in `self._xml_sessions` for import. | def build_xml_from_dict(self):
"""Build SecureCRT XML content from template (root+sessions+credentials+firewalls).
Method set's attribute self._sessions_xml.
Returns:
(ET.Element): XML content of sessions for importing to SecureCRT.
"""
# read default base(root) XML ... |
def __build_rdm_connection_ssh_session(self, **kwargs):
"""Set RDM SSH session (type 77)
Check if SSH session not exists in self.__rdm_connection_list and add it.
Args:
folder (str, optional, default=""): folder path
session (str): SSH session name
hostname ... | This function converts session data from a dictionary structure into connection objects by iterating through each session entry, determining its type (SSH, RDP, or Web), and invoking corresponding private methods to build RDM connection objects with parameters like hostname, credentials, and session-specific configurat... | def __sessions_dict_to_json_connections(self):
"""Set __rdm_connection_list from _sessions_dict"""
# get folder path and session in a loop
for idx, session_row in enumerate(self._sessions_dict["session"]):
# get folders structure
folder_path = self._sessions_dict["folder... |
def side_bar():
with st.sidebar:
st.header("Session Info")
session_id = st.text_input(
"Session ID",
key=f"session-id",
)
return session_id
def read_inference_json(bucket_name, key):
try:
# Read inference.json file from S3
respons... | The code creates a Stable Diffusion web app using Streamlit, enabling users to search, generate images, and view history. It initializes session states, interacts with S3 for data storage, and uses Pinecone for vector search. Tabs handle search queries, image generation, and history retrieval, leveraging cloud storage ... | def main():
st.set_page_config(layout="wide")
st.title("Stable Diffusion Playground")
# Instantiate session ID
session_id = side_bar()
# Set s3 paths
s3_inference_json_uri = f"{session_id}/inferences.json"
s3_image_prefix = f"{session_id}/image"
# read inference json
inference_jso... |
def indicators(df):
df['SMA_200'] = ta.trend.sma_indicator(df['Close'], window=200)
df['stochrsi_k'] = ta.momentum.stochrsi_k(df['Close'], window=10)
df.dropna(inplace=True)
df['Buy'] = (df['Close'] > df['SMA_200']) & (df['stochrsi_k'] < 0.05)
return df
def getdata(symbol):
frame = pd.DataFrame(... | The code defines a trading loop that continuously fetches market data, calculates technical indicators, checks for buy/sell signals, executes trades when conditions are met, and logs status updates. It runs indefinitely, pausing for 60 seconds between iterations to monitor and act on real-time trading opportunities whi... | def trading_loop():
global df
while True:
df = indicators(getdata(symbol))
if df is not None:
if checkbuy():
curr_order = buy(investment)
try:
checksell(curr_order)
except:
logs.insert(tk.END, "Not an order yet\n")
tim... |
def get_photo_stats(self, dt):
popular = self._flickr.stats.getPopularPhotos(date=dt, per_page=100, page=0)
df_popular = pd.DataFrame(popular['photos']['photo'])
while popular['photos']['pages'] - popular['photos']['page'] > 0:
popular = self._flickr.stats.getPopularPhotos(date=dt, ... | The main task of the code is to collect various statistics (photos, totals, streams, sets, collections) from a Flickr API for a given date/time, aggregate them into a list, measure the total execution time, and write each result to a database using `sqldb.write_df`. The TODO comment indicates a need for a decorator to ... | def get_all_stats(self, dt):
writelst = []
### TODO need a decorator to get fine-grained timing
start = time.time()
writelst.extend(self.get_photo_stats(dt))
writelst.extend(self.get_totals_stats(dt))
writelst.extend(self.get_stream_stats(dt))
writelst.extend(sel... |
def get_photo_stats(dt):
popular = flickr2.stats.getPopularPhotos(date=dt, per_page=100, page=0)
df_popular = pd.DataFrame(popular['photos']['photo'])
while popular['photos']['pages'] - popular['photos']['page'] > 0:
popular = flickr2.stats.getPopularPhotos(date=dt, per_page=100, page=popular['phot... | The main task of the code is to collect and write various statistical data from different functions (`get_photo_stats`, `get_totals_stats`, `get_stream_stats`, `get_set_stats`, `get_collection_stats`) into a list, then iterate through the list to write each item using `write_df` with the input `dt`. Finally, it prints ... | def get_all_stats(dt):
writelst = []
writelst.extend(get_photo_stats(dt))
writelst.append(get_totals_stats(dt))
writelst.extend(get_stream_stats(dt))
writelst.extend(get_set_stats(dt))
writelst.extend(get_collection_stats(dt))
for i in writelst:
write_df(dt, i)
print('retrieve... |
def get_dates():
connecting_string = 'Driver={ODBC Driver 17 for SQL Server};Server=tcp:woo.database.windows.net,1433;Database=BYWS;Uid=boss;Pwd=s7#3QzOsB$J*^v3;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;'
params = parse.quote_plus(connecting_string)
engine = sa.create_engine("mssql+pyodb... | The function `get_stats_batch` retrieves a list of dates, iterates through each date, and for each date, it fetches all statistics using `get_all_stats` and then closes the date using `close_date`, processing each date in sequence. | def get_stats_batch():
ls = get_dates()
for dt in ls:
get_all_stats(dt[0])
close_date(dt[0]) |
def find_leaves(node, leaves):
if len(node.children) == 0:
leaves.append(node)
return
else:
find_leaves(node.children[0], leaves)
find_leaves(node.children[1], leaves)
def calc_accuracy(node, dataset):
"""
calculate the accuracy starting from some node of the decision tre... | The function `find_best_parent` identifies the parent node in a decision tree whose removal (temporarily) maximizes the model's accuracy on the given dataset. It evaluates all leaf nodes, simulates removing their parent's children, calculates accuracy, and retains the parent that yields the highest accuracy. Finally, i... | def find_best_parent(node, dataset):
if len(node.children) == 0:
return None
leaves = []
find_leaves(node, leaves) # a list with all the leaves in the tree
best_value = None
# run on all the leaves in the tree
for leaf in leaves:
parent = leaf.parent
... |
def count_internal_nodes(node):
leaves = []
find_leaves(node, leaves)
num_of_leaves = len(leaves)
num_of_nodes = count_nodes(node)
return num_of_nodes - num_of_leaves
def calc_accuracy(node, dataset):
"""
calculate the accuracy starting from some node of the decision tree using
the given... | The function performs post-pruning on a decision tree by iteratively removing branches that minimize accuracy degradation. It tracks the number of internal nodes and tree accuracy after each pruning step until only the root remains, returning lists of these metrics for analysis. | def post_pruning(node, dataset):
number_of_nodes = [count_internal_nodes(node)]
tree_accuracy = [calc_accuracy(node, dataset)]
# run on a loop until we are left only with the root
while count_nodes(node) > 2:
temp = find_best_parent(node, dataset)
number_of_nodes.append(temp[1])
... |
def table_exists(self, table_name: str) -> bool:
"""
INPUT: Name of the table
FUNCTION: Checks if the table exists
OUTPUT: Returns True if the table exists, False if it doesn't
"""
self.execute(
f'SELECT name FROM sqlite_master WHERE type="table" AND nam... | This function creates or modifies an SQL table to match specified columns. If the table exists, it compares column lists, adding/removing columns as needed via ALTER TABLE. If the table doesn't exist, it creates it. Returns True if changes were made, False if no modifications were needed. | def create_table(self, table_name: str, columns: list[Column]) -> bool:
"""
INPUT: Name of the table and an array of column names
FUNCTION: Creates an SQL table with a name and columns.
OUTPUT: Returns True if table was created or updated, False if it already exists or was unmodifie... |
def _clean_string(self, text: any) -> any:
"""
INPUT: String to clean
FUNCTION: Cleans a string so it can be used in an SQL command
OUTPUT: Returns the cleaned string
"""
if not isinstance(text, str):
return text
return text.replace("'", "").repl... | The code's main task is to insert a new record into a specified database table using provided column-value pairs. It constructs an SQL INSERT statement, cleans input values, executes the insertion, commits the transaction, and returns True if successful. | def create_record(self, table_name: str, **kwargs) -> True:
"""
INPUT: Name of the table and a dictionary of column names and values
FUNCTION: Creates a record in the table
OUTPUT: Returns True if the record was created
"""
columns = ", ".join(list(kwargs))
... |
def get_cart(request):
unique_id =_unique_cart_id(request)
try:
cart = get_object_or_404(Cart, unique_cart_id=unique_id)
return cart
except :
return None
def get_cart_total(request):
#Get the cart
cart = get_cart(request)
cart_total = decimal.Decimal('0.00')
... | The main task of the code is to process a checkout by validating customer and address information from a form, creating a customer profile, saving the address, generating an order from the user's cart, calculating totals, and associating order items with the new order, ultimately clearing the cart upon successful compl... | def process_checkout(request):
form = CheckoutForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
middle_name = form.cleaned_data['middle_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
... |
def load_test_set(nrows=0, skip=0):
"""
loads the test set
:param nrows: specifies how many rows to read from the test set,
if 0 reads the entire dataframe in memory
:param skip: number of lines to skip from the beginning of the dataframe
:return: the test set
"""
# get fi... | The main task of the code is to evaluate a machine learning model's performance on a test dataset by loading the model, processing test data according to configuration parameters, making predictions, and computing evaluation metrics. It logs the test set composition, prediction time, and outputs metrics like accuracy, ... | def test_model():
"""
Test model performance on the test set according to config file parameters
:return: void just print the main evaluation metrics on the console
"""
# get testing parameters
model_fp = os.path.join(gv.ROOT_DIR, gv.BEST_MODEL_LOCATION)
model = load_model(model_fp)
... |
def animate_cards(self, destination):
if len(getattr(self, destination)) == 0: return
positions = self.bounding_boxes[destination].card_positions(len(getattr(self, destination)))
for ind, i in enumerate(getattr(self, destination)):
animation = Animation(pos=(positions[ind]-self.bound... | This function moves a card to a specified destination stack by checking its current position, inserting it at the correct index, updating the stack, and animating the change. If the card isn't in the destination, it deletes it and appends it there. Animations and broadcasts ensure UI updates. | def move_card(self, card_id, destination, cur_pos): #cur_pos [x, y]
if card_id in getattr(self, destination):
# cards in stack
number_cards = len(getattr(self, destination))
if number_cards == 0:
return
positions = self.bounding_boxes[destination... |
def create_card(self, name, summon_position=None, assigned_id=None, tapped=None):
card = card_creation(self.parent.card_database, name)
picture = Picture(source=card.normal, parent_object=self.parent,
card=card, assigned_id=assigned_id, opponent=self.opponent, tapped=tapped)
... | The main task of the code is to synchronize the game state with a provided payload by updating cards (adding, moving, or deleting them) based on their IDs and positions, ensuring visual consistency. It processes the payload to create new cards, adjust existing ones' positions/tapped status, remove obsolete cards, and a... | def load(self, payload):
try:
payload = ast.literal_eval(payload)
except:
return
if payload == self.past_payload: return
self.past_payload = payload
# find cards that need to be deleted or added
payload_ids = []
for i in payload.keys():
... |
def _get_similarity_list(imdb_id):
prefix = get_imdb_id_prefix_folder_name(imdb_id)
similarity_list_file_path = SIMILAR_LIST_SAVING_PATH.joinpath(prefix, f'{imdb_id}.json')
similarity_list = open_json(similarity_list_file_path)
return similarity_list
def get_user_seen_imdb_ids():
if current_user.is... | This function retrieves paginated, similarity-based movie recommendations for a given IMDb ID, filters out titles the user has already seen if specified, and returns structured JSON data containing the results, requested title details, pagination info, and user preference flags. | def get_limited_search_results(imdb_id, hide_seen_titles, page_index): # TODO: move this logic to search
similarity_list = _get_similarity_list(imdb_id)
max_page_number = math.ceil(len(similarity_list) / ONE_PAGE_SUGGESTIONS_AMOUNT) - 1 # page number starts from 0
if page_index > max_page_number:
... |
def _get_similarity_list(imdb_id):
prefix = get_imdb_id_prefix_folder_name(imdb_id)
similarity_list_file_path = SIMILAR_LIST_SAVING_PATH.joinpath(prefix, f'{imdb_id}.json')
similarity_list = open_json(similarity_list_file_path)
return similarity_list
def get_user_seen_imdb_ids():
if current_user.is... | The function retrieves movie similarity data and user viewing history, then compiles presentation data for a requested IMDb ID and its similar titles. It returns a JSON response containing both the requested movie's details and a list of similar movies, filtered by user engagement. | def get_all_search_results(imdb_id):
similarity_list = _get_similarity_list(imdb_id)
user_seen_imdb_ids = get_user_seen_imdb_ids()
results = get_movies_presentation_data(imdb_id, similarity_list, user_seen_imdb_ids)
requested_title_data = load_presentation_data(imdb_id)
data = {
"similarity_... |
def splitToPercentGreen(file1, size):
'''
Gets the percentage green of an image
Runs the full formatting and checks each pixel for greenery in terms of percents
Parameters
----------
file1: str
The location or name of the image
size: int
The number of section... | The function compares the greenery percentage of two images, which may be sourced from files or directories. It processes images by splitting them into sections, encrypting/saving them if required, and calculates the average percentage difference in greenery between the two images. The result is returned as a string in... | def comparator(usersName,file1, file2, size, directory1, directory2, save1, saveName1, save2, saveName2, fileName):
'''
Compares two images
Compares two images that can come from various locations and be saved or retrieved to directory
Parameters
----------
usersName: str
The... |
def num2words_conversion(num):
len_num = len(str(num))
if num <= 20: # ones
o = ones[num]
return o
elif 20 < num < 100: # tens
ten_split = divmod(num, 10)
t = twenties[ten_split[0]]
o = ones[ten_split[1]]
to = t + " " + o
return to
elif len_num =... | The function `words2numgreat3` converts a number into its English word representation based on its magnitude. It checks the number of digits in the input (`num`) and delegates conversion to specialized helper functions: `num2words_conversion` for numbers ≤ 3 digits, `thousands2words` for 4–6 digits, `millions2words` fo... | def words2numgreat3(num):
num_length = len(str(num))
if num_length <= 3: # hundreds or less length
hundreds_words = num2words_conversion(num)
return hundreds_words
elif 3 < num_length < 7: # thousands
return thousands2words(num)
elif 6 < num_length < 10: # millions
... |
def load_sprites():
sprites['background'] = load_sprite(res['background'])
sprites['player'] = load_sprite(res['player'])
sprites['bullet'] = load_sprite(res['bullet'])
sprites['groups']['asteroid'] = load_sprite_group(
res['asteroid'], 10000, 10015)
def create_asteroids():
global asteroid_t... | The code runs a game loop where a player controls a spaceship, dodging asteroids. It initializes game elements, updates game state, renders graphics, and maintains a frame rate. The loop continues until the player's character is destroyed, at which point the final score is printed. | def main():
global player
clock = pygame.time.Clock()
load_sprites()
player = Player()
while player.is_alive():
create_asteroids()
update()
draw()
clock.tick(FPS)
print('Final score:', player.score) |
def address_to_coord(address):
'''
Returns the latitude and longitude for a given address
'''
latlon = re.search(r'\-?\d+\.?\d*\s*,\s*\-?\d+\.?\d*', address)
if latlon != None:
text = latlon.string
text = text.split(',')
lat = float(text[0].strip())
longi = float(text... | The function retrieves an RGB satellite image centered at a given address or GPS coordinates, using Google Maps for the specified year or s2maps data with a filter applied. It converts addresses to coordinates, selects the image source based on the year, and returns a 10m/pixel resolution PIL.Image. | def get_new_image(adr:str, year:str) -> Image:
"""
Given the address or GPS coordinate, retuns an RGB image from google maps
or from s2maps depending on the requested year centered around the given point with resolution of 10m/pixel.
Arguments:
lat: latitude of the central point (float)
... |
def get_random_point_direction(self):
return rand.randrange(8)
def get_allowed_movements(self,direction):
if direction==NORTH:
return [(0,-1),(1,-1),(-1,-1)]
elif direction == SOUTH:
return [(0,1),(1,1),(-1,1)]
elif direction == EAST:
return [(1,0),(1,... | This code simulates random particle movement through a labyrinth to find an exit. It tracks the particle's path, adjusts direction randomly, checks movement validity, and draws the path on a video/image when the exit is reached. The function uses a lock to ensure synchronized path drawing if multiple particles are acti... | def find_exit_with_random_particles(self,video, img,color=(0,0,255),lock=None):
old_x = rand.randrange(self.line_length)
old_y = 0
current_grid_position = (0, 0)
first_point_delimiter = (0, 0)
second_point_delimiter = (self.line_length, self.line_length)
path_pa... |
def backup(self) -> None:
if self.online():
self.sendCommand("save-off")
self.sendCommand("save-all flush")
#TODO: wait for the server to flush (not as a static wait time)
timestr = datetime.now().strftime("%d-%m-%Y_%H:%M:%S")
subp.run(["borg", "create", f"{cfg.borgRepoPath}::{self.name}-{timestr}", self.... | This code starts a Minecraft server by executing a Java process with specific arguments. It handles screen session configuration when not in debug mode, uses predefined Java paths and arguments, applies log4j fixes, and ensures the server starts successfully. It also performs a backup, monitors server status, and raise... | def start(self,debug:bool) -> None:
self.backup()
args = []
if not debug:
args += ["screen", "-S"]
args += ["minecraft_"+self.name]
args += ["-dm"]
args += [cfg.javaPaths[self.javaVersion()]]
args += cfg.javaArgs
args += self._log4ShellFixArg()
args += ["-jar", self.jarFile(), "nogui"]
subp.run... |
def menuState(self):
ret, image = self.video_capture.read()
image = cv2.resize(image, (self.DISPLAY_WIDTH, self.DISPLAY_HEIGHT))
h, w, other = image.shape
black = np.zeros([h, w, 3], np.uint8)
self.addText(black, f"Main Menu", "C", scale=3)
self.addText(black, f"Start Ri... | This method determines the current state of an object and delegates to corresponding state-handling methods, such as menuState(), taskState(), or tutorialVideoState(), based on the value of self.state. It acts as a state machine dispatcher, routing control to the appropriate method for rendering or processing the curre... | def displayByState(self):
if self.state == "menu":
self.menuState()
elif self.state == "ringTask":
self.taskState()
elif self.state == "wireTask":
self.taskState()
elif self.state == "evaluation":
self.evaluationState()
elif self.st... |
def get_file(file_name, folder, folder_dest):
"""
Download a file from SharePoint and save it.
Args:
- file_name (str): The name of the file to download.
- folder (str): The folder in SharePoint where the file is located.
- folder_dest (str): The local folder destination.
"""
file_obj = SharePoint().do... | The code's main task is to download files from a SharePoint folder to a local destination, either by specifying a single file name or using a pattern to match multiple files. It uses conditional logic to call different helper functions based on whether a specific file name, a pattern, or no filters are provided, enabli... | def download(sharepoint_site_folder_name,
folder_dest,
file_name,
file_name_pattern):
"""
Download files from SharePoint based on specified criteria.
This function allows you to download files from a SharePoint site to a local
folder. You can specify the SharePoint folde... |
def is_slack_channel_exists(channel_name) -> bool:
return True if get_slack_channel(channel_name) else False
def create_channel(channel_name, create_private=False): # TODO CHANGE TO PRIVATE CHANNELS. CURRENTLY GET LIST THEM: https://stackoverflow.com/questions/53736333/slack-conversations-list-method-does-not-list... | The code sends a message to a specified Slack channel, ensuring the channel exists and the user is a member. It creates the channel if it doesn't exist, joins it if necessary, then posts the message using Slack's API, logging errors if the post fails. | def send_to_slack(channel, block):
if not is_slack_channel_exists(channel):
create_channel(channel)
if not is_in_slack_channel(channel):
join_channel(channel)
try:
client.chat_postMessage(channel=channel, blocks=block, text=block)
except SlackApiError:
logging.exception("... |
def readData(file_location,headers):
print("### Reading Data >> Start ###")
data = pd.read_csv(file_location,sep=",",names=headers)
print("### Reading Data >> End ###")
return data
def preprocessData(data,x_columns,y_column,x_y_split):
print("### Preprocessing Data >> Start ###")
data = data.dr... | The main task of the code is to preprocess dataset features, split data into training/test sets, initialize a neural network model with specified parameters, and evaluate its performance through four tests. It reads input data, handles file operations, and executes iterative training and validation processes for a clas... | def main():
print("### Main >> Start ###")
# creating a folder to save all the results
try:
os.makedirs('results')
except OSError as e:
if e.errno != errno.EEXIST:
raise
file_location = 'train_data.txt'
feature_columns = ['Jitter_local','Jitter_local_absolute','Jitt... |
def get_balance(self, address, block_number):
"""
@Notice: This function returns the balance the token for a specific address
@param address: The address you want to get the balance of
@return: The balance of the address in wei unit
"""
# Call the function and get the bal... | The function `insert_user_balance` inserts or updates a user's balance in the `user_balance` table. It retrieves the address's balance and calculates weekly change percentage using helper functions. The SQL query checks if the address and transaction hash already exist; if not, it inserts the balance, transaction detai... | def insert_user_balance(self, address, transaction_hash, timestamp, block_number):
"""
@Notice: This function insert or updates the balance of a specific address
in the user_balance table.
@param address: The address you want to insert/update the balance
@param transaction_hash:... |
def get_last_block_number(self):
"""
@Notice: This function will return the current block number from the provider
@return: The current block number
@Dev: We call the get_block method on the web3 provider and return the result
"""
return int(self.provider().eth.get_block(... | This function retrieves token transfer events between specified block ranges from Etherscan, handling the API's 1000-result limit via pagination. It iterates through blocks, fetches events, processes them with handle_event, and returns the last processed block number. | def fetch_events_in_blocks(self, current_block_number: int, last_block_number: int):
"""
This function iterates over block numbers to fetch all the events for the token transfer event
between `current_block_number` and `last_block_number`. It handles the 1000 results limit from the
eth... |
def get_current_block_number(self, current_block_number):
"""
@Notice: This function will return the last processed block number from the recorded block file
@param: current_block_number: the last processed block number
@return: The last processed block number and the current block numbe... | The main task of the code is to continuously monitor and process new blockchain events by iterating through blocks. It retrieves the current and last block numbers, logs their range, explores events within those blocks using `fetch_events_in_blocks`, and waits for new blocks. This loop runs indefinitely until an except... | def fetch_events(self):
"""
@Notice: This function will listen for new blocks to explore
@Dev: We first define from which block to start the exploration.
We call the fetch_events_in_blocks method to explore the blocks.
"""
try:
current_block_number = None
... |
def show_contacts():
entries = db.get_contacts()
win.change_text_edit(make_output_string(entries))
def add_new_contact():
information, aborted = [], False
for entry in ("Enter a name: ", "Enter a phone number: ", "Enter a comment: "):
while 1:
user_input, ok_pressed = win.get_input_t... | The code defines a function `handle_button_click` that routes user actions in a telephone book application. It uses a `match` statement to determine which button was clicked, invoking corresponding functions like `show_contacts`, `add_new_contact`, or `search_telephone_book`. Specific cases handle contact modification ... | def handle_button_click(button_text):
match button_text:
case "Show contacts":
show_contacts()
case "Add a new contact":
add_new_contact()
case "Search in the telephone book":
search_telephone_book()
case "Change a contact":
delete_o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.