dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def str_to_list(str):
return list(str.split(" "))
def str_to_int(M):
return [int(i) for i in M]
def mult_inv(e,r):
gcd,s,_=ExtendedEuclid(e,r)
if(gcd!=1):
return None
else:
return s%r
def Decryption(C, d, n):
M = []
for c in C:
M.append((c ** d) % n) ... | The code's main task is to receive and decrypt messages from a server. It handles alias requests by sending the client's alias, extracts RSA public key parameters (e, n, φ(n)) from messages containing "Keys:", processes the encrypted message (M) by decrypting it using the private key (d) derived from φ(n) and e, then o... | def client_receive():
while True:
try:
message = client.recv(1024).decode('utf-8')
if message == "alias?":
client.send(alias.encode('utf-8'))
else:
if message.find('Keys:')!= -1:
temp = message.find('Keys:')
... |
def scatter(self, inputs, kwargs, device_ids):
return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim, chunk_sizes=self.chunk_sizes)
def replicate(self, module, device_ids):
return replicate(module, device_ids)
def parallel_apply(self, replicas, inputs, kwargs):
return parallel_apply(replicas, input... | This code implements distributed data parallelism by scattering inputs to multiple devices, replicating the model on each device, executing computations in parallel, and gathering outputs. It handles single-device and multi-device scenarios, enabling efficient GPU utilization for large-scale neural network training. | def forward(self, *inputs, **kwargs):
if not self.device_ids:
return self.module(*inputs, **kwargs)
inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
if len(self.device_ids) == 1:
return self.module(*inputs[0], **kwargs[0])
replicas = self.replicate(self.module, self.device_ids... |
def playTurn(board, graphical_board, to_move):
if to_move == humanTurn and not game_finished:
action = humanAction()
if action is not None:
board, to_move = renderPiece(action, board, graphical_board)
elif to_move == computerTurn and not game_finished:
action = computerActio... | The code defines a game loop that handles user input, updates the game board, alternates turns between player and computer, checks for win conditions, and resets the game when finished. It uses Pygame for event handling and rendering, continuously updating the display and managing game state transitions until the game ... | def gameLoop():
global board, board_size, graphical_board, to_move, game_finished, move_first
while True:
for event in pygame.event.get():
pygame.display.update()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if move_first == ... |
def refresh_images_on_path(self):
#compare images found in path with current reel
images = self.find_all_supported_image_files_in_path(self.current_path)
if images == self.image_reel:
logger.debug("same")
elif len(images) > len(self.image_reel):
logger.debug("mor... | The main task of the code is to advance to and display the next image in a reel. It first refreshes the image path, checks if images exist in the reel, increments the current image position if available, scales the image for display, and shows it. If no images are present, it logs a debug message indicating the reel is... | def next_image(self):
self.refresh_images_on_path()
if len(self.image_reel) > 0:
#increase the current image pos properly
self.next_current_image()
#display the current image
self.get_scaled_image_and_display()
else:
#No images found i... |
def get_all_csv_paths(folder_path):
all_paths = glob.glob(folder_path + "/*/*.csv") + glob.glob(folder_path + "/*.csv")
return all_paths
def get_quartets(csv_path : str,
mode : int=1
):
'''
Mode
1 Only most probable
2 All most probable if they're not equally probab... | The main task of the code is to process CSV files from a specified folder by extracting quartet data, generating ASTRAL-formatted tree files, and saving metadata including source paths and quartet counts. It iterates through each CSV, constructs output file paths, writes quartets into tree files, and optionally stores ... | def get_quartets_from_folder(csvs_folder: str, save_metadata: bool, output_folder: str = "."):
all_paths = get_all_csv_paths(csvs_folder)
print(all_paths)
metadatas = []
for path in tqdm(all_paths):
nqc, quartets = get_quartets(path)
input_path_ASTRAL = output_folder + "/input_ASTRAL/"... |
def find_states(self):
basic_states=set()
self.tree.walk(find_states, basic_states)
state_combis = []
for i in range(0, len(basic_states)+1):
cs = itertools.combinations(basic_states, i)
for c in cs:
c = set(c)
state_combis.append(... | The code extracts a finite state machine (FSM) from a given tree structure by identifying states, transitions, and terms. It processes the FSM through flattening, removing invalid transitions, and re-flattening to simplify it, ultimately storing the refined FSM in `self.fsm` for further use. | def extract(self, tree):
self.tree = tree
(basic_states, state_combis) = self.find_states()
# pass through to function above. FIXME:
self.basic_states = basic_states
terms = self.find_terms()
fsm = self.extract_transitions(state_combis, terms)
fsm = self.fla... |
def predictPose(coords, classes, showClassPred = False, labels = False, addNoise = False, modelName = 'cat', checkPreds = False, altLabels = True, pruning = True):
if showClassPred: # display class prediction
showImage(classes)
population = np.where(classes > maskThreshold)[:2]
if not len(population):
return Fa... | The code evaluates machine learning models (either combined or separate class/vector models) on a dataset by generating predictions, comparing them to true labels using metrics like MAE and MSE, and optionally visualizing results, saving images, or recording accuracy for analysis. | def evalModels(modelSets, trials = 5, showImageChoice = False, showTrue = False, saveImage = False, saveAccuracy = False, allValid = False):
for modelSet in modelSets:
if type(modelSet.name) == dict:
if len(modelSet.name) == 2: # seperate models
classModel = models.modelsDict[modelSet.name['classModel']]
... |
def valid_guess_length(guess_word) :
#TODO: check if `guess_word` is longer than MAX_SIZE
#TODO: replace the line below
return False
def guess_in_dict(guess_word, dict) :
#TODO: check if `guess_word` is in the dictionary
#TODO: replace the line below
return False
def check_guess(guess_word, answ... | The function `process_guess` validates a guess word by checking its length and presence in a dictionary. If invalid, it returns `INVALID_GUESS`; otherwise, it compares the guess with the answer word using `check_guess` to determine the result. | def process_guess(guess_word, answer_word, dict) :
if valid_guess_length(guess_word) :
return INVALID_GUESS
elif not(guess_in_dict(guess_word, dict)):
return INVALID_GUESS
return check_guess(guess_word, answer_word) |
def register_options():
parser = OptionParser(version=VERSION)
parser.add_option('-t','--targets',dest='targets',
help='Your Target (one ip or more separated by ,) or cidr or range ex(192.168.1.1-10)')
parser.add_option("-P","--protocol",dest="proto",help="Enter your target protocol supportd pro... | The code defines a `main()` function that processes command-line options, suppresses output if silent mode is enabled, displays a banner, and executes a task (`run()`) when both targets and credentials are provided. It uses a specified protocol/port, delay, and handles duplicates/executions, with error handling for exc... | def main():
options = register_options()
if options.silent: # No output
Print.display = False
banner()
if options.targets and options.creds:
try:
run(options.targets, get_proto(options.proto, options.port), options.creds, options.delay, options.duplicate, options.exec)... |
def _create_source_file_name(self, args) -> str:
(_, year, month, day, dtime) = args
return self._DIR_SOURCE + \
'_' + year + month + day + \
'_' + dtime + \
'_' + self._source_file_sample + self._file_extension
def _check_source_file_existence(self, args) ->... | This function manages the workflow for creating or updating a product in a filesystem and GeoServer. It checks if source files exist, creates products if missing, moves files to product directories, publishes them to GeoServer, and verifies their existence, returning status messages like 'done' or error codes based on ... | def workflow(self, args) -> str:
""" Check if there are files in local dir then load by args. """
product, year, month, day, dtime = args
# 'AHI_L2_RGB_GEOSERVER', '2021', '08', '02', '0330'
tif_filename = self._create_source_file_name(args)
if not self._check_source_file_exist... |
def toggle_light(num_light, frequency):
"""toggle the LED given, without limite times"""
'''num is the number of the light, must in [0, 1, 2, 3]'''
'''the lights toggle forever acquiescently'''
'''freq is the frequency in Hz'''
leds = [pyb.LED(i) for i in range(1, 5)]
tim = pyb.Timer(Link_LED_Ti... | The code initializes a light toggle on pins 2 and 6, then waits for a switch press. Upon detection, it stops the light toggle, triggers a feedback function, and exits the loop. The main task is to control lighting based on switch input for system feedback. | def Light_Script_Ready():
flag = True
while True:
if flag:
toggle_light(2, 6)
flag = False
sw = pyb.Switch()
if sw.value():
toggle_light_stop(2)
Light_Feedback_Button()
pyb.delay(200)
break |
def load_tasks(self):
raw = self.load_json("tasks.json")
for task in raw:
self.tasks.append(Task.init__dic(task))
ids = [task.ID for task in self.tasks]
if len(ids) != 0:
high = max(ids)
self.max_ID = high
self.reuseID = set([i for... | The main task of the code is to load three data components—tasks, related tasks, and tags—into the object's data structure by calling the methods `load_tasks()`, `load_reTasks()`, and `load_tags()`. This initializes or populates the object with essential data elements for further processing or analysis. | def load_data(self):
self.load_tasks()
self.load_reTasks()
self.load_tags() |
def find_data_dir(self):
script_dir = os.path.dirname(os.path.abspath(__file__))
self.data_dir = os.path.abspath(os.path.join(script_dir,"../data"))
def load_json(self,file):
if (self.data_dir == None):
self.find_data_dir()
config_file = os.path.join(self.data_dir,file)
... | The code's main task is to initialize an object by locating the data directory, loading configuration settings from "config.json", and retrieving data. It sets up essential resources for the class by configuring the environment and preparing data for subsequent operations. | def __init__(self):
self.find_data_dir()
self.config = self.load_json("config.json")
self.load_data() |
def vertex_function(self, messages):
return tf.reduce_mean(messages, -1, keepdims=True)
def log(x, y, k, dim=2, axis=-1):
t = minkowski_inner_product(x, y, dim, axis, keepdims=True)
out = y + x * t / k
norm = minkowski_norm(out, dim, axis, keepdims=True)
out = out / norm
return out * hyperbo... | This code processes geometric data by computing weighted tangent vectors from message-passing, aggregating them per vertex, and applying an exponential map to update vertex positions in a manifold or graph structure. | def call(self, inputs):
vertices, edges, messages = inputs
num_points = tf.shape(vertices)[0]
weights = self.vertex_function(messages)
vertex_pairs = tf.gather(vertices, edges)
vectors = log(vertex_pairs[:, 0, :], vertex_pairs[:, 1, :], self.k)
vectors = weights * vectors... |
def should_ignore(self, path):
"""
Checks if the given path matches any entry in the ignore list.
"""
for entry in self.custom_ignore_list:
if entry in path:
return True
return False
def process_function(self, session, function_node: ast.FunctionDef, f... | The main task of the code is to process a Python file's Abstract Syntax Tree (AST) by iterating through its nodes, creating graph nodes and relationships for elements like functions, imports, classes, assignments, and return statements. It skips ignored files and uses the provided session to store or update these struc... | def process_tree(self, session, tree: ast.AST, file_path: str) -> None:
"""
Processes the AST of a Python file and creates nodes and relationships based on its structure.
"""
if self.should_ignore(file_path):
return # Skip processing this file
for node in ast.walk(tr... |
def get_row(self):
return self.y // 8
def get_column(self):
return self.x // 8
def at_tile_center(self):
if self.direction == 'up' or self.direction == 'down':
if self.y % 8 == 3:
return True
if self.direction == 'left' or self.direction == 'right':
... | This code controls a ghost's movement and animation in a game, handling transitions between modes (scatter, chase, frightened, eaten), path calculation, teleportation, and image updates. It switches animation frames, determines movement direction based on position and mode, and adjusts the ghost's image accordingly. Th... | def move(self):
# switch image to produce leg animation
self.image_counter += 1
if self.image_counter % 8 == 0:
if self.image_number == 1:
self.image_number = 2
elif self.image_number == 2:
self.image_number = 1
# if leaving ghost ... |
def bytesubstitution(text, box_name):
l = []
for i in range(len(text)):
hex_value = str(hex(text[i]))
if len(hex_value) == 4:
index1, index2 = eval("0x" + hex_value[-2]), eval("0x" + hex_value[-1])
else:
index1, index2 = 0, eval("0x" + hex_value[-1])
l.app... | This function decrypts a cipher image block using a key through multiple rounds of inverse AES operations, including inverse substitution, permutation, and mix columns, progressively shortening the key in each iteration to finalize decryption. | def __decrypt_img_block(self, cipher_img):
dupe_key = self.key
text = bytesubstitution(inv_permutation(key_xor(cipher_img, dupe_key[-4:])), "inv_s_box")
dupe_key = dupe_key[:-4]
for _ in range(9):
text = bytesubstitution(inv_permutation(inv_mix_columns(key_xor(text, dupe_key[... |
def bytesubstitution(text, box_name):
l = []
for i in range(len(text)):
hex_value = str(hex(text[i]))
if len(hex_value) == 4:
index1, index2 = eval("0x" + hex_value[-2]), eval("0x" + hex_value[-1])
else:
index1, index2 = 0, eval("0x" + hex_value[-1])
l.app... | This function decrypts a block of ciphertext using a key through multiple rounds of inverse operations including key XOR, inverse permutation, inverse substitution, and inverse mix columns. It iteratively reduces the key size, applies transformations to the cipher matrix, and finally converts the decrypted bytes to a h... | def __decrypt_block(self, cipher_matrix):
dupe_key = self.key
text = bytesubstitution(inv_permutation(key_xor(cipher_matrix, dupe_key[-4:])), "inv_s_box")
dupe_key = dupe_key[:-4]
for _ in range(9):
text = bytesubstitution(inv_permutation(inv_mix_columns(key_xor(text, dupe_ke... |
def findCusp(path_tree,v1,v2):
v1_path=shortestPath(path_tree,v1)
#maybe make set if have time? Runtime is currently o(n^2)
v2_path=shortestPath(path_tree,v2)
for vert in v1_path:
if vert in v2_path:
return vert
def findFunnel(path_tree,v1,v2):
funnel = []
cusp = findCusp(pat... | The function `addEdges` processes a polygon's vertices to add edges to a `path_tree` data structure. It iterates through consecutive vertex pairs, retrieves their representations from the `path_tree`, identifies geometric features like cusps and funnels, and updates the tree with these edges using the `edgeParent` meth... | def addEdges(polygon,path_tree):
for i in range(-1,len(polygon)-1):
v1 = polygon[i]
v2 = polygon[i+1]
dict=path_tree.makeDictionary()
v1vert = dict[v1]
v2vert = dict[v2]
cusp = findCusp(path_tree,v1vert,v2vert)
funnel= findFunnel(path_tree,v1vert,v2vert)
... |
def shortest_path_tree(polygon,source):
visited_vertices=[]
makeCCW(polygon)
source_vertex = PathTreeVertex(source)
path_tree = PathTree(source_vertex)
triang = tripy.earclip(polygon)
vertices_number = vertex_dict(polygon)
right_of_source = polygon[(vertices_number[source]+1)%len(polygon)]
... | The code constructs a visibility graph for a polygon using a shortest path tree rooted at (1,1), calculates distances and edge relationships, generates a triangulation via ear-clip algorithm, and verifies if specific edges exist in the triangulation. It also identifies vertices connected by edges in the triangulation a... | def test():
polygon = [(0, 0), (0, 3), (1, 3), (1, 1),(3,1),(3,0)]
# print(tripy.earclip(polygon))
tree=shortest_path_tree(polygon,(1,1))
addEdges(polygon,tree)
tree.print()
tree.addLengths()
print(tree.root.childlist)
print("Root's max dist is",tree.root.far_length)
print("Root's ... |
def remove_player(names_list):
display_players_list(names_list)
num = int(input("Select the number of the player to remove: "))
if num < len(names_list):
names_list.pop(num)
display_players_list(names_list)
return names_list
def too_few_players_check(names_list):
while len(names_list)<2:... | The function repeatedly removes players from the input list using remove_player(), checks if the remaining players meet the minimum requirement with too_few_players_check(), and continues looping until no further removals are needed (determined by remove_player_bool()). It returns the final list after all valid removal... | def remove_players_loop(names_list):
remove_name_bool = True
while remove_name_bool:
names_list=remove_player(names_list)
names_list = too_few_players_check(names_list)
remove_name_bool = remove_player_bool()
return names_list |
def get_names_list():
names_str = input("Please list the names of the players, separated by commas: ")
names_list = names_str.split(",")
for i in range(len(names_list)):
name = names_list[i]
if name[0]==' ':
names_list[i]=name[1:]
names_list = too_few_players_check(names_list... | The main task of the code is to allow users to interactively edit a list of player names by adding or removing entries until they confirm the list is correct. It retrieves an initial list, displays it, and loops through modification steps (removing or adding players) based on user input, updating the list each time. On... | def get_players_names():
names_list = get_names_list()
display_players_list(names_list)
all_correct_bool = helper.yes_no_question('Is this correct?')
while not all_correct_bool:
if remove_player_bool():
names_list = remove_players_loop(names_list)
if add_new_player_bool(... |
def __add_reaction(self, attrs):
'''Add reaction.'''
self.__reaction = utils.add_reaction(self.__model, attrs['name'])
self.__kinetic_law = self.__reaction.createKineticLaw()
def __add_protein(self):
'''Add protein.'''
species_id = utils.get_id(self.__uniprot_id)
if not ... | This code processes XML elements during parsing, identifying and handling specific tags like 'experiment', 'protein', 'dataset', etc. It extracts attributes, sets document IDs, and triggers methods to add data such as reactions, proteins, small compounds, and kinetic parameters to the document structure. | def startElement(self, name, attrs):
self.__start = True
self.__element_name = name
if name == 'experiment':
self.__document.setId(attrs['strendaId'])
elif name == 'assayConditions':
self.__parent = name
elif name == 'protein':
self.__unipro... |
def get_elements(listing, webstyle):
i = 3
element_list = []
while i < len(webstyle):
if webstyle[i] != "ex":
depth = int(webstyle[i+1])
html = webstyle[i]
comma = html.find(",")
colon = html.find(":")
element = html[:comma]
id_... | The function processes a list of HTML elements by filtering and formatting them based on a query, web style, URL, and website. It checks for valid elements, applies formatting, filters results, and collects valid entries into a list for return. | def get_listings(all_listings, webstyle, url, query, website):
all_listing_elements = []
for listing in all_listings:
if type(listing) is not bs4.element.Comment and type(listing) != 'NoneType':
listing_elements = get_elements(listing, webstyle)
listing_elements = format_elements... |
def update_queries(queries_cursor):
time.sleep(10)
global latest_query_id
current_high_id = queries_cursor.execute('''SELECT MAX(id) from queries;''').fetchone()[0]
if current_high_id != None and current_high_id > latest_query_id:
new_queries = queries_cursor.execute('''SELECT * from queries whe... | The main task of the code is to periodically update query data, remove outdated listings, and clean up the database of removed queries every 10 minutes using an infinite loop. It connects to an SQLite database, executes updates, and maintains data consistency by synchronizing queries and listings. | def listing_and_query_checker():
queries_conn = sqlite3.connect('data/queries.db')
queries_cursor = queries_conn.cursor()
while True:
time.sleep(600)
update_queries(queries_cursor)
remove_listings()
clean_removed_queries(queries_cursor) |
def get_new_header_and_proxy():
global current_header, current_proxy
f = open("data/Chrome.txt", "r")
number = random.randint(0, 841)
i = 0
while i < number:
if i == number -1:
selected_header = f.readline()
current_header["User-Agent"] = selected_header[:len(selected... | The code scrapes a webpage by handling proxy errors and retries, then extracts listings using BeautifulSoup and returns processed data based on the query and website style. | def run_scrape(query, webstyle, url, website):
global current_header, current_proxy, default_header
attempt_counter = 0
while True:
time.sleep(1)
try:
res = requests.get(url, headers=current_header, proxies=current_proxy)
res.raise_for_status()
if res.stat... |
def format_url(link, query):
page_number_loc = link.find("%d")
link = str(link)
query[1] = str(query[1])
if page_number_loc == -1:
return link % (query[1])
if link.find("%s") < page_number_loc:
return link % (query[1], 1)
else:
return link % (1, query[1])
def run_scrape(q... | This function scrapes new listings by formatting a URL based on the query, extracting data via scraping, and adding the result to a database if the listing ID doesn't already exist. | def initial_scrape_new_listing(query):
webstyle = webstyles[query[2]]
formated_link = format_url(webstyle[0], query)
data = run_scrape(query, webstyle, formated_link, query[2])
if check_id_existance(query[0]):
add_listing_to_db(query[0], query[2], data) |
def run_scrape(query, webstyle, url, website):
global current_header, current_proxy, default_header
attempt_counter = 0
while True:
time.sleep(1)
try:
res = requests.get(url, headers=current_header, proxies=current_proxy)
res.raise_for_status()
if res.stat... | The function `cycle_through_pages` scrapes data from multiple pages of a website by cycling through page numbers (1–4), using URL placeholders (`%d` for page numbers, `%s` for query terms). It checks if an ID already exists in the database before adding new listings, with random delays between requests to avoid overloa... | def cycle_through_pages(query, webstyle):
web_name = query[2]
i = 1
page_number_loc = webstyle[0].find("%d")
if page_number_loc == -1:
url = webstyle[0] % query[1]
data = run_scrape(query, webstyle, url)
if check_id_existance(query[0]):
add_listing_to_db(query[0], dat... |
def get_or_guess_labels(model_fn, x, y=None, targeted=False):
"""
Helper function to get the label to use in generating an
adversarial example for x.
If 'y' is not None, then use these labels.
If 'targeted' is True, then assume it's a targeted attack
and y must be set.
Otherwise, use the model's predictio... | This function performs the Carlini-Wagner L2 adversarial attack by iteratively finding minimal perturbations to deceive a neural network. It validates input bounds, scales data, initializes search parameters, and uses binary search with gradient ascent to optimize the attack. The code tracks best results, adjusts searc... | def _attack(self, x):
if self.clip_min is not None:
if not np.all(tf.math.greater_equal(x, self.clip_min)):
raise CarliniWagnerL2Exception(
f"The input is smaller than the minimum value of {self.clip_min}r")
if self.clip_max is not None:
if not np.all(tf.math.less_equal(x, self.... |
def advance_wavelet_filter(wtfname, j):
"""
advance_wavelet_filter -- Calculate the advance of the wavelet filter at jth level for a given wavelet.
NAME
advance_wavelet_filter -- Calculate the advance of the wavelet filter at jth level for a given wavelet.
INPUTS
wtfname = strin... | The function `cir_shift` circularly shifts MODWT wavelet and scaling coefficients to align them with the original data series. It adjusts each level's wavelet coefficients using calculated shifts and boundary indices, ensuring proper alignment. For scaling coefficients, it optionally subtracts the mean and applies a ci... | def cir_shift(WJt, VJ0t, subtract_mean_VJ0t=True):
"""
shift_modwt_coef -- shift the MODWT wavelet and scaling coefficients.
NAME
shift_modwt_coef -- Shift the MODWT wavelet and scaling coefficients.
INPUTS
WJt = JxN dwtArray of MODWT wavelet coefficents
... |
def isSExpression(listItem):
return listItem and listItem[0] == "(" and "." not in listItem
def buildListItems(listString):
index = 1
listItems = []
while index < len(listString) - 1:
[listItem, i] = getNextListItem(listString, index)
if listItem:
listItems.append(listItem)
... | The main task of the code is to recursively convert a list of items into a string representation of an S-expression. It processes each item, adding parentheses and periods, and handles nested S-expressions by recursively calling itself. The result is a nested Lisp-like syntax string with proper bracketing and element s... | def buildSExpression(listItems):
sExpression = ""
i = 0
for listItem in listItems:
sExpression += "("
if isSExpression(listItem):
sExpression += buildSExpression(buildListItems(listItem))
else:
sExpression += listItem
sExpression += "."
i += ... |
def sync_age_report(analytics,VIEW_ID,day):
data = get_age_report(analytics,VIEW_ID[2],day)
data = print_response(data)
save_age_report(data,VIEW_ID,day)
def sync_browser_report(analytics,VIEW_ID,day):
data = get_browser_report(analytics,VIEW_ID[2],day)
data = print_response(data)
save_browser_report(data,V... | The main task of the code is to synchronize multiple Google Analytics reports for a specified view and day. It triggers functions to sync data on age, browser, default channel, gender, user sessions, device usage, and page views, consolidating analytics into a structured format for further processing or analysis. | def sync_google_account(analytics,VIEW_ID,day):
sync_age_report(analytics,VIEW_ID,day)
sync_browser_report(analytics,VIEW_ID,day)
sync_default_channel_report(analytics,VIEW_ID,day)
sync_gender_report(analytics,VIEW_ID,day)
sync_user_session_report(analytics,VIEW_ID,day)
sync_device_report(analyt... |
def get_google_entity():
cursor = connection.cursor()
# server 1
# pg_select = """ select * from consultancy_integrations."alex_ga_tracking_id" limit 10 OFFSET 1 """
# server 2
pg_select = """ select * from consultancy_integrations."alex_ga_tracking_id" limit 3 OFFSET 51 """
# server 3
# pg_select = """ ... | The main task of the code is to process Google Analytics data for multiple entities over a specified date range (2020-01-01 to 2021-03-29). It iterates through each entity, syncs data for every day in the range using the Google Analytics API, and closes associated workbook files containing metrics like page views, user... | def main():
google_entity = get_google_entity()
sdate = date(2020, 1, 1)
edate = date(2021, 3, 29)
delta = edate - sdate
for entity in google_entity:
print('--------------------------------------')
print(entity[4])
for i in range(delta.days + 1):
dayRange = sdate + timedelta(days=i)
... |
def get_cell_ids(self) -> List[int]:
return [cell.id for cell in self.cells]
def exec_gravity(self, cell: Cell) -> List[CellChange]:
# If the cell under cell is empty, the cell under cell becomes the cell.
newY = cell.y
while newY - 1 >= 0 and self.get_cell(cell.x, newY - 1).id is None:
... | The main task of the code is to repeatedly apply gravity and neighbor-based game rules to all cells until no further changes occur, collecting all resulting cell changes in a list. It iterates until the set of cell IDs stabilizes, ensuring all dynamic updates from both rules are captured and returned as a list of CellC... | def exec_game_rules_all(self) -> List[CellChange]:
before = []
changes: List[CellChange] = []
while self.get_cell_ids() != before:
before = self.get_cell_ids()
for cell in [cell for cell in self.cells]:
if cell.id is not None:
changes... |
def get_query_for_deletion(query_object):
if query_object['KeepLatest']:
return get_query_for_old_records_deletion(query_object)
else:
return get_query_for_all_records_deletion(query_object)
def get_query_for_anonymisation(query_object):
queries = []
sub_queries_targets = set()
for t... | The main task of the code is to handle multiple Athena queries in AWS Lambda. It processes each query based on its 'Action' (Delete/Anonymize), generates the appropriate SQL query using helper functions, executes it via the Athena client, and collects QueryExecutionIds. It returns success with IDs or an exception on fa... | def lambda_handler(event, context):
try:
athena_client = boto3.client('athena', region_name='eu-west-1')
responses = []
for query in event['queries']:
if query['Action'] == 'Delete':
athena_query = get_query_for_deletion(query)
elif query['Action'] ==... |
def refresh_collections(session, uid, per_page):
results, count = Collection.search(session=session, uid=uid, order_by="name")
max_page = ceil(count / per_page) - 1
if (max_page < 0):
max_page = 0
return results, count, max_page
def single_collection_view(session, cid):
results, count = Coll... | The main task of the code is to display a user's collections in paginated format, allowing navigation between pages, viewing specific collections, creating new collections, and handling commands. It uses `refresh_collections` to fetch data, displays entries per page, and updates the list dynamically when collections ar... | def view_collections(session, current_user):
uid = current_user.uid
per_page = 15
results, count, max_page = refresh_collections(session, uid, per_page)
cur_page = 0
while (True):
# Print the current page
if(count == 1):
print("You have " + str(count) + " collection.")
... |
def draw_tyre_grip_loss(window: pygame.Surface, x: int, y: int, as_lost_grip: bool):
"""
Function that draw the tyre outline representing the grip of the tyre.
:param window: window where the tyre grip loss indicator will be drawn.
:param x: x coordinate of the tyre widget.
:param y: y coordinat... | The function `draw_tyre_widget` renders a tyre monitoring UI element on a Pygame window, displaying three key metrics: grip status (via `draw_tyre_grip_loss`), tyre wear percentage (via `draw_tyre_wear`), and temperature (via `draw_tyre_temp_gauge`). It uses input parameters like position coordinates, tyre temperature,... | def draw_tyre_widget(window: pygame.Surface, x: int, y: int, tyre_temp: float, tyre_wear: float, as_lost_grip: bool):
"""
Function that draw the entire tyre widget for one tyre.
:param window: window where the tyre widget will be drawn.
:param x: x coordinate of the tyre widget.
:param y: y coor... |
def check_user(chat):
user = get_user(chat)
if user and user.activated and not user.banned:
sr.remove()
return True
elif user is None:
add(sr(), models.User(id=chat.id, name=chat.name,
username=chat.username))
sr.remove()
chat.send((
... | The main task of the code is to handle user interaction by checking if the user is valid (via check_user(chat)), then sending a help message ("How can I help you?") along with a menu generated by the menu() function. It appears to be part of a command system for a chatbot or application, prompting users for further inp... | def info_command(chat, message, args):
"""
all the small things
"""
if not check_user(chat):
return
chat.send("How can I help you?", attach=menu(user=get_user(chat)))
sr.remove() |
def check_user(chat):
user = get_user(chat)
if user and user.activated and not user.banned:
sr.remove()
return True
elif user is None:
add(sr(), models.User(id=chat.id, name=chat.name,
username=chat.username))
sr.remove()
chat.send((
... | The function `pay_command` handles user debt payment requests by checking user validity, calculating their total invoice amount, and prompting them to transfer the debt (if ≥5 Tomans) to a specified card, followed by submitting a receipt photo. If the debt is under 5 Tomans, it informs the user payment isn't required. ... | def pay_command(chat, message, args):
"""
pay your debt here :P
"""
if not check_user(chat):
return
user = get_user(chat)
total, _ = total_invoices(user)
card = db_query(sr(), models.Info,
models.Info.title == 'card'
, one=True)
if total >... |
def check_user(chat):
user = get_user(chat)
if user and user.activated and not user.banned:
sr.remove()
return True
elif user is None:
add(sr(), models.User(id=chat.id, name=chat.name,
username=chat.username))
sr.remove()
chat.send((
... | This function manages user VPN credentials by either adding new ones via command arguments or displaying existing credentials along with a menu if they exist. If no credentials are found, it prompts the user to provide a username and password using the `/vpn` command format. | def vpn_command(chat, message, args):
"""
manage your vpn here
"""
if not check_user(chat):
return
if len(args) > 0:
return add_vpn(chat, message, args)
user = get_user(chat)
if user.vpn_username and user.vpn_password:
chat.send("Check out info menu!", attach=menu(u... |
def _kmeans(self, k: int) -> None:
"""
k: number of clusters.
Computes k means clustering for values in self.data.
"""
if not k>0:
raise ValueError("k must be greater than 0")
self.clear()
for _ in range(k): # initialize centroids
centroid = self._getRandomCentroid()
self._add(centroid)
for... | The function `_optimalPartition` generates multiple k-means clustering configurations by running k-means `self.samples` times, each time with a fresh initialization. It evaluates each configuration's cost, retaining the one with the lowest valid cost. The goal is to identify the optimal clustering configuration for a g... | def _optimalPartition(self, k: int) -> dict:
"""
k: number of clusters.
Gets self.sample number of kmeans configurations and returns the optimal configuration.
"""
samples = []
for i in range(self.samples):
self.clear()
self._kmeans(k)
samples.append(self._simpleCopy())
initialized = False
opt... |
def checkRange():
"""
Post: Function tests the scores to see if they are between 0-100
"""
data = generateClusters(50, 3, 1, 3)
myClusters = Clusters(data, 2)
scores = myClusters.orderedScores
l = len(scores)
count = 0
try:
for i in range(l):
if(scores[i] <= 100 and scores[i] >= 0):
count += 1
Clus... | The main task of the code is to execute a series of tests, checking if scores range from 0 to 100, handling of k=0, negative k values, and empty clusters. It appends "PASSED" or "FAILED" (or "NEGATIVE" for some cases) to a list based on the test outcomes, then prints the results. The function concludes by displaying "D... | def main():
"""
Post: Runs the main function that prints out the results of the test
"""
#k=None
print("Testing...")
completed = []
print("completed")
if checkRange() == 1:
completed.append("Check if scores range from 0 to 100: PASSED")
else:
completed.append("Check if scores range from 0 to 100: FAILED")... |
def _optimalPartition(self, k: int) -> dict:
"""
k: number of clusters.
Gets self.sample number of kmeans configurations and returns the optimal configuration.
"""
samples = []
for i in range(self.samples):
self.clear()
self._kmeans(k)
samples.append(self._simpleCopy())
initialized = False
opt... | This function automatically determines the optimal number of clusters (k) by evaluating silhouette coefficients for varying k values. It iterates through k from 2 to maxK, computes optimal partitions, and adjusts k based on score differences and thresholds. If scores improve, it updates the pivot; if scores degrade wit... | def _autoSolve(self) -> None:
"""
Pre: k==None.
Solves to produce clusters from data if k not selected by computing silhouette coefficients.
"""
pivot = None
optimal = None
for k in range(2, self.maxK+1): # testing configurations for values of k
if k > 2: # store current configuration as previous
... |
def dist(pt1: np.ndarray, pt2: np.ndarray) -> np.float64:
"""
Returns euclidean distance of pt1 and pt2.
"""
return np.sqrt(np.sum((pt2-pt1)**2))
def _solve(self) -> None:
"""
Pre: not already solved.
Post: becomes solved.
Solves to produce clusters from data.
"""
if self.k is not None:
self._sin... | This code initializes a clustering model to automatically determine optimal clusters (if k is unspecified) by configuring parameters like maxK, convergence thresholds, and data bounds. It validates inputs, sets up data structures for clustering, and prepares for iterative optimization using methods like _solve() and _g... | def __init__(self, data: np.ndarray, k: int=None, maxK: int=10, maxIterations: int=50, samples: int=10, alpha: float=0.85, accuracy: int=4) -> None:
"""
data: nth dimensional data to be clustered.
k: target number of clusters. If k=None, k will be automatically selected.
maxK: the maximum value of k that can be... |
def getCandidates(f):
try:
candidatelist = open(f,'r').read().strip().split('\n')
return candidatelist
except IOError:
print('%s not found'%f)
return []
def getPapers(f,n):
try:
paperlist = open(f,'r').read().strip().split('\n')
i = 0
for i in range(le... | The main task of the code is to process election votes by reading candidate and vote lists from files, separating formal and informal votes, normalizing the formal votes, and counting the votes for each candidate in a Nerdvanian election, then displaying the results including the number of informal and formal votes. | def main():
candidates = getCandidates(input('Enter candidate list file as <filename.txt>: '))
papers = getPapers(input('Enter vote list file as <filename.txt>: '), len(candidates))
papervotes = []
informal = []
for vote in papers:
if vote[0] != []:
papervotes.append(vote[0])
... |
def getCandidates(f):
try:
candidatelist = []
with open(f) as file:
for line in file:
candidatelist += line.strip().split('\n')
for i in range(len(candidatelist)):
candidatelist[i] = [candidatelist[i],[]]
return candidatelist
except IOError... | The code processes election data by reading candidate and ballot files, formalizing valid votes, conducting the election to determine a winner, and printing results including the winner and count of informal votes. | def main(candidatesfile,ballotsfile,optional=False):
candidates = getCandidates(candidatesfile)
papers = getPapers(ballotsfile,len(candidates),optional)
formalvotes = formalisevotes(padvotes([paper for paper in papers if paper != []],len(candidates)))
countvotes(candidates,formalvotes)
winner,formal... |
def get_config(self):
"""Get configuration file for image generations
Returns
----------
str
string of the filepath to the configuration
"""
config_url = os.environ.get("CONFIG_URL")
config_name = self.config['collection']['name']
config_bucket... | The main task of the code is to generate images for each granule's files using a configuration file, append the generated images to the granules' file lists, and return the modified input dictionary containing updated granules with their new images. The process includes logging AWS request details, downloading palette ... | def process(self):
"""Main process to generate images for granules
Returns
----------
dict
Payload that is returned to the cma which is a dictionary with list of granules
"""
config_file_path = self.get_config()
granules = self.input['granules']
... |
def get_lon_lat(self, param_group=None):
"""
Function to get the longitude masked array and latatiude masked array
Returns
-------
return a longitude and latitude masked array
"""
group, _, lon_var = self.config['lonVar'].rpartition('/')
_, _, lat_va... | The main task of the code is to generate images for each configured variable in a NetCDF file, handling parameters like image format, alpha channels, and geographic boundaries. It calculates output dimensions based on longitude/latitude arrays, processes variables with overrides, and returns a list of dictionaries cont... | def generate_images_group(self, image_format='png', world_file=False, granule_id="", group=None):
"""
Generates images for each configured variable in a NetCDF file.
Parameters
----------
image_format : string
Any output image formatted supported by matplotlib
... |
def get_quat_tan(fun_pos_x, fun_pos_y, fun_pos_z, idx, axis, frm):
"""
Function to obtain a quaternion that
aligns an axis with the tangent of a function.
"""
v_axis = AXIS[axis]
tan = [get_tan(fun_pos_x, frm), get_tan(fun_pos_y, frm), get_tan(fun_pos_z, frm)]
return get_quaternion(v_axis... | The function computes a quaternion to align a specified axis with the tangent of a function's curve and adjusts the up axis direction. It first calculates a quaternion to orient the tangent, then computes a secondary quaternion to align the up vector with the curve's lateral direction, combining them to return the fina... | def get_control_dir(fun_pos_x, fun_pos_y, fun_pos_z, idx, axis, up_axis, frm):
"""
Function to obtain a quaternion that
aligns an axis with the tangent of a function and with its up axis.
"""
v_axis = Vector(AXIS[axis])
v_up_axis = Vector(AXIS[up_axis])
# First quaternion to orient to tang... |
def _get_plugins_to_execute(self, profile: str | None, plugins: str | None) -> List[str]:
plugins_to_execute = self._read_plugins_from_profile(profile)
if len(plugins_to_execute) > 0:
print(f'Using plugins specified in profile: [{profile}]')
return plugins_to_execute
plu... | The main task of the code is to determine the execution order of plugins based on input parameters (profile, plugins list, or default registration order) and either print the plugin list or execute them. It prioritizes profile-defined order, then explicit plugin lists, then default registration, with an option to exit ... | def build(self, profile: str | None = None, plugins: str | None = None, list_plugins=False):
"""
Execute the build plugins in the specified order. The order in which the plugins will be executed will be
determined in the following way.
1. If the profile argument is present then lookup t... |
def function_generator(targ):
num = 0
for a in targ:
for b in targ:
for c in targ:
num += 1
yield (a, b, c, num)
def get_truths(a, b, c, targ):
return is_1to1(a, b, c), is_onto(a, b, c, targ), is_biject(a, b, c, targ)
def numstr(num, x):
return "f" + s... | The code analyzes functions generated by `function_generator(targ)` to determine if they are one-to-one (injective), onto (surjective), or bijective. It counts occurrences of each property and prints detailed results for each function, including parameters, property checks, and formatted output. | def print_funcs(targ):
count_oto = 0
count_onto = 0
count_bi = 0
for i in function_generator(targ):
a, b, c, num = i
oto, onto, bi = get_truths(a, b, c, targ)
if oto:
count_oto += 1
if onto:
count_onto += 1
if bi:
count_bi += 1
... |
def getMinimunResolutionOfShapeSets( shapesSet ):
"""
Get minimun resolution on a set of shapes.
"""
min_shape = ''
minResolution = sys.maxsize
for shape in shapesSet:
resolution = shape[ 0 ] * shape[ 1 ]
if resolution < minResolution:
minResolution = resolution
min_shape = shape
if len(min_shape) == 3... | This code processes a flower dataset to prepare it for neural network training by splitting images into color channels (R, G, B), resizing them to varying dimensions, and merging them into combinations (e.g., RG, RGB). It identifies the smallest image resolution across the dataset, rebuilds channel-specific datasets, a... | def main( ):
# Set paths.
root_path = '../../../datasets/flower_photos'
sub_sets = [ '/training', '/test', '/validation' ]
source_set = SOURCE
flowers = [ '/daisy', '/dandelion', '/roses', '/sunflowers', '/tulips' ]
channels = [ 'R', 'G', 'B' ]
# Create a combinational list of channels of the form: ['R', 'G', ... |
def setMaxRange(self, range):
self.CLIport.write(('sensorStop\n').encode())
time.sleep(0.01)
print('sensorStop\n')
idx = [i for i, s in enumerate(self.config) if "frameCfg" in s][0]
temp = self.config[idx].split(" ")
frameTime = np.min([float(temp[5]) * 1e3, 50e3])
... | This code optimizes sensor range parameters by evaluating radar detection performance across 10 range intervals. It iterates through each range, initializes sensor settings, captures radar data, generates heat maps from detected objects, calculates average signal intensity scores, and stores results to identify optimal... | def optimize(self, range_interval, eval_range):
detection_range = np.linspace(range_interval[0], range_interval[1], 10)
score = np.zeros(10)
for i in range(10):
self.byteBuffer = np.zeros(2 ** 15, dtype='uint8')
self.byteBufferLength = 0
self.setMaxRange(dete... |
def convert_nn_layers_parameter_list(hidden_layer_sizes_list):
string_hidden_layer_size = []
for i in hidden_layer_sizes_list:
string_hidden_layer_size.append(convert_nn_layers_parameter(i))
return string_hidden_layer_size
def convert_boosting_base_estimator_parameters_list(base_estimator_parameters... | This function generates a model complexity curve for a single parameter from grid search results, plotting training and cross-validation scores with error bars. It processes parameter values (including lists/classifiers), filters data based on optimal parameters, and saves the visualization with dataset/algorithm metad... | def plot_grid_search_model_complexity_1param(gs_results, plot_param, PLOT_SAVE_LOCATION, ALGO, DATASET, unused_params_value_dict=None, tick_spacing=1, text_wrap_len=30, ylim=None, figsize=default_figure_size, legend_loc='best', dt_param=""):
"""
References:
https://stackoverflow.com/questions/37161563/how-t... |
def convert_nn_layers_parameter_list(hidden_layer_sizes_list):
string_hidden_layer_size = []
for i in hidden_layer_sizes_list:
string_hidden_layer_size.append(convert_nn_layers_parameter(i))
return string_hidden_layer_size
def convert_boosting_base_estimator_parameters_list(base_estimator_parameters... | The main task of the code is to visualize model complexity curves for each hyperparameter in a grid search, plotting training and test scores with their standard deviations. It filters results based on the best parameters, handles specialized parameter types, and generates subplots with labeled axes, titles, and saved ... | def plot_grid_search_model_complexity(gs_results, PLOT_SAVE_LOCATION, ALGO, DATASET, unused_params_value_dict=None, tick_spacing=None, text_wrap_len=30, ylim=None, dt_param=""):
"""
References:
https://stackoverflow.com/questions/37161563/how-to-graph-grid-scores-from-gridsearchcv
https://stackoverflow.... |
def convert_nn_layers_parameter_list(hidden_layer_sizes_list):
string_hidden_layer_size = []
for i in hidden_layer_sizes_list:
string_hidden_layer_size.append(convert_nn_layers_parameter(i))
return string_hidden_layer_size
def convert_boosting_base_estimator_parameters_list(base_estimator_parameters... | The function generates a plot visualizing the training and prediction times of a machine learning model's grid search results, varying one parameter (plot_param) while keeping other parameters fixed at their optimal values. It plots mean times with standard deviation error bars, labels axes, applies formatting, and sav... | def plot_grid_search_training_times_1param(gs_results, plot_param, PLOT_SAVE_LOCATION, ALGO, DATASET, unused_params_value_dict=None, tick_spacing=None, text_wrap_len=30, ylim=None, figsize=default_figure_size, dt_param=""):
"""
References:
https://stackoverflow.com/questions/37161563/how-to-graph-grid-score... |
def convert_nn_layers_parameter_list(hidden_layer_sizes_list):
string_hidden_layer_size = []
for i in hidden_layer_sizes_list:
string_hidden_layer_size.append(convert_nn_layers_parameter(i))
return string_hidden_layer_size
def convert_boosting_base_estimator_parameters_list(base_estimator_parameters... | The function visualizes training and prediction times from grid search results, plotting mean times with error bars for each parameter combination. It filters results using best parameters, creates subplots per parameter, labels axes, and saves the plot with dataset/algorithm identifiers. The plot shows time variations... | def plot_grid_search_training_times(gs_results, PLOT_SAVE_LOCATION, ALGO, DATASET, unused_params_value_dict=None, tick_spacing=None, text_wrap_len=30, ylim=None, dt_param=""):
"""
References:
https://stackoverflow.com/questions/37161563/how-to-graph-grid-scores-from-gridsearchcv
https://stackoverflow.co... |
def convert_nn_layers_parameter_list(hidden_layer_sizes_list):
string_hidden_layer_size = []
for i in hidden_layer_sizes_list:
string_hidden_layer_size.append(convert_nn_layers_parameter(i))
return string_hidden_layer_size
def convert_boosting_base_estimator_parameters_list(base_estimator_parameters... | The main task of the code is to visualize the relationship between model parameters and grid search performance, plotting mean test/train scores with error bars and computation times for each parameter. It generates subplots showing accuracy trends and time metrics, filtering results by optimal parameter values, and sa... | def plot_grid_search_model_complexity_and_training(gs_results, PLOT_PREFIX, unused_params_value_dict=None, tick_spacing=1, dt_param=""):
"""
References:
https://stackoverflow.com/questions/37161563/how-to-graph-grid-scores-from-gridsearchcv
https://stackoverflow.com/questions/37161563/how-to-graph-grid-... |
def create_config(env=None):
if env is None:
env = env_location()
if not os.path.exists(os.path.dirname(env)):
os.mkdir(os.path.dirname(env))
if 'EMAIL' in os.environ:
email = os.environ['EMAIL']
else:
email = input("Enter your Foliobutler Email: ")
if 'API_KEY' in o... | The main task of the code is to initialize or manage a Foliobutler configuration environment. It checks if the environment file exists, creates it if necessary, and prompts for credentials. Depending on the action, it either initializes the config, adds an account, or syncs folio data using API credentials. It handles ... | def starter(env, action, ip, port):
if action.lower() == 'init':
return create_config(env)
if not os.path.exists(os.path.dirname(env)):
logging.error("Enviroment Path not exists: " + os.path.dirname(env))
if click.confirm('Do you want to create the folder?', default=True):
o... |
def choose_action(state, epsilon):
"""
Return action according to an epsilon-greedy exploration policy
"""
q_values = get_q([state])
if random.random() < epsilon:
action = random.randint(0, n_actions-1) / 10
print(f"Chosen risk level : {action}")
return action
else:
... | This code trains a reinforcement learning agent (DQN) to play a guessing game by iteratively choosing actions, updating the model based on rewards, and adjusting exploration (epsilon) over episodes. It evaluates performance periodically, updates the target network, and terminates training if the reward threshold is met... | def train():
nb_guesses = 0
nb_good_guesses = 0
state = [8, 7, 9, 0]
epsilon = EPSILON_START
ep = 0
total_time = 0
game = Game(codemaster,
guesser,
seed=time.time(),
do_print=False,
do_log=False,
game_name='train_risk_rl',
... |
def choose_clue(self, state, epsilon, avoid=[]):
"""
Return action according to an epsilon-greedy exploration policy
"""
if np.random.uniform()<epsilon:
index = np.random.randint(0, len(self.clues))
return index, 0
else:
q=self.get_q([state])[0... | The code trains a Q-network using Deep Q-Learning to optimize word-guessing strategies. It iterates through episodes, selects actions with an epsilon-greedy policy, updates the network via gradient descent, and decreases exploration rate (epsilon) over time. The agent evaluates its performance periodically, stopping ea... | def train(self):
epsilon = EPSILON_START
ep = 0
total_time = 0
losses = []
# objective and optimizer
objective = nn.MSELoss()
optimizer = optim.SGD(params=self.q_net_codemaster.parameters(), lr=LEARNING_RATE)
while ep < N_EPISODES:
rewards = [0... |
def Bisection_Method(my_f,start_point,end_point,epsilon):
x = sp.symbols('x')
f = my_f
f = lambdify(x, f)
temp = start_point
index = 0
A = [-1]*10
i = 1
g = 0
result = 0
print("i x f(x)")
while(start_point <= end_point) :
if i... | The code defines a mathematical function `my_f` composed of exponential, logarithmic, and polynomial terms. It allows user selection of a root-finding method (Bisection, Newton-Raphson, or Secant) to solve `my_f(x) = 0` within a specified interval [0, 1.5], using a given precision `epsilon`. The function is structured ... | def main():
x = sp.symbols('x')
# my_f = (math.pow((2 * x * math.e), -x) + math.log(2, 2 * math.pow(x, 2))) * (
# 2 * (math.pow((x, 3))) + 2 * (math.pow((x, 2))) - 3 * x - 5)
# my_f = x ** 4 + x ** 3 - 3 * x ** 2
log = math.log
e = math.e
a = lambda x: 2 * x * (e ** (-x))
b = l... |
def Newton_Raphson (my_f,start_point,end_point,epsilon):
x = sp.symbols('x')
f = my_f
f = lambdify(x, f)
A = [-1] * 20
index = 0
i = 1
x = 0.1
temp_start = start_point
temp_end = start_point + x
while round(temp_end,2) <= round(end_point,2):
result = (temp(my_f, temp_star... | The code's main task is to solve a nonlinear equation using either Newton-Raphson or secant method, and compute the integral of a complex function over [0.5, 1.0] using Romberg and Simpson's methods, with user-selected numerical techniques for root-finding and integration. | def main():
x = sp.symbols('x')
start_point = 0
end_point = 1.5
epsilon = 0.00001
my_f = (2 * x * math.e ** -x + sp.ln(2 * x ** 2)) * (2 * x ** 3 + 2 * x ** 2 - 3 * x - 5)
check = input("choose option: 1 to Newton_Raphson, 2 to secant_method ")
if check == '1':
Newton_Raphson(my_f, ... |
def linarit(A,P):
y1 = 0
y2 = 0
x1 = 0
x2 = 0
for i in range(len(A)-1):
if P > A[i][0] and P < A[i+1][0]:
y1 = A[i][2]
y2 = A[i+1][2]
x1 = A[i][1]
x2 = A[i+1][1]
result = (y1 - y2)*P/(x1 -x2) + (y2*x1 - y1*x2) / (x1 - x2)
return result... | The code's main task is to perform interpolation calculations using different methods (linear, polynomial, Lagrange, Neville) on a given dataset A at point P=1.28, based on user input. It prompts the user to select an interpolation method, applies the chosen algorithm to approximate the value at P, and outputs the roun... | def main():
A = [[1, 1.2, 0.112463],
[2, 1.3, 0.167996],
[3, 1.4, 0.222709]]
P = 1.28
check = input("choose option: 1 to linarit, 2 to polinomit, 3 to lagranz, 4 to nevil ")
if check == '1':
print(round(linarit(A, P),4))
elif check == '2':
print(round(polinomit(A... |
def ask_if_mulitple_folders():
global ANSWER_MULTIPLE_FOLDERS
get_path()
if_multiple = str(input('Are there multiple folders inside?: '))
if if_multiple in POSSIBLE_ANSWERS_MULTIPLE_FOLDERS:
ANSWER_MULTIPLE_FOLDERS = if_multiple
print(ANSWER_MULTIPLE_FOLDERS)
else:
ask_if_mul... | The code processes user input to perform specific string operations on a file path. It checks if multiple folders are involved and applies transformations like removing spaces, trimming characters, or modifying strings based on user-selected options, either for a single path or multiple folders. | def run():
ask_if_mulitple_folders()
ask_question()
if ANSWER_MULTIPLE_FOLDERS == 'n':
if ANSWER == '5':
remove_spaces(GIVEN_PATH)
elif ANSWER == '4':
remove_unnecessary_chars_ending(GIVEN_PATH)
elif ANSWER == '3':
remove_unnecessary_chars_beginnin... |
def if_multiple_folders():
global multiple_folders
prompt = str(input('Are there multiple folders inside the given path? (y/n): '))
if prompt not in desired_answers:
print('Please only type y or n.\n')
if_multiple_folders()
else:
multiple_folders = prompt
print(multiple_f... | The code's main task is to assess three conditions: whether multiple folders exist, if renaming is required, and if file conversion is needed. It sequentially checks these prerequisites, likely to determine subsequent actions in a file management or processing workflow. | def ask_questions():
if_multiple_folders()
need_to_rename()
need_to_convert() |
def ask_questions():
if_multiple_folders()
need_to_rename()
need_to_convert()
def append_path():
for folder in os.listdir():
global list_images
if multiple_folders == 'y':
os.chdir(f'{images_loc}/{folder}')
for image in os.listdir():
if image.find(... | The main task of the code is to execute three functions sequentially: `ask_questions()` to gather user input, `append_path()` to update a path or log, and `make_pdf()` to generate a PDF document, likely compiling data into a structured format. The overall purpose is to streamline a process involving user interaction, p... | def final():
ask_questions()
append_path()
make_pdf() |
def all_positions(self):
"""A generator that yields the positions in the board.
Yields:
tuple: A position as a :obj:`tuple` of the form (y, x) or
(row, col).
Examples:
The following is an example on how to use ``all_positions`` to
iterate through... | The main task of the code is to search for a given word in a puzzle grid by checking all valid paths from each position. It validates the input word's type, length, and existence, then iterates through possible starting positions and movements to find a sequence of characters matching the word. If found, it returns the... | def find(self, word):
"""Searchs for a ``word`` in the puzzle and gives the positions of the
characters of that word.
Args:
word (str): The word to search in the puzzle.
Returns:
A :obj:`list` of :obj:`tuple` of the form (y, x) containing the
coordin... |
def check_unique_fqns(self):
group_by_fqn: typing.Dict[str, str] = {}
for model in self.models.values():
for attr in model.attributes:
if not attr.ref:
if attr.fqn in group_by_fqn:
self.errors = True
print(
... | This method resolves inter-model references (`ref`/`extends`) after parsing, ensuring uniqueness and detecting cycles. It iteratively resolves dependencies, validates attributes, and establishes hierarchical relationships. Once stable, it converts string-based attribute IDs to actual objects, finalizing model structure... | def finish(self):
""" Resolves values referenced from other models using `ref` and `extends` attributes AFTER all models were parsed.
Here, sanity checks for `ref/extends` attributes are performed.
"""
semconv: SemanticConvention
# Before resolving attributes, we verify that ... |
def setup_parser():
parser = argparse.ArgumentParser(
description="Process Semantic Conventions yaml files."
)
parser.add_argument(
"--debug", "-d", help="Enable debug output", action="store_true"
)
parser.add_argument(
"--yaml-root",
"-f",
metavar="folder",
... | The code processes command-line arguments, parses semantic conventions (semconv) data, and renders it into either code or markdown format based on the specified 'flavor' parameter. It uses a CodeRenderer for code outputs or processes markdown content, generating the specified output file with the given template and pat... | def main():
parser = setup_parser()
args = parser.parse_args()
check_args(args, parser)
semconv = parse_semconv(args, parser)
if args.flavor == "code":
renderer = CodeRenderer.from_commandline_params(args.parameters)
renderer.render(semconv, args.template, args.output, args.pattern)... |
def to_markdown_attr(
self, attribute: SemanticAttribute, output: io.StringIO,
):
"""
This method renders attributes as markdown table entry
"""
name = self.render_attribute_id(attribute.fqn)
attr_type = (
"enum"
if isinstance(attribute.attr_ty... | The main task of the code is to render a Markdown table for a semantic convention (semconv), including attributes, notes, and constraints. It constructs a header with parameters, filters attributes based on context (e.g., group key, full mode), writes table headers and rows, and conditionally includes constraints. The ... | def _render_table(
self, semconv: SemanticConvention, parameters, output: io.StringIO
):
header: str
header = semconv.semconv_id
if parameters:
header += "("
header += ",".join(
par + "=" + val if val else par for par, val in parameters.items()... |
def get_config_dir():
# get the username
user = pwd.getpwuid(os.getuid())[0]
# stich the complete path
config_dir = os.path.join("/home", user, ".config", "netdog")
return config_dir
def write_configuration(config, filename, log=True):
# essential variables
config_dir = get_config_dir()
... | This function stores a server's public key and last known IP address into configuration files. It logs the action, creates a dictionary with server details, writes it to 'known_nodes', and updates 'known_network' with the server ID for tracking. | def store_server_info(message, server_ip):
# essential stuff
config_dir = get_config_dir()
server_id = message["hostname"]
public_key = message["data"]["payload"]
# write to log :)
logging.info("storing public key of server " + server_id)
# prepare data to be written
server_info = {
... |
def get_config_dir():
# get the username
user = pwd.getpwuid(os.getuid())[0]
# stich the complete path
config_dir = os.path.join("/home", user, ".config", "netdog")
return config_dir
def update_configuration(config, filename, force=False):
# read configuration from file
config_from_file = ... | The function accepts a pairing request by storing the client's public key and details in the 'known_nodes' configuration, then returns the server's public key for secure communication setup. | def accept_pairing_request(node_id, node_ip, public_key):
logging.info("pairing request received")
# essential varilables
config_dir = get_config_dir()
# generate node_info dictionary for storing
logging.info("storing public key of client " + node_id)
node_info = {
node_id: {
... |
def get_config_dir():
# get the username
user = pwd.getpwuid(os.getuid())[0]
# stich the complete path
config_dir = os.path.join("/home", user, ".config", "netdog")
return config_dir
def read_configuration(filename):
# essential variables
config_dir = get_config_dir()
config = None
... | The function `send_beacon()` collects system statistics using `conky`, parses them into a structured format, and transmits them as a "beacon" message to a server identified by `server_id` retrieved from the "known_network" configuration file, using port 1337. | def send_beacon():
# get config directory
config_dir = get_config_dir()
# checks
if os.path.exists(os.path.join(config_dir, "known_network")):
known_network = read_configuration("known_network")
if "server_id" in known_network:
# get id of server
server_... |
def get_config_dir():
# get the username
user = pwd.getpwuid(os.getuid())[0]
# stich the complete path
config_dir = os.path.join("/home", user, ".config", "netdog")
return config_dir
def find_hosts(network_info, mode):
# essential variables
node_list = []
host_info = []
ping_thread... | The main task of the code is to initiate a pairing request by retrieving a public key from configuration files, identifying a server host from network information, and sending a "pair" message with the public key to the server's IP address on port 1337. This establishes secure communication by sharing cryptographic cre... | def request_to_pair(network_info):
# get configuration directory
config_dir = get_config_dir()
# find server
server = find_hosts(network_info, mode = "server")
# get the public key
key_pair = read_configuration("keys")
public_key = key_pair["public_key"]
# send pairing request
... |
def read_configuration(filename):
# essential variables
config_dir = get_config_dir()
config = None
config_file_path = os.path.join(config_dir, filename)
# read configuration
if os.path.exists(config_file_path):
with open(config_file_path, "r") as config_file:
config = json.... | The function `pair_if_necessary` handles secure node pairing in a distributed system. It checks if the sender node is already in the known nodes list; if not, it accepts a pairing request, retrieves the server's public key, and sends a "pair_ack" message to establish secure communication. This ensures only unregistered... | def pair_if_necessary(message, node_ip):
# essential variables
sender_id = message["hostname"]
payload = message["data"]["payload"]
known_nodes_info = read_configuration("known_nodes")
# generate node list
if known_nodes_info:
node_list = [node_id for node_id in known_nodes_info]
i... |
def get_config_dir():
# get the username
user = pwd.getpwuid(os.getuid())[0]
# stich the complete path
config_dir = os.path.join("/home", user, ".config", "netdog")
return config_dir
def request_to_pair(network_info):
# get configuration directory
config_dir = get_config_dir()
# find ... | The main task of the code is to ensure a client is paired with a server and notifies the server of IP address changes. It checks if the client is already paired; if not, it initiates pairing. It then compares the last recorded IP address with the current IP address. If they differ, it sends an update message to the ser... | def client_checklist(known_network_info):
# essential variables
config_dir = get_config_dir()
# if no known server, find one and pair
if not os.path.exists(os.path.join(config_dir, "known_nodes")):
# start client pairing request
logging.info("the client is not paired with a server")
... |
def get_config_dir():
# get the username
user = pwd.getpwuid(os.getuid())[0]
# stich the complete path
config_dir = os.path.join("/home", user, ".config", "netdog")
return config_dir
def receive_transmission(connection):
# an empty string for storing data
transmission = ""
while True:... | This function handles incoming client connections by processing commands from the received data. It identifies the sender's IP, checks for valid transmissions, logs connection events, and executes corresponding actions based on the command type (e.g., pairing, executing commands, broadcasting files). It ensures proper ... | def handle_connection(connection):
# essential variables
sender_ip = connection.getpeername()[0]
config_dir = get_config_dir()
# receive data from client
input_transmission = receive_transmission(connection)
if not input_transmission:
logging.info("ping received from " + sender_ip)
... |
def get_config_dir():
# get the username
user = pwd.getpwuid(os.getuid())[0]
# stich the complete path
config_dir = os.path.join("/home", user, ".config", "netdog")
return config_dir
def probe_interfaces():
# essential variables
interface_dict = {}
# list available interfaces and remo... | The function `setup_network` configures network settings based on server/client mode. It retrieves network interfaces, checks for pre-known network info, and waits for server configuration or automatically detects a network for clients. If server, it initiates a beacon database cleanup thread; otherwise, it performs cl... | def setup_network(server=False):
# essential variables
config_dir = get_config_dir()
interface_dump = probe_interfaces()
known_network_info = read_configuration("known_network")
# get last known network information
logging.info("getting network information")
# if no known network and is se... |
def CategoryExtractor(self):
for i in range(1,22):
search="/html/body/div[2]/div/div[2]/div[1]/div["+str(i)+"]"
hrefs2 = self.driver.find_element_by_xpath(search)
title = self.driver.find_element_by_xpath(search+'/h2/a/span')
url = self.driver.find_element_by_xpat... | The code's main task is to perform category extraction, export the extracted categories, and manage the stopping of the extraction process through three methods: `CategoryExtractor` for extracting categories, `ExportCategory` for exporting them, and `StopExtractor` for halting the extraction. This workflow organizes da... | def Extraction(self):
self.CategoryExtractor()
self.ExportCategory()
self.StopExtractor() |
def readJsonAndMakeTestPairs(filename):
json_file = open(filename)
json_str = json_file.readlines()
pairs = list()
for s in json_str:
oneDict = ast.literal_eval(s)
if oneDict['gold_label'] == '-':
continue
pairs.append(tuple((oneDict['sentence1'].split(' '),oneDict['s... | The main task of the code is to process a JSONL file by extracting unary word features and NER features, save the features as joblib files, and generate a new JSONL file combining original data with the features. It reads input data, computes linguistic features, and stores them in specified directories for further use... | def getAndSave(filePathAndName, SAVE_DIR,st ):
fileName = filePathAndName.split('/')[-1]
print(f"Reading file : {fileName}")
tupleL = readJsonAndMakeTestPairs(filePathAndName)
jsonL = readJsonl(filePathAndName)
unaryWordFeatures = get_unaryWordFeatures1(tupleL,st)
print("Processed and saving una... |
def reload(self, cd):
self.cd = cd
self.json = self._load(self.data_j)
self.call = self._load(self.data_c)
try:
if not self.json["user"]["username"]:
self._create_user()
except KeyError:
self._create_user()
self._username = self.jso... | This function processes input commands by parsing them, checking for built-in commands like 'cd' and 'reload', executing them, and handling other commands by querying a call map. It outputs results or errors via a pipe and ensures reload operations are performed after command execution. | def _handle(self, inp):
cmd_set_seq = Parse().parse(inp.strip())
call = self.cmds_to_call_default_set.get(cmd_set_seq[0])
if call is not None:
if cmd_set_seq[0] == "cd":
c_d = call(cmd_set_seq, self)
self.reload(c_d)
if cmd_set_seq[0] == "r... |
def predict(self, data=None):
""" Makes predicitons off of the fitted GLM """
if isinstance(data, pd.Series):
data = data.to_frame().T
data = self.transform_data(data)
fitted = self.results.predict(data, offset=data["offset"])
fitted.name = "Fitted Avg"
return... | This code generates a partial dependence plot (PDP) for a specified field by creating a grid of base parameter values, predicting model outputs, adjusting for intercept shifts, and calculating confidence intervals. It transforms base parameters, repeats them for unique field levels, computes model predictions, applies ... | def set_individual_pdp(self, field):
unique_levels = self.data[field].unique()
base_dict = {}
for k, v in self.base_dict.items():
if type(v) is str:
base_dict[k] = v.replace("'", "")
else:
base_dict[k] = v
... |
def browse_nodes_for_execute(self, node=None):
"""Browse next nodes to execute.
This returns a collection of nodes that are ready to be executed, if
given a specific node it will only examine the successors of that node,
otherwise it will examine the whole graph.
"""
if ... | This function determines the next nodes to process in a workflow based on the current node's state and intention. If no node is provided, it returns all execute and revert nodes. For a given node, it checks its state (SUCCESS, REVERTED, FAILURE) and stored intention (EXECUTE/REVERT), then returns appropriate nodes: exe... | def get_next_nodes(self, node=None):
if node is None:
execute = self.browse_nodes_for_execute()
revert = self.browse_nodes_for_revert()
return execute + revert
state = self.get_state(node)
intention = self._storage.get_atom_intention(node.name)
if sta... |
def getMillis(self, extraDelay=0):
return round(time.time() * 1000) + extraDelay
def incrementDetectionCounter(self, resetCounter=False):
if resetCounter:
self.detectionCounter = 0
else:
self.detectionCounter += 1
def moveToNextPlayer(self):
self.setMovementTimer(... | The code detects movement or item presence, tracks frames for player transitions, and triggers actions like moving to the next player or notifying item detection. It uses a timer and frame counter to manage timing and state changes in a game or video processing context. | def movementDetected(self, movementDetected=False):
if self.movedTimer > self.getMillis() - self.characterChangeDelay:
return
if not movementDetected:
self.incrementDetectionCounter()
print(f'Frame: {self.detectionCounter}')
if self.detectionCounter == se... |
def setMovementTimer(self, extraDelay=0):
print('Waiting for timer...')
self.movedTimer = self.getMillis(extraDelay)
def getMillis(self, extraDelay=0):
return round(time.time() * 1000) + extraDelay
def moveToNextPlayer(self):
self.setMovementTimer()
wsh.AppActivate(self.applicati... | The main task of the code is to perform motion detection using a webcam, capturing video frames, detecting movement differences between consecutive frames, and saving images when items are detected. It also displays real-time motion alerts, manages a detection timer, and transitions to the next player upon item detecti... | def startVideoCapture(self):
print('Starting video capture...')
videoCapture = cv2.VideoCapture(0)
ret, frame1 = videoCapture.read()
ret, frame2 = videoCapture.read()
self.setMovementTimer(500)
while videoCapture.isOpened():
if self.itemDetected:
... |
def load_features():
global features
if not os.path.isfile(output_file):
print("creating features from scratch")
create_and_save_features()
else:
print("loading features file")
print(output_file)
# file = open(output_file, 'rb')
# features = pickle.load(file)
with open(output_file, 'r'... | The main task of the code is to run a machine learning experiment multiple times to evaluate accuracy on visualizations (e.g., charts) by organizing samples, loading features, performing cross-validation, and aggregating results. It categorizes data by visualization types, handles secondary labels, measures execution t... | def main():
# holds all available samples collected from urls.txt, separated by vis type
# valid vis types only
types_lists = {}
for k in symbol_dict:
types_lists[k] = []
# if vis sample has more than one label, put the second label in here
secondary_labels = {}
total_time = []
a... |
def load_features(self):
"""
Loads the features from the features.txt file if it exists. Otherwise
it extracts the features from the SVGs and creates a features.txt file
that holds all of the features.
"""
# handle base set (test set if training exists)
for collec... | The code verifies a classifier's performance by training (if enabled) and testing across multiple runs. It organizes samples, loads features, trains a RandomForestClassifier using cross-validation, and evaluates accuracy. It handles both training/testing splits, ensures data consistency, and aggregates results, outputt... | def run_verification(self):
"""
Runs the verification of the classifer given all of the presets
"""
# holds all available samples collected from urls.txt, separated by vis type
# valid vis types only
types_lists = {}
for k in symbol_dict:
types_lists[k... |
def is_time(time: str) -> bool:
return re.match(TIME_REGEX, time)
def today() -> date:
return dt.datetime.now().date()
def text_to_time(text: str) -> time | None:
if text == NONE_TIME:
return None
return dt.datetime.strptime(text, TIME_PATTERN).time() | The main task of the code is to create a `Record` object with the current day, a validated start time converted from text, and no stop time. It validates the input `start` is a valid non-null time before constructing the record. | def from_start(cls, start) -> Record:
assert is_time(start)
assert start != NONE_TIME
return Record(day=today(), start=text_to_time(start), stop=None) |
def is_time(time: str) -> bool:
return re.match(TIME_REGEX, time)
def today() -> date:
return dt.datetime.now().date()
def text_to_time(text: str) -> time | None:
if text == NONE_TIME:
return None
return dt.datetime.strptime(text, TIME_PATTERN).time() | The function creates a Record instance with today's date, a None start time, and a parsed stop time from the provided 'start' parameter. It validates that 'start' is a valid time and 'stop' is not NONE_TIME before returning the Record. | def from_stop(cls, stop) -> Record:
assert is_time(start)
assert stop != NONE_TIME
return Record(day=today(), start=None, stop=text_to_time(start)) |
def SRCNN(x):
# Define weights and biases.
# f1 = 9, f3 = 5, n1 = 64, n2 = 32.
weights = {'w1' : tf.Variable(tf.random_normal([9, 9, 1, 64], stddev=1e-3)),
'w2' : tf.Variable(tf.random_normal([1, 1, 64, 32], stddev=1e-3)),
'w3' : tf.Variable(tf.random_normal([5, 5, 32, 1], stddev=1e-3))}
biases = {'b1'... | The code trains an SRCNN model using gradient descent optimization to minimize L2 loss between predicted and ground-truth labels. It loads training data, processes it in batches, logs training progress every 10 steps, and saves checkpoints every 500 steps. The model is initialized with a checkpoint if available, and tr... | def train_SRCNN(x):
# Initialization.
model = SRCNN(x)
l2_loss = tf.reduce_mean(tf.square(labels - model))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(l2_loss)
train_data, train_label = load_data(train_path)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
prin... |
def _flatten_nested_iterable(struct):
"""
:param struct:
:return:
"""
result = []
for item in struct:
if hasattr(item, '__iter__') and not isinstance(item, str):
result.extend(_flatten_nested_iterable(item))
else:
result.append(item)
return result
def ... | This function processes input files using a system command to generate output files in a specified directory, applying filters and patterns. It checks input validity, runs the command if no existing outputs match the filter, and returns the resulting files. The function handles recursive collection or simple listing ba... | def syscall_ins_pat(inputfiles, outputpattern, outdir, filter, cmd, syscall, posrep=False, rec=False):
"""
System call for cases where a set of input files is split
into multiple output files (number determined at runtime), hence
outputfiles represents a matching pattern rather than a filename
:ret... |
def move(board,empty_cells,b,color):
table = board.copy()
empty_spaces = empty_cells.copy()
empty_spaces[b] -= 1
table[ empty_spaces[b], b ] = color
return table,empty_spaces
def checkwins(board,empty_cells,indices,color):
victory = -1
for i in indices:
moved = move(board,empty_cells... | The code evaluates potential moves on a board game by checking for immediate wins, assessing victory conditions, and recursively analyzing move outcomes based on board symmetry. It prioritizes symmetrical positions, uses depth-increased recursive evaluations, and returns the best move index or a strategic choice array ... | def brain(board,empty_cells,color):
deepness = 1
simm = isSymmetrical(board)
indices = np.where(empty_cells!=0)[0]
for i in indices:
moved = move(board,empty_cells,i,color)
win = checkwin2.run(moved[0]==color,moved[1],i)
if win==-2: return i
victory = checkwins(board,empty_c... |
def moves(board,empty_cells,b,color):
for x in b:
new_board = board.copy()
new_empties = empty_cells.copy()
new_empties[x] -= 1
new_board[ new_empties[x], x ] = color
yield new_board
yield new_empties
def checkwins(board,empty_cells,indices,color):
victory = -1
... | The code evaluates optimal moves for a game (likely Tic-Tac-Toe) by checking symmetrical board states, identifying immediate winning moves, and recursively analyzing deeper game states. It prioritizes symmetrical positions, checks for forced wins using `checkwin2.run`, and delegates further analysis to `think` or `conc... | def brain(board,empty_cells,color):
stop = empty_cells
deepness = 1
simm = isSymmetrical(board)
if simm==1:
indices = np.where(empty_cells[:4]!=0)[0]
move = moves(board,empty_cells,indices,color)
choices = np.zeros(indices.size,np.int8)
for i in range(0,indices.size):
... |
def new_screen():
"""
Clears the screen and prints a line.
"""
clear_screen()
print_line_h()
def get_input_yes_no(action):
"""
Prompts the user to confirm an action with 'Y' or 'N' and returns validated input.
Args:
action (str): The action to confirm. Used only for the prompt.
... | This function provides an exit menu option that prompts the user for confirmation. If confirmed, it displays a farewell message, copyright notice, waits for user input, clears the screen, and terminates the application using sys.exit(). The loop ensures repeated confirmation prompts until the user declines to exit. | def exit_app_ui():
"""
Menu action for "EXIT".
Exits the application after asking user for confirmation.
"""
while True:
new_screen()
if get_input_yes_no("QUIT") == True:
print(f"\nTHANK YOU FOR USING 'FLASH LINE_' - COME BACK SOON")
print_line_h()
... |
def get_input(prompt, object, disable_validation=True):
"""
Gets user input with a specified prompt.
Args:
prompt (str): The first part of the prompt.
object (str): Second part of the prompt. The name of the object to interact with.
Returns:
str: user_input
"""
prompt_c... | The main task of the code is to create a new flashcard box with a user-provided name. It checks if the name is unique, creates the box if valid, displays a confirmation message, waits for user input, and then launches the main menu. If the name already exists, it prompts the user to choose a different name. | def new_box_ui():
"""
Menu action for "NEW BOX".
Creates a new flashcard box and starts the main menu.
"""
global box
name = get_input(f"NAME OF NEW", "BOX", disable_validation=False)
if check_box(name) == False:
box = box.Box(name)
print(f"\nBOX '{name}' CREATED")
co... |
def new_screen():
"""
Clears the screen and prints a line.
"""
clear_screen()
print_line_h()
def get_input(prompt, object, disable_validation=True):
"""
Gets user input with a specified prompt.
Args:
prompt (str): The first part of the prompt.
object (str): Second part o... | The main task of the code is to create a new flashcard category by prompting the user for a unique name, checking if it already exists via `box.check_category()`, and adding it if valid, with feedback on success or name duplication. | def new_category_ui():
"""
Menu action for "NEW CATEGORY".
Creates a new category for flashcards.
"""
new_screen()
while True:
name = get_input("ENTER NAME OF NEW", "CATEGORY")
if box.check_category(name) == False:
box.add_category(name)
print(f"\nCATEGORY... |
def get_input(prompt, object, disable_validation=True):
"""
Gets user input with a specified prompt.
Args:
prompt (str): The first part of the prompt.
object (str): Second part of the prompt. The name of the object to interact with.
Returns:
str: user_input
"""
prompt_c... | The function creates a new flashcard by prompting the user for a question and answer, then associates it with the provided category. It updates the UI, adds the card to a storage system, and confirms creation with a message. | def new_card_ui(category):
"""
Menu action for "NEW FLASHCARD".
Creates a new flashcard within a given category.
Args:
category (str): The category the flashcard is associated with.
"""
question = get_input("ENTER", "QUESTION")
answer = get_input("ENTER", "ANSWER")
new_screen()
... |
def continue_enter():
"""
Pauses the execution of the script and waits for random user input to continue.
"""
input("\nPRESS 'ENTER' TO CONTINUE")
pass
def learn_cards(cards):
"""
For a set of flashcards, prints question, prompts user for answer.
Passes answer to handle_input to check co... | The function `learn_cards_ui` shuffles a given or default set of flashcards, tests the user on them via `learn_cards`, and displays the number of correct answers out of total attempts. It handles empty card sets by notifying the user and proceeds with learning otherwise, using a "LEARN ALL" menu action. | def learn_cards_ui(cards=None):
"""
Menu action for "LEARN ALL" (if cards is default).
Shuffles cards and calls learn_cards for a given set of flashcards (or all flashcards if default).
Args:
cards (list, optional): The list of flashcards to learn. Defaults to None.
"""
if cards == None... |
def mapDrag(self): # Drags Minimap To Maximum Size
initialMapSize = pyautogui.center (
pyautogui.locateOnScreen ( 'MapAdjust.png', confidence=0.7, grayscale=True ) )
while initialMapSize is None:
initialMapSize = pyautogui.center (
pyautogui.locateOnScreen ( 'MapA... | The main task of the code is to initialize and gather critical game state data for a tactician's strategy, including map dimensions, capture point coordinates, unit counts, and lord card positions. It retrieves map size parameters, calculates capture point locations, counts units on the map, and determines the lord's c... | def mainTacticianTrait(self):
global finalMapSizeY, finalMapSizeX, mapCornerY, mapCornerX, mapCenterY, mapCenterX, capturePointX
global capturePointY, total_units, units, lord_card_position_x, lord_card_position_y
self.mapDrag ()
self.toggleuniticon ()
finalMapSizeY, finalMapSize... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.