dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def __get_unread_messages(self) -> [telebot.types.Message]:
"""
Gets and prints telegram unread messages.
:returns: Array of messages or None, if exception occurred.
"""
try:
updates = self.__bot.get_updates(offset=self.__update_offset, timeout=1, allowed_updates=['m... | This method retrieves and filters unserviced Telegram user commands, validating access based on bot mode and whitelist, checking command support, and returning only supported UserRequest objects while sending refusal messages for invalid cases. | def get_unserviced_requests(self) -> [UserRequest]:
"""
Gets and prints telegram user's unserviced commands.
If bot mod is private, method does not return commands from users which are not in whitelist. To these users
bot sends a message with denial of access. If user's command is not s... |
def load_data():
df = pd.read_csv('../../data/Pokemon.csv')
return df
def clean_data(df):
data_clean = df.copy()
data_clean = data_clean[data_clean['is_legendary'] == 0]
data_clean = data_clean.filter(['name', 'type1', 'type2', 'hp', 'attack', 'defense', 'sp_attack', 'sp_defense', 'speed'])
data... | The main task of the code is to load and clean dataset, then process specific tank statistics ('sp_defense' and 'hp') from the cleaned data using the process_role function. It focuses on analyzing or preparing tank-related attributes for further analysis or modeling. | def main():
df = load_data()
data_clean = clean_data(df)
sp_tank_stats = ['sp_defense', 'hp']
process_role(data_clean, sp_tank_stats) |
def load_data_frame():
df = pd.read_csv('../../data/Pokemon.csv')
return df
def clean_df(df):
df_clean = df.copy()
df_clean = df_clean[df_clean['is_legendary'] == 0]
df_clean = df_clean.filter(['name', 'type1', 'type2', 'hp', 'attack', 'defense', 'sp_attack', 'sp_defense', 'speed'])
df_clean['ty... | The main task of the code is to load a Pokémon dataset, clean it, explore type distributions, analyze key statistics (HP, attack, defense, etc.), identify top values for these stats, and examine Pokémon roles. This provides insights into the dataset's structure, statistical properties, and functional classifications of... | def main():
df = load_data_frame()
df_clean = clean_df(df)
explore_types(df_clean)
stats = ['hp', 'attack', 'defense', 'sp_attack', 'sp_defense', 'speed']
explore_stats_wrapper(df_clean, stats)
explore_top_wrapper(df_clean, stats)
analyze_roles(df_clean) |
def CreateGraph(self, NETWORK_PATH, filename):
G = nx.Graph()
for line in open(os.path.join(NETWORK_PATH, filename + '.txt')):
strlist = line.split()
n1 = int(strlist[0])
n2 = int(strlist[1])
G.add_edges_from([(n1, n2)])
return G
def RegenGraphData... | This code dismantles a network by iteratively removing nodes predicted as critical by a model. It calculates the residual largest connected component size after each removal, storing results for analysis. The process involves graph creation, node scoring, sequential removal, and connectivity tracking. | def onepass_dismantle(self):
for Network in self.Network_list:
os.makedirs(self.RESULT_PATH, exist_ok=True)
# NETWORK_PATH = os.path.join(self.Test_PATH, Network)
NETWORK_PATH = self.Test_PATH
G = self.CreateGraph(NETWORK_PATH, Network)
original_larg... |
def handle_player_move(stones, current_player, game_board):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
... | This code implements a Go game using Pygame, handling player/AI moves, capturing logic, and determining the winner based on stone limits and prisoners. It initializes the game board, processes moves, updates captured stones, switches players, and displays a game-over screen when both players reach their stone limits, d... | def play_game(screen, selected_player):
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Go Game")
game_board = GameBoard(screen, BOARD_SIZE)
stones = [["" for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
current_player = "B"
black_stones_limit... |
def populate_tables_to_join_nodes(self, node):
# if node.node_type is in one of the joins
if node.node_type in self.list_joins:
self.store_get_tables_for_join.clear()
self.get_tables_for_join(node)
node.tables = self.store_get_tables_for_join.copy()
for child... | The main task of the code is to compare join structures between two SQL query execution plans. It identifies differences in join types, tables involved, and unmatched nodes. The method populates join-related data, matches similar nodes, checks discrepancies, and generates a detailed comparison string highlighting new n... | def compare_joins(self):
compareString = ""
# clear attribute of this class
self.store_get_all_nodes_type.clear()
self.store_get_tables_for_join.clear()
# We populate the 'tables' attribute for those node has a join type (Merge Join, Nested Loop, Hash Join).
# It will po... |
def add(key, value,keys):
slot = hashf(key)
for i in keys[slot]:
if i[0] == key :
insert(i[1],value)
return
a=Node('WWWWWWWWWWWWWWWWWWWWWW')
keys[slot].append([key , insert(a,value)])
return
def delete(key, value,k... | The main task of the code is to process a series of operations (put, delete, get, deleteall) on a multimap data structure, implemented as a list of lists. It reads commands from 'multimap.in', applies the operations to the multimap, and writes the results of 'get' queries to 'multimap.out'. The code handles multiple va... | def main():
size = 100029
keys = [[] for i in range(size)]
filein=open('multimap.in', 'r')
fileout=open('multimap.out','w')
for s in filein.readlines():
s=s.split()
if s[0] == 'put':
add(s[1],s[2],keys)
elif s[0]=='delete':
delete(s[1],s[2],keys)
... |
def check_login():
session_id = request.cookies.get("session_id")
if not session_id:
abort(401)
query = "select user_id from sessions where session_id = %s"
values = (session_id,)
db = get_db_conn()
cursor = db.cursor()
cursor.execute(query, values)
record = cursor.fetchone()
... | This function adds a new blog post by handling user authentication, image upload, and form data. It saves the image, inserts the post into the database with user ID and tags, and establishes tag-post relationships. If tags don't exist, they are created. The function returns the newly created post. | def add_post():
user_id = check_login() # get the user_id from the active session
image_file = request.files.get('image')
if image_file:
filename = secure_filename(image_file.filename) # Secure the filename
image_path = os.path.join('C:/Users/97252/Downloads', filename)
image = I... |
def check_login():
session_id = request.cookies.get("session_id")
if not session_id:
abort(401)
query = "select user_id from sessions where session_id = %s"
values = (session_id,)
db = get_db_conn()
cursor = db.cursor()
cursor.execute(query, values)
record = cursor.fetchone()
... | The function updates a post's title and body in the database after verifying the logged-in user is the author. It retrieves JSON data from the request, executes an SQL update query with the provided values, commits the transaction, and returns the updated post. | def update_post(post_id):
user_id = check_login() # get the user_id from the active session
data = request.get_json()
verify_author(post_id, user_id)
query = "update posts set title = %s, body = %s where id = %s"
values = (data['title'], data['body'], post_id)
db = get_db_conn()
cursor = db... |
def File():#use this to open and read text file, stores into list called "engish_words"
File_object = open(r"words.txt","r")
engish_words=[File_object.read().splitlines()]
return engish_words
def user():#method to get user input
user_tree=input("Which BST would you like today? : AVL or RB-->")
print... | The code's main task is to read data from a file, construct either an AVL or Red-Black (RB) tree based on user input, and handle anagrams. It first retrieves data via `File()`, then checks the user's choice to build the respective tree (AVL or RB). For AVL, it inserts data into the tree and attempts to display it (thou... | def main():#calls methods step by step
List=File()
print(List)
if user()=="AVL":#repeats if statement, dont know why
tree = AVLTree()
data = File()
print("Inserting data", data)
for key in data:
insert(tree,key)
display(tree)#not working
... |
def _click_button(self, index):
coord = get_coord(index, self.bitboard.shape)
self.bitboard.inverse_one(coord)
def _undo(self):
self.care_taker.undo()
self.update(None, False)
def _redo(self):
self.care_taker.redo()
self.update(None, False)
def set_bitboard(self):
... | This code initializes a GUI interface for a bitboard, setting up a grid of buttons to represent the board, action buttons for operations like inversion and shifting, and input controls for decimal values. It configures layouts, event handlers, and integrates with an observer pattern to update the UI based on bitboard c... | def __init__(self, master, bitboard, bg='white', fg='black', **kwargs, ):
tk.Frame.__init__(self, master, bg=bg, **kwargs)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
Observer.__init__(self)
self.bitboard = bitboard
self.bitboard.attach(self)
... |
def combine_all_vector_data(hurricane_name, toprint, overwrite):
"""
Combines all geojson files for the hurricane into one geojson file
The combined file will be saved in data/processed/geojson
PARAMETERS:
---
hurricane_name: name of the hurricane
toprint: whether or not to print pr... | The main task of the code is to combine, trim, filter, and save vector data (GeoJSON) related to a specified hurricane. It checks for an existing processed file, reprocesses data if needed, retains only flooded/damaged building points, adds country names, and saves the final GeoDataFrame. The function ensures efficient... | def combine_all_vector_data_and_save_for_hurricane(hurricane_name = DEFAULT_HURRICANE, toprint = True, overwrite = False):
# This is the path to the processed vector data file
if not os.path.isdir(PATH_TO_GEOJSONS):
os.mkdir(PATH_TO_GEOJSONS)
path = os.path.join(PATH_TO_GEOJSONS, hurricane_name + ".... |
def get_choice():
print()
print(" ", "." * 35)
print(" 1. display_line_of_symbols()")
print(" 2. display_intro()")
print(" 3. get_play_menu_selection()")
print(" 4. get_main_menu_selection()")
print(" 0. Exit")
selection = int(input(" Enter selection: "))
print(" ", "." * 35... | The main task of the code is to run a loop that repeatedly retrieves user input via `get_choice()` and executes corresponding test functions based on the selection: `test_display_line_of_symbols()` for 1, `test_display_introduction()` for 2, `test_get_play_menu_selection()` for 3, and `test_get_main_menu_selection()` f... | def main():
selection = 1
while selection > 0:
selection = get_choice()
if selection == 1:
test_display_line_of_symbols()
elif selection == 2:
test_display_introduction()
elif selection == 3:
test_get_play_menu_selection()
elif selectio... |
def get_choice():
print()
print(" ", "." * 35)
print(" 1. display_current_scores()")
print(" 2. game_is_over()")
print(" 3. get_winner_name()")
print(" 4. display_game_result()")
print(" 5. display_statistics()")
print(" 0. Exit")
selection = int(input(" Enter selection: ")... | The main task of the code is to run a menu-driven testing framework for game-related functions. It continuously prompts the user for a selection (1-5) and executes corresponding test functions: displaying scores, checking game status, determining winners, showing results, or displaying statistics. The loop terminates w... | def main():
selection = 1
while selection > 0:
selection = get_choice()
if selection == 1:
test_display_current_scores()
elif selection == 2:
test_game_is_over()
elif selection == 3:
test_get_winner_name()
elif selection == 4:
... |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if three_on_line(board) is not None:
return True
# validate board it's not full
full = True
for row in board:
if row.count(EMPTY) > 0:
full = False
return full
def utility(board):
... | The code implements a recursive minimax algorithm with memory adjustment for a game board. It evaluates terminal states, returns utility values, and explores all available actions. For each action, it recursively calculates scores, alternating between maximizing and minimizing players. It selects the maximum or minimum... | def evaluate_minimax(board, is_maximizing, memory):
if terminal(board):
return utility(board)
available_actions = actions(board)
scores = []
for current_action in available_actions:
board = result(board, current_action)
if is_maximizing:
scores.append( max(-math.inf... |
def player(board):
"""
Returns player who has the next turn on a board.
"""
count_x = 0
count_o = 0
for row in board:
count_x += row.count(X)
count_o += row.count(O)
if count_x > count_o:
return O
return X
def actions(board):
"""
Returns set of all possi... | The code implements the Minimax algorithm to determine the optimal move for the current player on a game board. It evaluates all possible actions recursively, considering both maximizing (player X) and minimizing (player O) scenarios. For each action, it calculates a score, updates the best move based on maximizing or ... | def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
ia_player = player(board)
is_maximizing = False
evaluate = math.inf
test = -10
if ia_player == X:
is_maximizing = True
evaluate = -math.inf
test = 10
for current_actio... |
def get_item_type(item):
if isinstance(item, Variable): # when displaying info about a variable
item_type = "Variable"
elif isinstance(item, Constant): # when displaying info about a constant
item_type = "Constant"
elif isinstance(item, Equation): # when displaying info about a equation
... | The main task of the code is to collect user input from GUI widgets, process it according to the selected item type (e.g., Logic, Variable, Equation, Method), and save the resulting structured data. It gathers text from entry fields, applies type-specific processing functions, and constructs objects like Method with ne... | def item_submit(container_widget, to_edit):
list_of_widgets = container_widget.winfo_children()
item_type_item_to_edit = get_item_type(item_to_edit)
time_type_selected = item_type_to_add_or_edit.get()
item_to_save = ""
list_of_txt_box_text = []
# collect all the text boxes into a list
for ... |
def add_edit_item_v_or_c_display(type_to_display, container_widget, to_edit, e_item):
r = container_widget.winfo_children()[-1].grid_info()['row'] + 3 # not sure why it always gets 0 but it works
lab_sym = Label(container_widget, text="Symbol:",
relief=relief_style, highlightthickness=1,... | This function dynamically updates a UI container by removing existing widgets and displaying type-specific elements based on 'type_to_display'. It resets a global step counter, then conditionally renders interfaces for variables, constants, equations, theories, or methods. For methods, it adds an option menu and button... | def add_edit_item_option_display(type_to_display, container_widget, to_edit):
# saves all the widgets after the first 5 which are always gonna be there
widgets = container_widget.winfo_children()[6:]
# deletes those widgets to remove remnants
for w in widgets:
w.destroy()
# reset this valu... |
def add_edit_item_option_display(type_to_display, container_widget, to_edit):
# saves all the widgets after the first 5 which are always gonna be there
widgets = container_widget.winfo_children()[6:]
# deletes those widgets to remove remnants
for w in widgets:
w.destroy()
# reset this valu... | This function creates a pop-up window for adding or editing items, featuring a scrollable canvas, input fields for name/definition, an item type dropdown, and a submit button. It dynamically populates fields when editing, sets the window title based on mode, and configures scrolling functionality for handling multiple ... | def add_edit_item_window(to_edit):
# stuff for creating the pop-up window
small_win = Toplevel()
small_win.configure(background=color_dark)
small_win.grid_rowconfigure(0, weight=1)
small_win.grid_columnconfigure(0, weight=1)
small_win.grab_set() # stops the user from interacting with the... |
def add_edit_item_window(to_edit):
# stuff for creating the pop-up window
small_win = Toplevel()
small_win.configure(background=color_dark)
small_win.grid_rowconfigure(0, weight=1)
small_win.grid_columnconfigure(0, weight=1)
small_win.grab_set() # stops the user from interacting with the... | This function dynamically displays detailed information about a selected item (e.g., name, type, description, steps) in a GUI frame. It clears previous content, identifies the item type, and renders corresponding elements using type-specific formatting and helper functions, while allowing editing via a button. | def display_info(r):
# destroys anything that was in the frame before
for widget in frm_info_inner.winfo_children():
widget.destroy()
global item_to_edit
display_item = search_results[r] # get the search_result from the corresponding row
item_to_edit = display_item # in the case... |
def scan_dir(self,path,Dir,File):
if os.path.isdir(path):
Dir.append(path)
for filename in glob.glob(path+'/*'):
self.scan_dir(filename,Dir,File)
else:
File.append(path)
def send_data(self,d):
self.Handle.write(d)
def send_file(self,f):
... | The code's main task is to scan a directory, collect its subdirectories and files into lists, send the directory structure as JSON data, and then transmit each file individually. It first processes the input directory `d`, populates `Dir` and `File` lists via `scan_dir`, sends the directory structure using `send_data`,... | def send_directory(self,d):
Dir=[]
File=[]
self.scan_dir(d,Dir,File)
self.send_data(json.dumps(Dir))
self.send_data(json.dumps(File))
for i in File:
self.send_file(i) |
def valid_mlrank(mlrank):
prod = np.prod(mlrank)
return all(prod//r > r for r in mlrank)
def initialize_factors(shape, mlrank, iter_modes, update_order, seed, dtype=None):
factors = [None]*3
update_modes = iter_modes[update_order[0]]
random_state = np.random if seed is None else np.random.RandomStat... | The function computes the HOOI (Higher-Order Orthogonal Iteration) decomposition of a sparse tensor in COO format, returning factor matrices and a core tensor. It iteratively updates factors using a specified order, stopping when convergence or max iterations are reached. The decomposition approximates the input tensor... | def sparse_hooi(
idx, val, shape, mlrank,
max_iters=15, update_order=None, iter_callback=None,
growth_tol=0.001, materialize_core=False,
seed=None, dtype=None, verbose=True
):
'''
Computes HOOI decomposition of a sparse tensor provided in COO format.
Usage:
u0, u1, u2, g = sparse_hooi(id... |
def process_command_line():
"""
Parse command line arguments
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
Return a Namespace representing the argument list.
"""
# Create the parser
parser = argparse.ArgumentParser(prog='border_crossing_model_4',
... | The code processes command-line arguments, runs a specified number of simulation replications based on the scenario, consolidates vehicle log data, computes summary statistics, and prints results with formatted pandas output. | def main():
args = process_command_line()
print(args)
num_reps = args.num_reps
scenario = args.scenario
if len(args.output_path) > 0:
output_dir = Path.cwd() / args.output_path
else:
output_dir = Path.cwd()
# Main simulation replication loop
for i in range(1, num_reps... |
def crawl(directory):
"""
Parse a directory of HTML pages and check for links to other pages.
Return a dictionary where each key is a page, and values are
a list of all other pages in the corpus that are linked to by the page.
"""
pages = dict()
# Extract all links from HTML files
for f... | The main task of the code is to compute and print PageRank values for a given corpus of web pages using both sampling and iterative methods. It first validates input, crawls the corpus, calculates ranks via sampling with specified parameters, prints results, then recalculates ranks iteratively and prints them again. Th... | def main():
if len(sys.argv) != 2:
sys.exit("Usage: python pagerank.py corpus")
corpus = crawl(sys.argv[1])
ranks = sample_pagerank(corpus, DAMPING, SAMPLES)
print(f"PageRank Results from Sampling (n = {SAMPLES})")
for page in sorted(ranks):
print(f" {page}: {ranks[page]:.4f}")
... |
def save_attention(attention, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_linear(attention.wq, pathlib.Path(path, 'wq'))
save_linear(attention.wk, pathlib.Path(path, 'wk'))
save_linear(attention.wv, pathlib.Path(path, 'wv'))
save_linear(attention.wo, pathlib.Path(path, 'wo'))
... | The main task of the code is to save the components of a transformer block to a specified directory. It creates the directory structure, then serializes the attention mechanism, feedforward network, and two RMS normalization layers into separate subdirectories within the given path. | def save_transformer_block(transformer_block, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_attention(transformer_block.attention, pathlib.Path(path, 'attention'))
save_feedforward(transformer_block.feed_forward, pathlib.Path(path, 'feedforward'))
save_rmsnorm(transformer_block.atten... |
def save_scalar(s, name, path):
s = np.array([1.0, float(s)]).astype(np.float32)
np.save(pathlib.Path(path, f'{name}.npy'), s)
def save_transformer_block(transformer_block, path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_attention(transformer_block.attention, pathlib.Path(path, 'attent... | This function saves a transformer model's components to a specified directory, including layer counts, individual transformer blocks, normalization layers, embeddings, output layers, and scalar parameters like sequence length and scaling factors. It creates the directory structure, serializes each component, and stores... | def save_transformer(transformer, path):
with torch.no_grad():
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
save_scalar(len(transformer.layers), 'n_layer', path)
for idx, layer in enumerate(transformer.layers):
save_transformer_block(layer, pathlib.Path(path, f'layer{idx... |
def build_filter(self, term):
"""
Returns a bio.tools filter for a given EDAM term
"""
filters_template = {'topic': 'topicID="%s"', 'format':'dataFormatID="%s"', 'operation':'operationID="%s"', 'data':'dataTypeID="%s"'}
if 'topic' in term:
filters = filters_template[... | The function `query_for_terms` processes a list of terms (EDAM or free text) by querying a database (e.g., bio.tools). It constructs filters based on the `EDAM` flag, executes queries, and converts results into two dataframes per term: a general summary and detailed data. Results are stored in dictionaries for easy ret... | def query_for_terms(self, terms : list, EDAM=False):
'''
Takes a list of EDAM terms or free text keywords and does a query for each.
EDAM=True for edam terms, EDAM=False for freetext keywords. Default: EDAM=False.
Return a dictionary of results of the form: {<term>: <dataframe of results... |
def query_biotools(self):
search_performed = False
# Querying EDAM terms
if self.verbosity:
if self.edam_terms:
print(f"{bcolors.OKBLUE}Querying bio.tools for EDAM terms:{bcolors.ENDC}")
else:
text_warn = "No EDAM terms provided."
... | The code defines a method `run_pipeline` that orchestrates a workflow by sequentially executing three tasks: querying biotools data, processing the retrieved results, and ranking the tools based on specific criteria. Its main task is to automate the retrieval, analysis, and prioritization of bioinformatics tools in a s... | def run_pipeline(self):
self.query_biotools()
self.process_results()
self.rank_tools() |
def get_new_coordinates(self, dir, pawn):
"""
Returns the coordinates one square in a different direction to (x,y).
"""
x, y = (pawn.coordinates)
if dir == NORTHWEST:
return x - 1, y - 1
elif dir == SOUTHWEST:
return x + 1, y - 1
elif dir =... | This function determines the available pawns a player can move by checking valid positions on the board. It evaluates both regular pawn moves and captures, handling non-king pawns by checking two potential directions, while kings use a separate method for their moves. The function ensures moves stay within bounds and v... | def get_available_pawns(self, player_pawns_list, p2_list, dir):
temp_dict = player_pawns_list
player_available_pawns = []
for p in temp_dict:
if not temp_dict[int(p)].is_king:
x, y = self.get_new_coordinates(dir[0], temp_dict[p])
a, b = self.get_new_co... |
def get_player2_moves(self, dir1, dir2, pawn):
get_pawn_moves = []
nw_x, nw_y = self.get_new_coordinates(dir1, pawn)
ne_x, ne_y = self.get_new_coordinates(dir2, pawn)
if self.check_boundry(nw_x, nw_y) and self.board[nw_x][nw_y] > 0 and self.board[nw_x][nw_y] != OBSTACLE:
nw_n... | This function determines and returns a list of legal move coordinates for a given pawn on a board, considering its type (player 1, player 2, or king) and position. It checks the pawn's ID, direction, and status (e.g., king) to decide which movement logic to apply, returning valid moves or an empty list if no moves are ... | def get_moves(self, pawn):
"""
:param pawn Pawn object
:return array array of coordinates the pawn can move to
Returns a list of legal move locations from a set of coordinates (x,y) on the board.
If that location is empty, then get_moves() return an empty list.
"""
... |
def get_moves(self, pawn):
"""
:param pawn Pawn object
:return array array of coordinates the pawn can move to
Returns a list of legal move locations from a set of coordinates (x,y) on the board.
If that location is empty, then get_moves() return an empty list.
"""
... | This function identifies and returns coordinates of potential chain captures for a given pawn. It retrieves all possible moves, checks each for a capture type (move_type == 1), and collects qualifying coordinates into a list for strategic gameplay analysis. | def get_chain_capture_coordinates(self, pawn):
chain_capture_coordinates = []
moves_list = self.get_moves(pawn)
for coordinate in moves_list:
move_type = self.check_move_type(pawn, self.get_direction_from_coordinates(pawn, coordinate))
if move_type == 1:
c... |
def get_direction_from_coordinates(self, pawn, new_coordinate):
x, y = (pawn.coordinates)
new_x, new_y = new_coordinate
if x > new_x and y > new_y:
return NORTHWEST
elif x < new_x and y > new_y:
return SOUTHWEST
elif x > new_x and y < new_y:
re... | This method handles pawn movement on a board, updating the pawn's position and board state. It determines the move type (simple or capture), executes the move, and checks for potential chained captures. If a pawn reaches the last row (depending on its ID), it becomes a king. The function returns coordinates for chained... | def move_pawn(self, pawn, coordinate):
"""
This method handle the pawn movement inside the board
:param pawn_id int
Changes the position of the pawn selected and state of board
:return list if the move is of type capture and can be chained
"""
dire... |
def lrtvbloff(): # If we're streaming to the TV backlights, this will be NOOP
units = [28, 29, 39]
off(units)
def lrdl(onstate=True, bri=254, ct=CTCOOL):
'''Living room downlights on/off, brightness, CT'''
units = [22, 23, 24, 25]
dl(units, onstate, bri, ct)
def brmin():
units = [5, 9, 16]
o... | The main task of the code is to control multiple light units by turning them on, setting specific brightness (bri=154), hue (8402), and saturation (143) values, while handling an Edison bulb as a special case with lower brightness and warm color temperature. It also checks if a bedroom light (unit 9) is on, and if so, ... | def lrteevee():
lrtvbloff()
units = [11, 12, 13, 14, 15, 17, 20]
on(units)
setlevels(units, bri=154)
sethues(units, hue=8402, sat=143)
# The edison bulb is a special case.
lrdl(onstate=True, bri=1, ct=CTWARM)
if ison(9): # If the bedroom is on, bring it down
brmin() |
def lrtvbloff(): # If we're streaming to the TV backlights, this will be NOOP
units = [28, 29, 39]
off(units)
def lrdl(onstate=True, bri=254, ct=CTCOOL):
'''Living room downlights on/off, brightness, CT'''
units = [22, 23, 24, 25]
dl(units, onstate, bri, ct)
def brmin():
units = [5, 9, 16]
o... | The main task of the code is to configure and control multiple light units for a cinema setup. It turns on specified units, adjusts their brightness and color settings, handles a special Edison bulb, and checks if the bedroom light (unit 9) is on to adjust it accordingly. | def lrcinema():
lrtvbloff()
units = [11, 12, 13, 14, 15, 17, 20]
on(units)
setlevels(units, bri=39)
sethues(units, hue=8402, sat=140)
# The edison bulb is a special case.
lrdl(onstate=False)
if ison(9): # If the bedroom is on, bring it down
brmin() |
def lrdl(onstate=True, bri=254, ct=CTCOOL):
'''Living room downlights on/off, brightness, CT'''
units = [22, 23, 24, 25]
dl(units, onstate, bri, ct)
def brsp2(force=False):
units = [5, 9, 36]
if ison(16) or ison(36) or force: # keyed on the bedside table light
on(16) # the key is off, but we... | This function configures room lighting by activating specific backlights and adjusting brightness levels when the end-table lamp is on or forced. It ensures lower backlights (28,29) are on, reduces TV backlight brightness, disables play lights (39) and candleboxes (17,20), then executes lighting adjustment routines (lr... | def lrsp2(force=False):
# 2021-11-30: revising the behaviour of SP2 after moving lights around the room
units = [11, 12, 13, 14, 15, 28, 29, 39] # this probably isn't needed now
if ison(12) or force: # keyed on the end-table lamp
on([28,29]) # the two lower backlights should always be on here.
... |
def parse_inputs():
desc = 'dns_understanding_alluvium.py: Data analysis file -constructs Alluvium plots between users\' understanding/familiarity w/DNS and their beliefs on SDNS\'s impact on their security/privacy'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-f',
... | The main task of the code is to parse input parameters, merge dataframes from specified files, and generate three visualizations analyzing SDNS (Secure Domain Name System) metrics: trustworthiness, security, and privacy. The function orchestrates data assembly and plotting to evaluate SDNS performance across these crit... | def main():
params = parse_inputs()
mergedFrame = assemble_dataframe(params.fullDfFile, params.dnsCodesFile)
build_sdnsTrustworthiness_plot(mergedFrame)
build_sdnsSecurity_plot(mergedFrame)
build_sdnsPrivacy_plot(mergedFrame) |
def print_balance() -> None:
"""
This function will print the user's balance
Args:
None
Returns:
None
"""
print("Your balance is: $" + str(check_balance()))
def deposit(amount: float = None) -> float:
"""
This function will deposit money into the user's account
Arg... | The function `menu_logic` routes user input from the main menu to corresponding actions: printing balance, depositing, withdrawing, or exiting. It executes the appropriate function based on the integer choice (1-4) provided by the user, ensuring program flow aligns with the selected option. The function is designed to ... | def menu_logic(choice: int) -> None:
"""
this function calls the appropriate function based on the user's choice
Should only be called in conjunction with the main_menu function
Args:
choice (int): The user's choice from the main_menu function (1-4) - this is checked in the main_menu function
... |
def authenticate_user() -> bool:
"""
This function authenticates the user by asking for their
username and pin
The function will only prompt 3 times for a username and pin
Keyword arguments:
Return: True if the username and pin are correct, otherwise return False
"""
# Create a for loo... | The main task of the code is to run a Bank Account Management System by authenticating the user and presenting a menu-driven interface for account management tasks, looping until the user chooses to exit. | def main():
"""
Main function to run the program
Whatever code is in this function will run when the program is executed
"""
print("Welcome to the Bank Account Management System")
if authenticate_user() is True:
print("Authentication Successful!")
# Keep prompting the user to en... |
def states():
"""
Computes every possible state.
Each state consists of 4 elements:
state[0] = the open card (the card that is currently being passed between players)
state[1] = the number of chips on the open card
state[2] = the number of chips currently in possession ... | The code initializes an agent by setting up parameters (epsilon, step_size) and creating a Q-table for reinforcement learning. It constructs state/action spaces, initializes reward structures, and creates a zero-filled DataFrame for Q-values, indexed by states and columns by actions. The 'visit' variable is a copy of t... | def agent_init(self, agent_init_info):
"""
Initializes the agent to get parameters and import/create q-tables.
Required parameters: agent_init_info as dict
"""
# (1) Store the parameters provided in agent_init_info
self.states = states()
self.state_dict =... |
def states():
"""
Computes every possible state.
Each state consists of 4 elements:
state[0] = the open card (the card that is currently being passed between players)
state[1] = the number of chips on the open card
state[2] = the number of chips currently in possession ... | The main task of the code is to initialize an agent by configuring parameters (epsilon, step_size, rewards), setting up state/action spaces, and creating/loading a Q-table from a CSV file. If the CSV fails to load, it generates a new zero-initialized Q-table with states as rows and actions as columns, then copies it to... | def agent_init(self, agent_init_info):
"""
Initializes the agent to get parameters and import/create q-tables.
Required parameters: agent_init_info as dict
"""
global q
# (1) Store the parameters provided in agent_init_info
self.states = states()
... |
def parse_args(argv: List[str]) -> Namespace:
parser = argparse.ArgumentParser('Example Python CLI')
parser.add_argument('-n', '--name', type=str, help='say hello to this name')
parser.add_argument('-j', '--json', action='store_true', help='fetch some sample json data')
return parser.parse_args(argv)
de... | The main task of the code is to execute different actions based on command-line arguments: if a 'name' argument is provided, it calls `say_hello` with that name; if a 'json' flag is provided, it calls `fetch_json` to retrieve JSON data. | def main() -> None:
args = parse_args(sys.argv[1:])
if args.name:
say_hello(args)
elif args.json:
fetch_json() |
def get_param(net):
new_param = []
with torch.no_grad():
j = 0
for name, param in net.named_parameters():
new_param.append(param.clone())
j += 1
torch.cuda.empty_cache()
gc.collect()
return new_param
def set_param(net, old_param):
with torch.no_grad():
... | The code implements a diffusion model fine-tuning method called "erasediff" to selectively forget a specific class while preserving others. It trains the model using ambiguous data, applying parameter masking (via a mask file) and a BOME algorithm that combines data reconstruction loss (on remaining data) and query los... | def erasediff(
class_to_forget,
train_method,
batch_size,
unl_eps,
K_steps,
lambda_bome,
rem_num,
lr,
config_path,
ckpt_path,
mask_path,
diffusers_config_path,
device,
image_size=512,
ddim_steps=50,
):
# MODEL TRAINING SETUP
model = setup_model(config... |
def get_param(net):
new_param = []
with torch.no_grad():
j = 0
for name, param in net.named_parameters():
new_param.append(param.clone())
j += 1
torch.cuda.empty_cache()
gc.collect()
return new_param
def set_param(net, old_param):
with torch.no_grad():
... | The code trains a diffusion model to remove NSFW content from images using semi-supervised learning. It employs the BOME algorithm, optimizing parameters based on `train_method` (e.g., training specific layers or all layers). The model uses pseudo-labels, combines forgetting (NSFW data) and retaining (non-NSFW data) lo... | def erasediff(
unl_eps,
K_steps,
lambda_bome,
rem_num,
train_method,
batch_size,
lr,
config_path,
ckpt_path,
mask_path,
diffusers_config_path,
device,
image_size=512,
ddim_steps=50,
):
# MODEL TRAINING SETUP
model = setup_model(config_path, ckpt_path, devi... |
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def sample_visualization(self, model, name, cond_scale):
config = self.config
total_n_samples = config.training.visualization_samples
assert total_n_samples % config.data.n_classes == 0
... | The code trains a diffusion model to perform "diffusion forget" using the BlindSpot method, which involves two stages: (1) training a proxy model on data excluding a target class, and (2) using this proxy to guide unlearning in the original model. The proxy model is trained with antithetic sampling and EMA, while the s... | def train_blindspot(self):
args, config = self.args, self.config
logging.info(f"Training diffusion forget with BlindSpot.")
# Dataset
_, trainloader_all, trainloader_rem, _, _ = load_data(args)
# trainloader_rem = all_but_one_class_path_dataset(config, os.path.join(args.ckpt_fol... |
def create_sub_cert(CN, CACert, CAkey, snum, START, END,
C='CA', ST='Ontario', L='Toronto',
O='Libreswan', OU='Test Department',
emailAddress='',
ty=crypto.TYPE_RSA, keybits=2048,
sign_alg='sha256', isCA=False, ocsp=Fals... | This function generates end-entity certificates from a main CA, customizing each certificate's key size, validity period, signer CA, OCSP response, organization name, common name, and algorithm based on the certificate's name. It creates and stores certificates, keys, and PKCS12 files for each entry in the input list. | def create_mainca_end_certs(mainca_end_certs):
""" Create the core set of end certs from mainca
"""
serial = 2
print("creating mainca's end certs")
for name in mainca_end_certs:
# put special cert handling here
print(" - creating %s"% name)
keysize = 3072
if name == '... |
def create_sub_cert(CN, CACert, CAkey, snum, START, END,
C='CA', ST='Ontario', L='Toronto',
O='Libreswan', OU='Test Department',
emailAddress='',
ty=crypto.TYPE_RSA, keybits=2048,
sign_alg='sha256', isCA=False, ocsp=Fals... | The code generates certificate chains (EE→IA1→IA2→…→CA) by creating intermediate certificates (int_n) signed by prior CAs, culminating in end-entity (endcert) and revoked certificates (endrev). It uses `create_sub_cert` to build each link, stores certs/keys, and exports PKCS12 files. Global variables track the end-revo... | def create_chained_certs(chain_ca_roots, max_path, prefix=''):
""" Create the EE->IA1->IA2->IAx-->CA chains.
Last in the chain is the end cert
TODO: Add more complex trust chain situations
"""
global endrev_name
global top_caname
min_path = 1
ca_cnt = 0
for chainca in chain_ca_roots... |
def create_root_ca(CN, START, END,
C='CA', ST='Ontario', L='Toronto',
O='Libreswan', OU='Test Department',
emailAddress='pklis@example.com',
ty=crypto.TYPE_RSA, keybits=2048,
sign_alg='sha256'):
""" Create a root CA - Ret... | The function generates root Certificate Authority (CA) certificates for each name in the provided list, saves them as files in the 'cacerts/' directory, and stores the certificates and keys for later use. It creates each CA with a specific Common Name (CN), valid dates, and outputs the results to disk. | def create_basic_pluto_cas(ca_names):
""" Create the core root certs
"""
print("creating CA certs")
for name in ca_names:
print(" - creating %s"% name)
ca, key = create_root_ca(CN="Libreswan test CA for " + name,
START=dates['OK_NOW'],
... |
def create_basic_pluto_cas(ca_names):
""" Create the core root certs
"""
print("creating CA certs")
for name in ca_names:
print(" - creating %s"% name)
ca, key = create_root_ca(CN="Libreswan test CA for " + name,
START=dates['OK_NOW'],
... | The main task of the code is to generate a comprehensive set of X.509 test certificates, PKCS#12 files, keys, and CRLs for the Pluto test harness. It creates root CAs, end-entity certificates with varied attributes (e.g., key usages, constraints, critical flags), chained certificate hierarchies, and special cases to va... | def run_dist_certs():
""" Generate the pluto test harness x509
certificates, p12 files, keys, and CRLs
"""
# Add root CAs here
basic_pluto_cas = ('mainca', 'otherca', 'badca')
# Add end certs here
mainca_end_certs = ('nic','east','west', 'road', 'north', # standard certs
... |
def reset_files():
for dir in ['keys/', 'cacerts/', 'certs/', 'selfsigned/',
'pkcs12/',
'pkcs12/curveca',
'pkcs12/mainca',
'pkcs12/otherca',
'pkcs12/badca',
'crls/',
'fake',
'fake/keys/',
... | The main task of the code is to generate and manage certificate files, including creating self-signed certificates, resetting files, handling directory changes, and producing GMT date timestamps for tracking. It executes certificate generation processes for base and "fake" directories, creates NSS passwords, and ensure... | def main():
outdir = os.path.dirname(sys.argv[0])
cwd = os.getcwd()
if outdir:
os.chdir(outdir)
global dates
global dirbase
reset_files()
dates = gen_gmtime_dates()
print("format dates being used for this run:")
# TODO: print the display GMT times
for n, s in dates.items(... |
def _train_val_once(self, epoch: int, num_epochs: int, num_images: int = 0):
print()
print('[*] Epoch {}/{}'.format(epoch, num_epochs))
swa = (epoch > self._swaStart)
train_auroc, train_loss, train_acc = self.__train_val_once(num_images)
self._plot_cfm("train", epoch)
if ... | This code trains a machine learning model for a specified number of epochs, performing training and validation in each epoch. It optionally plots loss statistics, resets training metrics, updates batch normalization layers for a SWA model, and outputs the total training time. The function returns training and validatio... | def train(self, num_epochs: int = 10, num_images: int = 0) -> (list, list):
start_time = time.time()
for epoch in range(1, num_epochs + 1):
train_res, val_res = self._train_val_once(epoch, num_epochs, num_images)
if self._graphLoss:
self._plot_stats(epoch, train_... |
def _train_val_once(self, epoch: int, num_epochs: int, num_images: int = 0):
print()
print('[*] Epoch {}/{}'.format(epoch, num_epochs))
swa = (epoch > self._swaStart)
train_auroc, train_loss, train_acc = self.__train_val_once(num_images)
self._plot_cfm("train", epoch)
if ... | This code implements an active learning loop where the model iteratively selects informative samples from a pool using BatchBALD, adds them to the training set, retrains, and evaluates performance. It splits data into train/pool, transforms datasets, trains with DataLoader, tracks metrics, and updates a SWA model with ... | def train_active(self, num_images: int = 0) -> None:
total_size = len(self._trainData)
train_size = int(0.99 * total_size)
pool_size = total_size - train_size
train, pool = random_split(self._trainData, [train_size, pool_size])
train = TransformedDataset(train, transformer=self.... |
def _reset_model(self) -> None:
def _reset_weights(m):
'''
Try resetting model weights to avoid
weight leakage.
'''
for layer in m.children():
if hasattr(layer, 'reset_parameters'):
layer.reset_parameters()
... | The code performs k-fold cross-validation for a machine learning model. It splits the dataset into k folds, trains the model on each fold while validating on the remaining data, and evaluates performance using accuracy and loss. Temporary checkpoints are saved for each fold, and the best model (highest accuracy, lowest... | def train_cross_validate(self, k_folds: int = 5, folders: list[str] = None, num_images: int = 0):
if folders:
total_size = len(folders)
else:
full_dataset = ConcatDataset([self._origTrainData, self._origTestData])
total_size = len(full_dataset)
fraction = 1 /... |
def create_image(
title: str,
font_size: int,
font_file: str,
x_size: int,
y_size: int,
text: str = None,
) -> Image:
"""
The create_image function creates a new image with the given title, font
size, and font file. It also takes in an x_size and y_size to determine
the dimension... | The gen_image function generates an image with customizable title, font, size, and dimensions. It either saves the image to disk or returns a base64-encoded string. Parameters include text, format, and to_file flag. | def gen_image(
title: str,
font_size=80,
font='arial',
x_size=500,
y_size=500,
to_file=False,
format='PNG',
text=None,
) -> Optional[str]:
"""
The gen_image function creates an image with the given title, font size,
font type, x and y sizes. The function can either save the i... |
def execute(self, command):
self.logger.debug(u"Command: {0} {1}".format(self.shell, command))
return Popen([command], stdout=PIPE, stderr=PIPE, shell=True, executable=self.shell)
def stop(self, process):
if process.poll() is None:
self.logger.warning("Process is freezing. Force quit... | The code executes a command with a timeout, waiting for the process to complete. If the timeout elapses, it terminates the process. It returns either the logged output or a Result object, depending on the 'silent' parameter. | def call(self, command, timeout, silent=None):
proc = self.execute(command)
while timeout > 0:
sleep(1)
if proc.poll() is not None:
break
timeout -= 1
if timeout == 0:
self.stop(proc)
if silent:
return self.log... |
def clean_message(input_str):
'''(str) -> str
Convert string to all caps and remove all non-alpha characters
>>> clean_message("adsfadsf")
'ADSFADSF'
>>> clean_message("Asjth54akljg53!248^%#$")
'ASJTHAKLJG'
'''
# create an empty string-format result variable
res = ""
# check ea... | The function `process_message` encrypts or decrypts a message using a provided deck and command. It processes each character of the input message by applying either `encrypt_letter` or `decrypt_letter` with a keystream value derived from the deck. The result is constructed character-by-character and returned as the fin... | def process_message(pm_deck, message, command):
''' (list of int, str, str) -> str
Take a deck, a message and the decrypt/encrypt command and return either
a decrypted message or an encrypted one.
>>> process_message([16, 1, 4, 7, 10, 19, 22, 13, 25, 28, 3, 6, 9, 12,\
15, 18, 21, 24, 27, 5, 8, 11,... |
def test_failure(query):
''' (str) -> int
try to catch some common mistakes that are made. Hopefully most
failures will be caught by this and the user will be able to fix the
issues themselves.
>>> test_failure("select yo from oscas")
1
>>> test_failure("asdfadsf")
5
'''
# if t... | The code executes a SQL-like query by parsing it, validating syntax, and processing data from tables. It checks for errors (e.g., invalid tables/columns) and applies `FROM`, `WHERE` (if present), and `SELECT` operations to return structured results. The function handles query execution, data filtering, and error handli... | def run_program(query):
''' (str) -> str/table
run the entire query performing all steps of the program. REQ: the query
must be in the correct form
>>> run_program('select o.title,m.title from oscars,movies')
{'o.title': ['Toy Story 3', 'Toy Story 3', 'Toy Story 3', 'The Lord of\
the Rings: Th... |
def predict(board_arr, attack_matrix, turn):
board_arr = np.asarray([board_arr])
attack_matrix = np.asarray([attack_matrix])
attack_matrix = tf.keras.utils.normalize(attack_matrix)
absolute_prediction = model.predict([board_arr, attack_matrix])
if turn:
prediction = absolute_prediction[0][0... | The code's main task is to process a chess FEN string input, convert it into a model-friendly format (one-hot encoding, attack matrix, turn), predict a score, calculate the average score of legal moves, and identify the best move and minimum loss for a chess position. It continuously accepts FEN inputs until "stop" or ... | def main():
# Request FEN string, then make prediction
while 1:
FEN = input('Board FEN: ')
if FEN.lower() is 'stop' or FEN.lower() is 'quit':
break
test_board = chess.Board(FEN)
# if not test_board.turn:
# FEN = test_board.mirror().fen()
# print(f... |
def get_name_by_conversation_map(messages_dir: str) -> dict[str, str]:
pattern = re.compile(r'[-+]?[\d]+/messages.*')
mapping = {}
uniq_names = set()
with open_html(Path(f'{messages_dir}/index-messages.html')) as data:
soup = BeautifulSoup(data, 'html.parser')
for link in soup.find_all('... | The main task of the code is to process and save images from messages into a structured directory format using multithreading. It organizes images by conversation, generates unique filenames with timestamps, and leverages parallel threads to efficiently save data to the specified output directory. | def process_messages(
messages_dir: str = typer.Argument(
..., help='Path to your messages directory in data copy'
),
out_dir: str = typer.Argument(OUT_DIR, help='Path to save out data'),
threads: int = typer.Option(16, help='Number of parallel threads to save data'),
) -> None:
start_time =... |
def initialize_cluster_chracterstics(self,pixel_values):
self.pixel_values = pixel_values
self.n_samples, self.n_features = pixel_values.shape
random_sample_idxs = np.random.choice(self.n_samples, self.K, replace=False)
self.centroids = [self.pixel_values[idx] for idx in random_sample_id... | The code performs image segmentation by iteratively clustering pixel values into groups. It initializes cluster characteristics, updates cluster assignments and centroids in each iteration, and stops when centroids converge. The function returns labels indicating which cluster each pixel belongs to, achieving segmentat... | def segment(self, pixel_values):
self.initialize_cluster_chracterstics(pixel_values)
for _ in range(self.max_iters):
self.clusters = self.update_clusters(self.centroids)
centroids_old = self.centroids
self.centroids = self.update_centroids(self.clusters)
... |
def _create_clusters(self, centroids):
clusters = [[] for _ in range(self.K)]
for idx, sample in enumerate(self.X):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)
return clusters
def plot(self):
_, ax = plt.subplots(fig... | This code implements the K-means clustering algorithm. It initializes centroids by randomly selecting K data points, iteratively assigns samples to the nearest centroid, updates centroids as the mean of their assigned clusters, checks for convergence between iterations, and returns cluster labels for the input data. | def predict(self, X):
self.X = X
self.n_samples, self.n_features = X.shape
random_sample_idxs = np.random.choice(self.n_samples, self.K, replace=False)
self.centroids = [self.X[idx] for idx in random_sample_idxs]
for _ in range(self.max_iters):
self.clusters = self.... |
def is_genie(premake_filename):
return premake_filename == 'genie.lua'
def is_vcvars_setup():
return platform.system() == 'Windows' and 'VisualStudioVersion' in os.environ
def get_vs_version():
VS_VERSION_LOOKUP = {
'8.0': 'vs2005',
'9.0': 'vs2008',
'10.0': 'vs2010',
'11.0': ... | This function determines the appropriate build subdirectory for a Premake project based on the operating system and build environment. It checks if the Premake file is GENie-compatible, identifies the OS (Linux, macOS, Windows), and selects a build directory (e.g., 'gmake_linux', 'ninja_macos-arm64'). For Windows, it v... | def find_build_subdir(premake_filename, premake_subdir):
system = platform.system().lower()
build_subdir = ''
if not is_genie(premake_filename):
# premake5 case
if system == 'linux' or 'bsd' in system:
build_subdir = 'gmake_linux'
elif system == 'darwin':
... |
def print_welcome() -> None:
"""Print a welcome message"""
print('''
-------------------------------------------------------------------------------------------
_ _ _____ _____ _______
| | (_) / ____| __ \__ __|
| | ___ _ __ _ __ _ | (___ | | | | ... | The function processes command-line arguments to execute simulations or demos. It validates inputs, lists available demos if requested, runs specific demos (e.g., Conway, SmoothLife, Lenia), or initiates a simulation from a file or CLI parameters. It exits after completing the chosen task, ensuring proper argument hand... | def handle_args(args:dict) -> None:
"""The main execution sequence. Run siumlations and exit.
Args:
args (dict): CLI arguments from user
"""
print_welcome() # Welcome message
args = validate_args(args) # Clean args
if args == -1:
exit(-1)
elif args['list_demos'... |
def ageparts():
delete = []
for part in looseparts:
looseparts[part] -= 1
if looseparts[part] == 0:
space.remove(part.body, part.poly)
del allparts[allparts.index(part)]
delete.append(part)
for part in delete:
del looseparts[part]
def makeparts():
... | The code defines a continuous loop that repeatedly executes simulation steps, timing each function's execution and accumulating durations in `timings`. It calls functions like `ageparts()`, `gravity()`, `control()`, and `space.step()` in a cycle, handling exceptions to ensure uninterrupted operation. The loop pauses br... | def loop():
try:
while True:
try:
global timereps, reps
start_time_forstepping = time.time()
start_time = time.time()
ageparts()
timings[0] += (time.time() - start_time)
start_time = time.time()
... |
def normalize(X):
X_p = X.copy()
norm_vector = list()
for col in X.columns:
m = np.max(np.abs(X_p[col]))
X_p[col] = X_p[col]/m
norm_vector. append(m)
return X_p, np.array(norm_vector)
def euclidean_distance(x, y):
"""
Computes euclidean distance between two sets of points... | This code performs k-means clustering by initializing centroids using k-means++ (randomly selecting the first centroid, then iteratively choosing points farthest from existing centroids). It normalizes input data, runs iterative k-means refinement for a specified number of iterations, and optionally visualizes cluster ... | def fit(self, X, iterations = 10, visualize = False):
"""
Estimates parameters for the classifier
Args:
X (array<m,n>): a matrix of floats with
m rows (#samples) and n columns (#features)
"""
# normalize X to compensate for the difference in o... |
def solve_exact(X_train, X_test,
y_train, y_test,
reg=0, save=False):
X_train = torch.from_numpy(X_train)
X_test = torch.from_numpy(X_test)
start = time.time()
K_train = ntk_kernel(X_train, X_train).numpy()
end = time.time()
#print("KERNEL TRAIN MATRIX shape and ... | The code evaluates a model's performance under various data corruptions (e.g., blur, noise) using kernel methods. It loads CIFAR-10 data, normalizes it, and solves an exact model. For each corruption type, it computes four accuracy metrics: direct prediction on corrupted data, baseline training on corrupted data, trans... | def main():
SEED = 17
np.random.seed(SEED)
random.seed(SEED)
flatten = True
X_train, y_train, X_test, y_test = dl.load_cifar(num_train=50000,
num_test=10000,
flatten=flatten,
... |
def read_streamsdf(charts_df = read_chartsdf(), tracks_df = read_tracksdf()):
streams_df = charts_df.merge(tracks_df, on='track_id', how='left')
streams_df = streams_df.drop(columns='track_name_y')
streams_df = streams_df.rename(columns={'track_name_x': 'track_name'})
streams_df['date']=pd.to_datetime(s... | The code defines a Streamlit app to visualize marketing strategies and streaming data for selected OPM (Original Pilipino Music) mainstay artists. Users choose an artist from a dropdown, which displays their image and a tailored plot showing streams and marketing metrics. An expander reveals a comparative area chart an... | def opm_mainstay():
st.title('OPM Mainstay Artists')
title = '<p style="font-size: 30px;"><b>Mainstay Tracks:</b></p>'
st.markdown(
f'''
{title} \n
- Top 15th percentile of appearances in Top 200 \n
- Average position is in the top 25% of the Top 200''', unsafe_al... |
def check_initial_args(initial_price_or_prices, pnl_volatility_estimate, initial_volumes):
assert isinstance(initial_price_or_prices, float) or isinstance(initial_price_or_prices, np.ndarray), \
'initial_price_or_prices should be a numpy.ndarray or a float'
if isinstance(initial_price_or_pri... | This code initializes bulk classification buckets by handling two input scenarios: either a single initial price (float) or arrays of prices/volumes (np.ndarray). It validates inputs, then delegates to specific initialization methods based on data type, enabling flexible setup for price/volume data and volatility estim... | def initialize(self, initial_price_or_prices, pnl_volatility_estimate=None, initial_volumes=None):
"""
Initialize the buckets in the bulk classification.
1. Provide an initial price
2. Provide a series of prices in a numpy.ndarray, a volatility estimate and a series of
volu... |
def check_initial_args(initial_price_or_prices, pnl_volatility_estimate, initial_volumes):
assert isinstance(initial_price_or_prices, float) or isinstance(initial_price_or_prices, np.ndarray), \
'initial_price_or_prices should be a numpy.ndarray or a float'
if isinstance(initial_price_or_pri... | This method initializes bulk classification buckets by handling two scenarios: either a single initial price (float) or a series of prices (numpy array) alongside volatility estimates and volumes. It validates inputs and delegates to appropriate initialization methods based on the type of `initial_price_or_prices`, ens... | def initialize(self, initial_price_or_prices, pnl_volatility_estimate=None, initial_volumes=None):
"""
Initialize the buckets in the bulk classification.
1. Provide an initial price
2. Provide a series of prices in a numpy.ndarray, a volatility estimate and a series of
volu... |
def slice_image(image):
path = save_image(image)
img = Image.open(path)
img_size = img.size
width, height = img.size
# baru
bboxes = split_by_box(path)
upper = 0
slice_size_vert = float(height/N_ROW)
slice_size_horz = float(width/N_COLLUMN)
row_slices = N_ROW
collumn_slices ... | The function processes an image by slicing it, detecting connected components (non-blank regions), adjusting their size with padding, applying denoising if specified, and marking non-blank slices. It returns the modified image with bounding boxes, a list of processed slices, and a boolean matrix indicating which slices... | def create_connected_component_slices(image, color, **kwargs):
original_image, slice_list, size, slice_border = slice_image(image)
if not color:
original_image, slice_list = convert_to_black_white(original_image, slice_list)
if kwargs.get('denoise_type', 'none') == 'auto':
denoi... |
def slice_image(image):
path = save_image(image)
img = Image.open(path)
img_size = img.size
width, height = img.size
# baru
bboxes = split_by_box(path)
upper = 0
slice_size_vert = float(height/N_ROW)
slice_size_horz = float(width/N_COLLUMN)
row_slices = N_ROW
collumn_slices ... | The main task of the code is to process image slices by converting them to black/white if no color is specified, applying denoising, detecting non-blank slices, drawing red borders around valid slices, and reinserting them into the original image. It returns the modified image, a list of processed slices, and a boolean... | def create_box_slices(image, color, **kwargs):
original_image, slice_list, size, slice_border = slice_image(image)
if not color:
original_image, slice_list = convert_to_black_white(original_image, slice_list)
if kwargs.get('denoise_type', 'none') == 'auto':
denoise_list(slice_li... |
def create_box_slices(image, color, **kwargs):
original_image, slice_list, size, slice_border = slice_image(image)
if not color:
original_image, slice_list = convert_to_black_white(original_image, slice_list)
if kwargs.get('denoise_type', 'none') == 'auto':
denoise_list(slice_li... | The main task of the code is to process an image by slicing it into regions based on the specified `slice_type` (box or number), apply optional parameters like color, thickness, and padding, resize each slice to a given pixel size, and save them into organized directories under a project folder. The function uses times... | def bulk_save(path, project_id, includes, pixels, slice_type, color, **kwargs):
img = Image.open(path)
if slice_type == 'box':
if color:
image, result_image_list, boolean_list = create_box_slices(img, color)
else:
image, result_image_list, boolean_list = create_box_... |
def print_wallet_types():
print(
"For a detailed list of the relevant wallets (signers) involved in DeFi Armor, please see the README.md"
)
print("To summarize:")
print(
"\t - DEPLOYMENT: this wallet will be used to execute the setup transactions. It can be any wallet with gas."
)
... | This script guides users through setting up DeFi Armor by selecting a blockchain network (eth, celo, etc.), handling an Eulith API token, and executing actions like deploying armor, enabling Safes, or submitting transactions. It interacts with the user to configure armor features on blockchain networks using a CLI inte... | def main():
print_banner()
print("~~ Welcome to the DeFi Armor interactive setup script ~~")
print(
f"If you prefer to use a regular CLI, please see the README.md for further instructions"
)
print("\n\n")
print_wallet_types()
if not os.path.exists('eulith_token.txt'):
eulit... |
def LogAndPrint(self, Message):
self.LoggerObject.LogAndPrint(Message)
def LaunchReadAuth(self):
'''
Launches authenticator.exe
Requires NodeJS to be installed ?
https://www.npmjs.com/package/authenticator-cli
https://www.npmjs.com/package/pkg
'''
self.LogAndPrint("LaunchReadAuth(): Start")
AuthF... | This code automates logging into an Okta portal by entering a username and password, handling two-factor authentication via a generated code, and navigating post-login steps. It uses Selenium to interact with web elements, waits for page elements, and exits on errors. | def LoginToOkta(self):
'''
Logging to OKTA
Reads: self.OktaLogin, self.OktaPassword
'''
self.LogAndPrint("\nLoginToOkta(): Start")
self.DriverObject.get("https://esri.okta.com/")
time.sleep(3)
# User and password
self.LogAndPrint("LoginToOkta(): Username: " + str(self.OktaLogin))
self.DriverO... |
def is_data_available(self) -> bool:
return False
def _receive_data(self) -> bytes:
return bytes()
def interpret_data(self, data: bytes):
opcode = data[0]
params = data[1:]
func = self.data_handlers.get(opcode, None)
if not isinstance(func, type(None)):
ret = ... | The code's main task is to check if data is available, receive it if available, and interpret the received data. It performs these steps in sequence: first verifying data availability, then retrieving the data, and finally processing it through an interpretation method. | def tick(self):
if self.is_data_available():
data = self._receive_data()
self.interpret_data(data) |
def check_small_tables_available_lunch(people_requested, booking_id,
customer_name,
date,
people,
start_time):
"""
Function to check small tables
availa... | The function `check_lunch_time` determines the appropriate table size based on the number of guests (`people_requested`) and routes the request to the corresponding function (`check_small_tables_available_lunch`, `check_medium_tables_available_lunch`, or `check_large_tables_available_lunch`) to check table availability... | def check_lunch_time(people_requested, booking_id,
customer_name, date, people,
start_time):
"""
Function to check party size and call
functions according to it, to look for
best suitable tables at lunch time
"""
# get Booking instance to pass it into the n... |
def check_small_tables_available_dinner(people_requested,
booking_id,
customer_name,
date,
people,
start_time):
"""
... | The function `check_dinner_time` determines the appropriate table size based on the number of guests requested (`people_requested`) and calls corresponding functions to check availability for small (1-2), medium (3-4), or large (5-7) tables during dinner. It retrieves a booking instance and passes relevant details to t... | def check_dinner_time(people_requested,
booking_id,
customer_name,
date,
people,
start_time):
"""
Function to check party size and call
functions according to it, to look for
best suitable table... |
def button_press(self, value):
# Get the current value in the entry
entryVal = self.number_entry.get()
entryVal += value
# Clear the entry box
self.number_entry.delete(0, "end")
# Insert the new value going from left to right
self.number_entry.insert(0, entryVal)... | This code initializes a calculator GUI with a text entry field and buttons for digits 0-9, basic arithmetic operations (+, -, *, /), and special functions (Factorial, Nth Fibonacci). It sets up the window properties, styling, and layout using Tkinter, preparing the interface for user interaction to perform calculations... | def __init__(self, root):
self.entryVal = StringVar(root, value="")
root.title("Calculator")
root.geometry("597x344")
root.resizable(width=False, height=False)
style = ttk.Style()
style.configure("TButton", font="Serif 15", padding=10)
style.configure("TEntry", f... |
def automatic_clean(data, aimcategory):
pre_tags, pre_descriptions = information_extract(data, aimcategory)
after_tags = tokenize(pre_tags)
after_descriptions = tokenize(pre_descriptions)
full_text = further_process(after_tags, after_descriptions)
full_list = []
for lst in full_text:
... | The code analyzes text data by cleaning it based on a category, extracting nouns, calculating their frequency, and generating a word cloud to visualize the most common nouns in the text. | def text_analysis(data, category):
full_list = automatic_clean(data, category)
noun = automatic_noun(full_list)
wordcloud = FreqDist(noun)
draw_wordcloud(wordcloud) |
def test_black_check(ctx):
with ctx.cd(os.path.join(PROJECT_PATH, "api")):
ctx.run(f"black --check {PROJECT_NAME}")
def fail(message: str) -> None:
print_error(message)
exit(1)
def print_success(message: str) -> None:
color_print(message, "\x1b[32m")
def test_safety(ctx):
with ctx.cd(os.path... | The function `_run_tests` executes pytest with specific configurations to run tests, clear cache, capture output, and generate coverage reports. If plugins are enabled, it adds security, formatting, and code quality checks. It runs tests in the "api" directory, then verifies code formatting (via Black) and checks for k... | def _run_tests(ctx, use_plugins=True):
with ctx.cd(os.path.join(PROJECT_PATH, "api")):
pytest_command_args = (
"pytest",
"--cache-clear",
"--capture=no",
"--showlocals",
"--verbose",
f"--cov={PROJECT_NAME}",
"--cov-report ht... |
def _det_m(self, word):
classes = self._reduce(word)
if len(classes) < 2:
return 0
if classes[0] == 'C':
classes = classes[1:]
if classes[-1] == 'V':
classes = classes[:len(classes)-1]
if (len(classes)/2) >= 1:
return len(classes)//... | This function implements Step 1 of the Porter stemming algorithm to reduce word endings. It removes suffixes like 'sses', 'ies', and 's', then processes 'eed', 'ed', and 'ing' suffixes with vowel/consonant checks. Conditional adjustments add 'e' or modify letters based on measure checks, and replaces 'y' with 'i' if vo... | def _step1(self, word):
# 1a
if word.endswith('sses'):
word = word[:-2]
elif word.endswith('ies'):
word = word[:-2]
elif not word.endswith('ss') and word.endswith("s"):
word = word[:-1]
# 1b1
b2 = False
if len(word) > 4... |
def _det_m(self, word):
classes = self._reduce(word)
if len(classes) < 2:
return 0
if classes[0] == 'C':
classes = classes[1:]
if classes[-1] == 'V':
classes = classes[:len(classes)-1]
if (len(classes)/2) >= 1:
return len(classes)//... | This function applies suffix removal rules to a word during stemming. It first removes trailing 'e's if conditions on word measure (_det_m) and length are met. Then, it removes 'd' if preceded by 'l' and measure criteria are satisfied, returning the modified word. | def _step5(self, word):
# 5a
if self._det_m(word)>1 and word.endswith('e'):
word = word[:-1]
elif self._det_m(word) == 1 and (not self._chk_o(word)) and word.endswith('e') and len(word) > 4:
word = word[:-1]
# 5b
if self._det_m(word) > 1 and self._chk_d(wo... |
def _step1(self, word):
# 1a
if word.endswith('sses'):
word = word[:-2]
elif word.endswith('ies'):
word = word[:-2]
elif not word.endswith('ss') and word.endswith("s"):
word = word[:-1]
# 1b1
b2 = False
if len(word) > 4... | The main task of the code is to perform word stemming by sequentially applying five internal steps (_step1 to _step5) to reduce a given word to its root or stem form, typically used in natural language processing for text normalization. | def stem(self, word):
stem = self._step1(word)
stem = self._step2(stem)
stem = self._step3(stem)
stem = self._step4(stem)
stem = self._step5(stem)
return stem |
def print_game(game: Chess, msg: str):
clear_console()
print_board(game)
print(" " + msg)
def player_turn(self) -> int:
return self.turn % 2
def parse_move(self, move: str) -> Tuple:
if len(move) < 2:
return parse_fail(move)
original_move = move
move = move.strip(... | The code implements a turn-based game loop where players input moves, which are parsed and executed. It checks for game-ending conditions (checkmate) and updates the game state, printing progress and handling delays between turns until the game concludes. | def start(self, sleep_time: float = 0):
msg = ""
while not self.done:
print_game(self, msg)
move = input(" {} move: ".format("White" if self.player_turn() else "Black"))
result = self.parse_move(move)
msg = result[1]
if result[0]:
... |
def filter_chain(iterable: Iterable, *filters: LambdaType) -> Iterable:
for filter_func in filters:
iterable = filter(filter_func, iterable)
return iterable
def _get_moves(self, coord: Tuple[int, int], player_color: Color, find_empty: bool = True) -> Generator:
opponent_color = opposite_color(pl... | This method generates all valid moves for a player's pieces on a chessboard. It filters coordinates based on the player's color and an optional starting position, then yields each move after checking if it results in self-check unless skip_check is True. | def get_moves(self, player_color: Color, skip_check: bool = False,
start_coord: Tuple[int, int] = None) -> Generator[Tuple[int, int], None, None]:
match_color = lambda coord: self.game.board[coord].color == player_color
match_pos = lambda coord: True if start_coord is None else coord =... |
def define_model(trial):
# Function to randomly construct the next model as part as the random search conducted using optuna.
# Convolution layers per block
n_conv_layers_b1 = trial.suggest_int("n_conv_layers_b1", 1, 3)
n_conv_layers_b2 = trial.suggest_int("n_conv_layers_b2", 1, 3)
n_conv_layers_b... | This function trains and evaluates a neural network model using hyperparameters suggested by Optuna. It prunes underperforming trials based on validation accuracy and generalization gap, saves successful models meeting performance thresholds, and records training metrics. The goal is to optimize model architecture/para... | def objective(trial):
global model_count
global pruned_model_count
# Generate model
model = define_model(trial).to(device)
# Initialize optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=lr, eps=eps, weight_decay=wd)
# Training of the model
for epoch in range(num_epochs):
... |
def training_step(model, batch, criterion):
# Receives the next training batch from the data loader, calculates the corresponding loss and returns that loss.
images, labels = batch
images, labels = images.to(device), labels.to(device)
out = model(images)
loss = criterion(out, labels)
return loss... | The function trains a model for a specified number of epochs using the provided data loaders, optimizer, and loss criterion. It performs training and validation phases, tracks training loss and accuracy, and calculates the generalization gap (difference between training and validation accuracy). Training stops early if... | def fit(epochs, model, train_loader, val_loader, train_loader_small, optimizer, criterion):
# Actual training loop. Trains model until its suitable to be considered in this work.
for epoch in range(epochs):
# Training phase
model.train()
train_losses = []
# Iterate trough whole... |
def retrieve_params(df):
# Loads architectural params calculated and saved within the random search.
params = {}
for _, row in df.iterrows():
key, value = row['keys'], row['values']
params[key] = value
return params
def define_model(params):
# Constructs model using architectural par... | The code trains multiple shadow models for a specified victim architecture using a dataset, saving models that meet quality criteria. It initializes hyperparameters, loads data, trains shadow models on random subsets, checks model performance, and stores valid models with their training indices for further analysis. | def process_victim_architecture(architecture):
'''
This program has been build for a job processing system, receiving an integer value defining the architecture for which
the shadow models are to be trained. Architectures have been selected using a prelimary random search.
Architectures need to be pre... |
def loss_and_gradients_kl(self, inputs, parameters, score_mask, fisher_mask):
with tf.GradientTape() as tape:
tape.watch(self.trainable_variables)
loss = self.kl_loss(inputs, parameters, score_mask, fisher_mask)
gradients = tape.gradient(loss, self.trainable_variables)
... | The code computes the loss and gradients of a neural network model given inputs, parameters, and masks. If the number of network calls exceeds a threshold (`maxcall`), it splits inputs into batches, processes each batch to calculate loss and gradients using a specified method (KL divergence, deepsets, or MSE), and accu... | def compute_loss_and_gradients(self, inputs, parameters, score_mask, fisher_mask, lossfn='kl'):
# total number of network calls
ncalls = inputs.shape[0] * inputs.shape[1]
# accumulate gradients or not?
if ncalls > self.maxcall:
# how many batche... |
def __file_exists(self):
if not os.path.exists(self.file_name):
return False
return True
def __validate_worksheet(self, sheet_name):
worksheets = self.__retrieve_worksheets()
return False if sheet_name not in worksheets else True
def __read_spreadsheet(self, sheet_name, **kwa... | The main task of the code is to retrieve the header columns from a specified spreadsheet worksheet. It first checks if the file exists and validates the worksheet name. If valid, it reads the spreadsheet's first row (nrows=0) to extract headers and returns them as column values. Errors are raised for missing files or i... | def retrieve_headers(self, sheet_name):
if not self.__file_exists():
raise FileNotFound
if not self.__validate_worksheet(sheet_name):
raise WorkSheetNotFound
headers = self.__read_spreadsheet(sheet_name, nrows=0)
return headers.columns.values |
def __file_exists(self):
if not os.path.exists(self.file_name):
return False
return True
def __validate_worksheet(self, sheet_name):
worksheets = self.__retrieve_worksheets()
return False if sheet_name not in worksheets else True
def __read_spreadsheet(self, sheet_name, **kwa... | The code retrieves records from a specified spreadsheet sheet after verifying the file's existence and the validity of the worksheet name. It raises exceptions if the file or sheet is not found, then reads all rows from the validated sheet and returns the records. | def retrieve_records(self, sheet_name):
if not self.__file_exists():
raise FileNotFound
if not self.__validate_worksheet(sheet_name):
raise WorkSheetNotFound
records = self.__read_spreadsheet(sheet_name, nrows=0)
return records |
def __file_exists(self):
if not os.path.exists(self.file_name):
return False
return True
def __validate_worksheet(self, sheet_name):
worksheets = self.__retrieve_worksheets()
return False if sheet_name not in worksheets else True
def __get_row_counts(self, sheet_name):
... | The function retrieves a specified number of records from a spreadsheet by validating the file and worksheet existence. It calculates the number of rows to read by subtracting the requested count from the total rows in the sheet, then reads and returns that many records. Exceptions are raised if the file or worksheet i... | def retrieve_limited_records(self, sheet_name, number_of_rows_retrieved):
if not self.__file_exists():
raise FileNotFound
if not self.__validate_worksheet(sheet_name):
raise WorkSheetNotFound
record_count = self.__get_row_counts(
sheet_name) - number_of_rows_r... |
def __file_exists(self):
if not os.path.exists(self.file_name):
return False
return True
def __validate_worksheet(self, sheet_name):
worksheets = self.__retrieve_worksheets()
return False if sheet_name not in worksheets else True
def retrieve_headers(self, sheet_name):
... | This method retrieves and returns the headers of a specified spreadsheet sheet as a dictionary, but only if all specified condition keys (from **kwargs) exist in the headers. It validates file existence, worksheet name, and required headers, raising exceptions if any checks fail. | def retrieve_records_by_condition(self, sheet_name, **kwargs):
if not self.__file_exists():
raise FileNotFound
if not self.__validate_worksheet(sheet_name):
raise WorkSheetNotFound
if all(item in self.retrieve_headers(sheet_name) for item in kwargs.keys()):
df... |
def get_valid_locations(board):
valid_locations = []
for col in range(COL_COUNT):
if is_valid_location(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return win(board, PLAYER_PIECE) \
or win(board, AI_PIECE) \
or len... | The code implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move for a player (AI or human) in a turn-based game (likely Connect Four). It recursively evaluates all valid board states up to a specified depth, maximizing the AI's score and minimizing the opponent's score. Terminal states (... | def minimax(board, depth, alpha, beta, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board) # For determining if current state is terminal
# On end of search depth or winning board
if depth == 0 or is_terminal():
if is_terminal:
if... |
def login_check(self):
"""
login_check() - if require_authentication return user else None
"""
if self.require_authentication:
self.session.connect()
if self.session.data.get('is_authenticated'):
return self.session.data['user']
return ... | The main task of the code is to handle editing of database records in a web application. It retrieves a record's fields for editing, processes form submissions to update or insert new records, and renders an HTML form. The function checks user authentication, handles both GET (viewing data) and POST (saving changes) re... | def edit_fields(self, env, coll, id):
"""edit_fields(env, coll, id) - render a specific record as fields
** combine with edit_schema() during refactor
"""
if not self.login_check():
return abort(401)
try:
if not id == 'new':
key = {'_id': Objec... |
def get_available_video_filenames(self):
"""Gets the filenames for all videos that have not been previously selected for labeling."""
video_filenames = self.get_all_video_filenames()
selected_videos = self.read_previously_selected_videos()
available_video_filenames = [video for video i... | The main task of the code is to randomly select a specified number of video filenames from the available pool for each iteration. If insufficient videos are available, it resets the selection history and retries. The selected videos are then recorded to track previously chosen files, ensuring diversity in selections ac... | def select_from_available_videos(self):
"""Select video filenames from the available for this step"""
num_select = self.config["data-inclusion"]["number-of-videos-each-iteration"]
available_videos = self.get_available_video_filenames()
if len(available_videos) < num_select:
... |
def get_all_image_data(self) -> List[Dict]:
"""Gets the image data for all videos included in the AL."""
all_data_file = self.config["data-inclusion"]["all-image-data-json-path"]
data = pd.read_json(all_data_file)
image_data = []
for _, row in data.iterrows():
... | The method selects data for active learning by loading all images or specific videos based on the 'use-all-videos' config, then filters out previously used images by comparing image IDs against historical records, returning a list of dictionaries containing image metadata like paths, crop info, and fold assignments for... | def select_data(self) -> List[Dict]:
"""This method selects the data to be used in the current active learning step.
If use-all-data:
Read the all images json using the get_all_image_data method.
Else:
Select the video filenames to be included.
Read t... |
def get_classical_queen_moves(row, column):
source = column_names[column] + row_names[row]
moves = []
# Add vertical moves
for i in range(1,8):
moves.append( source + column_names[column] + row_names[(row+i) % 8])
# Add horizontal moves
for i in range(1,8):
moves.append( sourc... | The main task of the code is to generate all possible classical and quantum moves for queens and knights on each square of an 8x8 chessboard, creating bidirectional mappings between each unique move and a sequential index. This enables efficient move indexing and retrieval in a chess simulation or quantum chess framewo... | def enumerate_all_moves():
move_counter = 0
move_to_index = {}
index_to_move = {}
# Loop over all starting squares
for i in range(8):
for j in range(8):
### Classical moves
#### Queen moves
classical_queen_moves = get_classical_queen_moves(i,j)
... |
def export(self, func):
if func:
self.all_lines = self.canvas.find_all()
self.points = []
for i in self.all_lines:
self.points.append(self.canvas.coords(i))
self.mask = Image.new("RGB", (self.screen_size[0], self.screen_size[1]), "black")
... | This code initializes a GUI application for drawing and editing masks. It sets up a window with tools like pen/eraser buttons, brush size slider, and save/export functions. A canvas is created for drawing, with optional image loading. The window adjusts size based on screen dimensions, supports undo via Ctrl+Z, and inc... | def __init__(self,
master,
image_file=None,
size=(500,500),
load_func=None):
super().__init__(master=master)
self.title("Draw Mask")
self.resizable(False, False)
self.wm_iconbitmap()
self.after(... |
def make_file_list_boto(folder, bucket, ps3):
"""
Function that queries s3 to get file size list and file names list from path p , folder folder
As I know the bucket to look for files, and prefix
folder: like "user"
bucket: like "data-lake-us-east-2-549323063936-internal"
ps3: path like "obfuscated_data/farm/PROD... | The function `processor` retrieves JSON files from an S3 bucket, processes their contents, and loads the data into a PostgreSQL database. It handles schema creation/drop based on the `count` parameter (0 for dropping existing tables, 1 for preserving them). The data is organized into specified tables (e.g., 'user', 'fa... | def processor(ps3, folder, bucket, db_user, db_host, db_port, db_name, db_pwd, env_name, count):
""" Function which does the actual job: having bucket and ps3 path, gets list of files in that folder,
and organizes input of the content in those into DB.
ps3: path like "obfuscated_data/farm/PROD/staging/USA/"
bucket:... |
def log(message):
print('{0}: {1}'.format(logging_prefix(), message))
def get_files_info_boto(folder, env_name):
"""
Function that queries s3 to get files information from folder folder
As I know the bucket to look for files, and prefix
folder: like "grower"
env_name: like 'dev','sit', etc
return: pandas df, wit... | The function `files_info_collector` retrieves metadata (file names, sizes, dates) from an S3 bucket for a specified folder, logs processing times, and writes this data into a PostgreSQL database. It drops and recreates a table for the folder's data, ensuring fresh storage. The function also generates a report message w... | def files_info_collector( folder, db_user, db_host, db_port, db_name, db_pwd, env_name):
"""
For selected folder, coleects from s3: fname, size, date info
ps3: "s3://data-lake-us-east-2-549323063936-encrypted/Agrian/AdHoc/NoETL/" path to root bucket on s3, where other folders with data persist
folder: like "grower"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.