dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_empty_table(self):
parsed_table = defaultdict(list)
columns, parsed_header = self._get_table_columns()
for i, column in columns.items():
parsed_table[column.col_name_str] = ""
return parsed_table
def _get_overflow_record(self, record_pointer):
"""
G... | The main task of the code is to parse table data from linked pages by processing record offsets, handling deleted rows, overflow pages, and extracting valid records. It iterates through data chunks, resolves offsets, retrieves overflow records, and parses each row using _parse_row, storing results in a defaultdict(list... | def parse(self):
"""
This is the main table parsing function. We go through all of the data pages linked to the table, separate each
data page to rows(records) and parse each record.
:return defaultdict(list) with the parsed data -- table[column][row_index]
"""
if not sel... |
def read_csv_to_variable(file_path: str, start_row: int = 0, end_row: int = 100):
data = []
with open(file_path, mode='r', encoding='utf-8') as csvfile:
csv_reader = csv.DictReader(csvfile)
data = [row for i, row in enumerate(csv_reader) if start_row <= i < end_row]
return data
def fork_repo... | The main task of the code is to process a CSV file containing repository data, fork and clone each repository, apply patches from specified URLs, handle errors by deleting problematic repositories, and log the total number of successfully patched versions. It reads CSV entries, iterates through repository patches, clon... | def main(args: argparse.Namespace):
global patched_counter
csv_file_path = 'final_data_v3.csv'
csv_data: list = read_csv_to_variable(csv_file_path, start_row=int(args.start_index), end_row=int(args.end_index))
for repo_patch_dict in csv_data:
if (scantist_ossops_base_url := fork_repo_r... |
def generate_key() -> bytearray:
return get_random_bytes(SIZE_BLOCK)
def generate_IV() -> bytes:
iv = bytearray(SIZE_BLOCK)
for i, byte in enumerate(iv):
iv[i] = random.randrange(0, 255)
return bytes(iv)
def submit(key: bytearray, iv: bytearray) -> bytes:
ciphertext: bytes = b''
user_st... | The main task of the code is to generate a cryptographic key and initialization vector (IV), use them to encrypt data via the `submit` function, and then verify the encrypted result using the `verify` function with the same key and IV. This process likely involves encryption, validation, or integrity checking of the ci... | def task2():
key = generate_key()
iv = generate_IV()
ciphertext = submit(key, iv)
plaintext = verify(ciphertext, key, iv) |
def submit(key, iv):
prepend_string = "userid=456;userdata="
append_string = ";session-id=31337"
user_string = input("Enter Your Data:")
user_string = quote(user_string)
# My cbc encryption method takes care of padding so it doesn't have to be done here
complete_string = prepend_string + user_... | The main task of the code is to generate a random key and IV, encrypt data using the `submit` function, tamper with the resulting ciphertext, and verify the integrity of the tampered data using the original key and IV. The process demonstrates encryption, tampering, and verification steps, likely for testing security m... | def part2():
part2_key = get_random_bytes(BLOCK_SIZE)
part2_iv = get_random_bytes(BLOCK_SIZE)
ciphertext = submit(part2_key, part2_iv)
tampered = tamper(ciphertext)
print(verify(part2_key, part2_iv, tampered)) |
def insertOptionsMenu(root):
options=[int(x) for x in range(1,6)]
variable=tkinter.StringVar(root)
variable.set(options[0])
menu=tkinter.OptionMenu(root,variable,*options,
command=lambda a:setRemainingText())
menu.place(x=480,y=200)
return ... | This code creates a GUI application using tkinter for a booking system. It sets up a window with a background image, title, and icon, initializes global variables for seat data and menu options, and adds UI components like buttons, text displays, and a submit button linked to provided title/emailID. The mainloop starts... | def create(title,emailID):
global root
root = tkinter.Tk()
root.geometry("700x600+330+50")
root.title("BookYourShow",)
root.iconbitmap(default='assets\icon.ico')
img=Image.open("assets/bg3.jpg")
photo=ImageTk.PhotoImage(img)
bg=tkinter.Label(root,image=ph... |
def reset_metrics(self):
for key in self.loss_metrics.keys():
self.loss_metrics[key].reset_states()
def train_step(self, data_pairs):
u,v,w, u_mag, v_mag, w_mag, u_hr,v_hr, w_hr, venc, mask = data_pairs
x_target = tf.concat((u_hr, v_hr, w_hr), axis=-1)
with tf.GradientTape()... | The main task of the code is to train a neural network using provided training and validation TensorFlow datasets over a specified number of epochs. It performs training and validation loops, tracks metrics like loss and accuracy, logs progress, saves the best model based on validation performance, and optionally bench... | def train_network(self, trainset, valset, n_epoch, testset=None):
"""
Main training function. Receives trainining and validation TF dataset.
"""
# ----- Run the training -----
print("==================== TRAINING =================")
print(f'Learning rate {self.optimiz... |
def generate_initial_pop(size_pop) :
'''
generate the initial population, which will be a random set of individuals
these will eventually mutate to (hopefully) the optimal solution
'''
# TODO : no idea how to preallocate storage for this
population = []
i = 0
while i < size_pop :
... | The code implements a simple genetic algorithm to evolve a population over multiple generations. It starts with a random initial population, iteratively generates new populations using selection, crossover, and mutation (via `next_generation`), and tracks the best-performing individual in each generation. The function ... | def multi_gen(nb_generation, size_pop, best_sample, lucky_few, nb_children):
'''
start with a random population and produce nb_gen new generations based on
simple genetic algorithm
returns a list of the best performing individual per generation
'''
# TODO : memory preallocation
historic = [... |
def rotate_mat(angle) :
rot = np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]])
return rot
def collide_missile_rock(rocks, missiles, score) :
'''
check collision of any rock with any missile and update (decrease size)
rock and delete missile if true
... | This function renders a game screen, displaying lives and score, updating player/asteroid/missile positions, handling collisions (scoring and life loss), and drawing game elements like the player's ship, asteroids, and missiles. It returns the updated score and triggers game over when lives reach zero. | def draw(canvas, score, visualize=True) :
global lives
# print('in draw')
# score = 0
if visualize :
# print(visualize)
canvas.fill(BLACK)
# print lives and score
fontsize = 15
text1 = "lives: %i" % lives
text2 = "score: %i" % score
text_font = pygame... |
def spawn_random_rocks(ship, score) :
# global score
# TODO : make dependent on score? spawn several at once, random locations
# but not on top of the ship
# print("Spawning rocks")
# not sure what number to divide score by
# TODO : seems NNs have no idea what to do when there is less than 5 rock... | The code defines a `game_loop` function that runs an Asteroids-style game, supporting both human and AI (neural network) control. It initializes Pygame, manages game entities (player, rocks, missiles), handles input/events, and updates the game state. The AI version uses a neural network to predict actions (turn, thrus... | def game_loop(isAI=False, nn=None, visualize=True) :
global canvas, player, time, lives, missiles, rocks, is_running, SPAWN_ROCKS, t
if isAI :
random.seed(seed)
pygame.init()
if visualize :
canvas = pygame.display.set_mode((CANVAS_WIDTH,CANVAS_HEIGHT))
pygame.display.set_captio... |
def prepare_base_url(full_url):
parsed_url = urlparse(full_url)
query_params = parse_qs(parsed_url.query)
query_params.pop('page', None)
# Reconstruct the query string, ensuring spaces are encoded correctly
query_string = "&".join(f"{key}={value[0].replace(' ', '%20')}" for key, value in query_para... | The main task of the code is to scrape data from multiple pages of a website by iterating through each page, constructing URLs with page numbers, navigating to each page, scrolling to load content, extracting data, and consolidating all scraped data into a single pandas DataFrame for aggregation and analysis. | def scrape_all_pages(driver, full_query_url):
all_data = pd.DataFrame()
# Prepare the base URL by removing the 'page' parameter
base_url = prepare_base_url(full_query_url)
# Get the total number of pages
total_pages = get_total_pages_from_inspire(driver, full_query_url)
for page in range(1, t... |
def build_weights_around_walls(grid, blocks, weight):
outerBlocks = []
for block in blocks:
(blockX, blockY) = block
directions = [(blockX+1, blockY), (blockX, blockY-1), (blockX-1, blockY), (blockX, blockY+1)]
for i in directions:
if i in grid.weights:
grid.... | The main task of the code is to initialize a grid-based pathfinding visualization by setting up a canvas, defining obstacles, calculating weighted regions around walls, executing an A* search algorithm to find a path from a start to a goal point, and rendering the computed path, costs, and navigation details on the can... | def initialize(event=None):
global limit
c.delete("all")
cfg.GRID_SIZE = min(c.winfo_width() / cfg.GRID_WIDTH, c.winfo_height() / cfg.GRID_HEIGHT)
# print('WINDOW', c.winfo_width(), c.winfo_height())
# print('GRID', cfg.GRID_WIDTH, cfg.GRID_HEIGHT, cfg.GRID_SIZE)
diagram4 = GridWithWeight... |
def processed(self, url):
return url in self.urls_processed
def get_parser(self, url):
page = req.get(url)
return BS(page.content, 'html.parser')
def parse_match_report(self, match_report_parser, season, match_round, match_url):
"""
:param match_report_parser: Parser for the matc... | The function processes URLs of individual match reports from a league's fixture page by extracting links from table rows, checking if they've been processed, fetching their content, parsing the match report, and handling exceptions to log failed URLs. | def parse_fixture_page_from_results_page(self, league_round_parser, season, match_round):
"""
:param match_round: The round the match is taking place in
:param season: The current season being parsed
:param league_round_parser: The league round parser for the fixture round pa... |
def processed(self, url):
return url in self.urls_processed
def get_parser(self, url):
page = req.get(url)
return BS(page.content, 'html.parser')
def get_fixture_round_from_url(self, url):
url_elements = url.split('/')
return url_elements[len(url_elements) - 2]
def parse_fixture_... | The function extracts fixture round URLs from an archive page parser, checks if they've been processed, and parses each fixture page if unprocessed. It constructs URLs from form options, retrieves parsers, identifies match rounds, and stores processed URLs to avoid duplication. | def parse_archive_results(self, archive_results_parser, season):
"""
:param season: current season being parsed
:param archive_results_parser: The parser for the results archive page
Takes the parser for the archive page and obtains and processes the url for each fixture roun... |
def processed(self, url):
return url in self.urls_processed
def parse_archive_results(self, archive_results_parser, season):
"""
:param season: current season being parsed
:param archive_results_parser: The parser for the results archive page
Takes the parser for the ... | The code parses an archive page to extract and process result pages for specific seasons of a league. It identifies season rows, filters relevant seasons, retrieves their URLs, and processes unprocessed URLs by parsing their results and marking them as processed. | def parse_archive_page(self, archive_parser):
"""
:param archive_parser: parser of the archive page of a given league
Parses an archive page to obtain and process the page that represents the results pages for each season of interest for the given league
"""
season_rows =... |
def get_parser(self, url):
page = req.get(url)
return BS(page.content, 'html.parser')
def get_second_divsion_href(self, parser):
"""
Get the url to the second division page of a league using the parser
"""
second_division_anchor = parser.find('div', {'class':'subnavi'... | The code parses a league home page to extract archive links pointing to historical season results. It retrieves both the main league and second division URLs, collects archive links from both, and processes each unprocessed archive page by parsing its content and marking it as processed. | def parse_league_home_page(self, league_home_url):
"""
Parse the league home page for the archive links
The archive link contains the page that has all the links to the past results for each season of the league
"""
print(f"Currently Crawling: {league_home_url}")
... |
def filter(self, img):
img = 1 - np.mean(img, axis=2)
sal = np.maximum(
0, np.prod([ndimage.convolve(img, flt) for flt in self.flts], 0)
)
if self.hand_pos_sal:
hand_pos = self.handPos()
# # improve saliency of hand if near object
# max_... | This function simulates a single step in an environment by executing an action, updating joint/sensor states, processing visual saliency, and returning an observation dictionary containing joint positions, touch sensors, visual data, eye position, and object position. It integrates background image processing, visual a... | def sim_step(self, action):
self.set_action(action)
joints, sensors, obj_pos = self.get_observation()
self.bground_img = self.bground.step(
[
self.bground_height / 2 + self.taskspace_ylim[0],
self.bground_width / 2 + self.taskspace_xlim[0],
... |
def set_seed(self, seed=None):
self.seed = seed
if self.seed is None:
self.seed = np.frombuffer(os.urandom(4), dtype=np.uint32)[0]
self.rng = np.random.RandomState(self.seed)
def init_worlds(self):
self.world_files = [
getresource("box2dsim", "models", "arm_2obj_d... | The code initializes a 2D robotic arm simulation environment, defining joint parameters, action/observation spaces (using Gym's Box and Dict spaces), rendering settings, and reward functions. It sets up a reinforcement learning environment for a single-arm robot with touch sensors and object position tracking, preparin... | def __init__(self):
super(Box2DSimOneArmEnv, self).__init__()
self.set_seed()
self.init_worlds()
self.init_map()
self.num_joints = 5
self.num_arm_joints = 3
self.num_hand_joints = 2
self.num_joint_positions = 7
self.num_touch_sensors = 4
... |
def create_pattern(order_length_quantities: Dict, rer_one: bool) -> Tuple[List[int], List[int], List[int]]:
"""
This function creates a cutting pattern based on the demand and lengths of the given objects. The pattern is
sorted by the first sorting method if rer_one is True, and sorted by the second sorting... | The function `create_individual` generates cutting patterns to fulfill demand for objects of varying lengths using a base material. It iteratively creates patterns, adjusts remaining demand, and toggles sorting methods to optimize patterns. The output is a list of cutting patterns that collectively meet all demands, va... | def create_individual(order_length_quantities):
"""
Create a cutting pattern for a given set of objects and base length.
Parameters:
objects (dict): Dictionary containing the objects to be cut with their corresponding length and demand.
base_length (int): The length of the base material.
Retur... |
def demand_length(sorted_objects: Dict[int, int]) -> Tuple[List[int], List[int]]:
"""
This function calculates the demand for each type of object and sorts the objects in descending order by length.
Parameters:
sorted_objects (dict): A dictionary containing the length of each object as the keys and the... | The main task of the code is to generate offspring patterns by combining and alternating between two parent patterns (ind1 and ind2), applying them to fulfill demand for objects of varying lengths while minimizing waste. It dynamically switches parents during the process, ensures demand reduction, and constructs valid ... | def createOffspring(ind1: List[List[int]], ind2: List[List[int]], order_length_quantities) -> List[List[int]]:
"""
This function creates offspring patterns by combining patterns from two individual patterns, using a random selection
process. It also applies the selected patterns to the demand for objects of... |
def stop():
global server_socket
if server_socket:
server_socket.close()
server_socket = None
def handle_root(client):
wlan_sta.active(True)
ssids = sorted(ssid.decode('utf-8') for ssid, *_ in wlan_sta.scan())
send_header(client)
client.sendall("""\
<html>
<h... | This code sets up a web server on a specified port to handle HTTP requests, control hardware (e.g., relays for gate operations), and provide a configuration interface. It initializes Wi-Fi access points, listens for client connections, parses URLs, and executes corresponding actions like serving web pages, processing c... | def start(port=80):
global server_socket
addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]
stop()
wlan_sta.active(True)
wlan_ap.active(True)
wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)
server_socket = socket.socket()
server_socket.bind(addr)
server_... |
def read_profiles():
with open(NETWORK_PROFILES, 'r') as f:
lines = f.readlines()
profiles = {}
for line in lines:
ssid, password = line.strip("\n").split(";")
profiles[ssid] = password
# profiles = {"peet": "10042541"}
return profiles
def do_connect(ssid, password):
wlan_st... | The main task of the code is to establish a working WLAN connection by scanning for available networks, attempting to connect using stored profiles, and starting a web server for connection management if automatic connection fails, returning the connected WLAN instance or None. | def get_connection():
"""return a working WLAN(STA_IF) instance or None"""
# First check if there already is any connection:
if wlan_sta.isconnected():
return wlan_sta
connected = False
try:
# ESP connecting to WiFi takes time, wait a bit and try again:
time.sleep(3)
... |
def load_from_json(self, file: str) -> bool:
try:
self.graph.nodes.clear()
self.graph.edges.clear()
self.graph.e_dictOfSrc.clear()
self.graph.e_dictOfDest.clear()
dict = json.loads(file)
list_nodes = dict["Nodes"]
... | The main task of the code is to render a graph visualization using Pygame, including scaling node/edge positions, handling button interactions (load/save/TSP/shortest path), and updating the display with user inputs. It calculates coordinate bounds, draws nodes/edges, processes button presses for file operations and pa... | def draw(self):
self.min_x = float(min(list(self.graph.nodes.values()), key=lambda n: n.pos[0]).pos[0])
self.max_x = float(max(list(self.graph.nodes.values()), key=lambda n: n.pos[0]).pos[0])
self.min_y = float(min(list(self.graph.nodes.values()), key=lambda n: n.pos[1]).pos[1])
self.max... |
def intersection_unicodes(fonts):
"""..."""
# Get a set of universal unicode characters for a font
all_unicodes = [
get_unicode_chars(font)
for font in fonts
]
int_unicodes = all_unicodes[0]
for unis in all_unicodes:
int_unicodes.intersection_update(unis)
# Conve... | This code initializes a font generator that combines multiple fonts by intersecting their Unicode characters, stripping each font of non-overlapping glyphs based on options, and merging them into a single font. The seed ensures reproducibility, while the options control processing parameters. | def __init__(self, fonts, seed=0, options=OPTIONS):
"""Construct a CeaseAndDesistSansGenerator"""
self.fonts = fonts
self.seed = seed
self.options = options
self.unicodes = intersection_unicodes(self.fonts)
self.unicode_lists = [[] for _ in self.fonts]
self.re... |
def get_computed_values(self, in_values):
comp_values=in_values
for layer in self.network:
current_comp_values=[]
for node in layer:
current_comp_values.append(self.activare_cu_funcTANH(node.no_weights,node.weights,comp_values))
comp_values=current_com... | This code trains a neural network using backpropagation over multiple epochs. It iterates through training data, computes network outputs, compares them to true labels, performs backpropagation to calculate errors, and updates weights after each batch. The process repeats for a specified number of epochs to minimize pr... | def fit(self):
for _ in range(self.no_epochs):
for train_input, train_output in zip(self.train_in,self.train_out):
self.get_computed_values(train_input)
real=[0]*self.no_classes
real[train_output]+=1
self.backPropagation(real)
... |
def display_gOmessage(msg):
global flip
font = pygame.font.Font("C:\Windows\Fonts\Ebrima.ttf", 16)
text = font.render(msg, True, (0, 0, 0))
textRect = text.get_rect()
textRect.center = (ui_width // 2, ui_height // 2)
screen.fill(white)
screen.blit(text, textRect)
a= True
whil... | This function handles turn switching in a chess game, checking for stalemate conditions (50-move rule, stalemate state), updating check status, flipping the board in P2F mode, managing pass pawn rules, and updating the game state for display. It also triggers end-of-game messages for stale conditions and resets tempora... | def switchSide():
global flip
global selectedPiece
global passPawn
global check
global checked
global currentAlliance
global mode
global moves
global count
global gO
if moves[currentAlliance] == 50:
display_gOmessage("50 Shade of Stale")
gO = True
#The che... |
def display_gOmessage(msg):
global flip
font = pygame.font.Font("C:\Windows\Fonts\Ebrima.ttf", 16)
text = font.render(msg, True, (0, 0, 0))
textRect = text.get_rect()
textRect.center = (ui_width // 2, ui_height // 2)
screen.fill(white)
screen.blit(text, textRect)
a= True
whil... | The main task of the code is to run a chess game loop, handling player and bot moves, validating piece movements, checking for checkmate, managing castling, pawn promotion, and updating the game state and display in real-time using Pygame. | def main():
global gO
global currentAlliance
global currentPieces
global wPieces
global bPieces
global checked
global mode
global selectedPiece
global pieceMove
global count
global moves
while not gO:
if currentAlliance == "W":
currentPieces = wP... |
def permute(self,text, permutationArray):
return [text[x-1] for x in permutationArray]
def roundFunction(self, text, roundNo):
if len(text) != 32 :
raise Exception("Inside Round Function, text length should\
be 32 but {} is given for {}".format(len(text), text))
text = self.permute(text, expansion_P_box)... | This function encrypts or decrypts a 64-character text block using a Feistel network structure. It validates input length, applies initial permutation, splits data into 32-character halves, iterates through rounds with round functions and XOR operations, and applies a final permutation to produce encrypted/decrypted ou... | def runForEachBlock(self, text, action):
if len(text) != 64:
raise Exception("text length should be exactly 64 but \
it is {}".format(len(text)))
text = self.permute(text, initial_message_permutation)
textL = text[ : 32]
textR = text[32 : ]
for roundNo in range(self.nRound):
if action == "enc... |
def getPermutaion(self, ofSize):
res = [x+1 for x in range(ofSize)]
np.random.shuffle(res)
return res
def permute(self,text, permutationArray):
return [text[x-1] for x in permutationArray]
def roundFunction(self, text, roundNo):
if len(text) != self.blockSize/2 :
raise Exception("Inside Round Function, te... | This code processes a block of text using a Feistel network structure. It applies initial permutation, splits the block, performs multiple rounds of encryption/decryption with XOR operations, and applies a final inverse permutation. The task is to securely transform the input block based on the specified action (encryp... | def runForEachBlock(self, text, action):
if len(text) != self.blockSize:
raise Exception("text length should be exactly {} but \
it is {}".format(self.blockSize, len(text)))
if self.initial_message_permutation == None:
self.initial_message_permutation = self.getPermutaion(self.blockSize)
text = sel... |
def Decrypt(word,key):
return XOR(word,key)
def Signup():
if internet():
Name= wait_for_input('Enter Your Name: ')
import re
ECon=None
while ECon == None:
Email= input('Email: ')
ECon= re.search(r'[^@]+@[^@]+\.[^@]+', Email)
if ECon ==... | The main task of the code is to load and decrypt a password database file (PL) by renaming it, importing its contents, decrypting stored information using a Decrypt function, and returning decrypted data (PLE, PLD, InfoD, InfoE). If the file is missing, it handles errors, attempts to restore from backups, and prompts t... | def Load_DB():
while True:
if files.exists('PL'):
files.rename('PL','PL.py')
from PL import PL,InfoE
InfoD=[]
for info in InfoE[:2]:
NEW = ''.join([Decrypt(char,'4') for char in info])
InfoD.append(NEW)
InfoD.append... |
def Decrypt(word,key):
'''
In this case we do not need these two functions
But I made it to make it easy for you if you want to
change Encryption type :)
'''
return XOR(word,key)
def Signup():
if not internet():
sg.Popup("Signup Requires Internet Connection.")
exit()
... | The main task of the code is to load and decrypt a password database (PL) by checking file existence, renaming files, decrypting stored data using a Decrypt function, and handling scenarios where the database is missing. If the database isn't found, it attempts to restore from alternative paths or prompts users to sign... | def Load_DB():
while True:
if files.exists('PL'):
files.rename('PL','PL.py')
#] We can use read_lines() + eval()
from PL import PL,OFNI
files.rename('PL.py','PL')
PLE=PL
PLD=[]
for PASSWORD in PLE:
NEW=[]
... |
def getcache():
cache = ucsc_halls_json()
cache = json.loads(cache)
return cache
def gethall(hall, date):
meals = getmeals(hall['code'], date)
if len(meals) > 0:
return {
'name': hall['name'],
'code': hall['code'],
'hours_url': hall['hours_url'],
... | The main task of the code is to check if a cache of hall data is still fresh. If not, it fetches the latest data for the next 7 days, updates the cache with hall availability, and redirects. It uses a print output flag for debugging, stores results in a JSON cache, and ensures data freshness by recalculating when the c... | def fullcrawl(print_output = None):
cache = getcache()
age = cache.get('time') or 0
age = time.time() - age
if age < CACHE_AGE:
if print_output:
print('Cache is fresh')
return redirect('/')
cache = {
'dates': {}
}
today = datetime.datetime.now().astime... |
def execute(sql, params=(), return_id=False):
# executes and commits query of passed sql
"""
Generic function to execute a sql command, commit, and close the cursor
:param sql:
:return:
"""
column_names = None
ret = False
if sql:
with connect_db() as conn:
try:
... | This function precomputes and stores aggregated data in a database table by iterating through parameter configurations. It truncates the target table, retrieves parameter IDs, filters relevant parameters, adjusts for missing sub-parameters when AEN is off, fetches aggregated data, adds IDs, and inserts results into the... | def precompute_aggregates():
sql = 'truncate table aggregate_data;'
execute(sql)
# now find out what the set of values is for each parameter
sql = 'select id from parameters;'
ids = [ row['id'] for row in fetchall(sql) ]
params_of_interest = ['starting_cases', 'test_delay', 'p_running_app... |
def state_seq(deltaT: Dict[Tuple[State, str], State], q: State, w: str) -> List[State]:
path = [q]
state = q
for a in w:
if (state, a) in deltaT:
state = deltaT[state, a]
path.append(state)
else:
break
return path
def is_state_dead_end(self: "... | This function removes a specified state entry from a transducer, handles non-divergent states by deleting them, updates internal structures, and pulls output backward. It first identifies a state sequence, removes the terminal state, checks for dead-end states, iteratively removes non-divergent states, adjusts tracking... | def remove_entry_and_pull_output(self: "Transducer", v: str) -> "Transducer":
t = state_seq(self.deltaT, self.s, v)
self.F.remove(t[-1])
i = 1
p = t[-i]
non_divergent_states = []
if self.is_state_dead_end(p):
while ... |
def construct_initial(self, input: str, output: str) -> "Transducer":
states = [State() for _ in range(len(input) + 1)]
self.Q = set(states)
self.s = states[0]
self.F = set([states[-1]])
self.deltaT = {(states[i], input[i]) :states[i + 1] for i in range(len... | The code initializes a transducer by processing a list of string pairs. It first sets up initial states using the first entry, then iteratively adds subsequent entries in order. Progress is logged every 10,000 entries. Finally, it reduces the transducer's structure while preserving the empty word case. | def __init__(self, D: List[Tuple[str, str]]) -> "Transducer":
self.construct_initial(*D[0])
for i, entry in enumerate(D[1:]):
if i % 10_000 == 0:
print(f"ENTRY {i}; WORD {D[i][0]}")
self.add_entry_in_order(*entry)
self.... |
def traverse_lcp(self: "Transducer", w: str) -> str:
state = self.s
prefix = ""
for a in w:
if (state, a) in self.deltaT:
prefix += a
state = self.deltaT[state, a]
else:
break
return prefix
def increase_... | The main task of the code is to add a new input-output entry to a transducer in an out-of-order manner. It first identifies the longest common prefix of the input, adjusts the transducer's structure by increasing counts except for this prefix, then inserts the entry in order. Finally, it reduces the transducer's comple... | def add_entry_out_of_order(self: "Transducer", input: str, output: str) -> "Transducer":
prefix = self.traverse_lcp(input)
self.increase_except(prefix)
self.add_entry_in_order(input, output)
self.reduce_except_for_empty_word() |
def increase_except(self: "Transducer", w: str) -> "Transducer":
state = self.s
k = 0
while k < len(w) and (state, w[k]) in self.deltaT:
next_state = self.deltaT[(state, w[k])]
if not self.is_state_convergent(next_state):
state =... | The main task of the code is to remove a specific entry `v` from a transducer, adjusting its state by increasing counts for other entries, removing the entry and updating outputs, then reducing the transducer's structure while handling the empty word case. This operation modifies the transducer's internal state to excl... | def remove_entry_out_of_order(self: "Transducer", v: str) -> "Transducer":
self.increase_except(v)
self.remove_entry_and_pull_output(v)
self.reduce_except_for_empty_word() |
def forward(self):
"""Run forward pass; called by both functions <optimize_parameters> and <test>."""
self.fake_B = self.netG(self.real_A) # G(A)
self.fake_B_bin = self.sig((self.gaussian_blur((((self.fake_B)+1)/2)*255)/255).clamp(0,1))
def backward_D(self):
"""Calculate GAN loss for th... | This function optimizes a GAN's generator (G) and discriminator (D) networks. It first computes fake images via G, then updates D to distinguish real/fake data using backpropagation. Next, it disables D's gradients and updates G to generate more realistic fakes, ensuring both networks improve iteratively through gradie... | def optimize_parameters(self):
self.forward() # compute fake images: G(A)
# update D
self.set_requires_grad(self.netD, True) # enable backprop for D
self.optimizer_D.zero_grad() # set D's gradients to zero
self.backward_D() # calculate gradie... |
def resolve_config(cli_args: dict, conf: dict) -> None:
"""
Receives arguments passed into cli, configuration file, and resolves them to context.
cli args - are strongest and will overrride same param from config file.
If no argument is passed - will take one from config file.
If there is no argumen... | The code processes command-line arguments to resolve configuration settings, checks for a `requirements.txt` file, parses package dependencies, retrieves version information, and outputs formatted results. It handles configuration resolution, dependency validation, and conditional debugging output based on flags like `... | def list(index: str = None, debug: bool = None, out: str = None) -> None:
ctx["cwd"] = os.getcwd()
config = get_config_from_file(ctx=ctx)
resolve_config(cli_args=dict(index=index, debug=debug, out=out), conf=config)
print("Context resolveds: ", ctx)
if not check_if_requirements_exists():
p... |
def resolve_config(cli_args: dict, conf: dict) -> None:
"""
Receives arguments passed into cli, configuration file, and resolves them to context.
cli args - are strongest and will overrride same param from config file.
If no argument is passed - will take one from config file.
If there is no argumen... | The function `bump` processes package version updates by loading configuration, validating input parameters, checking for a `requirements.txt` file, parsing dependencies, and verifying the existence of the specified package. It prepares context for subsequent operations, exits if errors occur, and ensures prerequisites... | def bump(
index: str = None, debug: bool = None, out: str = None, package: str = None
) -> None:
ctx["cwd"] = os.getcwd()
config = get_config_from_file(ctx=ctx)
resolve_config(cli_args=dict(index=index, debug=debug, out=out), conf=config)
print("Context resolveds: ", ctx)
print(f"Command Bump:... |
def check_if_processed(self, flow_path):
if not os.path.exists(flow_path):
os.makedirs(flow_path)
return False
finished_file_marker = os.path.join(flow_path, "finished_traces")
if os.path.exists(finished_file_marker):
print(f"file processed, skipping {flow... | The code processes a dataset to track objects across frames, converting images to numpy arrays, updating active traces, and storing completed traces. It skips specified frames, updates progress, and saves results to a file path, returning it upon completion. | def calculate(self, dataset, max_len=-1, skip=0):
result_path = os.path.join(
dataset.get_path(), dataset.get_name(), "traces")
if self.check_if_processed(result_path):
return result_path
stored_traces = []
trace_list = []
max_len = self.get_max_frame_... |
def load_flow_graph(self, result_path):
pkl_path = os.path.join(result_path, "edges.pkl")
print(f"\nLoading edges from {pkl_path}!")
with open(pkl_path, "rb") as file:
edges = pickle.load(file)
pkl_path = os.path.join(result_path, "covis.pkl")
print(f"\nLoading ... | This function processes a graph by loading and prefiltering it, then filtering out images with insufficient covisible sets and missing keys. It stores the cleaned graph data and confirms completion with a message. | def filter_bad_sets(self, path):
_, name = os.path.split(path)
graph_path = os.path.join(path, self.graph_name)
"""
if self.check_if_processed(graph_path):
return None
"""
edges, covisibility_graph = self.load_flow_graph(graph_path)
covisibility_... |
def init_weigths(self, range_gen):
for i in range(1, len(self.layers)):
self.layers[i].weigths = np.random.uniform(
range_gen[0],
range_gen[1],
(self.layers[i].size, self.layers[i - 1].size + 1))
def error(self, X, Y, error_type):
if error_type... | This code trains a model by iteratively updating its weights using gradient descent. It initializes weights, calculates initial error, and enters a loop where it updates weights, tracks error changes, and stops when the error difference falls below a tolerance threshold or reaches max_epoch. The process prints progress... | def fit(self, X, y, alpha, tolerance, error_type, range_gen=(0, 1), print_each=50,
max_epoch=None):
self.init_weigths(range_gen)
error = []
error.append(self.error(X, y, error_type))
self.update_weigths(X, y, alpha, error_type)
error.append(self.error(X, y, error_type... |
def generate_belief_rep(self):
"""Generates a belief representation suitable for belief-space policy
optimisation. This code uses three tricks to make inference tractable:
1. Maintain a maximium number of hypotheses by using the Expectation
Density heursitic to eliminate excess hypot... | The code simulates a single step in an Active Search Belief MDP, updating the agent's belief state based on sensed intervals. It processes actions, generates observations, adjusts hypothesis boundaries dynamically (adaptive grid), computes posterior estimates, and calculates rewards. The function returns the updated be... | def step(self, action, verbose=False, obs=None):
"""Takes a step in the Active Searach Belief MDP.
Args:
action:
The intervals to sense by the full team of agents, as specified
by the left and right boundary of each sensed interval. For
example, if... |
def acquire_every_move(self): #acquire all the psuedo-legal moves without taking into account if the kings are in check or not
moves = [] #moves = to an empty list
for row in range(8): #8x8 board
for coloumn in range(8):
turn = self.panel[row][coloumn][0] #get the turn
... | This function determines valid castling moves for a king by checking if the king is not in check and if castling is still possible on the king's or queen's side, then adds those moves to the provided list. | def acquire_c_moves(self, row, coloumn, moves): #function to get the castle moves
if self.player_1: #if it is the white player
self.player_1 = not self.player_1 #sswitch the player
opp_moves = self.acquire_every_move() #get the opponents moves
for move in opp_moves: #for ever... |
def acquire_every_move(self): #acquire all the psuedo-legal moves without taking into account if the kings are in check or not
moves = [] #moves = to an empty list
for row in range(8): #8x8 board
for coloumn in range(8):
turn = self.panel[row][coloumn][0] #get the turn
... | The function `get_correct_moves` generates all valid moves by first storing current en passant and castling states. It creates all possible moves, adds castling options, then iterates through each move: simulates it, checks if the king is in check, removes invalid moves, and restores the game state. Finally, it returns... | def get_correct_moves(self): # returns a list of all the correct moves
temp_ep_possible = self.ep_possible # store the value of the en passant possible
temp_castle_possible = castle_possible(self.live_castle_possible.wks, self.live_castle_possible.bks,self.live_castle_possible.wqs, self.live_castle_pos... |
def _check_legacy_exist(self):
processed_folder_exists = os.path.exists(self.processed_folder)
if not processed_folder_exists:
return False
return all(
check_integrity(os.path.join(self.processed_folder, file)) for file in (self.training_file, self.test_file)
)
d... | This code initializes a dataset by loading image data and targets, handling download/checks, applying transformations, and normalizing pixel values to [0,1] by dividing by 255. It distinguishes between training/test sets via the 'train' flag and supports custom transforms. | def __init__(
self,
root: str,
train: bool = True,
transform: Optional[Callable] = None,
target_transform: Optional[Callable] = None,
download: bool = False,
) -> None:
super().__init__(root, transform=transform, target_transform=target_transform)
self... |
def get_model(framework, model_variant):
"""
Load the desired EfficientPose model variant using the requested deep learning framework.
Args:
framework: string
Deep learning framework to use (Keras, TensorFlow, TensorFlow Lite or PyTorch)
model_variant: string
Eff... | The code performs pose estimation on video or image data using a specified EfficientPose model and deep learning framework. It validates inputs, loads the model, processes the input for pose predictions, and optionally visualizes results or stores coordinates in CSV format. The function returns a boolean indicating tra... | def perform_tracking(video, file_path, model_name, framework_name, visualize, store):
"""
Process of estimating poses from camera/video/image.
Args:
video: boolean
Flag if camera or video is supplied, else assumes image
file_path: path
System path of video/image ... |
def copy_chunk_bits(self, new_chunk=None):
self.w = ['0'*32] * 64
if new_chunk is None:
chunk = self.binary_msg_with_padding_and_length[0:512]
else:
chunk = new_chunk
for i in range(16): # 16 = 512-bit chunk / 32-word segments
self.w[i] = (chunk[(i*... | The main task of the code is to generate a hexadecimal hash digest by processing each data chunk through bit copying, word extension, compression, and formatting the resulting hash values with leading zeros. It iterates over `self.chunks`, applies cryptographic operations, and concatenates 8-character hexadecimal repre... | def digest(self):
# print(f'found {len(self.chunks)} chunks in self.chunks')
for chunk in self.chunks:
hash_pre = time.time()
self.copy_chunk_bits(chunk)
hash_post = time.time()
self.timer = hash_post-hash_pre
self.extend_... |
def generate_css(row_length=24) -> str:
# Set minimum size of a square in pixels.
# Also a scaling factor in vw, so it won't be overrun in case of too many intervals
scale = (32 / row_length)
min_size=12
# Define constants for the size and spacing of the squares
SQUARE_SIZE = f'max({min_size}p... | The code generates an HTML chart from a 2D string list (`timeline`), styling it with dynamic CSS. It creates a titled webpage (`"Steamlapse"` or personalized with a name), embeds styled squares for each timeline entry, separates rows with line breaks, and appends a legend. The output is a complete HTML string for rende... | def generate_html_chart(timeline: List[List[str]], name=None) -> str:
# Generate internal stylesheet
css = generate_css(len(timeline[0]))
title = "Steamlapse"
# Different title if name is not set
if name is not None and type(name) == str:
title = (name+"'s Steamlapse")
# Start th... |
def get_csv():
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(initialdir="./data")
return file_path
def get_intervals(default=24):
return int(input ("Intervals (default " + str(default) + "): ") or default)
def persona_from_path(filename):
return os.path.basename(split_fil... | The main task of the code is to generate and save an HTML chart from a CSV file. It handles user input for file path and interval settings, processes the data to create a timeline, generates the HTML content, and saves it to a file named after the detected persona. The function uses default values if not specified and ... | def save_html_chart(path=None, use_defaults=True, intervals=24):
if not type(path) == str:
print("No path entered. Spawning file dialog.")
path = get_csv()
if not use_defaults:
intervals = get_intervals()
else:
print("Using default intervals:", intervals)
persona = ... |
def s_f(facto_sum:int):
s_f_split = splitInt(facto_sum)
s_f_summed = sum(s_f_split)
return s_f_summed
def f_2(factos:list):
facto_sum = sum(factos)
return facto_sum
def f_1(split:list):
factos = []
for i in range(len(split)):
factos.append(facto(split[i]))
return factos
def s... | The code finds the smallest integer n such that applying functions f_1, f_2, and s_f in sequence to the result of splitInt(n) equals the input value i. | def g(i:int):
n = 1
while ((s_f(f_2(f_1(splitInt(n))))) != i):
n = n + 1
return n |
def selectionSort(self,arr):
n = len(arr)
for i in range(0,n):
minIndex = i
for j in range(i,n):
if arr[j] < arr[minIndex]:
minIndex = j
self.arr_clr[j] = BLUE
self.draw(arr,'Selection Sort')
if(... | The main task of the code is to create an interactive sorting algorithm visualization application using Pygame. It allows users to select and execute different sorting methods (selection, bubble, insertion, merge, quick) via keyboard inputs, generate new random arrays with TAB, and visually display the sorting process ... | def main_loop(self):
run = True
menu = "I: insertion, B: bubble, S: selection, M: merge, TAB: new array"
try:
while run:
pygame.time.delay(10)
keys = pygame.key.get_pressed()
for event in pygame.event.get():
... |
def possiblewidths(num, edge_length):
width_list = []
for k in range(num)[2:num]:
if num % k == 0:
height = (num / k) - 2
width = k - 2
if 2 * (width + height) == edge_length:
width_list.append(k)
return width_list
def colormetric(self, name, matc... | The code solves a jigsaw puzzle by matching pieces based on their edges, colors, and orientation. It initializes with the top-left corner, rotates pieces to align sides, and uses heuristics (overlap and color metrics) to match border (edges/corners) and middle pieces iteratively. It determines puzzle dimensions, arrang... | def solve(self, start=0, iteration=1):
completed_puzzle = np.array([]) # output 2d
total_list = [] # list of all unmatched pieces
open_list = self.type["corner"].copy() # to explore
closed_list = [] # explored/matched
parent = {open_list[start]: None}
for i in self.... |
def labeling(self):
contours, _ = cv2.findContours(self.binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for i, cont in enumerate(contours):
hull = cv2.convexHull(cont)
M = cv2.moments(cont)
center = (M['m10'] / M['m00'], M['m01'] / M['m00'])
# boundin... | This code processes a puzzle piece by segmenting and binarizing the input image, labeling its type (e.g., corner, edge), and solving it if it is a valid corner piece. It initializes data structures for feature extraction, performs color space conversion, and checks labeling results. If the piece is a corner with no amb... | def __init__(self, puzzle_piece, flag=0):
self.Seg = Segmentation()
self.orig = puzzle_piece
self.binary, self.foreground = self.Seg.binarize(self.orig)
self.foreimg = cv2.cvtColor(self.foreground.astype(np.float32) / 255, cv2.COLOR_BGR2Luv)
# TEST IMAGES---------
self.... |
def getLowestID(lines):
lowest = getHighestID(lines)
for line in lines:
binary = getSeatBinary(line)
seatID = getSeatID(binary)
if seatID <= lowest:
lowest = seatID
return lowest
def getHighestID(lines):
highest = 0
for line in lines:
binary = getSeatBina... | The main task of the code is to identify missing seat IDs from a list of boarding passes. It processes each line to extract seat IDs, sorts them, and then checks for gaps between the lowest and highest IDs. The function returns a list of missing seat IDs by iterating through the expected range and comparing it to the s... | def getYourSeatID(lines):
IDs = []
missingIDs = []
lowest = getLowestID(lines)
highest = getHighestID(lines)
count = lowest
print(lowest)
print(highest)
for line in lines:
binary = getSeatBinary(line)
index = len(binary) - 1
ID = getSeatID(binary)
if ID no... |
def prettier(self):
for i in range(1, 80):
print("-", end='')
print("")
def minDistance(self, distance, spt):
min = 1e7
for u in range(self.N):
if distance[u] < min and spt[u] == False:
min = distance[u]
min_index = u
return min_index
def showResult(self, distance, neighb... | This code implements Dijkstra's algorithm to find the shortest paths from a source node to all other nodes in a graph. It initializes distance and predecessor arrays, iteratively selects the node with the minimum tentative distance, updates distances for its neighbors, and records predecessors. Finally, it displays the... | def dijkstraSearch(self, source_node):
self.prettier()
distance = [1e7] * self.N
neighbor = [-1] * self.N
distance[source_node] = 0
spt = [False] * self.N
for c in range(self.N):
u = self.minDistance(distance, spt)
spt[u] = True
for v in range(self.N):
if self.graph[u][... |
def prettier(self):
for i in range(1, 80):
print("-", end='')
print("")
def showResult(self, distance, neighbor):
print("Node \tSource Distance \tShortest Path")
for node in range(self.N):
print(node, "\t", distance[node], "\t\t", end='')
self.displayShortestPath(neighbor, node)
... | This code implements the Bellman-Ford algorithm to find shortest paths from a source node in a weighted graph, detect negative weight cycles, and display results. It initializes distances, relaxes edges iteratively, checks for negative cycles post-iteration, then outputs distance arrays and predecessor nodes for path r... | def bellmanFordSearch(self, source_node):
self.prettier()
infinite = 1e7
distance = [infinite] * self.N
neighbor = [-1] * self.N
distance[source_node] = 0
for c in range(self.N - 1):
for u, v, w in self.graph:
if distance[u] != infinite and distance[u] + w < distance[v]:
... |
def populate_coverpoint(self, cg_n, cp):
cp_n = QStandardItem("CVP: " + cp.name)
cov_n = QStandardItem("%0.2f%%" % cp.coverage)
cov_p = QStandardItem()
cov_p.setData(round(cp.coverage, 2), QtCore.Qt.UserRole+1000)
cg_n.appendRow([cp_n, cov_n, cov_p])
for bn in cp... | This function populates a tree model with hierarchical data from a report. It clears existing items, then iterates through covergroups to create rows with type names, coverage percentages, and nested data. It adds coverpoints, crosses, and recursively processes nested covergroups, structuring them as child items under ... | def populate_model(self):
self.clear()
root = self.invisibleRootItem()
for cg in self.report.covergroups:
cg_n = QStandardItem("TYPE: " + cg.instname)
cov_n = QStandardItem("%0.2f%%" % cg.coverage)
cov_p = QStandardItem()
cov_p.setData(rou... |
def train(
model_name: str,
fold: int,
debug: bool,
epochs: int,
num_workers: int=4,
run: str=None,
resume_weights: str="",
resume_epoch: int=0,
):
"""
Model training
Args:
model_name : string name from the models configs listed in models.py file
fold: e... | (The main task of the code is to manage a machine learning workflow via command-line arguments, supporting actions like training, testing, metric evaluation, and prediction generation. It parses parameters such as model name, experiment ID, epochs, and batch size, then executes corresponding functions (train, test_mode... | def main():
parser = argparse.ArgumentParser()
arg = parser.add_argument
arg("--action", type=str, default="train", help="Choose action: train, test_model, check_metric, generate_predictions")
arg("--model", type=str, default="resnet50_512", help="String model name from models dictionary")
arg("--ru... |
def parse_params():
parser = ArgumentParser(description='NXT3 SFX packer')
parser.add_argument('--output-sh', action='store', required=True, metavar='FILE.SH',
help='Where to write the installer executable')
parser.add_argument('--output-rbf', action='store', required=True, metavar='... | The main task of the code is to generate specified output files (e.g., .sfx, .rbf, .uf2) by parsing input parameters and passing them to dedicated writing functions. The `main()` function orchestrates this process, using `parse_params()` to extract configuration details and then invoking `write_sfx()`, `write_rbf()`, a... | def main():
info = parse_params()
write_sfx(info.nxt3, info.battd, info.include_data, info.sfx, info.output_sh)
write_rbf(info.output_rbf)
write_uf2(info.output_uf2, info.output_sh, info.output_rbf) |
def initial_position(self, alpha):
return np.array(
[
interpolate(
-config.frame_x_radius / 2, config.frame_x_radius / 2, alpha
),
-config.frame_y_radius,
0,
]
)
def initial_velocity(self, alpha):... | This code animates characters of a message sequentially by calculating their launch times and positions. It sorts characters by start time, adjusts timing gaps, skips whitespace, and initializes each letter's visual properties (position, velocity, colors) based on alpha values. The animation waits between letters and e... | def construct(self):
alphas = np.linspace(0, 1, len(message))
launch_sequence = sorted(
enumerate(zip(map(self.start_time, alphas), alphas)), key=itemgetter(1)
)
earliest_start = launch_sequence[0][1][0]
launch_sequence = [
(index, time - earliest_start, a... |
def closeWindow(self):
self.window.close()
self.programRunning = False
def __allowLeftRightArrowKeysForNavigation(self, enabled):
if enabled:#allow User to use left and right arrow keys to navigate duplicate contacts
self.window.bind(const.Layout.RIGHT_ARROW_KEY_BINDSTRING, const.Lay... | The code processes GUI events in a loop, handling user interactions like navigation buttons, explanation displays, and saving data. It updates the UI based on events, manages duplicate contact navigation, validates data before progressing, and shows error/success messages. The function reads events from a window, execu... | def runEventLoop(self):#this function should get called repeatedly from an external while loop
self.event, self.values = self.window.read(timeout = const.Layout.WINDOW_WAIT_TIMEOUT_MILLISECOND)
if self.event == gui.WIN_CLOSED or self.event == gui.Exit:#somehow, this line works only if placed above the ... |
def init_normalization(self):
if True:
print('Dataset normalization : ' + self.opt.normalization)
if self.opt.normalization == 'UnitBall':
self.normalization_function = pointcloud_processor.Normalization.normalize_unitL2ball_functional
elif self.opt.normalization == 'Bou... | This code initializes a ShapeNet dataset handler for 3D point cloud and image data, setting up paths, normalization, and caching mechanisms. It filters data by category/subcategory, splits into training/validation sets, loads taxonomy/CSV metadata, and prepares point cloud/image pairs for subsequent processing or model... | def __init__(self, opt, category, subcategory, svr=False, train=True):
self.opt = opt
self.num_sample = opt.number_points if train else 2500
self.SVR = svr
self.train = train
self.mode = 'training' if train else 'validation'
self.category = category
self.subcateg... |
def save_chunks_as_file(
video_id: str, video_chunk_dir: str, start: int, end: int
) -> List:
"""
Save all the video and audio chunks as files.
"""
if end == -1:
end = int(information.get_video_information(video_id=video_id)["duration"])
required_chunks = generate_all_chunks_in_range(st... | The function retrieves video and audio chunks from Redis, assembles them into a video file, muxes with audio if present, and saves the final WebM file to a cache directory with a naming convention based on video ID and time range, then cleans up temporary files. | def egress(video_id: str, start: int, end: int) -> str:
"""
Egress the video from redis and save it as a file in the cache directory.
Returns the path to the video file.
"""
# create temporary directory
egress_dir = os.path.join(config.EGRESS_PATH, unique.get_new_fetch_id())
os.mkdir(egres... |
def summaryIndicators(self, data):
if len(data) > 2:
macd = data[-2]['macd']
macdh = data[-2]['macdh']
macdmin = data[-3]['macdhmin']
macdmax = data[-3]['macdhmax']
#local macd minimum
if not macd is None and not macdh is None and macdh <=... | This function monitors cryptocurrency trading data by processing kline messages to update asset records with price timestamps, open/close values, and indicators. It manages data history, triggers buy/sell actions based on signals and status flags, and adjusts asset states (active/trading) while maintaining order lifeti... | def monitor(self, msg, log=True):
if msg['e'] == 'kline':
k = msg['k']
asset = self.assets[k['s'] + k['i']]
data = asset['data']
rec = defaultdict(lambda:None)
rec['ts'] = k['t']
rec['open'] = float(k['o'])
rec['close'] = float(... |
def prepareHistory(self, start, log=True):
start_ts = datetime.timestamp(parse(start))
ts = None
for _, asset in self.assets.items():
i = Sec[asset['interval']]
sts = floor(start_ts / i) * i * 1000
ts = sts if ts is None else min(ts, sts)
symbol = ... | The code tunes trading parameters for assets by reading a configuration file, simulating trades with generated parameter sets, and selecting the best-performing parameters based on profit and order counts. It iterates through historical data, evaluates parameter effectiveness, and ranks winners by their performance acr... | def tune(self, config):
f = open(config, "r")
for line in f:
p = line.split()
symbol = p[0] + self.baseQuote
asset = self.assets[symbol + p[2]]
asset['testMin'] = [float(min) for min in p[8:13]]
asset['testMax'] = [float(max) for max in p[13:1... |
def prepareHistory(self, start, log=True):
start_ts = datetime.timestamp(parse(start))
ts = None
for _, asset in self.assets.items():
i = Sec[asset['interval']]
sts = floor(start_ts / i) * i * 1000
ts = sts if ts is None else min(ts, sts)
symbol = ... | The code simulates a trading process by initializing a balance, preparing historical trade data, executing trades, selling assets with status 2, and printing initial and final balances along with asset details. It tracks balance changes and outputs results for analysis. | def demo(self, start):
quoteBalance = self.quoteBalance
print("%s initial balance %s" % (self.baseQuote, quoteBalance))
ts = self.prepareHistory(start)
self.testTrades(ts)
for _, asset in self.assets.items():
if asset['status'] == 2: self.sell(asset, False)
... |
def menu_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_application()
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
# Check if user clicks on one of the choices using the rectangle... | This method runs a game loop that handles different game states (MENU, GAME_OVER, PLAY, MAPMAKING) by processing events, updating game logic, and rendering appropriate visuals. It checks the player's status, manages transitions to GAME_OVER when needed, and maintains a consistent frame rate via the clock. | def run_game(self):
while True:
if self.mode == "MENU":
self.menu_events()
self.draw_menu()
elif self.mode == "GAME_OVER":
self.draw_game_over()
elif self.mode == "PLAY":
if self.player.is_dead():
... |
def is_close_to_player(self):
distance = self.pos.distance_to(self.game.player.pos)
return distance < ZOMBIE_CHASE_DISTANCE
def has_line_of_sight(self, target_pos):
"""Check if there is a direct line of sight to the target position (e.g., the player)."""
# Define the start and end points... | This code updates an enemy's behavior by checking its health, proximity to the player, and line of sight. If close enough and visible, it directly chases the player; otherwise, it follows a precomputed path. It toggles between chasing and path-following states based on distance, ensuring efficient navigation and target... | def update(self, player_pos):
if self.health<=0:
self.kill()
#self.follow_path() # Now we use follow_path instead of directly aiming at the player
# Check the distance to the player
if self.is_close_to_player() and self.has_line_of_sight(player_pos):
# If close e... |
def configure_buildtime(
org_root: pathlib.Path, *, client: httpx.Client, run: Callable
) -> None:
write_jupyter_config(org_root)
basic_directories(org_root)
ncolonize_jupyter(org_root)
configure_helm_build(org_root, client=client, run=run)
land_starship(org_root, client=client, run=run)
def con... | The main task of the code is to execute different configuration or management functions based on command-line arguments, using environment variables and subprocess operations. It handles "buildtime", "runtime", or "ncolony" commands by calling respective functions to configure organizational settings, with validation f... | def main(
argv: Sequence[str] = sys.argv,
env: Mapping[str, str] = os.environ,
run: Callable = subprocess.run,
) -> None:
org_root = pathlib.Path(env["ORG_ROOT"])
client = httpx.Client(verify=env.get("VERIFY_CA", True), follow_redirects=True)
if argv[1] == "buildtime":
configure_buildtim... |
def get_depressing_mask(cfg):
depr_mask = np.ones((cfg.mask_size, cfg.mask_size)) * 0.2
depr_mask[5 : cfg.mask_size - 5, 5 : cfg.mask_size - 5] = 1
cfg.depr_mask = depr_mask
def get_threshold(cfg, auto_encoder):
"""Statistics of SSIM threshold using training set."""
print("estimating threshold...")
... | The function processes test images using an autoencoder to detect anomalies by comparing original and reconstructed images. It generates SSIM/L1 residual maps, applies thresholding and background masks, performs morphological operations, and saves the original, reconstructed, residual mask, and visualized results in th... | def get_results(cfg, auto_encoder, test_list=None):
get_depressing_mask(cfg)
if cfg.ssim_threshold < 0 or cfg.l1_threshold < 0:
get_threshold(cfg, auto_encoder)
if test_list is None:
test_list = get_file_list(cfg.test_dir, cfg.img_suffix)
test_path_s = len(cfg.test_dir)
if cfg.test_d... |
def gini(data):
counts = class_counts(data)
impurtity = 1
for disease in counts:
prob_of_disease = counts[disease] / float(len(data))
impurtity -= prob_of_disease**2
return impurtity
def unique_symptom(data):
symptom = []
for d in data:
[symptom.append(d[s]) for s in... | This function identifies the optimal feature (symptom) to split data by maximizing information gain using Gini impurity. It iterates through unique symptoms, partitions data based on each symptom, calculates information gain for each split, and returns the highest gain along with its corresponding question. | def find_best_split(data):
best_info_gain = 0
best_question = None
current_uncertainty = gini(data)
n_symptoms = unique_symptom(data)
for symptom in n_symptoms:
question = Question(symptom)
match_rows, unmatch_rows = partition(data,question)
if len(match_rows) == 0 or len(u... |
def generate_population(gen_code_len, population, mutation_probability):
for index in range(population):
poblacion.append(Subject(mutation_probability, quantity=gen_code_len))
def selection(poblat, elitism):
file.write("Seleccion de individuos\n")
total = evaluation(poblat)
for subject in poblat... | This code implements a genetic algorithm to solve optimization problems (e.g., N-Queens, Knapsack) by evolving a population over generations. It writes each generation's state, applies selection, crossover, and mutation, and terminates when a solution is found or after a set number of iterations. The best individual's ... | def start(gen_code_len=32, generations=100, population=10, mutation_percentage=.2,
elitism=.4, genetic_merch=.5, percentage_newcomers=.6):
i = 1
global file, best_subject
generate_population(gen_code_len, population, mutation_percentage)
if problem == 1:
file = open('reports/N_Queens.t... |
def train(self, train_dataset):
self.node_cnt = 0
return self.build_tree(train_dataset)
def evaluate(self, root_node, val_dataset):
correct, wrong = [0, 0], [0, 0]
for _, row in val_dataset.iterrows():
predicted = self.predict(row, root_node)
if predicted == row[... | The code performs k-fold cross-validation on a dataset using a decision tree classifier. It splits the data into k partitions, trains the model on k-1 folds, evaluates accuracy and balanced accuracy on the validation fold, accumulates results across all folds, and outputs average metrics. It also saves the decision tre... | def run(self):
val_size = math.floor(len(self.dataset) / self.CROSS_VAL)
sum_accuracy = 0
sum_bal_acc = 0
for i in range(self.CROSS_VAL):
start, end = val_size * i, min((i + 1) * val_size, len(self.dataset))
train_dataset = pd.concat(
[self.dataset... |
def _get_snapshot_image(self, element: Any, id: str):
"""
Gets, or create, the snapshot image from the element.
Args:
element: the element to create the snapshot.
id: a unique id to gets the snapshot file name.
Returns:
A tuple of the Image and a boo... | The code asserts whether a UI element's screenshot matches a saved snapshot. It captures the element's image, compares it with the stored snapshot using a unique ID, and raises an error if discrepancies are found. If no differences are detected, it exits silently. The function handles image retrieval, comparison, and c... | def assert_match_snapshot(self, element: Any, id: str):
"""
Assert if a screenshot of a element matches to the saved snapshot of it.
Args:
element: the element to create the comparison and snapshot image.
id: a unique id to gets the snapshot file names.
"""
... |
def _batch_type(self):
return {
'bert': self._bert_batch(),
'glove': self._glove_batch()
}[self._embed]
def _intialize_hyperparam_loss(self):
self._optimizer = optim.Adam(
self._model.parameters(),
lr = self._lr
)
self._loss_func... | The main task of the code is to train a machine learning model over multiple epochs by initializing hyperparameters and loss functions, processing training batches, tracking metrics, normalizing results, printing updates, saving training outcomes to a CSV file, and storing the trained model's weights for future use. | def start_training(self):
self._logger.info('Initialize hyperparameters and loss functions')
train_batch = self._batch_type()
self._intialize_hyperparam_loss()
self._model.train()
for epoch in range(1, self._epochs + 1):
# Reset every epoch
se... |
def get_bean_name(self):
self.bean_name = input("Bean name: ")
self.bean_name = self.bean_name[0].capitalize() + self.bean_name[1:]
if len(self.bean_name) == 0:
print("Bean name cant be null")
self.get_bean_name()
def will_generate_get_set(self):
answer = input("G... | The main task of the code is to generate a Java bean class by retrieving a bean name, determining if get/set methods are needed, fetching JSON data, creating the bean structure, and copying the generated code to the clipboard for quick use. | def start(self):
self.get_bean_name()
self.will_generate_get_set()
self.get_json_response()
self.generate_bean()
self.copy_to_clipboard() |
def squareUnderAttack(self, r, c):
# Determine if the enemy can attack the square r, c
self.whiteToMove = not self.whiteToMove # Switch to opponent's turn
oppMoves = self.getAllPossibleMoves()
self.whiteToMove = not self.whiteToMove # Switch the turn back
for move in oppMoves:... | This function generates valid castling moves for a chess engine by checking if the current square is under attack (returning early if so) and then delegating to helper methods to add kingside or queenside castling moves to the 'moves' list, based on the current player's castling rights. | def getCastleMoves(self, r, c, moves, allyColor):
if self.squareUnderAttack(r, c):
return # Can't castle while we are in check!
if (self.whiteToMove and self.currentCastlingRight.wks) or (not self.whiteToMove and self.currentCastlingRight.bks):
self.getKingsideCastleMoves(r, c, ... |
def checkForPinsAndChecks(self):
pins = [] # Squares where the allies pinned piece is and direction pinned from
checks = [] # Squares where enemy is applying a check
inCheck = False
if self.whiteToMove:
enemyColor = 'b'
allyColor = 'w'
startRow = se... | The code generates valid chess moves considering checks, pins, and castling. It first checks if the king is in check, then filters moves to block checks or capture threatening pieces. For double checks, the king must move. If no valid moves exist, it identifies checkmate or stalemate. Finally, it adds castling moves an... | def getValidMoves(self):
# All moves considering checks
moves = []
self.inCheck, self.pins, self.checks, ally = self.checkForPinsAndChecks()
if self.whiteToMove:
kingRow = self.whiteKingLocation[0]
kingCol = self.whiteKingLocation[1]
else:
king... |
def simhash(text: str) -> str:
sh = [0] * 128
words = text.strip().split(" ")
for word in words:
word_hash = hashlib.md5(str.encode(word)).hexdigest()
for i, bit in enumerate(hex_to_bits(word_hash)):
if int(bit) == 1:
sh[i] += 1
else:
... | The code processes a set of documents by generating simhash fingerprints, creates candidate pairs using Locality-Sensitive Hashing (LSH) for approximate similarity detection, and answers similarity queries by comparing input queries against the precomputed candidates. It reads n documents, builds simhashes, generates L... | def main():
n = int(input())
sim_hashes = []
for i in range(n):
sim_hashes.append(simhash(input()))
candidates = create_candidates_lsh(sim_hashes)
q = int(input())
for i in range(q):
query = input()
result = parse_query(candidates, query, sim_hashes)
print(re... |
def zero_weights_on_graph(graph: dict):
for node in graph.keys():
graph[node] = 0
return graph
def find_shortest_paths(current_edges_graph: dict, weight_graph: dict, first_node: int, second_node: int):
current_path = []
current_cost = 0
paths_counts = find_full_paths_recursive(current_edges... | This code calculates edge centralization in a graph by adjusting edge weights based on the number of shortest paths between node pairs. It iterates over all node pairs, computes their shortest paths, and distributes 1.0 divided by the path count to each edge in those paths, effectively measuring how central edges are i... | def calculate_centralises(graph: dict, input_graph: dict, source_weight_graph: dict):
graph = zero_weights_on_graph(graph)
for first_node in input_graph.keys():
for second_node in input_graph.keys():
if first_node >= second_node:
continue
shortest_paths = find_s... |
def calculate_total_weights(graph_weights):
count = 0
for weight in graph_weights.values():
count += weight
return count
def get_graph_groups(source_graph: dict, graph_centralises: dict, weight_graph: dict):
groups = {}
visited = set()
for node in source_graph.keys():
if node i... | The code calculates the modularity of a graph by comparing the actual number of edges within groups to the expected number under a random distribution, normalizing the result by the total edge weight. It iterates over all node pairs in each group, computes their contribution to modularity, and aggregates it into a fina... | def calculate_modularity(graph_input: dict, graph_weights: dict, graph_centralises: dict):
q = 0
m = calculate_total_weights(graph_weights)
groups = get_graph_groups(graph_input, graph_centralises, graph_weights)
for group in groups:
for first_node in group:
for second_node in group... |
def read_input():
graph = {}
line = input()
while len(line.strip()) > 0:
left, right = (int(x) for x in line.split(" "))
if left not in graph:
graph[left] = []
if right not in graph:
graph[right] = []
graph[left].append(right)
graph[right].a... | The code performs community detection on a graph by iteratively adjusting node centralities and edge weights to maximize modularity. It reads graph input, calculates non-similarity metrics, initializes weights, and iteratively updates centralities while tracking modularity scores. The process removes edges until no con... | def main():
DEBUG = False
graph_input, graph_features = read_input()
non_similarity = calculate_non_similarity(graph_features)
graph_weights = add_starting_weights_to_graph(graph_input, non_similarity)
communities_over_iterations = []
graph_centralises = graph_weights.copy()
while True... |
def epsilonGreedyAction(self,state):
# print("Get Epsilon Greedy Action")
legalActions = self.getLegalActions(state)
# print(self)
# print(state)
# print(legalActions)
action = "None"
if len(legalActions) == 0:
return action
if util.flipCoin... | This code updates the Q-value for a given state-action pair using the Bellman equation. It calculates the new Q-value by combining the previous value (weighted by (1 - alpha)) with a target value (weighted by alpha), which includes the immediate reward and the discounted maximum Q-value of the next state. The epsilon-g... | def update(self, state, action, nextState, reward):
"""
The parent class calls this to observe a
state = action => nextState and reward transition.
You should do your Q-Value update here
NOTE: You should never call this function,
it will be called on your behal... |
def setCameraRoll(self):
cameraRollNode = self.cameraRollTransformSelector.currentNode()
cameraTransformNode = self.cameraTransformSelector.currentNode()
upAngleVector = self.angle_to_unit_vector(self.upAngleSliderWidget.value) # Desired view up vector
cameraMatrix = vtk.vtkMatrix4x4()
cameraTransfo... | (The code generates a depth map from a 3D view by capturing the z-buffer, cropping a central region, flipping, resizing, applying perspective correction, and saving the processed depth data to an output node for visualization or further processing.) | def generateDepth(self):
cameraNode = self.cameraSelector.currentNode()
# Fix roll
camera = cameraNode.GetCamera()
#camera.SetViewUp(self.angle_to_unit_vector(self.upAngleSliderWidget.value))
self.setCameraRoll()
# Undistort
self.undistortImage()
outputNode = self.outputIm... |
def getValidLoc():
validLoc = []
cBoard = gameState()
for i in range(con4.x):
if isValid(i):
validLoc.append(i)
return validLoc
def gameState():
cBoard = list()
for i in range(con4.x):
cBoard.append(list())
for i in range(con4.x):
for j in range(len(con4.s... | Your return
The function `winMove(turn)` identifies a winning move by iterating through valid game positions. For each valid location, it simulates placing the current player's piece (`turn`) and checks if this move satisfies the winning condition using `checkwin()`. If a winning move is found, it returns the corresp... | def winMove(turn):
validLoc = getValidLoc()
for i in validLoc:
cBoard = gameState()
cBoard[i].append(turn)
if checkwin(cBoard, i, con4.wincon) == True:
return validLoc[i] |
def gameState():
cBoard = list()
for i in range(con4.x):
cBoard.append(list())
for i in range(con4.x):
for j in range(len(con4.setup[i])):
cBoard[i].append(con4.setup[i][j])
return cBoard
def getValidLoc():
validLoc = []
cBoard = gameState()
for i in range(con4.x)... | This function determines the optimal move in a game by evaluating all valid moves. It calculates scores for each potential move, identifies the highest score, and randomly selects one of the best moves to return. | def bestMove():
bestScore = -1000
scoreList = list()
cBoard = gameState()
validLoc = getValidLoc()
bestCol = list()
for i in validLoc:
cBoard = gameState()
cBoard[i].append(turn)
score2 = score(cBoard, i)
scoreList.append(score2)
print(str(score2) + " :sco... |
def load_data(x_file, d_file, y_file):
x_file = './Med2Vec_data/' + x_file
x_seq = np.array(pickle.load(open(x_file, 'rb')), dtype='object')
d_seq = []
if len(d_file) > 0:
d_file = './Med2Vec_data/' + d_file
d_seq = np.array(pickle.load(open(d_file, 'rb')), dtype='object')
y_seq = ... | The code predicts the next patient visit's ICD9 codes using a trained model. It restores model weights, loads test data, prepares sequences by aligning next-to-last visits (input) with last visits (target), trains a prediction model on visit representations, and evaluates predicted probabilities against true labels. | def predict_next_visit(med2vec, saver, config, three_digit=False):
# get trained model (weights)
ckpt = tf.train.get_checkpoint_state(config['model_path'])
if ckpt and ckpt.model_checkpoint_path:
saver.restore(med2vec.sess, ckpt.model_checkpoint_path)
# open TESTING data
test_seq_file = 'te... |
def Create_visited_stops(self):
coordinates = np.array(self.points)
self.x_coordinates = coordinates[:, 0] # first column of the array being the x coordinates
self.y_coordinates = coordinates[:, 1]
def Create_Distance_Matrix(self):
self.stop_distances = np.zeros((self.stop_count, self.st... | Your return
The code initializes a reinforcement learning environment for managing sampling points. It sets parameters like stop count, maximum limit, and points, then creates a list of visited stops, a distance matrix, and renders the environment. The action and observation spaces are defined based on the number of ... | def __init__(self,stop_count = None,max_limit = None, points = None):
print(f"Initialized Sampling Point Environment with {stop_count} random visited_stops")
# Initialization
# added
self.points = points
self.stop_count = stop_count
self.action_space = self.stop_count ... |
def get_mini_batches(self, X, y, batch_size):
m = X.shape[1]
mini_batches = list()
num_batches = math.floor(m/batch_size)
for i in range(0, num_batches):
mb_X = X[:, i * batch_size : (i+1) * batch_size]
mb_y = y[:, i * batch_size : (i+1) * batch_size]
... | The code trains a neural network with three hidden layers using mini-batch gradient descent. It shuffles the data in each epoch, splits it into mini-batches, performs forward and backward passes to compute gradients, and updates the model's parameters (weights and biases) iteratively using the specified learning rate. | def train(self, X, y):
# loop through number of iterations
for i in range(0, self.num_epochs):
# shuffle X and y
random = np.arange(len(X[1]))
np.random.shuffle(random)
X_shuffle = X[:,random]
y_shuffle = y[:,random]
# ... |
def load_cities():
cities = open(f'data/cities').read().split('\n')
# Remove empty city names
return [city for city in cities if len(city) > 1]
def query_mentions_from_subreddits(reddit, cities, subreddits):
mentions = dict()
for subreddit in subreddits:
try:
submissions = query_submissions(reddit, subreddit)... | The main task of the code is to generate a live heatmap visualizing the geographical distribution of Ukraine war-related discussions on Reddit. It queries specified subreddits for city mentions, smooths the data over time, retrieves geolocation data for cities, and compiles the results into an interactive HTML map with... | def main():
load_dotenv()
now = datetime.utcnow().strftime(TIME_FORMAT)
# init praw
reddit = praw.Reddit(
client_id=os.getenv('REDDIT_API_ID'),
client_secret=os.getenv('REDDIT_API_SECRET'),
username=os.getenv('REDDIT_USERNAME'),
password=os.getenv('REDDIT_PASSWORD'),
user_agent='ukraine war hotmap'
)
... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--checkpoint",
dest="checkpoint",
nargs="+",
required=True,
help="Path to the checkpoint to be used for the evaluation",
)
parser.add_argument(
"-b",
"--batch-... | The code evaluates multiple pre-trained encoder-decoder models on specified datasets using given checkpoints. It loads models (with CUDA support), processes test data via a data loader, runs evaluations (including beam search), and formats results into markdown tables showing error rates, correctness, and highest proba... | def main():
options = parse_args()
is_cuda = use_cuda and not options.no_cuda
hardware = "cuda" if is_cuda else "cpu"
device = torch.device(hardware)
for dataset_name in options.dataset:
results = {"best": {}, "mean": {}, "highest_prob": {}}
for checkpoint_path in options.checkpoint... |
def loginsuccess():
#make this go to our main quaver page
global root
global screen3
screen3 = Toplevel(screen)
screen3.title("SUCCESS")
screen3.geometry("150x100")
Label(screen3,text = " LOGIN SUCCESSFUL").pack()
Button(screen3,text = "OK", command = delete2).pack()
session()
r... | The code defines a `loginuser` function that handles user authentication by checking if a provided username (as a file name) exists in the current directory and verifying the password against the file's content. It clears input fields, checks for username validity, reads the file, and triggers success or error messages... | def loginuser():
#called when login button clicked
username1 = usernameverify.get()
password1 = passwordverify.get()
usernameentry1.delete(0,END)
passwordentry1.delete(0,END)
#to get files in working directory list
listoffiles = os.listdir()
#this returns a list of all files in our cur... |
def src_to_tmp(
filepath: str or PosixPath,
src_path: str or PosixPath,
tmp_path: str or PosixPath
):
'''
If filepath is an absolute path and is located in src_dir, convert it into
working dir path. Return filepath otherwise.
'''
filepath_ = Path(filepath)
src_path_ = Path(src_path).... | This function processes a link tag by determining the appropriate filepath and anchor based on attributes like 'src', 'meta_id', 'title', or 'anchor', then generates a Markdown link to the corresponding location in a document or file. It handles multiple cases for link resolution, including using relative paths, metada... | def process_links(self, block) -> str:
'''Process a link tag and replace it with Markdown link to proper anchor'''
self.logger.debug(f'Processing link {block.group(0)}')
tag_options = Options(self.get_options(block.group('options')))
caption = block.group('body')
if 'src' in tag... |
def is_seq(board, y, x, col):
return is_in_range(board, y, x) and board[y][x] == col
def is_in_range(board, y, x):
return 0 <= y < len(board) and 0 <= x < len(board[y])
def is_bounded(board, y_end, x_end, length, d_y, d_x):
col = board[y_end][x_end]
end_blocked = is_bound(board, y_end+d_y, x_end+d_x, co... | The function `detect_row` counts the number of open and semi-open sequences of a specified length and color (`col`) along a given direction (`d_y`, `d_x`) starting from a position (`y_start`, `x_start`) on a board. It traverses the board, checks for consecutive pieces, and updates counts based on whether sequences are ... | def detect_row(board, col, y_start, x_start, length, d_y, d_x):
open_seq_count, semi_open_seq_count = 0, 0
y, x = y_start, x_start
cur_len = 1 if is_seq(board, y, x, col) else 0
while is_in_range(board, y, x):
if not is_seq(board, y+d_y, x+d_x, col):
if cur_len == length:
... |
def make_empty_board(sz):
board = []
for i in range(sz):
board.append([" "]*sz)
return board
def put_seq_on_board(board, y, x, d_y, d_x, length, col):
for i in range(length):
board[y][x] = col
y += d_y
x += d_x
def print_board(board):
s = "*"
for i in range(len(bo... | The code tests the `is_bounded` function by placing a sequence of pieces on a board and checking if a specific position is marked as 'OPEN'. It initializes a board, positions a sequence, and verifies the bounded status at a target coordinate. The test passes if the result matches 'OPEN', otherwise it fails. The main ta... | def test_is_bounded():
board = make_empty_board(8)
x = 5; y = 1; d_x = 0; d_y = 1; length = 3
put_seq_on_board(board, y, x, d_y, d_x, length, "w")
print_board(board)
y_end = 3
x_end = 5
if is_bounded(board, y_end, x_end, length, d_y, d_x) == 'OPEN':
print("TEST CASE for is_bounded ... |
def make_empty_board(sz):
board = []
for i in range(sz):
board.append([" "]*sz)
return board
def put_seq_on_board(board, y, x, d_y, d_x, length, col):
for i in range(length):
board[y][x] = col
y += d_y
x += d_x
def print_board(board):
s = "*"
for i in range(len(bo... | This code tests the 'detect_row' function by placing a sequence of 'w' pieces on a board and checking if it correctly identifies the row with one open space and zero other pieces, verifying the function's output against expected results. | def test_detect_row():
board = make_empty_board(8)
x = 5; y = 1; d_x = 0; d_y = 1; length = 3
put_seq_on_board(board, y, x, d_y, d_x, length, "w")
print_board(board)
if detect_row(board, "w", 0,x,length,d_y,d_x) == (1,0):
print("TEST CASE for detect_row PASSED")
else:
print("TEST... |
def make_empty_board(sz):
board = []
for i in range(sz):
board.append([" "]*sz)
return board
def put_seq_on_board(board, y, x, d_y, d_x, length, col):
for i in range(length):
board[y][x] = col
y += d_y
x += d_x
def print_board(board):
s = "*"
for i in range(len(bo... | The code tests the `detect_rows` function by placing a horizontal sequence of 3 white pieces on an 8x8 board and verifying if it correctly detects one such sequence with no other results, printing "PASSED" or "FAILED" accordingly. | def test_detect_rows():
board = make_empty_board(8)
x = 5; y = 1; d_x = 0; d_y = 1; length = 3; col = 'w'
put_seq_on_board(board, y, x, d_y, d_x, length, "w")
print_board(board)
if detect_rows(board, col,length) == (1,0):
print("TEST CASE for detect_rows PASSED")
else:
print("TES... |
def get_py_files(path):
"""
Argument:
path - path to directory
Return list of paths with Python files
"""
py_path_to_files = []
data = dir_jogging(path)
path_files, files = data[0], data[1]
for i in range(len(data[0])):
if check_file(path_files[i], files[i]):
... | The function `find_mds` extracts all occurrences of the string "import" from Python files in a specified directory, processes them to remove duplicates and unnecessary entries, and returns a list of unique import statements found. | def find_mds(path):
"""
Argument path - path to directory
"""
paths = get_py_files(path)
strings = [find_string_in_file(p, "import") for p in paths]
strings = matrix_to_list(strings)
strings = remove_unnecessary_items(strings)
return list(set(strings)) |
def check_builtin(pkgs):
"""
Find builtin modules in project.
Check pkgs with builtin Python modules
"""
builtin_py = parse_builtin_from_python_libs()
return [i for i in pkgs if i in builtin_py]
def parse_local(pkgs, files):
local = []
# clean pkgs
for i in range(len(pkgs)):
... | The function `analyze_mds` categorizes elements from the input `mds` list into three types—builtin, local, and external—based on their presence in the current working directory (`files`). It uses helper functions to determine each category: `check_builtin` identifies built-in packages, `parse_local` finds local files, ... | def analyze_mds(mds, files):
"""
Return dictionary with names of package`s type
===================ARGUMENTS==================
mds - list of mds
files - list of files that situated in cwd
"""
builtin = check_builtin(mds)
local = parse_local(mds, files)
outside = parse_outside(mds, lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.