dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def mkdirs( p ):
try:
os.makedirs( p )
except FileExistsError:
pass
def GetGadgetConfigDir( vimspector_base ):
return os.path.join( GetGadgetDir( vimspector_base ), '.gadgets.d' )
def GetConfigDirForFiletype( vimspector_base, filetype ):
if not filetype:
filetype = 'default'
return os.path.join( ... | The code creates necessary installation directories for a plugin or configuration system. It generates a base configuration directory using `GetGadgetConfigDir` and a filetype-specific directory using `GetConfigDirForFiletype`, ensuring proper structure for a Vim plugin like vimspector. | def MakeInstallDirs( vimspector_base ):
mkdirs( GetGadgetConfigDir( vimspector_base ) )
mkdirs( GetConfigDirForFiletype( vimspector_base, '_all' ) ) |
def width(self):
return obs.obs_source_get_width(self.source)
def set_width(self):
scale_vec = obs.vec2()
scale_vec.x = self.scale()
scale_vec.y = self.scale()
obs.obs_sceneitem_set_scale(self.item, scale_vec)
def crop_top(self):
self.crop.top = self.params['crop_top']
... | This code updates an object's parameters using keyword arguments, adjusts crop boundaries when a 90-degree rotation is specified, and applies the changes through various setter methods to modify the object's display properties. | def update(self, **kwargs):
self.params = {
"rotation": 0,
"width": self.width(),
"crop_top": 0,
"crop_bottom": 0,
"crop_left": 0,
"crop_right": 0,
"position_x": 0,
"position_y": 0,
... |
def convert_token_to_prediction(tokens, start, end):
prediction = tokens[start]
for i in range(start+1, end+1):
if tokens[i][0:2] == '##':
prediction += tokens[i][2:]
else:
prediction += ' ' + tokens[i]
return prediction
def normalize_answer(s):
"""Lower text and re... | The code evaluates a model's performance on a question-answering task by predicting answer spans from input text, comparing them to ground-truth answers. It calculates exact match accuracy and average F1 score across a dataset, using token-level predictions and normalization. The model outputs start/end positions, whic... | def predict(eval_dataset,qids,answers):
n = len(eval_dataset)
exact_match = 0
f1_sum = 0
for i in range(n):
input_ids = eval_dataset[i]['input_ids'].to(device)
attention_mask = eval_dataset[i]['attention_mask'].to(device)
qid = small_val_ids[i]
golden_answer = answers[i]... |
def do_moves(self, move_str: str):
parsed, moves = parse_moves(move_str)
if not parsed:
print("Parsing failed after", end=' ')
for move in moves:
print(move[0], end='')
if move[1] == 3:
print("'", end='')
elif ... | This function visualizes the effect of a CMLL (Corner Orientation and Permutation) algorithm on edge orientation (EO) in a Rubik's Cube. It applies initial setup moves, captures the cube state, executes the CMLL algorithm, and compares edge orientations before/after using EO_mask. It generates translucent images of the... | def CMLL_affects_EO(self, CMLL: str, CMLLsetup: str, initial_EO: str, show_img=False):
self.do_moves(initial_EO)
self.do_moves(CMLLsetup)
previous_state = copy.deepcopy(self.pieces)
self.do_moves(CMLL)
# print(self.viscube_image(translucent=True, show_img=show_img, mask=previous_... |
def create_bpmn_description(structure_list: [Structure], actor_list: list, title: str,
theme: str = "BLUEMOUNTAIN") -> str:
"""
Create the input syntax for the BPMN model based on the list of structures and actors.
construct the lanes according to the actors
and then add the ... | This function generates a BPMN model from provided structures and actors, using a theme. It creates a syntax description, optionally enhances it with an LLM based on input text, then renders and saves the model to a specified path. If LLM enhancement fails, it defaults to a basic syntax improvement before rendering. | def create_bpmn_model(structure_list: [Structure], actor_list: list, title: str, save_path: str, text_description: str,
theme: str = "BLUEMOUNTAIN"):
"""
Create a BPMN model from a list of structures and actors.
Args:
structure_list: the list of structures
actor_list: t... |
def get_info(self):
self.selected_paths = {}
self.paths = {}
self.orientation_points = {}
self.layers = [self.document.getroot()]
self.Zcoordinates = {}
self.transform_matrix = {}
self.transform_matrix_reverse = {}
self.Zauto_scale = {}
def recurs... | This code initializes a laser engraving tool by configuring logging, setting orientation points, defining tool parameters (speed, power commands), and preparing for engraving. It handles error cases, creates a log file if enabled, ensures orientation points exist, and sets up the laser tool's G-code commands for operat... | def effect(self):
global options
options = self.options
options.self = self
options.doc_root = self.document.getroot()
if self.options.log_create_log:
try:
if os.path.isfile(self.options.log_filename):
os.remove(self.options.log_fil... |
def get_orientation_points(self, g):
""" Get the orientation points from the svg (if they exist.)
"""
# Get the container children.
items = g.getchildren()
# Reverse the list.
items.reverse()
#
p2, p3 = [], []
p = None
# Loop through each ... | This function recursively processes SVG elements to identify and categorize paths, layers, and orientation points for G-code generation. It traverses nested groups, collects selected items, validates orientation data, and enforces compatibility with paths/dynamic offsets. Errors are reported for unsupported objects or ... | def recursive_search(g, layer, selected=False):
items = g.getchildren()
items.reverse()
for item in items:
# If selected is checked
if selected:
# Add to selected dictionary.
self.svg.selected[item.get("id")] = i... |
def get_unused_outputs_from_dash():
masternode_outputs = dash_cli(['masternode', 'outputs'])
masternode_outputs = json.loads(masternode_outputs)
masternode_list = dash_cli(['masternode', 'list'])
available_outputs = [output for output in masternode_outputs if output not in masternode_list]
print(f"A... | The main task of the code is to generate and lock sufficient 1000 Dash outputs for masternode setup. It checks for unused outputs, creates new transactions to send 1000 Dash to new addresses, locks these outputs, and repeats until the required number of masternode outputs (MAX_NUM_MASTERNODES) is achieved. The process ... | def generate_outputs():
"""Check if there are unused 1000 Dash outputs"""
# get masternode outputs
unused_outputs = get_unused_outputs_from_dash()
while len(unused_outputs) < MAX_NUM_MASTERNODES:
missing = MAX_NUM_MASTERNODES - len(unused_outputs)
print(f"Missing {missing} masternode ou... |
def get_unused_outputs_from_dash():
masternode_outputs = dash_cli(['masternode', 'outputs'])
masternode_outputs = json.loads(masternode_outputs)
masternode_list = dash_cli(['masternode', 'list'])
available_outputs = [output for output in masternode_outputs if output not in masternode_list]
print(f"A... | The main task of the code is to register a masternode on the Dash network by generating a BLS key pair, preparing and signing a registration transaction with a selected funding output, and submitting it to the blockchain. It handles address generation, transaction construction, and writes a reactivation command for fut... | def performMasternodeRegistration(
onionAndPort: str) -> str:
"""Method return bls private key"""
# Generate outputs if necessary
if len(get_unused_outputs_from_dash()) < 10:
generate_outputs()
# Get the next funding transaction from masternode outputs and use that for the registration... |
def sub_total_cost(order):
"""
Gather costs of idividual line items into a subtotal.
"""
cost = 0
for food, quantity in order.items():
if food == 'id':
continue
cost += cost_of_items(food, quantity)
return cost
def total_cost(order):
"""
Calculate cost of orde... | The main task of the code is to format an order into a structured receipt, displaying the order ID, subtotal, sales tax, total due, and itemized list with aligned currency values. It calculates costs, applies tax, and constructs a formatted string using specified templates for each receipt component. | def receipt_display(order):
"""
Format an order into a receipt.
"""
sub_total = sub_total_cost(order)
print(ORDER_RECEIPT.format(
id=order['id'],
total_due=format(currency(total_cost(order)), '>33'),
subtotal=format(currency(sub_total), '>34'),
sales_tax=format(curren... |
def receipt_display(order):
"""
Format an order into a receipt.
"""
sub_total = sub_total_cost(order)
print(ORDER_RECEIPT.format(
id=order['id'],
total_due=format(currency(total_cost(order)), '>33'),
subtotal=format(currency(sub_total), '>34'),
sales_tax=format(curren... | This function processes user actions by routing them to appropriate handler functions based on the action verb. It splits the user request into an action and options, then calls functions like receipt_display, menu_display, remove_order_item, or category_display depending on the action. If no match, it adds an order it... | def handle_user_action(order, user_request):
"""
Dispatch to handler functions based on user action verb.
"""
action, *options = user_request.split()
if action == 'order':
receipt_display(order)
elif action == 'menu':
menu_display()
elif action == 'remove':
remove_ord... |
def load_menu():
global CATEGORY_VIEW, MENU
file_name = clean_input(REQUEST_MENU_FILE)
if not file_name:
return
try:
with open(file_name) as istream:
csv_content = istream.read()
except OSError:
print('File {} could not be found'.format(file_name))
return
... | The code's main task is to manage a menu and order processing system. It loads a menu, displays it, initializes an order with an ID, and continuously handles user input to update the order. The loop processes cleaned user requests until input handling completes, facilitating order customization or submission. | def main():
"""main."""
load_menu()
menu_display()
order = generate_blank_order_with_id()
while handle_input(order, user_request=clean_input(USER_INPUT_REQUEST)):
pass |
def preprocess_file(filename):
'''
From a path, gets the name of the file and extracts the content
'''
sdve_file_name = filename.split("/")[1][:-5]
with open(filename) as f:
content = f.readlines()
content = [line.strip() for line in content] # Remove trailing and leading spaces
con... | The main task of the code is to analyze a file by extracting statistical metrics such as the number of temporary/global variables, processes, assignments in guards/effects, and compilation details. It processes the file content, computes max/mean values for operations in guards/effects, and compiles the file to determi... | def process_file(sdve_filepath):
'''
Output a dictionary with stats from a file path
'''
max_ops_in_guard = 0
mean_ops_in_guard = 0
max_ops_in_effect = 0
mean_ops_in_effect = 0
# Preprocess
file_name, content = preprocess_file(sdve_filepath)
print("Getting stats for: ... |
def get_prompt(n_examples):
"Get the prompt with the given version and number of example tasks."
examples = random_seed_tasks(n_examples)
template = open(PROMPT_PATH).read()
return render(template, tasks=examples, n_tasks=N_TASKS,
enumerate=enumerate, randint=random.randint, len=len)
d... | The main task of the code is to run a parallel processing loop using a worker pool to generate and analyze task responses, collecting statistics on cost, time, and token usage, while evaluating task similarity and outputting performance metrics like tokens per second, cost per task, and task completion rates. | def main_loop():
stats = Counter()
tasks = []
#
t0 = time.time()
pool = Pool(N_WORKERS)
for _ in tqdm(range(N_ROUNDS), total=N_ROUNDS,
desc='rounds', ncols=80, position=0):
batch = []
prompts = [get_prompt(N_EXAMPLES) for _ in range(N_TURNS)]
for resp in... |
def won():
root.destroy()
def on_button_click1():
nm = entry1.get()
ml = entry2.get()
client_socket.send(nm.encode('utf-8'))
client_socket.send(ml.encode('utf-8'))
window.destroy()
lose(2)
window = tk.Tk()
window.config(bg="#1e1f1f")
window.title("Snak... | The main task of the code is to handle a button click event by generating a random number, displaying a corresponding image, sending the number to a server via a socket, receiving a response ('a' or 'b'), updating the game state (player position or outcome), and scheduling the image removal after 500ms. It facilitates ... | def on_button_click():
run = random.randint(1, 6)
message = f'{run}'
new_image = ImageTk.PhotoImage(Image.open(f'{run}.jpg').resize((80, 80)))
button.config(image=new_image)
client_socket.send(message.encode('utf-8'))
where = client_socket.recv(1024).decode('utf-8')
print(where)
if where... |
def l_diff_between_periods(self, variable):
"""
Calculates the difference in the labor force between the current and next period.
Parameters:
variable (float): The current labor force value, which should be a non-negative number.
Returns:
float: The difference between t... | The function numerically computes the steady-state values of a model's labor force, output, output per worker, and birth rate, using optimization with multiple initial guesses. It adjusts outputs based on whether technological growth is included (`with_A_growth`). The method iterates over random guesses, minimizes resi... | def numerical_solution_steady_state(self, with_A_growth = False):
"""
Finds the steady state of the model numerically and handles edge cases where initial guesses might lead to non-viable solutions.
Parameters:
with_A_growth (bool): A flag indicating whether to account for technologic... |
def c2_optimal(l, p1, p2, w, par):
numerator = (1 - par.alpha) * ( w * l + par.T + firm_profit(p1, w, par) + firm_profit(p2, w, par) )
denominator = p2 + par.tau
return numerator / denominator
def consumer_utility(tau, T, script_l, p1, p2, w, par):
c1 = c1_optimal(script_l, p1, p2, w, par)
c2 = ... | This function computes the Social Welfare Function (SWF) for varying values of tau by iterating through a tau array. For each tau, it calculates corresponding T using an optimal function, derives consumer utility, and computes SWF. It returns arrays of tau values, computed T values, and SWF results to analyze trade-off... | def tau_to_maximize_SWF(tau_array, script_l, y2, p1, p2, w, par):
SWF_array = []
T_array = []
for tau in tau_array:
parameters = copy.deepcopy(par)
parameters.tau = tau
T = tau * c2_optimal(script_l, p1, p2, w, parameters)
parameters.T = T
T_array.append(T)
... |
def generateRoomTimes(self):
# each room will have time intervals from e.g. 4pm - 11pm
# cabin 1 6:00:
# who was in the room (person IDs)
# what each person contains at this time (either here or in person)
# what the room contains at this time (either here ... | This code initializes a murder mystery scenario by setting up rooms, people, events, and timelines. It generates room schedules, creates events, initializes room states, and ultimately determines the murderer based on the generated data and logic. | def __init__(self, gen):
self.gen = gen
self.people = self.gen.people
self.rooms = self.gen.rooms
self.locationGraph = self.gen.locationGraph
self.startTime = '16:00'
self.topics = self.gen.topics
self.generateRoomTimes()
self.setupEvents()
self.in... |
def _verify_web_hook(form: Dict[str, Any]) -> None:
if not form or form.get('token') != SLACK_TOKEN:
raise ValueError('Invalid request/credentials!')
def _get_information() -> Optional[bool]:
datastore_client = datastore.Client()
key = datastore_client.key(DATASTORE_KIND_NAME, _relevant_document_id(... | (The code handles a Slack slash command by verifying the incoming POST request, checking if a dog is in the office, and returning a formatted Slack message with the dog's status. It accepts only POST requests, validates the webhook, retrieves office status data, maps it to a response message, and returns the result as ... | def slash_command(request: Dict[str, Any]) -> Response:
"""Triggered from Slack slash command via an HTTPS endpoint.
Args:
request (dict): Request payload.
"""
if request.method != 'POST':
return 'Only POST requests are accepted', 405
print('Triggered Slack slash command.')
fo... |
def _verify_web_hook(form: Dict[str, Any]) -> None:
if not form or form.get('token') != SLACK_TOKEN:
raise ValueError('Invalid request/credentials!')
def _set_information(in_office: bool) -> None:
datastore_client = datastore.Client()
key = datastore_client.key(DATASTORE_KIND_NAME, _relevant_documen... | This code handles a Slack action triggered via an HTTPS endpoint by parsing user input to determine if a dog is in the office, updating the status, and sending a formatted response message back to Slack. It verifies the webhook, constructs a status message, and uses the provided response URL to communicate the updated ... | def action(request: Dict[str, Any]) -> Tuple[str, int]:
"""Triggered from Slack action via an HTTPS endpoint.
Args:
request (dict): Request payload.
"""
if request.method != 'POST':
return 'Only POST requests are accepted', 405
print('Triggered Slack action.')
form = json.load... |
def search(data, toplevel_pattern, secondlevel_pattern=None):
# print(toplevel_pattern, secondlevel_pattern)
if toplevel_pattern['type'] in data.keys():
collection = data[toplevel_pattern['type']]
toplevel_records = search_in_collection(collection, toplevel_pattern)
#print(toplevel_recor... | The function retrieves histogram data from `scadata` based on parameters in `histogram`, extracts bin values, and aggregates them into a combined histogram for return. | def get_histogram(scadata, histogram):
#print(json.dumps(histogram, indent=4))
hists=search(scadata, {'type': 'statistic', 'object': histogram['module'], 'name': histogram['histogram_name']})
# we are looking for the bins, but they are a vector: conversion to JSON string
rv=[get_bins(h) for h in hists]
... |
def io_vector_labels(self):
"""
Gets the human-readable names of each field in the input and output vectors.
Useful for keeping track of how the input and output vectors are supposed
to map to the behaviors of the organism and its actions in the world.
"""
return {
'sensors': ['FORWARD', '... | This code processes actuator inputs to execute movement or orientation commands in a grid-based environment. It prioritizes single valid commands, updates the agent's orientation for 'TURN' actions, and adjusts position for 'GO' commands based on direction. The function checks for terminal states ('DEAD', 'VICTORY') an... | def act(self, actuators):
self.turn += 1
cmds = [label for idx,label in enumerate(self.io_vector_labels()['actuators']) if actuators[idx]>0]
# To make the problem space a little more tractable and less linearly inseparable,
# I'll say that 'GO' overrides other commands.
#if 'GO' in cmds:
# cm... |
def get_relative_ahead_xy(self, xy, orientation):
from operator import add
viewmods = [[0,-1], [1,0], [0,1], [-1,0]]
viewmod = viewmods[orientation]
viewxy = list(map(add, xy, viewmod))
return viewxy
def mapsquare(self, xy, orientation=0):
x = xy[0]
y = xy[1]
outdict = {
"traversib... | The main task of the code is to process an agent's movement or orientation change based on the specified action (TURN_LEFT, TURN_RIGHT, FORWARD) in a grid environment, updating the agent's position or orientation if the action is valid. If the 'interactive' flag is True, it also triggers a visualization update. | def submit_action(self, action, interactive=False):
if action == "TURN_LEFT":
self.agentOrientation = (self.agentOrientation + 3) % 4
elif action == "TURN_RIGHT":
self.agentOrientation = (self.agentOrientation + 1) % 4
elif action == "FORWARD":
toxy = self.get_relative_ahead_xy(self.agentP... |
def initialize_parameters_deep(layer_dims):
np.random.seed(3)
parameters = {}
L = len(layer_dims)
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) * 0.01
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
assert(p... | This code implements a deep neural network training process using gradient descent. It initializes parameters, iteratively performs forward and backward propagation, updates parameters with gradients, and tracks costs. The function returns trained parameters and cost history for a multi-layer model with specified dimen... | def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
np.random.seed(1)
costs = []
parameters = initialize_parameters_deep(layers_dims)
for i in range(0, num_iterations):
AL, caches = L_model_forward(X, parameters)
... |
def convert_message_to_numbers(self, message):
"""converts character to index position within
alphabit and store resulting integers in a list
Args:
message (string): message to be encrypted
Returns:
list: list of index values for each char of the
mes... | The main task of the code is to encode a given message by converting each character to numbers, encoding each number individually, and then transforming the encoded numbers back into letters to produce and print the ciphertext. | def encode_message(self, message):
"""Takes a string and encodes each char of the string
printing the final result
Args:
message (string): message to transform
"""
character_list = self.convert_message_to_numbers(message)
encoded_message = []
for ind... |
def get_all_nfa_states(z,o,e,f):
states = []
for i in range(len(z)):
item = z[i].split(",")
states.append(item[0])
states.append(item[1])
for i in range(len(o)):
item = o[i].split(",")
states.append(item[0])
states.append(item[1])
for i in range(le... | The code decodes an NFA description by parsing its components (states, transitions, initial/final states), constructs the NFA's transition table, and converts it into a DFA using subset construction. It returns the resulting DFA. | def decode_NFA(nfa_description):
z = nfa_description.split("#")[0].split(";")
o = nfa_description.split("#")[1].split(";")
e = nfa_description.split("#")[2].split(";")
f = nfa_description.split("#")[3].split(",")
states = get_all_nfa_states(z,o,e,f)
nfa_table = construct_nfa_table(z, o, e, st... |
def log_in_website(driver: webdriver, base_url: str) -> webdriver:
"""Login to Robert Parker's website using credentials from 'cred' file"""
driver = open_webdriver()
sign_in_url = base_url + "/sign-in"
try:
driver.get(sign_in_url)
except:
logger.error(f"Login page could not be loade... | (The code exports wine reviews for a specified country by scraping data from a website. It logs in, navigates to relevant pages, extracts review data, converts it into a DataFrame, and saves it as a CSV file in the designated directory. The process uses predefined settings and logs progress.) | def export_reviews(country: str, presets: BaseSettings) -> None:
"""Get the reviews from the URL and write to a CSV file"""
base_url: str = presets.url
raw_data_dir: Path = presets.raw_data_dir
logger.info(f"Get wine reviews of {country}")
driver = log_in_website(driver, base_url)
page_urls = ... |
def concat_data(dir: Path) -> pd.DataFrame:
"""Return a concatenated DataFrame of all csv files in the raw data directory"""
data = []
for file in os.listdir(dir):
if file.endswith(".csv"):
logger.info(f"Reading file {file}")
temp = pd.read_csv(dir / file, delimiter=",", inde... | The code's main task is to load raw review data, concatenate it into a DataFrame, perform exploratory data analysis, clean/preprocess the data, generate descriptive statistics, and save the cleaned dataset as a CSV file. The function orchestrates data handling, analysis, and storage based on provided settings, logging ... | def get_insights(presets: BaseSettings) -> None:
"""Get insights in the reviews and save cleaned dataset"""
raw_data_dir: Path = presets.raw_data_dir
cleaned_data_file: Path = presets.cleaned_data_file
df = concat_data(raw_data_dir)
data_exploration(df)
df = prepare_data(df)
describe_data(d... |
def Preprocess():
# Load the dataset
diamonds_df = pd.read_csv("diamonds.csv")
print("======================Task1======================")
# Print some results from the dataset to get some information
# print("Columns: ", diamonds_df.columns)
# print(diamonds_df.head())
# This is ju... | The main task of the code is to perform cross-validation for polynomial regression models on multiple datasets. It determines the optimal polynomial degree and parameters (p0) by minimizing prediction errors across 4 folds. After selecting the best degree for each dataset, it visualizes true vs. estimated prices using ... | def main():
feature_array_list, target_array_list = Preprocess()
# Task 2 on Wards
print("======================Task6=====================")
# Task 6
# Create the k fold
kf = model_selection.KFold(n_splits=4, shuffle=True)
# This records the best p0 from the k folds
best_p... |
def init_solution_pool_v2(self):
"""Initialize solution pool.
Generate S feasible assignments as follows:
- First create a number of solutions where all users take the same representation
- Do a number of crossover operations to create the rest of the solution pool
"""
self.solution_pool = ... | The code executes a genetic algorithm to optimize a scenario by iteratively generating and refining solutions. It logs generation data if specified, tracks the best solution, checks for convergence to halt early, and returns the optimal solution as a JSON object with performance metrics like generations, execution time... | def execute(self):
"""Run the genetic algorithm.
Returns the scenario JSON object with placement decisions plus some
algorithm-specific information.
"""
# check if we will store data per generation in a file
log_generation_data = False
if self.generations_file is not None:
try:
... |
def write_to_dump(new_print):
write_to_meta()
with open(f"node{node_num}/dump.txt","a") as file:
file.write(new_print)
def write_to_log(new_log):
write_to_meta()
with open(f"node{node_num}/log.txt","a") as file:
file.write(new_log)
def heartbeat():
global hb,acks,commitindex,lastAppl... | This function designates the current node as the leader, initializes Raft consensus parameters (matchIndex, nextIndex), logs a no-op entry, and starts a heartbeat timer to maintain leadership. It waits 2.5 seconds before triggering a lease timer and initiating heartbeat messages to coordinate with followers. | def leader_job():
global term,acks,t4,lastApplied,leader
leader=node_num
write_to_dump(f"Node {node_num} waiting for leader's lease time to get over\n")
lastApplied+=1
log.append(["NO","OP",term,lastApplied])
write_to_log(f"NO OP {term} {lastApplied}\n")
matchIndex=[0]*6
nextIndex=[l... |
def strip_lines(s):
return LEAD_TRAIL_SPACE_REGEX.sub('', s).strip()
def to_regex(m):
if m.strip() == '':
msg = "Will not compile an empty match"
raise ExceptionWithExcerpt(msg, repr(m))
result = re.compile(m, re.MULTILINE | re.VERBOSE)
if result.match('') and result.search('abcedfg', ... | This code processes files by applying macro definitions, handling include directives with custom replacements, preprocessing, and performing post-processing replacements to generate modified output files. | def worker(dsl, paths):
pre_macros = '\n'.join(chain(dsl.pre_defines, dsl.pre_undefines))
post_macros = '\n'.join(chain(dsl.post_defines, dsl.post_undefines))
include_match = r"""
^ # Beginning of line
[ \t]* # Spaces
[#] # Macro start
[ \t]* # Spaces
inc... |
def makeBoard(constant):
'''This function makes the nested list for all my tiles and makes a list containing all of the indexes of the mines. While taking in the constants'''
#The whole board
tiles = []
for y in range (constant[1], constant[0]*constant[3][1] + constant[1], constant[0]):
#Each ro... | The main task of the code is to run a Minesweeper game loop using Pygame, initializing display settings, loading assets, handling user input (mouse/keyboard), updating game state (tile reveals, flags, timers), playing sound effects, and rendering graphics. It processes events like clicks, checks win/loss conditions, ma... | def mainGame(constant):
'''This function defines the 'mainline logic' for our game.'''
# Display
screen = pygame.display.set_mode(constant[6])
#Set display caption according to the size of the screen
if constant[6] == (308,387):
pygame.display.set_caption("Minesweeper! (Beginner)")
el... |
def _sample_beam(self, fc_feats, att_feats,attr_labels, att_masks=None, opt={}):
beam_size = opt.get('beam_size', 1)
batch_size = fc_feats.size(0)
p_fc_feats, p_att_feats, pp_att_feats, p_att_masks,attr_feats, p_attr_feats= self._prepare_feature(fc_feats, att_feats, att_masks,attr_labels)
... | This code generates sequences (e.g., captions) using either beam search or sampling, depending on the 'beam_size' parameter. It processes input features (fc/att/attr), initializes hidden states, and iteratively computes log-probabilities for each token position. The function returns the generated sequences and their lo... | def sample(self, fc_feats, att_feats, attr_labels,att_masks=None, opt={}):
sample_max = opt.get('sample_max', 1)
beam_size = opt.get('beam_size', 1)
temperature = opt.get('temperature', 1.0)
decoding_constraint = opt.get('decoding_constraint', 0)
if beam_size > 1:
re... |
def q_to_rot(self, q):
"""Transformation of quaternion to rotation matrix"""
qx = q[0]
qy = q[1]
qz = q[2]
qw = q[3]
r = np.array([[1 - 2 * qy * qy - 2 * qz * qz, 2 * qx * qy - 2 * qz * qw, 2 * qx * qz + 2 * qy * qw],
[2 * qx * qy + 2 * qz * qw, 1 ... | This code initializes an object representing a detected entity (e.g., vehicle, pedestrian) with properties like class, priority, position, orientation, and bounding box dimensions. It validates the input data, computes geometric attributes (distance, rotation, volume), and sets up the object's pose and spatial represen... | def __init__(self, tl, seq_no, scene_no):
"""INIT"""
"""Object valid?"""
self.valid = False
"""Unique id for this object in this sequence"""
self.id = 0
"""Unique number for this sequence"""
self.seq_no = 0
"""Unique number for this scene in the current se... |
def changeDirection(self, number):
if not self.moved or self.ki:
self.moved = True
if self.calcDirect(self.direction + 1) == self.calcDirect(number) or self.calcDirect(self.direction - 1) == self.calcDirect(number) or self.ki:
self.direction = self.calcDirect(number)
def ... | The code's main task is to control an entity's movement by evaluating potential directions to avoid collisions (death), adjusting direction based on safety checks, and managing body segments by adding a new part and removing the last if no apple is consumed at the head's new position. | def go(self):
self.moved = False
if self.ki:
self.changeDirection(self.getBestDirect())
if self.checkOnDeath(self.calculateDirectCoords(self.parts[0].copy(), self.direction)):
if not self.checkOnDeath(self.calculateDirectCoords(self.parts[0].copy(), 0)):
... |
def go(self):
self.moved = False
if self.ki:
self.changeDirection(self.getBestDirect())
if self.checkOnDeath(self.calculateDirectCoords(self.parts[0].copy(), self.direction)):
if not self.checkOnDeath(self.calculateDirectCoords(self.parts[0].copy(), 0)):
... | The code updates an object's state over time by accumulating time intervals (`self.window.dt`). When the accumulated time (`self.count`) reaches or exceeds a specified `time` threshold, it triggers an action (`self.go()`), checks if the first component (`self.parts[0]`) is dead, and if so, initiates a death process (`s... | def update(self, time):
self.count += self.window.dt
if self.count >= time:
self.count -= time
self.go()
if self.checkOnDeath(self.parts[0]):
self.die() |
def initialDocsForCenter(shapeFileState, dataFramePath, city, rename=False):
# Reading the data files from the Census webpage
interestedPolygon = gpd.read_file(shapeFileState)
if ".xlsx" in dataFramePath:
Points = pd.read_excel(dataFramePath).set_index("NAME")
else:
Points = pd.read_csv(dataFramePath).s... | This function processes geographic and temporal data by generating time zone clusters around a central point, analyzing spatial distributions of churches, and preparing structured datasets for machine learning. It reads input files, creates time-based clusters, extracts spatial points within defined zones, and organize... | def TimeZoneProcessFromCenter(shapeFileState, excelChurchesLatLong, timeRadi, fileNameExit, city, county, state, Print=False):
# Reading the initial documents and making a respective dataframes
interestedPolygon, churchesCRM, centroidInterestedZone = initialDocsForCenter(shapeFileState, excelChurchesLatLong, city)
... |
def calculate_speed(current_speed, zone_3_durations: list):
TS = total_workout_score(zone_3_durations, [3] * len(zone_3_durations))
if TS >= 0.25:
return min(current_speed + 7 * (4/3 * TS - 1/3), 100)
else:
return max(current_speed + 7 * (4 * TS - 1), 10)
def calculate_strength(current_stren... | This function calculates updated physical attributes (speed, strength, health, jump height) based on workout data and current stats. It extracts durations from HR zones 2/3 in workout_data, then applies calculation functions to adjust each stat using zone-specific durations, sleep data, and current values. Results are ... | def stats_change(fitness_data, workout_data, current_speed, current_strength, current_health, current_jump_height):
zone_3_durations = []
zone_2_durations = []
hr_zones = []
workout_durations = []
if not workout_data.empty:
zone_3_durations = [duration for duration, zone in zip(workout_data[... |
def load():
global words
if words:
return words
words = {}
with codecs.open(dictionary, 'r', encoding='utf-8') as f:
for row in f:
parts = row.split(',', 3)
if len(parts) < 2:
continue
words[parts[0]] = parts[1]
words['ei'] = ''
... | The function processes input text to generate annotated or analyzed output based on parameters. It uses `mark()` for initial processing, `chart()` for visualization, and `emotionBayes()` for sentiment analysis. Depending on `dataonly` and `lexiconbased` flags, it returns either raw data, emotion scores, or formatted te... | def marktext(text, dataonly, lexiconbased):
"""For web"""
load()
t = mark(text)
s = chart(t[1], t[2])
if dataonly:
if dataonly == "2":
return s[0]
if dataonly == "3":
return emotionBayes(t[3], t[1], t[2])
return s[1] + t[0]
if not lexiconbased:
... |
def parseAItable(year):
"""parsing AI table"""
AI = AI_table[year]
CL_AGE = Codes(AI)["CL_AGE"]
age_to_USA_age = CL_AGE_to_USA_age(CL_AGE)
if year in [2016, 2011]:
condition = lambda key: key["RGINDR"] == '1' # and key["ABIDENT"] == '2'
relevant_key = "ABIDENT"
elif year in [2006... | The main task of the code is to process and combine AI and VM data for a given year by retrieving files, parsing tables, merging dataframes, executing geospatial processing, adding demographic columns, final data processing, and writing results. It consolidates AI and VM datasets into a unified dataframe, applies trans... | def main2(year):
get_file(root(AI_table[year]), AI_url[year])
get_file(root(VM_table[year]), VM_url[year])
print(f"processing data for {year}")
aidf = parseAItable(year)
vmdf = parseVMtable(year)
global vmaidf
vmaidf = pd.concat([vmdf, aidf[['1','2']].rename(columns={'1':'E','2':'A'})], axis... |
def reset_mouth(self):
self.original.move_to(self)
self.become(self.original)
return self
def __middle_y(self):
mouth_bottom_y = self.get_bottom()[1]
return ((self.get_top()[1] - mouth_bottom_y) / 2) + mouth_bottom_y
def __middle_x(self):
mouth_left_x = self.get_left()[0]... | This function transforms points to create a mouth shape by resetting the mouth, calculating symmetry axes, and applying a lambda function that adjusts coordinates using symmetry and distance scaling based on center and edge positions. | def o_mouth(self):
self.reset_mouth()
middle_y = self.__middle_y()
middle_x = self.__middle_x()
y_symm = lambda y: -1 if y < middle_y else 1
x_symm = lambda x: -1 if x > middle_x else 1
self.apply_function(
lambda p: [x_symm(p[0]) * self.__center_distance_x(p[... |
def _parse_raw_request(raw_request: bytes) -> Tuple[Dict[str, Union[str, Dict[str, str]]], Dict[str, str]]:
headers = {}
error_code = error_message = None
method = path = proto = ''
bfile = BytesIO(raw_request)
try:
first_line = bfile.readline().strip()
me... | This method parses an HTTP request, validates its method, handles errors, determines the appropriate response status and body based on the request path, and constructs a response object, adjusting for HEAD requests by setting an empty body. | def parse_request(self, directory: Path):
error, request = self._parse_raw_request(self.raw_request)
self.request = Request(**request)
if error['code']:
status = HTTPStatus.BAD_REQUEST.value
body = BytesIO(error['message'].encode())
elif self.request.method not in... |
def connectBridge(self, i, j, direction, n):
if (n > 0):
self.drawBridge(i, j, direction, n, False)
self.grid[i][j].branchValue[direction] -= n
self.grid[i][j].restBridge -= n
def updateAdjacentBridge(self, i, j, direction):
x = 0; y = 0
if direction == 0:
... | This function processes bridge connections on a grid based on the given mode. For modes 0 and 1, it iterates through branches, connects bridges, updates adjacent nodes' bridge capacities, and adjusts branch values. In other modes, it uses a 'valid' array to connect bridges, resets branch values, and propagates changes ... | def solveNode(self, i, j, mode, valid = [0, 0, 0, 0]): # mode 0 is step 7, mode 1 is step 8
if mode == 0:
for k in range(0, 4):
branchTemp = self.grid[i][j].branchValue[k]
if (branchTemp > 0):
self.connectBridge(i, j, k, branchTemp)
... |
def connectBridge(self, i, j, direction, n):
if (n > 0):
self.drawBridge(i, j, i, j, direction, n, False)
self.grid[i][j].branchValue[direction] -= n
self.grid[i][j].restBridge -= n
def updateAdjacentBridge(self, i, j, direction, n):
if (n > 0):
x = 0; y =... | This code processes a node's branches in a grid. For each branch, if active, it connects a bridge, resets the branch value, updates adjacent bridges, identifies the next node, reduces its remaining bridges, zeros its corresponding branch, and updates the node. The task is to propagate bridge connections and adjust adja... | def solveNode(self, i, j, valid):
for k in range(0, 4):
branchTemp = self.grid[i][j].branchValue[k]
if (branchTemp > 0):
self.connectBridge(i, j, k, valid[k])
self.grid[i][j].branchValue[k] = 0
self.updateAdjacentBridge(i, j, k, valid[k])
... |
def check_alien_collision(settings,alien,ship,screen,game_stats,bullet):
"""detecs alien and ship collision and calls ship hit reaction"""
if pygame.sprite.spritecollideany(ship,alien):
ship_hit(settings,game_stats,screen,ship,alien,bullet)
def check_alien_bottom(settings,alien,ship,screen,game_stats,bu... | The function `update_alien` updates alien movement and checks interactions. It calls functions to detect collisions with the ship/bullets, checks if aliens reach the screen bottom (game over condition), verifies fleet edge boundaries for direction changes, and updates the alien's position. This ensures proper alien beh... | def update_alien(settings,alien,ship,screen,game_stats,bullet):
"""call the update alien, moves alien"""
check_alien_collision(settings,alien,ship,screen,game_stats,bullet)
check_alien_bottom(settings,alien,ship,screen,game_stats,bullet)
check_fleet_edges(settings,alien)
alien.update() |
def load_MNIST():
(X_train, Y_train), (_, _) = mnist.load_data()
# Scale from -1 to 1
X_train = (np.float32(X_train) - 127.5) / 127.5
# expand to (60000, 28, 28, 1)
X_train = np.expand_dims(X_train, axis=3)
return X_train
def build_generator():
optimizer = Adam(lr=0.0002, decay=8e-9)
mod... | The code trains a Generative Adversarial Network (GAN) on the MNIST dataset. It alternates between training the discriminator on real/fake images and the generator using noise, with random label flipping to improve robustness. The GAN architecture is built from separate generator and discriminator models, and checkpoin... | def train():
X_train = load_MNIST()
generator = build_generator()
print(generator.summary())
discriminator = build_discriminator()
print(discriminator.summary())
gan = build_GAN(generator, discriminator)
print(gan.summary())
for epoch in range(NUMBER_OF_EPOCHS):
batch = 0
... |
def initialize(self):
parameters = {}
np.random.seed(self.seed)
L = len(self.layer_dims)
for l in range(1,L):
parameters['W'+str(l)] = np.random.randn(self.layer_dims[l],self.layer_dims[l-1])*np.sqrt(1/self.layer_dims[l-1])
parameters['b'+str(l)] = np.zeros((self.... | The code performs a gradient checking to verify the correctness of the backward propagation in a neural network. It computes analytical gradients via backpropagation and compares them with numerically approximated gradients by perturbing parameters and calculating cost differences. The relative difference between these... | def grad_check(self,X,Y,epsilon=1e-7,print_msg=False):
parameter = self.initialize()
AL , caches = self.L_forward_model(X,parameter)
grads = self.L_backward_model(AL,Y,caches)
layer = self.layer_dims
grad = {}
for l in range(1,len(layer)):
grad['dW'+str(l)] = ... |
def upload(filename, resource_type="image", extra_fields={}):
body = {
"api_key": api_key,
}
files = {
"file": open(filename, 'rb')
}
timestamp = int(time.time())
body["timestamp"] = timestamp
body.update(extra_fields)
body["signature"] = create_signature(body, api_sec... | The code processes an obituary submission by decoding multipart/form-data, extracting image and text fields, uploading the image to S3, generating text via a chat model, creating audio from the text, and storing structured obituary data in DynamoDB with associated media URLs. | def lambda_handler(event, context):
body = event["body"]
if event["isBase64Encoded"]:
body = base64.b64decode(body)
content_type = event["headers"]["content-type"]
data = decoder.MultipartDecoder(body, content_type)
binary_data = [part.content for part in data.parts]
name = binary_data... |
def get_args(argv):
parser = argparse.ArgumentParser(prog = 'tusv.py', description = "unmixes mixed copy numbers for breakpoints and segments and infers phylogeny with various phylogenetic constraints")
parser.add_argument('-i', '--input_directory', required = True, type = lambda x: fm.valid_dir_ext(parser, x, ... | The main task of the code is to process input data by unmixing it into components using specified parameters like the number of leaves, cluster constraints, and regularization terms. The `main` function parses command-line arguments, generates a README file, and orchestrates the unmixing process via the `unmix` functio... | def main(argv):
args = get_args(argv)
write_readme(args['output_directory'], args)
unmix(args['input_directory'], args['output_directory'], args['num_leaves'], args['c_max'], args['lambda1'], args['lambda2'], args['restart_iters'], args['cord_desc_iters'], args['processors'], args['time_limit'], args['metad... |
def gen_U(m, n):
U = np.random.rand(m, 2*n-1)
rowsums = np.sum(U, 1)
for i in xrange(m):
U[i, :] = U[i, :] / rowsums[i]
return U
def gen_F(Q, m, l, r, f_scale):
h_scale = float(f_scale) / 2.0 # scale for breakpoints
F = h_scale * np.random.rand(m, l + r)
for b in xrange(0, l):
for s in xrange(0, r):
if Q[... | The code sets parameters for a computational model, generates data structures (U, Q, F, G, A, H), and tests functions related to processing these structures. It involves testing methods like get_U, get_C, and get_UCE, which likely handle operations on genomic or similar data, with parameters for copy number analysis an... | def main(argv):
random.seed(1)
np.random.seed(1)
m = 3 # samples
n = 4 # leaves
l = 6 # breakpoints
r = 10 # segments
c_max = 7 # maximum copy number
f_scale = 5
U = gen_U(m, n)
Q = np.array([ np.arange(0, r) == random.randint(0, r-1) for bp in xrange(l) ], dtype = int)
F = gen_F(Q, ... |
def get_sample_dict(reader):
BP_sample_dict, CN_sample_dict, CN_sample_rec_dict_minor, CN_sample_rec_dict_major, CN_sample_rec_dict = dict(), dict(), dict(), dict(), dict()
SNV_sample_dict = {}
bp_id_to_mate_id = {} # key is id (str). val is mate id (str)
bp_id_to_tuple = {} # key is (chrm_num, pos, d... | The code processes genomic VCF files to generate matrices for analyzing structural variants (SVs) and single nucleotide variants (SNVs). It constructs data structures (dictionaries, graphs) from variant data, filters invalid entries (e.g., unpaired breakpoints, non-existent positions), and returns matrices (F_phasing, ... | def get_mats(in_dir, n, const=120, sv_ub=80):
print("get mats")
sampleList = fm._fnames_with_extension(in_dir, '.vcf')
m = len(sampleList)
sampleList.sort()
bp_id_to_mate_id, bp_id_to_tuple = {}, {}
BP_sample_dict, CN_sample_dict, CN_sample_rec_dict, CN_sample_rec_dict_minor, CN_sample_rec_di... |
def soft_thresh(x,thresh):
n = len(x)
res = np.zeros(n)
for i in range(n):
if np.abs(x[i])>thresh:
res[i] = x[i]-np.sign(x[i]-thresh)*thresh
if np.abs(x[i])<=thresh :
res[i] = 0
return(res)
def soft_thresh_der(x,thresh):
n = len(x)
res = np.zeros(n)
fo... | The code implements the Generalized Variational Approximate Message Passing (GVAMP) algorithm for signal recovery in inverse problems. It iteratively updates variables x and z using soft-thresholding, proximal operators, and matrix inversions, incorporating L1/L2 regularization. The algorithm tracks convergence metrics... | def GVAMP(F, y, x0, l1, l2, loss='squared', damp=0, nb_iterations=100, tol=1e-15):
#Initialization
M,N = np.shape(F)
Q1x_0=np.random.random()
Q2z_0=np.random.random()
h1x_0=np.random.rand(N)
h2z_0=np.random.rand(M)
rho_0 = np.linalg.norm(x0)
conv_vec = np.zeros(nb_iterations)
a... |
def dbconnect():
# connect to database
global mydb
resetDB()
try:
print("regular dbconnect")
mydb = mysql.connector.connect(
#connect to db
host="127.0.0.1",
user="root",
passwd="pwpw",
database="shenzhendata"
)
print(my... | The main task of the code is to execute a sequence of operations: print a message, connect to a database, preprocess data, and import the processed data into the database. The function orchestrates these steps in order, likely for data pipeline or ETL processes. | def main():
print("the main")
dbconnect()
preprocessing()
import_to_db() |
def _prepare_random_payment(self, start_channel, rand=random.Random()):
payment_hash = generate_payment_hash(rand)
num_hops = rand.randint(1, 19)
hops = self.generate_hops(
start_channel.remote_pubkey,
num_hops,
rand=rand
)
return (payment_has... | The code generates a random payment route starting from a given channel, prepares payment details (hash and hops), logs route information (hops, distance), and initiates the payment. It outputs the payment hash, route path, hop count, and route distance before sending the payment via the specified route. | def make_random_payment(self, start_channel):
pub_key = start_channel.remote_pubkey
print("\nAt chan: {} ({})".format(
pub_key,
self.channel_graph.get_node(pub_key).alias
))
payment_hash, hops = self._prepare_random_payment(start_channel)
route_distance =... |
def get_outs_and_runners(pitch_data):
runner1, runner2, runner3 = get_runners(pitch_data)
outs = pitch_data['outs_when_up']
return (outs, runner1, runner2, runner3)
def single(outs, runner1, runner2, runner3):
"""return the situation (outs & baserunners) that results from a single"""
r1 = True
r2 = runner1
r3 = ... | The function `get_end_re` calculates the **expected run expectancy** after a batted ball by evaluating outcomes (single, double, triple, home run, out) using a run expectancy matrix and a neural network model. It computes run expectancies for each outcome based on current game state (outs, runners), combines them with ... | def get_end_re(pitch_data, re_matrix, model):
"""gets run expectancy after a batted ball"""
outs, runner1, runner2, runner3 = get_outs_and_runners(pitch_data)
o, r1, r2, r3, runs = single(outs, runner1, runner2, runner3)
single_re = get_re_from_mat(re_matrix, o, r1, r2, r3) + runs #run expectancy of a single
o, r1... |
def change_in_re(pitch_data, re_matrix, model):
"""calculcate change in run expectancy from the beginning to the end of a plate appearance"""
start = get_start_re(pitch_data, re_matrix)
end = get_end_re(pitch_data, re_matrix, model)
delta = start - end #subtract this way so that higher number is better
return delt... | The code processes Statcast data to calculate run expectancy changes for pitchers based on specific play types (e.g., strikes, walks). It iterates through each row, applies different calculation functions (change_in_re, strikeout, walk) depending on event types, aggregates results in a dictionary, and returns a DataFra... | def season_change_2(statcast_data, re_matrix, model):
values = {}
for index, row in statcast_data.iterrows():
try:
if row['type'] == 'X':
if 'bunt' in row['des'].lower():
continue
val = change_in_re(row, re_matrix, model)
add_to_dict(values, row['pitcher'], val)
elif row['events'] in ['strike... |
def get_statcast_data():
dfs = [pd.read_csv('data/statcast_data{}.csv'.format(i)) for i in range(3,10)]
return pd.concat(dfs)
def load_re_matrix():
"""run expectation matrix"""
return pd.read_csv('re_matrix.csv', delimiter='\t', index_col=0)
def season_change_2(statcast_data, re_matrix, model):
values = {}
for in... | The main task of the code is to calculate and merge player value metrics (Value/G, Value/IP, Value/BF) from statcast data with MLB pitching statistics for 2019, adjusting innings pitched to standard 1/3 increments, then sorting results by total Value in descending order for performance analysis. | def calculate():
statcast_data = get_statcast_data()
re_matrix = load_re_matrix()
model = load_model()
values = season_change_2(statcast_data, re_matrix, model)
ids = get_id_table()
table = pd.merge(values, ids, how='inner', left_on=['id'], right_on=['mlb_id'])
stats = pitching_stats.pitching_stats_bref(2019)
t... |
def forward(model, batch, calc_acc=False):
outputs = model(**batch)
loss = outputs.loss
stats = {}
stats['loss'] = loss.detach().float().item()
if calc_acc:
correct = (outputs.logits.argmax(-1) == batch["labels"]).sum().item()
accuracy = correct / batch["labels"].numel()
st... | The code trains a model using gradient accumulation, logging, evaluation, and checkpointing. It iterates over training data, computes loss, performs backpropagation, updates the optimizer, adjusts the learning rate, logs metrics, evaluates on test data, and saves checkpoints. The loop continues until the total training... | def train(model, train_dataloader, test_dataloader, accelerator, lr_scheduler,
optimizer, logger, args, tokenizer):
model.train()
train_averager = Averager()
while args.current_train_step <= args.optim.total_steps:
if isinstance(train_dataloader.dataset, IterableDataset):
tra... |
def MakeRevertVocab(vocab):
dic = {}
for k, v in vocab.items():
dic[v] = k
return dic
def MakeInput(char, vocab, arr):
idx = vocab[char]
tmp = np.zeros((1,))
tmp[0] = idx
arr[:] = tmp
def MakeOutput(prob, vocab, sample=False, temperature=1.):
if not sample:
idx = np.argma... | This code generates text using a pre-trained LSTM model. It loads model parameters, initializes an inference model with GPU context, and iteratively predicts the next character based on a starter sentence. The model generates a 600-character sequence by feeding its own predictions back as input, appending results to th... | def generate_txt():
_, arg_params, __ = mx.model.load_checkpoint("obama", 75)
# build an inference model
model = rnn_model.LSTMInferenceModel(
num_lstm_layer,
len(vocab) + 1,
num_hidden=num_hidden,
num_embed=num_embed,
num_label=len(vocab) + 1,
arg_params=arg... |
def has_empty_weights(module: nn.Module, recurse: bool = False) -> bool:
"""
Check if a module has any empty weights.
Parameters
----------
module : nn.Module
PyTorch module to check for empty weights.
recurse : bool, default=False
If True, recursively check sub-modules, by defa... | This function loads weights into a neural network module, handling memory optimization by freeing unused tensors. It fetches required weights, filters them if preloading is disabled, and loads them into the model. If some weights remain unloaded, it issues warnings about missing weights. The process ensures efficient m... | def weights_loading_hook(self, *args, **kwargs) -> None:
# If there are no empty weights then we don't need to run
if not has_empty_weights(self):
return None
# Free previously unreferenced tensors
free_memory()
# Get the empty weights names for the current module o... |
def clean_output_dir(self):
# Clean output path
files = glob.glob('output/*')
for f in files:
os.remove(f)
def load_yolo(self):
# load the COCO class labels our YOLO model was trained on
labelsPath = os.path.sep.join([self.yolo_path, "aerial.names"])
LABELS = ... | This code initializes a vehicle tracking and counting system using YOLO for object detection and Sort tracker for ID assignment. It sets up input/output paths, loads YOLO model, initializes line counters, memory storage, and video processing components. The main task is to process video frames, detect cars, track them ... | def __init__(self, input_path, output_path, yolo_path, confidence_val, threshold_val):
# Get inputs from user
self.input_path = input_path
self.output_path = output_path
self.yolo_path = yolo_path
self.confidence_val = confidence_val
self.threshold_val = threshold_val
... |
def iterations(list_points, list_speeds, slicing=1000):
figures = []
for i in range(len(list_points[::slicing])):
points = list_points[::slicing]
speeds = list_speeds[::slicing]
point = points[i]
speed = speeds[i]
figure = Plot(start, end, point, sensors, speed)
f... | The function `Visialise` generates visualizations of iterative data by plotting the last iteration's points and speeds using a specified density, and separately visualizing energy data from `Iter_E`, utilizing the `Plot` and `PlotE` functions. | def Visialise(Iter_Points, Iter_Speeds, Iter_E, slicing = 5000):
length = len(iter_Points)
points = iter_Points[length-1]
speeds = iter_Speeds[length-1]
iterations(iter_Points, iter_Speeds, slicing)
density = 250
a = Plot(start, end, points, sensors, speeds, density)
b = PlotE(Iter_E) |
def evaluate_the_grid(self, rays):
# Given a (Batch*dt) x 3 rays, output a tensor with shape (Batch*dt) x 4
# rays = torch.randn([500,3])
#Normalization to -1, 1
grid = rays.reshape(1, 1, 1, -1, 3)
# the padding_mode and align_corners setting should be doublechecked after we have... | The function performs volumetric rendering using neural fields by computing signed distance functions (SDF), gradients, and colors for ray samples. It estimates ray section properties, calculates weights via cumulative product, blends with background if provided, and returns rendered color, SDF, gradients, and Eikonal ... | def render_core(self,
rays_o,
rays_d,
z_vals,
sample_dist,
background_alpha=None,
background_sampled_color=None,
background_rgb=None,
cos_anneal_ratio=0.0): #is... |
def update_learning_rate(self):
if self.iter_step < self.warm_up_end:
learning_factor = self.iter_step / self.warm_up_end
else:
alpha = self.learning_rate_alpha
progress = (self.iter_step - self.warm_up_end) / (self.end_iter - self.warm_up_end)
learning_fa... | The code trains a neural renderer to generate realistic images by optimizing a loss function that combines color accuracy, eikonal loss (for surface normals), and mask alignment. It uses random camera poses and lighting, renders rays, and iteratively updates model parameters via backpropagation to minimize the loss, lo... | def train(self, img_batch_size, resolution):
self.writer = SummaryWriter(log_dir=os.path.join(self.base_exp_dir, 'logs'))
if self.method == 'Network':
self.update_learning_rate()
res_step = self.end_iter - self.iter_step
# image_perm = self.get_image_perm()
Batch_size... |
def evaluate_the_grid(self, rays):
# Given a (Batch*dt) x 3 rays, output a tensor with shape (Batch*dt) x 4
# rays = torch.randn([500,3])
#Normalization to -1, 1
grid = rays.reshape(1, 1, 1, -1, 3)
# the padding_mode and align_corners setting should be doublechecked after we have... | This function performs volumetric rendering by sampling along rays, applying perturbation and up-sampling for detail, and combining inside/outside scene contributions. It returns refined colors, weights, gradients, and other metrics for each ray, enabling realistic 3D scene rendering with neural networks. | def render(self, rays_o, rays_d, near, far, perturb_overwrite=-1, background_rgb=None, cos_anneal_ratio=0.0):
batch_size = len(rays_o)
sample_dist = 2.0 / self.n_samples # Assuming the region of interest is a unit sphere
z_vals = torch.linspace(0.0, 1.0, self.n_samples)
z_vals = near +... |
def get_alphas(emotion, all_annotations, subtract_mode=False):
'''
Compute Krippendorff's alphas.
Parameters
----------
emotions: string
an emotion category name to compute IRR for.
all_annotations: dict
of the form {'perspective': dict}, where sub-dicts are of the form {'pid': d... | The main task of the code is to generate heatmaps for seven emotions (arousal, valence, cheerful, happy, angry, nervous, sad) using Krippendorff's alpha values from the input annotations. It visualizes these metrics in a grid of subplots, normalizing data to a -1 to 1 scale, adding color bars, and annotating cells with... | def plot_heatmaps(all_annotations):
'''
Plots heatmaps for seven emotions of 'arousal', 'valence', 'cheerful', 'happy', 'angry', 'nervous', and 'sad'.
Parameters
----------
all_annotations: dict
of the form {'perspective': dict}, where sub-dicts are of the form {'pid': dataframe}
... |
def _gen_ansatz(self, params: List[float]) -> List[cirq.Circuit]:
qubits = cirq.LineQubit.range(self.num_qubits)
z_circuit = cirq.Circuit()
param_counter = 0
for _ in range(self.num_layers):
# Ry rotation block
for i in range(self.num_qubits):
z_c... | The function computes the negative expectation value of a Hamiltonian $ H $ using quantum circuits. It generates ansatz circuits from input parameters, calculates ideal probabilities for $ z $- and $ x $-basis measurements, and combines them to estimate $ H $'s expected value. The result is returned as $ -H_{\text{expe... | def f(params: List) -> float:
z_circuit, x_circuit = self._gen_ansatz(params)
z_probs = self._get_ideal_probs(z_circuit)
x_probs = self._get_ideal_probs(x_circuit)
H_expect = self._get_expected_H_from_probs(z_probs, x_probs)
return -H_expect |
def _get_expected_H_from_probs(self, probs_Z: Counter, probs_X: Counter) -> float:
avg_energy = 0.0
# Find the contribution to the energy from the X-terms: \sum_i{X_i}
for bitstr in probs_X.keys():
bit_list_X = [bitstr[i] for i in range(len(bitstr))]
avg_energy += self._... | The main task of the code is to compute a score comparing the average energy from experimental measurements (Z and X basis probabilities) to the ideal energy from noiseless simulations. It normalizes experimental and ideal probabilities, calculates their expected Hamiltonian values, and returns a fidelity metric (1 - |... | def score(self, counts: List[Counter]) -> float:
"""Compare the average energy measured by the experiments to the ideal
value obtained via noiseless simulation. In principle the ideal value
can be obtained through efficient classical means since the 1D TFIM
is analytically solvable.
... |
def handle_corner_click(self, idx, is_left):
# self.change_text("You {} clicked on corner {}.\n The adjacent cells are:\n {}".format("left" if is_left else "right", idx,"\n".join(map(lambda s: str(s),self.corners[idx]))))
# self.remove_children(idx)
# self.add_circle(idx, 10, "orange")
#... | This code handles mouse clicks on a canvas by determining if the click occurred on a corner, edge, or center of an item. It checks overlapping items at the click coordinates, prioritizes corners, then edges, then centers, and triggers corresponding handler methods while updating the last click state. | def handle_click(self, x, y, is_left):
items = self.c.find_overlapping(x,y,x+5,y+5)
if len(items)==0:
return
corner = False
corner_idx = None
for nearby in items:
if nearby in self.corners:
corner = True
self.last_click=(ne... |
def tutorial_board(self):
y = "yellow"
p = "purple"
r = "red"
g = "green"
o = "orange"
b = "blue"
palette = [y,p,r,g,o,b]
self.board_colors = [[choice(palette) for i in range(self.width)] for j in range(self.height)]
self.part_of_flood = np.full... | This function initializes an easy game mode by setting up the game board with predefined color configurations, handling tutorial mode, initializing game state variables like move count and flood regions, and triggering the initial click on the top-left corner to start the game. | def new_easy_game(self):
#runs before starting the game; you can use this to set up the game
if self.in_tutorial == True:
self.tutorial_board()
return
self.total_moves = 23
y = "yellow"
p = "purple"
r = "red"
g = "green"
o = "oran... |
def tutorial_board(self):
y = "yellow"
p = "purple"
r = "red"
g = "green"
o = "orange"
b = "blue"
palette = [y,p,r,g,o,b]
self.board_colors = [[choice(palette) for i in range(self.width)] for j in range(self.height)]
self.part_of_flood = np.full... | This function initializes a "hard" difficulty game by setting up the board with predefined color configurations, handling tutorial mode, initializing game variables like move count, and triggering the first move on the top-left corner to start the game. | def new_hard_game(self):
#runs before starting the game; you can use this to set up the game
self.game_type = "hard"
if self.in_tutorial == True:
self.tutorial_board()
return
self.total_moves = 19
y = "yellow"
p = "purple"
r = "red"
... |
def new_easy_game(self):
#runs before starting the game; you can use this to set up the game
if self.in_tutorial == True:
self.tutorial_board()
return
self.total_moves = 23
y = "yellow"
p = "purple"
r = "red"
g = "green"
o = "oran... | The code initializes a new game by resetting move counters, disabling the tutorial, and starting either an easy or hard game mode based on `self.game_type`. It then updates the displayed text to show the current move count. | def start_game(self, key):
self.move_count = 0
self.in_tutorial = False
if self.game_type == "easy":
self.new_easy_game()
else:
self.new_hard_game()
self.change_text(("Moves: ", self.move_count, " / ", self.total_moves)) |
def readFormulaFile(text):
lines = text.strip().split('\n')
num_clauses = -1
num_props = -1
formula_dict = {}
clause_idx = 0
for line in lines:
clause_idx += 1
words = line.split()
if (words[0]=="c"):
continue
elif(words[0]=="p"):
num_p... | The code determines the type of a logical formula (Horn, renamable Horn) or converts it to a 2-CNF format. For `n=1`, it checks if the formula is Horn. For `n=2`, it generates a 2-CNF representation. For `n=3`/`4`, it checks renamable Horn status, returning "renamable" (with assignments for `n=4`) or "not renamable". T... | def solve(inputString, n):
formula_dict = readFormulaFile(inputString)
if(n==1):
if(checkHorn(formula_dict)):
return "already horn"
else:
return "not horn"
elif(n==2):
gDict,num_props,num_clauses = returnG(formula_dict)
final_ans = "c 2-CNF formula which is sat iff input is renamable Horn\n"
final_... |
def readFormulaFile(formula_file):
text = open(formula_file,"r")
lines = text.readlines()
num_clauses = -1
num_props = -1
formula_dict = {}
clause_idx = 0
for line in lines:
clause_idx += 1
words = line.split()
if (words[0]=="c"):
continue
elif(... | The code processes a logical proof file against a given formula, generating an output file. It reads formulas and a modified proof, then recursively validates the proof structure. If valid, it outputs the proof entries; otherwise, replaces "??” with "np” to indicate placeholders. The main task is to validate and format... | def solve(formula_file,modified_proof_file,ouput_file):
proof_file = modified_proof_file
outputFileName = ouput_file
TEST = False
formula_dict = readFormulaFile(formula_file)
if(DEBUG): print("FORMULA: "+str(formula_dict))
proof_dict = {}
proof_idx = 0
ptext = open(proof_file,"r")
... |
def Combine(Y, l_x, pair1, pair2):
p1, p2 = pair1
p3, p4 = pair2
if p1 is None:
return p3, p4
elif p3 is None:
return p1, p2
d1 = distance(p1, p2)
d2 = distance(p3, p4)
if d1 < d2:
p5, p6 = p1, p2
d = d1
else:
p5, p6 = p3, p4
d = d2
... | This function finds the closest pair of points in a set using a divide-and-conquer approach. It recursively splits the point set into halves, computes closest pairs in each half, and combines results by checking points near the dividing line. The base case uses brute-force for small subsets. | def FindClosestPoints(X, Y):
if len(X) > 3:
m = len(X) // 2
l_x = (X[m].x + X[m+1].x) / 2
X_l = X[:m]
X_r = X[m+1:]
p1, p2 = FindClosestPoints(X_l, Y)
p3, p4 = FindClosestPoints(X_r, Y)
p5, p6 = Combine(Y, l_x, (p1, p2), (p3, p4))
return p5, p6
... |
def leftmost_lowest(points):
return min(points, key=lambda p: (p.x, p.y))
def merge_sort(arr, p, r, p0):
if p < r:
q = (p + r) // 2
merge_sort(arr, p, q, p0)
merge_sort(arr, q + 1, r, p0)
merge(arr, p, r, q, p0)
def turns_left(p0, p1, p2):
x0, y0 = p0.x, p0.y
x1, y1 = p1.... | The main task of the code is to compute the convex hull of a set of 2D points using the Graham scan algorithm. It identifies the leftmost lowest point, sorts remaining points by polar angle, and constructs the hull by iteratively checking left turns to remove non-convex points, returning the convex hull as a list of ve... | def graham_scan(X):
p0 = leftmost_lowest(X)
Q = [p for p in X if p != p0]
merge_sort(Q, 0, len(Q) - 1, p0)
S = [p0, Q[0], Q[1]]
for i in range(2, len(Q)):
while len(S) >= 2 and not turns_left(S[-2], S[-1], Q[i]):
S.pop()
S.append(Q[i])
return S |
def instruction_step(self):
try:
self.data_path.fetch_instruction()
self.tick("Fetch instruction (IP -> AR, mem[IP] -> CR)")
self.tick("Fetch Instruction (IP + 1 -> IP)")
if self.data_path.cr.opcode.get_type() in [CommandTypes.DATA, CommandTypes.JUMP]:
... | This code executes instructions in a simulated processor, handling interrupts like input, error, or halt. It runs instruction steps in a loop until an interrupt changes, processes input interrupts by updating memory and program counter, and recursively calls itself for NONE interrupts. It returns the output, tick count... | def run(self, interrupt_type=InterruptType.NONE):
while self.interrupt == interrupt_type:
self.instruction_step()
self.instruction_counter += 1
if self.interrupt == InterruptType.INPUT:
self.__print__(f"Input: {self.data_path.memory[IN_ADDR].value}")
self... |
def trimmer(code):
result = []
for line in code:
if ";" in line:
line = line[: line.index(";")]
line = line.strip()
if line:
result.append(line)
return result
def section_split(source):
data, code = [], []
section = None
for line in source:
... | The code translates input data (asmm) into a structured JSON format by trimming, splitting into data/code sections, building instruction sets, and extracting start/interrupt addresses for disassembly or analysis. | def translate(asmm):
result = trimmer(asmm)
data, code = section_split(result)
ins = Instructions()
build_data(data, ins)
start_address, interrupt_address = build_code(code, ins)
result = json_builder(ins)
return result, start_address, interrupt_address |
def cfgrad_vec(angles, matrix, na,nr, n_measurements, bitmap, param_list): # Calculates gradient of cost function
# Returns 2 outputs
vvec = copy.deepcopy(angles)
nq, cdepth, nparam = na+nr, int(len(angles)/(na+nr)), len(angles) # Get number of qubits, depth of circuit number of parameters
mes_res... | The code implements a **stochastic gradient descent (SGD)** algorithm to optimize quantum circuit parameters (angles) by minimizing a cost function defined by a matrix and measurements. It iteratively updates angles using gradient estimates, tracks cost function values and parameter history, and returns the optimal ang... | def minimize(self, n_qubits, c_depth, matrix, angles, measurements, max_shots = None):
print("Stochastic gradient descent")
sst1 = time.time()
# Initial params/data/hyperparams
nreg = int(np.ceil(np.log2(len(matrix)/self.n_ancilla)))
ini... |
def cfgrad_vec(angles, matrix, na,nr, n_measurements, bitmap, param_list): # Calculates gradient of cost function
# Returns 2 outputs
vvec = copy.deepcopy(angles)
nq, cdepth, nparam = na+nr, int(len(angles)/(na+nr)), len(angles) # Get number of qubits, depth of circuit number of parameters
mes_res... | This function implements the ADAM optimizer to minimize a quantum circuit's cost function by iteratively updating parameters (angles) using gradient descent with momentum and adaptive learning rates. It computes gradients, updates moments, applies bias correction, and tracks optimal angles and cost values over iteratio... | def adam(self, n_qubits, c_depth, matrix, angles, measurements, max_shots = None):
print("ADAM optimizer")
sst1 = time.time()
# Initial params/data/hyperparams
nreg = int(np.ceil(np.log2(len(matrix)/self.n_ancilla)))
initial_angles = copy.deepc... |
def print_board(board):
for row in board:
print(" | ".join(row))
print("---------")
def check_winner(board, player):
# Check rows, columns, and diagonals for a winner
for i in range(3):
if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
... | The code implements a Tic-Tac-Toe game where users can choose between Player vs Player or Player vs Computer modes. It handles symbol selection, validates inputs, manages the game board, checks for wins/draws, and alternates turns. In Player vs Computer mode, the AI selects optimal moves using a predefined function, wi... | def play_tic_tac_toe():
player_choice = input("Choose Game Mode :\n1. Player vs Player\n2. Player vs Computer\nEnter Choice (1/2) : ")
if player_choice not in ('1', '2'):
print("Invalid Choice. Please Enter Either '1' or '2'.")
return
if(player_choice == '1'):
player_symbol = i... |
def setChan(self, ch):
self.write('inst:nsel ' + str(ch))
def write(self, msg):
self.connGpib()
self.pro.write(msg)
def read(self):
return self.pro.read() | The main task of the code is to check whether the output of a specified channel (1, 2, or 3) is enabled (True) or disabled (False). It achieves this by setting the channel, querying its output status via a command, converting the response to a boolean, and returning the result. | def getOutput(self, ch):
'''
check if the output of a channel (1,2,3) is on (True) or off (False)
'''
self.setChan(ch)
self.write('CHAN:OUTP:STAT?')
out = bool(float(self.read()))
return out |
def setChan(self, ch):
self.write('inst:nsel ' + str(ch))
def write(self, msg):
self.connGpib()
self.pro.write(msg)
def read(self):
return self.pro.read() | The code measures the voltage on a specified channel by setting the channel, sending a measurement command, reading the response, converting it to a float, and returning the voltage value. | def getVolt(self, ch):
self.setChan(ch)
self.write('MEAS:VOLT? CH' + str(ch))
voltage = float(self.read())
return voltage |
def setChan(self, ch):
self.write('inst:nsel ' + str(ch))
def write(self, msg):
self.connGpib()
self.pro.write(msg)
def read(self):
return self.pro.read() | This code measures the current on a specified channel (ch) of a device. It sets the channel using `setChan`, sends a measurement command (`MEAS:CURR? CH#`), reads the result, converts it to a float, and returns the current value. The function interfaces with hardware to retrieve real-time current data for the given cha... | def getCurr(self, ch):
self.setChan(ch)
self.write('MEAS:CURR? CH' + str(ch))
current = float(self.read())
return current |
def setChan(self, ch):
self.write('inst:nsel ' + str(ch))
def enable(self, ch):
'''
Enables output for channel (1,2,3) but does not turn it on.
Depending on state of power supply, it might need to be called
before the output is set.
'''
self.setChan(ch)
... | This function sets the output status (ON/OFF) of a specified power supply channel by sending the appropriate SCPI command. It first selects the channel, enables it, then checks the input type to determine whether to send 'ON', 'OFF', or the raw string command. The function ensures the channel is active and configured b... | def setOutput(self, ch, out):
'''
set status of power supply channel
ch - channel (1,2,3) to set status
out - ON: True|1|'ON' OFF: False|0|'OFF'
Calls enable to ensure a channel can be turned on. We might want to
make them separate (and let us use disable as a safety fe... |
def str_to_a32(b):
if isinstance(b, str):
b = makebyte(b)
if len(b) % 4:
# pad to multiple of 4
b += b'\0' * (4 - len(b) % 4)
return struct.unpack('>%dI' % (len(b) / 4), b)
def aes_cbc_encrypt_a32(data, key):
return str_to_a32(aes_cbc_encrypt(a32_to_str(data), a32_to_str(key)))
d... | The function `stringhash` computes a custom hash of a string using AES-CBC encryption. It converts the input string to a 32-bit array, initializes a hash state, XORs the string's 32-bit components into the hash, then applies 16,384 rounds of AES-CBC encryption with the provided key. The final 32-bit hash values are enc... | def stringhash(str, aeskey):
s32 = str_to_a32(str)
h32 = [0, 0, 0, 0]
for i in range(len(s32)):
h32[i % 4] ^= s32[i]
for r in range(0x4000):
h32 = aes_cbc_encrypt_a32(h32, aeskey)
return a32_to_base64((h32[0], h32[2])) |
def _login_user(self, email, password):
logger.info('Logging in user...')
email = email.lower()
get_user_salt_resp = self._api_request({'a': 'us0', 'user': email})
user_salt = None
try:
user_salt = base64_to_a32(get_user_salt_resp['s'])
except KeyError:
... | The code's main task is to authenticate a user via email/password or anonymously, retrieve the trash folder's node ID, and log completion. It handles login logic, sets up the trash folder reference, and returns the instance for method chaining. | def login(self, email=None, password=None):
if email:
self._login_user(email, password)
else:
self.login_anonymous()
self._trash_folder_node_id = self.get_node_by_type(4)[0]
logger.info('Login complete')
return self |
def get_node_by_type(self, type):
"""
Get a node by it's numeric type id, e.g:
0: file
1: dir
2: special: root cloud drive
3: special: inbox
4: special trash bin
"""
nodes = self.get_files()
for node in list(nodes.items()):
if n... | This function retrieves files associated with a specified node (e.g., trash can) by querying an API, processing the response, and returning a dictionary of files filtered to match the target node. It handles both integer-based special nodes and direct node IDs, converting them as needed, then filters results to include... | def get_files_in_node(self, target):
"""
Get all files in a given target, e.g. 4=trash
"""
if type(target) == int:
# convert special nodes (e.g. trash)
node_id = self.get_node_by_type(target)
else:
node_id = [target]
files = self._api_... |
def get_node_by_type(self, type):
"""
Get a node by it's numeric type id, e.g:
0: file
1: dir
2: special: root cloud drive
3: special: inbox
4: special trash bin
"""
nodes = self.get_files()
for node in list(nodes.items()):
if n... | The main task of the code is to import a public file into a user's cloud storage by encrypting its key and name, then making an API request to add it to the specified destination. If no destination node or name is provided, it defaults to the '/Cloud Drive' folder and the file's original name. The function handles encr... | def import_public_file(self,
file_handle,
file_key,
dest_node=None,
dest_name=None):
"""
Import the public file into user account
"""
# Providing dest_node spare an API call to ret... |
def find_path_descriptor(self, path, files=()):
"""
Find descriptor of folder inside a path. i.e.: folder1/folder2/folder3
Params:
path, string like folder1/folder2/folder3
Return:
Descriptor (str) of folder3 if exists, None otherwise
"""
paths = p... | This function creates a folder hierarchy by recursively generating directories from a given path name. It checks if each directory already exists, reusing existing nodes when possible, and creates new ones if not. The parent node for each directory is determined sequentially, starting from a root or specified destinati... | def create_folder(self, name, dest=None):
dirs = tuple(dir_name for dir_name in str(name).split('/') if dir_name)
folder_node_ids = {}
for idx, directory_name in enumerate(dirs):
existing_node_id = self.find_path_descriptor(directory_name)
if existing_node_id:
... |
def get_files(self):
logger.info('Getting all files...')
files = self._api_request({'a': 'f', 'c': 1, 'r': 1})
files_dict = {}
shared_keys = {}
self._init_shared_keys(files, shared_keys)
for file in files['f']:
processed_file = self._process_file(file, shared_... | The code exports a file or folder by encrypting node keys with AES, generating share keys, and making an API request to retrieve a downloadable link, returning the folder link after processing. | def export(self, path=None, node_id=None):
nodes = self.get_files()
if node_id:
node = nodes[node_id]
else:
node = self.find(path)
node_data = self._node_data(node)
is_file_node = node_data['t'] == 0
if is_file_node:
return self._expor... |
def _parse_url(self, url):
"""Parse file id and key from url."""
if '/file/' in url:
# V2 URL structure
url = url.replace(' ', '')
file_id = re.findall(r'\W\w\w\w\w\w\w\w\w\W', url)[0][1:-1]
id_index = re.search(file_id, url).end()
key = url[id... | This method deletes a file by parsing its URL to extract a public handle, converting it to a file ID, and then moving the file to a deleted state using the move method with a status code of 4. | def delete_url(self, url):
"""
Delete a file by its url
"""
path = self._parse_url(url).split('!')
public_handle = path[0]
file_id = self.get_id_from_public_handle(public_handle)
return self.move(file_id, 4) |
def medial(arrays):
"""Returns a rational approximation to the median of each component.
Each entry in arrays is assumed to be a numpy.array() of some
given size, with different components having potentially very
different scales. For each component, this looks at that
component of each entry in a... | The function `contrast` compares datasets in 'passed/' and 'failed/' subdirectories under `pairdir` to highlight differences. It reads CSV data, rescales numeric columns to align their medians, filters out irrelevant columns, and computes the salient differences (delta) between the datasets. The output includes rescale... | def contrast(pairdir):
"""Contrast failed/ with passed/ datasets under pairdir.
Singe parameter, pairdir, should name a directory under which may
be found data, in the CSV-vased form expected by coincsv, in each
of two subdirectories failed/ and passed/.
This attempts to report on the salient diff... |
def do_n_attacks(vae, victim_sentence, victim_model, ppl, use, args):
victim_label = prob_to_label(victim_model(victim_sentence))
# Get sentences with the different label.
import nlp
sst2_data = nlp.load_dataset('glue', 'sst2')['train']
sentences = [e['sentence'] for e in sst2_data if e['label'] !=... | The code evaluates adversarial attacks on a victim model using the SST-2 dataset. It generates adversarial examples via a VAE, compares original/attacked sentences' predictions and perplexity, and saves results in a timestamped JSON file. | def do_evaluation(vae, victim_model, ppl, use, args):
# Get validations examples.
import nlp
sst2_data = nlp.load_dataset('glue', 'sst2')['validation']
victim_sentences = sst2_data['sentence']
victim_sentences = random.sample(victim_sentences, args.n_eval)
advs = []
for i, vs in enumerate(v... |
def find_basins(field: List[List[int]]) -> Generator[Tuple[int, int], None, None]:
for y in range(len(field)):
for x in range(len(field[y])):
neighbour = get_neighbours(x, y)
values = [field[y][x] for x, y in neighbour]
if field[y][x] < min(values):
... | The code processes a grid of elevation values to identify basins (regions of low elevation), calculates their sizes, and returns the product of the three largest basin sizes. It converts input lines into a numerical grid, locates basins, measures each basin's area, sorts sizes in descending order, and computes the prod... | def solve(lines: List[str]):
global field
field = [[int(c) for c in line] for line in lines]
basins = find_basins(field)
sizes = []
for b in basins:
size = measure_size(b, set())
sizes.append(size)
sizes.sort(reverse=True)
return prod(sizes[:3]) |
def loginAdmin():
max_attempt = 5
username = "admin"
password = "admin123"
for i in range(max_attempt):
name = input("Enter your username: ")
psw = input("Enter you password: ")
if name == username and psw == password:
print("login Successful, you'r Welcome as Admin!")
return True
at... | The code's main task is to manage a ticketing system by authenticating users (admin or normal) and directing them to respective menus. Admins log in to access admin functionalities, while users log in to interact with their menu. If a user creates a new ticket, it is saved. The loop continues until invalid input or suc... | def main():
print("Welcome to the Ticketing System :)")
while True:
input_type = input("Type A/a for Admin or U/u for normal User: ")
if input_type == "a" or input_type == "A":
if loginAdmin():#check if the result of loginAdmin is True
adminMenu(tickets_list)#if true, call adminMenu() fnc
... |
def set_limit_price(self,
product: str,
factor: float = 0.1,
granuality: str = "1m") -> float:
recent_data = self._get_candle_data(product=product, granuality=granuality)
price_stats = self._price_stats(symbol=product)
re... | This function sets up a limit order using a specified factor from trade_info. It calculates the limit price, updates trade_info with price details, and executes the order if valid. If successful, it logs details and marks the setup as complete; otherwise, it logs errors. If no factor is provided, it disables the limit ... | def trigger_limit_order(self,
amount: float,
market: str,
trade_info: Dict[str, Any],
limit_tag: str = "limit_order",
stage_granuality: str = "1m") -> Dict[str, Any]:
"""
... |
def get_ticker(self, symbol: str):
# Get ticker - Combine version 1 and 2 of the ticket
response = requests.get(self.puplic_url + f"/v1/pubticker/{symbol.lower()}")
market_data_v1 = response.json()
response = requests.get(self.puplic_url + f"/v2/ticker/{symbol.lower()}")
market_... | This function simulates a market order by placing an "immediate-or-cancel" limit order with an aggressively high buy price (twice the current bid) to achieve market-order-like execution. It calculates the required crypto amount, constructs the API payload, submits the order, and waits until it completes, returning the ... | def create_market_order(self,
amount: float,
product: str = "btcgbp",
tag: str = "") -> Dict[str, Any]:
"""
The API doesn't directly support market orders because they provide you with no price protection.
Instea... |
def pre_process(curr_file):
transactions_df = read_file(curr_file)
line_no = 0
for amount in transactions_df['Amount']:
if not (is_num(amount)):
logging.warning(f'"{amount}" is not a numeric value at line {line_no}, transaction removed')
transactions_df = transactions_df.dro... | The main task of the code is to process transaction files (JSON/CSV/XML), allowing users to interactively view account data (list all entries or specific transactions), switch files, and export data. It logs actions, validates file formats, and provides a menu-driven interface for managing financial records with debugg... | def main():
logging.info(f'Execution started')
curr_file = TRANSACTIONS_FILE
if (curr_file.lower().endswith(('.json', '.csv', '.xml'))):
updated_accounts = pre_process(curr_file)
selection = ''
while selection != QUIT_MENU:
print_menu(curr_file)
logging.info(f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.