dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_symbol(self):
self.symbols = self.filter_symbols()
self.symbol_name = st.selectbox("Select Instrument", self.symbols.name)
self.symbol = self.symbols.loc[self.symbols['name'] == self.symbol_name].index[0]
def get_start_end(self):
default_start_date, default_end_da... | The main task of the code is to generate and display financial charts and related data for a given stock symbol. It fetches stock information, allows users to view news, and toggles between chart display modes (browse or show). The function retrieves stock data, indicators, and renders time-based charts (minutes/days) ... | def handle_option_chart(self):
self.get_symbol()
# Set start and end point to fetch data
self.get_start_end()
self.get_chart_indicators()
if st.checkbox('Display News'):
info_downloader = InfoDownloader(self.symbol_name)
... |
def get_chart_indicators(self):
self.display_checkboxes_moving_averages(self.exponential_moving_averages)
self.display_checkboxes_quant_figure_indicators()
def get_start_end(self):
default_start_date, default_end_date = self.get_default_start_end()
self.start_date = st.sidebar.date_input... | This method processes sector ETF data by retrieving chart indicators and time frames, then iterates through sector-ETF pairs to generate minute and daily analysis figures for each. It sets symbols and names dynamically, enabling comparative financial visualization across sectors. | def handle_option_sectors(self):
self.get_chart_indicators()
self.get_start_end()
for sector in self.sector_etf:
self.symbol = self.sector_etf[sector]
self.symbol_name = sector + ' ' + self.sector_etf[sector]
self.quant_figure_minutes()
... |
def get_selected_stocks(self):
selected_market = st.sidebar.selectbox(options=["SP500", "NASDAQ100", "DJ30", "DAX", "eToro"], label="Market")
stock_data = PyTickerSymbols()
if selected_market == 'DJ30':
stocks = stock_data.get_dow_jones_nyc_yahoo_tickers()
... | The main task of the code is to generate quantitative stock charts (minutes/days) based on user inputs. It handles both uploaded CSV files (with Symbol/Name columns) and pre-selected stocks, using checkboxes to toggle time frames and a button to trigger chart display. The function processes data, sets symbols/names, an... | def handle_option_watchlist(self):
stocks = self.get_selected_stocks()
self.get_chart_indicators()
self.get_start_end()
show_minutes = st.sidebar.checkbox('Show Minutes')
show_days = st.sidebar.checkbox('Show Days')
uploaded_file = st.file_uploader("Choose a cs... |
def get_selected_stocks(self):
selected_market = st.sidebar.selectbox(options=["SP500", "NASDAQ100", "DJ30", "DAX", "eToro"], label="Market")
stock_data = PyTickerSymbols()
if selected_market == 'DJ30':
stocks = stock_data.get_dow_jones_nyc_yahoo_tickers()
... | The main task of the code is to calculate and display intraday momentum scores and volatility for selected stocks using historical price data. It retrieves stock prices, computes momentum metrics via the MomentumScore class, and visualizes results in Streamlit, including last-trading-day prices, intraday momentum, and ... | def handle_option_momentum(self):
stocks = self.get_selected_stocks()
self.get_start_end()
if st.sidebar.button("Calculate Momentum"):
momentum_score = MomentumScore()
last_trading_day, collected_prices = self.get_prices_last_trading_day(stocks)
coll... |
def handle_option_backtest(self):
self.get_symbol()
strategy_name = st.selectbox('Strategy', self.strategies)
execute = st.button(label="Execute")
self.get_start_end()
if execute:
cerebro = backtrader.Cerebro() # create a "Cerebro" engine instance
... | The code's main task is to handle user selections via a sidebar dropdown, routing the application flow to specific methods like backtesting, chart generation, or data overview based on the chosen option. It directs the app's functionality by invoking corresponding handlers for each selected feature. | def run(self):
self.option = st.sidebar.selectbox('Options', self.options)
if self.option == 'Backtest':
self.handle_option_backtest()
if self.option == 'Chart':
self.handle_option_chart()
if self.option == 'Overview':
self.handle_option_overview()
... |
def getTweets(tweet, TWEET_MODE):
'''get tweet string based on tweet extraction mode'''
tweetString = ''
try:
# get tweet text from json
if TWEET_MODE == 'compact':
tweetString = (tweet['text'].encode('utf-8').decode("utf-8"))
else:
tweetString = (tweet['full... | The code searches Twitter for specified terms using Twython, retrieves tweets, extracts metadata (text, favorites, retweets, timestamps, user info, hashtags, URLs), and prints detailed results. It handles connection errors and empty search results, iterating through each query to output structured tweet data. | def SearchTwitter(searchTerms):
try:
# Initiate a twitter connection
twitter = Twython(app_key=APP_KEY,
app_secret=APP_KEY_SECRET,
oauth_token=ACCESS_TOKEN,
oauth_token_secret=ACCESS_TOKEN_SECRET,
client_args = { "hea... |
def Closed(filename):
"""
Function to check if an input file exists and not open.
Returns True if the File is closed
Returns False if the File is Open/Not Found.
"""
if Found(filename) is True:
try:
os.rename(filename, filename)
# print('%s is Closed!' % (os.path.... | The main task of the code is to automate data entry from an Excel sheet into web forms by parsing PID and address information. It checks if the Excel file is closed, launches a Chrome browser, reads the workbook, processes each row to extract PID and address details, navigates to specific websites based on PID format, ... | def main():
if not Closed(xl_path):
print('Please close the file and re-run this bot.')
else:
wb = None
try:
driver = webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=options)
driver.maximize_window()
print("Google Chrome Launc... |
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2] )
print(board[3] + " | " + board[4] + " | " + board[5] )
print(board[6] + " | " + board[7] + " | " + board[8] )
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1-9 :")
... | The code defines a function to play a game, managing turns for two players, checking game status after each move, and announcing the winner or a tie once the game ends. It alternates player turns, updates the game state, and terminates when a player wins or the game ends in a draw. | def play_game():
display_board()
while game_still_going:
handle_turn(current_player)
check_if_game_over()
flip_player()
if winner == "X" or winner == "0":
print(winner + " Won.")
elif winner == None:
print(" Tie.") |
def circle_from(A, B):
# Set the center to be the midpoint of A and B
C = [ (A[0] + B[0]) / 2.0, (A[1] + B[1]) / 2.0]
# Set the radius to be half the distance AB
return [C, dist(A, B) / 2.0]
def is_valid_circle(c, P):
# Iterating through all the points to check
# whether the points ... | The code computes the **minimum enclosing circle (MEC)** for a set of 2D points. It iterates through all pairs and triples of points to generate candidate circles, checking if they enclose all points and have a smaller radius than the current MEC. The MEC is updated whenever a valid, smaller circle is found, ensuring t... | def minimum_enclosing_circle(P):
# To find the number of points
n = len(P)
if (n == 0):
return [[0, 0], 0]
if (n == 1):
return [P[0], 0]
# Set initial MEC to have infinity radius
mec = [[0, 0], INF]
# Go over all pair of points
for i in range(n):
for j... |
def load_text(file_name):
with open(file_name, 'r') as file:
text = file.read()
sentences = sent_tokenize(text)
return sentences
def create_bow_dictionary(sentences):
# preprocessing the sentences by stemming them
processed_docs = []
for doc in sentences:
processed_docs.append(pr... | The main task of the code is to perform topic modeling on input text using LDA. It loads text from a file, creates a bag-of-words corpus, builds an LDA model with specified topics, and classifies sentences into topics, returning grouped sentences per topic. | def get_topics(file_name, topics):
# enter the name of the file and the number of topics
sentences = load_text(file_name)
# create the dictionary and BOW corpus
dictionary, bow_corpus = create_bow_dictionary(sentences)
# create the LDA model
lda_model = create_model(topics, bow_corpus, dictionar... |
def random_string(length, letters=string.ascii_letters):
return ''.join(random.choice(letters) for i in range(length))
def make(info, target=None):
if target is None:
target = inquirer.text(message="Target?").execute()
print_and_run(f"{info.full_snakemake} {target} {info.snakemake_args}")
if in... | (The code defines an interactive interface for managing Snakemake workflows, parsing command-line arguments to configure execution parameters (e.g., Slurm, resources, job settings). It dynamically determines the Snakemake executable, constructs commands, and provides a menu-driven loop for actions like running targets,... | def interact():
parser = argparse.ArgumentParser(prog='Snakemake interact')
parser.add_argument("--cmd", default="cat")
parser.add_argument("--path", default=".")
parser.add_argument("--hostname", default=socket.gethostname())
parser.add_argument("--slurm", default=None)
parser.add_argument("--... |
def mqtt_connect():
try:
client.connect()
print('Connected succesfully to MQTT server')
except Exception as e:
print('Could not connect to MQTT server {}{}'.format(type(e).__name__, e))
print(rtc.datetime())
sleep(5)
#client.disconnect()
gc.collect()
def s... | The main task of the code is to establish an MQTT connection, subscribe to feeds, and continuously check for incoming messages in a loop. It runs in a separate thread, reconnects on errors, and includes garbage collection. The function handles exceptions, logs timestamps, and retries after delays, ensuring persistent M... | def mqtt_connect_and_subscribe():
'''
This loop is intended for being called in a separate thread in order to wait for incoming messages
Included the connect, subscribe and check mqtt msg functions
'''
start = time.ticks_ms()
try:
mqtt_connect()
subscribe_to_feeds()
whil... |
def make_flashes(inputs, flashes):
new_flashes = []
for f in flashes:
neighbors = get_adjacents(f[0], f[1])
for n in neighbors:
if n not in STEP_FLASHES:
inputs[n[0]][n[1]] += 1
if inputs[n[0]][n[1]] == 10:
inputs[n[0]][n[1]] = 0
... | This function processes a matrix by incrementing each element, resetting to 0 and tracking positions where values reach 10. It updates global flash counters, applies flash effects, and checks if all elements have flashed, setting a step marker if so. | def make_step_part_one(inputs, step_number=0):
global STEP_FLASHES
global COUNT_FLASHES
global ALL_FLASHES_STEP
flashed = []
for i in range(0, len(inputs)):
for j in range(0, len(inputs[i])):
inputs[i][j] += 1
if inputs[i][j] == 10:
inputs[i][j] = 0
... |
def is_finished(self):
for image in self.brackets.row_image:
if len(image) != 9:
return False
return True
def stage_one(self):
changes = False
for row in self.I:
for col in self.I:
cell = self.grid[row][col]
if not c... | This code solves a Sudoku puzzle by iterating through multiple solving stages (stage_one to stage_five), applying strategies like bracket/orthogonal covers and backtracking when necessary. It tracks solution steps in `stage_list`, handles pruning, and returns True if solved, updating the grid and backtrack count. | def solve(self, active_stages=ALL_STAGES_ARRAY):
self.stage_list = []
while not self.is_finished():
if STAGE_ONE_INDEX in active_stages and self.stage_one():
self.stage_list.append(STAGE_ONE_LABEL)
elif STAGE_TWO_INDEX in active_stages and self.stage_two():
... |
def remove_perished(self):
"""
removes pairs from the market that have been in the market for their time_to_critical amount of time
"""
participants = self.participants
perished = list()
for p in participants:
if p.time_in_market >= p.time_to_critical:
... | The code updates the market by adding new pairs, removing perished/matched pairs, and adding altruists. It increments participants' time_in_market and dialysis days if update_time is True, tracks wait times for recipients, removes matched pairs from the market, and manages altruists by adding them as pairs and updating... | def update(self, added_pairs=list(), matched_pairs=list(), altruists=list(), update_time=False):
"""
updates the market by adding pairs, removing perished pairs, removing matched pairs, and adding altruists
:param added_pairs: a list of tuples of participants in the form (recipiant, donor) that ... |
def reset_visited(self):
for i in range(len(self.nodes)):
self.nodes[i].visited = False
def print_image(self):
img = [["black" for i in range(self.image_size)] for j in range(self.image_size)]
# fill img array
for node in self.nodes:
img[node.y][node.x] = node.co... | This code performs a depth-first search (DFS) starting from a specified node, visualizing the traversal by changing the node's color and printing the image at each step. It uses a stack to manage the search, marks nodes as visited, and ensures only unvisited nodes of the same color as the start node are processed, upda... | def dfs(self, start_index, color):
# reset visited status
self.reset_visited()
# print initial state
print("Starting DFS; initial state:")
self.print_image()
# Create stack, change color and visit status of starting node, and print image
stack = Stack()
s... |
def parse_setcompare_out(output_c, nb_top):
"""
Parse the output of setCompare C script and return a dictionary with the coding word
and its occurence if the length is 20 or a tuple containing its occurence and
a list of word_20 associated
"""
with open(output_c, "r") as filin:
text = fi... | The main task of the code is to generate a dictionary (`dic_hits`) mapping decoded DNA sequences to their occurrences and genomic coordinates, based on input parameters. It parses sequence data, decodes ranks into sequences, processes occurrences, and searches genomic coordinates using different functions depending on ... | def create_dic_hits(param, genomes_in):
"""
Definition
"""
dic_index, nb_hits = parse_setcompare_out(param.f, int(param.nb_top)) if int(param.sl) == 20 else parse_setcompare_other(param.f, int(param.nb_top))
dspl.eprint("NB_HITS ==> {} Length DIC_INDEX ==> {}".format(nb_hits, len(dic_index))... |
def discretizeTime(time):
'''
function to map 24-hours format time to one of the six 4 hours intervals.
'''
if '00:00' <= time < '04:00':
return 't1'
elif '04:00' <= time < '08:00':
return 't2'
elif '08:00' <= time < '12:00':
return 't3'
elif '12:00' <= time < '16:00'... | The code processes input data by parsing features, creating a structured DataFrame, converting data types, integrating with external datasets, and encoding categorical variables for machine learning use. | def genDataPoint(input):
# Get the individual features from user input
features = [feature.strip() for feature in input.strip().split(",")]
# Assign variables for each feature
latitude = features[0]
longitude = features[1]
district = features[2]
resolved = 0
date = features[3]
time_interval = discretizeTime(... |
def run_one_epi(graph_name, beta, n, it, gamma=1., n_sites = 10, sub_rate = 0.5):
np.random.seed(it)
if graph_name == "complete":
graph_args = dotdict({
"name":"complete",
"N": n,
})
else:
raise Exception("graph_name not understood")
#print(graph_args)
... | The main task of the code is to simulate an epidemic model on a graph, varying transmission probabilities (probas), and saving results. It runs multiple experiments with different seeds, generates phylogenetic trees, and writes outputs (CSV, Nexus) for analysis. Parameters like beta, gamma, graph structure, and samplin... | def main(graph_name = "complete", n = 500, beta_avg = 5, num_seeds = 100, sampling = 1, gamma = 1, probas = np.linspace(0.05, 0.45, 9), fasta=False, nexus=False, heuristic=False, heuristic_informed=False):
# to do:
# write_to_fasta needs to write a .nex file instead of .fasta so we don't have to use beastgen wi... |
def best_split(data_pd: pd.DataFrame, class_var: str, exclude_features: list = []) -> float:
"""
Returns the name of the best feature to split on at this node.
If the current node contains the most info (all splits lose information), return None.
EXCLUDE_FEATURES is the list of variables we want to omit... | This function recursively builds a decision tree up to a maximum depth of 2 by selecting the best feature to split data, then recursively processing left/right subsets while excluding already-used features. It stops when no further splits are possible or depth limits are reached, printing split details at each step. | def build_decision_tree(node_data: pd.DataFrame, class_var: str, depth: int = 0, exclude_features: list = []) -> None:
"""Build a decision tree for NODE_DATA with
CLASS_VAR as the variable that stores the class assignments.
EXCLUDE_FEATURES is the list of variables we want to omit from our list of choices""... |
def read_json_file(filename):
if os.path.exists(filename) and os.path.getsize(filename) > 0:
with open(filename, 'r') as file:
data = json.load(file)
return data
else:
return False
def datetime_to_int(dt):
timestamp = int(dt.timestamp())
return timestamp
def write_jso... | The code updates a JSON file's 'LastTimeSaved' field with the current timestamp and logs a message if "saves" exists in "SpecificLogging". | def saveMeNow():
file_data = read_json_file(filename)
file_data['LastTimeSaved'] = datetime_to_int(datetime.datetime.now())
write_json_file(filename, file_data)
if "saves" in get_value_from_json("SpecificLogging"):
logIfAllowed(f"Saved by turning on.", 'info') |
def read_json_file(filename):
if os.path.exists(filename) and os.path.getsize(filename) > 0:
with open(filename, 'r') as file:
data = json.load(file)
return data
else:
return False
def get_value_from_json(key, filename = 'settings.json'):
file_data = read_json_file(filena... | The function resets specific settings in a JSON file by comparing keys against predefined rules. It replaces values with defaults or comparison-based values, handles errors, and logs changes if enabled. | def resetSettings():
file_data = read_json_file(filename)
for key in file_data:
if key in get_value_from_json('ResetSettingsOnDeletion')['ResetTheFollowingSettingsOnDeletion']:
try:
if get_value_from_json('ResetSettingsOnDeletion')['CompareTo'] == "DEFAULT":
... |
def read_json_file(filename):
if os.path.exists(filename) and os.path.getsize(filename) > 0:
with open(filename, 'r') as file:
data = json.load(file)
return data
else:
return False
def datetime_to_int(dt):
timestamp = int(dt.timestamp())
return timestamp
def write_jso... | The code's main task is to update a JSON file's 'LastTimeSaved' timestamp with the current time, save the changes, and log a message if allowed by the 'saves' setting in 'SpecificLogging' | def saveMeNow():
file_data = read_json_file(filename)
file_data['LastTimeSaved'] = datetime_to_int(datetime.datetime.now())
write_json_file(filename, file_data)
if "saves" in get_value_from_json("SpecificLogging"):
logIfAllowed(f"Saved by user.", 'info') |
def q_dot_assemble(self):
_q_dot = self.q_dot.to_numpy()
q_dot_arr = _q_dot if not lagrange or self.parent is None else _q_dot[3:]
for c in self.children:
arr = c.q_dot_assemble()
q_dot_arr = np.hstack([q_dot_arr, arr])
return q_dot_arr
def fill_Jc(self):
... | This method performs top-down constraint propagation in a tree structure. It initializes global variables for velocities and Jacobians, projects vertices, and recursively processes children. If the node is root, it solves the system and traverses with the computed values, scaling by time step dt. The core task is const... | def top_down_constrained(self):
global globals
dt = 3e-4
if self.parent is None:
globals.q_dot = self.q_dot_assemble()
globals.Jc = np.zeros_like(globals.Jc)
globals.Jc_dot = np.zeros_like(globals.Jc_dot)
else :
self.fill_Jc()
... |
def lagrange_explicit_euler(self, q_dot, q):
'''
ret = dydt
treat rotation and translation seperately in two 3*3 jacobian matrix
'''
_Jw = Jw(q[3], q[4], q[5])
# M = block_diag(ti.Matrix.identity(float, 3) * self.m, _Jw.transpose() @ _Jw * self.Ic)
# M = J.transp... | This code performs a midpoint integration step using Lagrange's formulation to update the system's 6-DoF state (position and Euler angles). It computes intermediate states (q_mid, q_dot_mid), applies explicit Euler integration, updates the full state (q, q_dot), calculates the rotation matrix from Euler angles, applies... | def lagrange_midpoint(self):
'''
Lagrange Formulation
6 DoFs all stacked together as q
3 COM velocities + 3 euler angles (rotation X1 Z2 X3)
'''
dt = 1e-4
dq, dq_dot = self.lagrange_explicit_euler(
self.q_dot[None], self.q[None])
q_mid = self.... |
def fill_C(k, pk, r_kl, r_pkl):
line = np.zeros((3, n_dof))
line_pk = np.zeros((3, n_dof))
fill_Jck(line, k, r_kl)
fill_Jck(line_pk, pk, r_pkl)
return line_pk - line
def U(C):
m, n = C.shape[0], C.shape[1]
# for i in range(m):
# i = np.argmax()
'''
pivoting not needed for 2 ... | This code simulates and visualizes an articulated multibody system with interactive controls. It sets up a 3D scene, defines rigid body links (AffineCube), computes constraint matrices for joints, and performs real-time physics simulation. The loop handles camera navigation, applies forces, updates particle positions, ... | def main():
formatter = '{:.2e}'.format
np.set_printoptions(formatter={'float_kind': formatter})
window = ti.ui.Window(
"Articulated Multibody Simualtion", (800, 800), vsync=True)
canvas = window.get_canvas()
canvas.set_background_color((0, 0, 0))
scene = ti.ui.Scene()
camera = ti.ui... |
def q_dot_assemble(self):
_q_dot = self.q_dot.to_numpy()
q_dot_arr = _q_dot if not lagrange or self.parent is None else _q_dot[3:]
for c in self.children:
arr = c.q_dot_assemble()
q_dot_arr = np.hstack([q_dot_arr, arr])
return q_dot_arr
def fill_Jwk(self, Jw_k: t... | The function `top_down_lagrange` computes the dynamics of a multibody system using Lagrangian mechanics. It initializes Jacobian matrices, velocity terms, and force components, then aggregates them to form the mass matrix $M$, Coriolis matrix $C$, and force vector $f$. It solves the equation of motion $M \ddot{q} = -C ... | def top_down_lagrange(self):
'''
unknowns layout:
(q_0[0:5], q_1[3:5], q_2[3:5],..., q_n[3:5])
'''
global globals
dt = 3e-4
if self.parent is None:
globals.q_dot = self.q_dot_assemble().reshape((-1, 1))
# print(globals.q_dot)
gl... |
def energy(stems_actual, mu, alpha, beta, p1, p2):
k = 0
pseudoknots_actual = potential_pseudoknots(stems_actual)
cost = 0
for i in range(0, len(stems_actual)):
k_i = stems_actual[i][4]
loop_i = stems_actual[i][3]
cost += alpha*((k_i-mu)**2)-beta*(k_i-loop_penalty(loop... | This function evaluates the performance of a model using hyperparameters (alpha, beta, p1, p2) on RNA structures. It computes energy, builds optimization models, samples solutions with QBSolv, calculates metrics (MCC), and returns an average cost based on deviation from a target value. Results are cached to avoid redun... | def cost_function(hyper_params):
print(hyper_params)
if str(hyper_params) in past_params:
print("Previous value")
return past_params[str(hyper_params)]
else:
alpha = hyper_params[0]
beta = hyper_params[1]
p1 = hyper_params[2]
... |
def get_structures(pks, size, input_dir):
subdirectory = input_dir +'/data'+'/'+pks+'/'+size
bprna = []
fasta = [f for f in os.listdir(subdirectory) if f.endswith('.fasta.txt')]
for f in fasta:
bprna.append(subdirectory+"/"+f.split(".")[0])
return bprna
def spsa_optimizer_callback(nb_fct_eva... | The code retrieves environment variables, loads hyperparameters, initializes a quantum annealer solver with an embedding, prepares training data, optimizes model parameters using SPSA, and saves results. It processes RNA structures, trains a model on AWS Braket, and outputs final values and loss. | def main():
print(os.environ)
input_dir = os.environ["AMZN_BRAKET_INPUT_DIR"]
hp_file = os.environ["AMZN_BRAKET_HP_FILE"]
job_name = os.environ["AMZN_BRAKET_JOB_NAME"]
s3_bucket = os.environ["AMZN_BRAKET_OUT_S3_BUCKET"]
device_arn = os.environ["AMZN_BRAKET_DEVICE_ARN"]
with open(hp_file, "r... |
def get_structures(pks, size, input_dir):
subdirectory = input_dir +'/data'+'/'+pks+'/'+size
bprna = []
fasta = [f for f in os.listdir(subdirectory) if f.endswith('.fasta.txt')]
for f in fasta:
bprna.append(subdirectory+"/"+f.split(".")[0])
return bprna
def spsa_optimizer_callback(nb_fct_eva... | The code retrieves environment variables and hyperparameters, loads RNA structure data, configures a quantum annealer (DWave) via Amazon Braket, optimizes model parameters using SPSA, and saves results including final values, loss, and hyperparameters to S3. | def main():
print(os.environ)
input_dir = os.environ["AMZN_BRAKET_INPUT_DIR"]
hp_file = os.environ["AMZN_BRAKET_HP_FILE"]
job_name = os.environ["AMZN_BRAKET_JOB_NAME"]
s3_bucket = os.environ["AMZN_BRAKET_OUT_S3_BUCKET"]
device_arn = os.environ["AMZN_BRAKET_DEVICE_ARN"]
with open(hp_file, "r... |
def get_code_setup_parameters() -> Tuple[str, str, str]:
"""
Returns the code setup parameters:
s3_uri: the S3 location where the code is stored.
entry_point: the entrypoint into the code.
compression_type: the compression used to archive the code (optional)
These values are stored i... | The main task of the code is to download customer code from an S3 URI, unpack it, execute the specified entry point (either as a process or subprocess), and log a failure if the execution returns a non-zero exit code, ensuring proper error handling and cleanup. | def run_customer_code() -> None:
"""
Downloads and runs the customer code. If the customer code exists
with a non-zero exit code, this function will log a failure and
exit.
"""
s3_uri, entry_point, compression_type = get_code_setup_parameters()
local_s3_file = download_customer_code(s3_uri)
... |
def create_symlink():
"""
The ML paths are inserted by the backend service by default. To prevent confusion we link
the Braket paths to it (to unify them), and use the Braket paths from now on.
"""
try:
os.symlink(OPT_ML, OPT_BRAKET)
except OSError as e:
if e.errno != errno.EEXIS... | The main task of the code is to set up the Braket container by creating symbolic links and required paths, then download and execute customer-specific code. This involves initializing the environment and running user-defined logic within the containerized setup. | def setup_and_run():
"""
This method sets up the Braket container, then downloads and runs the customer code.
"""
print("Beginning Setup")
create_symlink()
create_paths()
run_customer_code() |
def find_operator(s):
# Regular expression to match arithmetic and conditional operators
pattern = r'&|not_in|is_in|==|!=|>=|<=|>|<|//'
matches = re.findall(pattern, s)
return matches
def get_operand_val(operand, trace, spec, error_codes, spec_globals):
oper = operand.strip()
if 'tag.' in oper:
... | The code processes a rule by splitting it into operands using an operator, evaluates each operand's value based on provided parameters, applies the operator to the evaluated values, and returns the result of the operation. | def process_rule(rule, trace, spec, error_codes, spec_globals):
out = False
operator = find_operator(rule)
operands = rule.split(operator[0])
#print("operands" , operands , "operator" , operator)
left = get_operand_val(operands[0], trace, spec, error_codes, spec_globals)
right = get_operand_val... |
def find_logical_operator(s):
matches = re.findall(r'\)\s*(.*?)\s*\(', s)
return matches
def get_strings_between_parentheses(s):
matches = re.findall(r'\((.*?)\)', s)
return matches
def process_rule(rule, trace, spec, error_codes, spec_globals):
out = False
operator = find_operator(rule)
ope... | The main task of the code is to evaluate error codes against specified rules using logical operations on trace and spec data, identifying valid error codes that match the rules. It processes each error code's rules, applies logical operators to sub-rules, and accumulates valid error codes if any rule evaluates to true,... | def process_cmd_rules(trace, spec, error_codes, spec_globals):
error = 'NO_ERROR'
#print("+++++++++++++++++++++++++++++++++++++++++")
print("trace ")
pprint.pprint(trace)
key = list(trace.keys())
print("\n")
print("error_codes")
pprint.pprint(error_codes[key[0]])
print("\n")
pri... |
def median_of_medians(arr, start, end):
"""
Median of medians recursive algorithm
"""
# Base case: Just sort and return median if length <= 5
arr_length = end - start + 1
if arr_length <= 5:
pointer_insertion_sort(arr, start, end)
subarray = arr[start:end + 1]
median_offs... | Your return
The code implements the **Quickselect algorithm** with **median of medians** to find the kth smallest element in an array. It selects an ideal pivot using median of medians, partitions the array around this pivot, and recursively searches the relevant subarray based on pivot position relative to k. This e... | def quick_select_kth_smallest(arr, start, end, k):
"""
Finds the kth smallest value of an array using the quick select and median of medians algorithm.
"""
# Find ideal pivot using median of medians
ideal_pivot_index = median_of_medians(arr, start, end)
# Partition the array about the pivot... |
def normalize(v):
l = length(v)
v /= l
return v
def furNormal(pos, density):
eps = 0.01
x, _ = furDensity(ti.Vector([pos.x + eps, pos.y, pos.z]))
y, _ = furDensity(ti.Vector([pos.x, pos.y + eps, pos.z]))
z, _ = furDensity(ti.Vector([pos.x, pos.y, pos.z + eps]))
return normalize(ti.Vector... | This function calculates fur shading by combining diffuse and specular lighting with noise texture and depth-based modulation. It computes light direction (L), view direction (V), and halfway vector (H), then uses fur normals (N) to determine diffuse (diff) and specular (spec) components. A noise texture samples color ... | def furShade(pos, uv, ro, density):
L = ti.Vector([0.0, 1.0, 0.0])
V = normalize(ro - pos)
H = normalize(V + L)
N = -furNormal(pos, density)
# N = normalize(pos)
diff = ti.max(0.0, N.dot(L) * 0.6 + 0.6)
spec = ti.pow(max(0.0, N.dot(H)), shininess)
sample = ti.Vector([(uv.x + PI) / PI, ... |
def intersectSphere(ro, rd, r):
b = (-ro).dot(rd)
det = b * b - ro.dot(ro) + r * r
t = -1.0
if(det >= 0.0):
det = ti.sqrt(det)
t = b - det
return t
def furDensity(pos):
uv = cartesianToSpherical(ti.Vector([pos.x, pos.z, pos.y]))
sample = ti.Vector([(uv.x + PI) / PI, (uv.y + P... | This code calculates ray-sphere intersection and accumulates fur-like shading by iterating through layers, adjusting color based on density and alpha values, stopping when opacity reaches 95%.) | def scene(ro, rd):
p = ti.Vector([0.0, 0.0, 0.0])
r = 1.0
t = intersectSphere(ro - p, rd, r)
c = ti.Vector([0.0, 0.0, 0.0, 0.0])
if t > 0.0:
pos = ro + rd * t
# color = furShade(pos, ti.Vector([0.0, 0.0]), ro, 0.0)
# c = ti.Vector([color.x, color.y, color.z, 1.0])
for... |
def normalize(v):
l = length(v)
v /= l
return v
def rotateY(p, a):
sa = ti.sin(a)
ca = ti.cos(a)
return ti.Vector([ca * p.x + sa * p.z, p.y, -sa * p.x + ca * p.z])
def scene(ro, rd):
p = ti.Vector([0.0, 0.0, 0.0])
r = 1.0
t = intersectSphere(ro - p, rd, r)
c = ti.Vector([0.0, 0.0... | This code renders a 3D scene using ray tracing by calculating pixel colors based on rotating camera and ray directions over time. It normalizes UV coordinates, applies Y-axis rotation to both the camera position (ro) and ray direction (rd), computes color via a scene function, and assigns the result to each pixel. The ... | def paint():
roty = ti.sin(iTime[None] * 1.5)
for i, j in pixels:
uv = 1.0 * ti.Vector([i, j]) / iResolution
uv = uv * 2.0 - 1.0
uv.x *= float(iResolution.x) / iResolution.y
rd = ti.Vector([uv.x, uv.y, -2.0])
rd = normalize(rd)
ro = ti.Vector([0.0, 0.0, 2... |
def _advance(self):
"""Cosume the next token and advance one token ahead."""
self.tok, self.nexttok = self.nexttok, next(
self.tokens, Token("None", None))
def comma_separated_list(self, item_parser):
"""Parse a comma-separated list using the specified item parser.
Args:
... | This method parses and constructs a nested procedure application by repeatedly processing operands enclosed in parentheses, creating an Application object with the operator and parsed operands, returning the resulting application structure. | def application(self, operator):
"""A precedure application containing operator and operands.
Note that the operator and operands have not yet been evaluated, since
a specific environment is required.
Args:
operator (Lambda or Variable): the operator can be lambda
... |
def _accept(self, toktype):
"""Test and consume the next token if it matches the toktype."""
if self.nexttok and self.nexttok.type == toktype:
self._advance()
return True
else:
return False
def application(self, operator):
"""A precedure application co... | This function parses expressions into an abstract syntax tree (AST) by handling literals, variables, lambda expressions, and parenthesized sub-expressions. It checks the next token type, constructs corresponding AST nodes (Literal, Variable, Lambda, or application), and recursively processes nested expressions. Errors ... | def expr(self):
"""Begin to parse a expression."""
if self.nexttok.type is None:
raise SyntaxError('Incomplete expression')
elif self._accept("LITERAL"):
return self.application(Literal(self.tok.value))
elif self._accept("NAME"):
return self.applicatio... |
def set_hand(self):
hand_str = ''
l = ''
for line in self.game:
if f'Dealt to {self.player_name}' in line:
h_start, h_end = line.find('[')+1, line.find(']')
hand_str = line[h_start:h_end]
h1, h2 = hand_str.split(' ')
self.player_hand[... | This function gathers game data through key stages (preflop, postflop, etc.), tracks game states, determines winners, and assigns results based on hand rankings. It records each stage's status, checks if the player wins, compares hand strengths against winners, and returns a list of game records with outcome results. | def gather_full_game_data(self):
records = []
self.set_hand()
self.set_winner_list()
self.process_preflop()
records.append(self.get_current_status(0))
if self.game_complete != True:
self.process_postflop()
records.append(self.get_current_status(1))... |
def random_number(self):
return random.randint(1, 500)
def id_exists(self, id):
phantom_ticket = self.get_ticket_by_id(id)
return phantom_ticket != {}
def generate_code(self):
first_two_digits = random.randint(11,99)
four_characters = self.get_random_string(4)
... | The code generates a unique ticket ID, assigns it along with a code and submission date to a ticket, adds the ticket to a data list, and saves the updated list to a file, returning the created ticket. | def create_ticket(self, ticket):
ticket_id = self.random_number()
id_existence = self.id_exists(ticket_id)
while id_existence :
ticket_id = self.random_number()
id_existence = self.id_exists(ticket_id)
ticket["id"] = ticket_id
ticket["c... |
def find_best_split(rows):
#find the best question to ask by iterating over every feature/value and calculating the information gain
current_impurity = gini(rows)
best_gain = 0
best_question = None
n_features = len(rows[0])-1
datasets = np.array(rows)
for col in range(n_features):
... | The code recursively constructs a decision tree by splitting data rows based on the best information gain. If gain is zero, it creates a leaf node; otherwise, it partitions data into true/false subsets, recursively building subtrees for each branch, and returns a decision node with the question and branches. | def build_tree(rows):
gain, question = find_best_split(rows)
if gain == 0:
return Leaf(rows)
true_rows, false_rows = partition(rows, question)
true_branch = build_tree(true_rows)
false_branch = build_tree(false_rows)
return Decision_Node(question, true_branch, false_branch) |
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def power(self):
return self.bin_op(self.call, (cc.TT_POW), self.factor) | This code parses unary operations (plus/minus) by recursively calling 'factor' and creating a UnaryOpNode. If no unary operator is found, it delegates to 'power()' to parse other expressions. It handles token advancement and error checking via ParseResult, returning appropriate nodes or errors. | def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (cc.TT_PLUS, cc.TT_MINUS):
res.register_advancement()
self.advance()
factor = res.register(self.factor())
if res.error:
return res
return res... |
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def expr(self):
res = ParseResult()
if self.current_tok.matches(cc.TT_KEYWORD, "BUCKET"):
res.register_advancemen... | This method parses a sequence of statements, handling newlines and expressions. It collects parsed expressions into a list, skips newlines, and returns a ListNode containing the statements with their start and end positions. It uses a loop to process multiple statements, ensuring proper error handling and reversal of p... | def stmts(self): # sourcery skip
res = ParseResult()
stmts = []
pos_start = self.current_tok.pos_start.copy()
while self.current_tok.type == cc.TT_NEWLINE:
res.register_advancement()
self.advance()
stmt = res.register(self.expr())
if res.... |
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def stmts(self): # sourcery skip
res = ParseResult()
stmts = []
pos_start = self.current_tok.pos_start.copy()
... | This function parses an 'ELSE' clause in a conditional expression, handling either a block of statements (if followed by a newline) or a single expression. It constructs a ParseResult containing the parsed content and a boolean flag indicating whether it's a statement block, returning this result for further processing... | def if_expr_c(self):
res = ParseResult()
else_case = None
if self.current_tok.matches(cc.TT_KEYWORD, "ELSE"):
res.register_advancement()
self.advance()
if self.current_tok.type == cc.TT_NEWLINE:
res.register_advancement()
self... |
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def expr(self):
res = ParseResult()
if self.current_tok.matches(cc.TT_KEYWORD, "BUCKET"):
res.register_advancemen... | This code parses a 'LOOP' statement by validating syntax elements like 'LOOP', identifier, '=', 'TILL', 'STEP', and 'DO', then constructs a ForNode with variables (var_name), start/end values, step value, and loop body (expr or stmts). It handles errors for missing keywords and invalid tokens, returning a parse result ... | def for_expr(self):
res = ParseResult()
if not self.current_tok.matches(cc.TT_KEYWORD, "LOOP"):
return res.failure(
InvalidSyntaxError(
self.current_tok.pos_start,
self.current_tok.pos_end,
"Expected 'LOOP'",
... |
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def expr(self):
res = ParseResult()
if self.current_tok.matches(cc.TT_KEYWORD, "BUCKET"):
res.register_advancemen... | This code parses a procedure definition by validating syntax elements like 'PROC', identifier, parentheses, and arguments. It collects parameters, checks for a return type or body, and constructs a ProcNode with the procedure's name, arguments, return expression, or body, ensuring proper structure and error handling fo... | def proc_def(self):
res = ParseResult()
if not self.current_tok.matches(cc.TT_KEYWORD, "PROC"):
return res.failure(
InvalidSyntaxError(
self.current_tok.pos_start,
self.current_tok.pos_end,
"Expected 'PROC'",
... |
def get_closest_vertices_in_other_mesh(mesh1, vertices, mesh2):
output = set()
for (j, vertex) in enumerate(vertices):
v1 = mesh1.positions[vertex]
closest = (math.inf,)
for (i, v2) in enumerate(mesh2.positions):
dist = np.linalg.norm(v1 - v2)
closest = min(closes... | The code merges two 3D meshes by iteratively aligning their boundary loops through snapping regions computed via geodesic distances. It alternates between meshes, adjusting vertices based on elasticity, and merges them into a unified mesh using correspondence points and snapping regions, with final output depending on ... | def merge(mesh1, mesh2, iterations, elasticity, smoothing_factor):
# find unordered boundary loops, and the vertices on the other mesh closest to them
boundary_vertices1 = mesh1.find_boundary_vertices()
closest_vertices_to_loop1_in_mesh2 = get_closest_vertices_in_other_mesh(mesh1, boundary_vertices1, mesh2)... |
def add_snapping_region_boundary(boundaries, new_mesh, mesh, snapping_region, point_cloud):
boundary_vertices = set()
for vertex in snapping_region:
for next_vertex in mesh.adjacency_list[vertex]:
if next_vertex not in snapping_region:
boundary_vertices.add(vertex)
bound... | The function `remesh` generates a new mesh by combining two input meshes (`mesh1`, `mesh2`) with their respective snapping regions. It uses a point cloud, priority queue, and proximity-based logic to iteratively merge, split, or grow triangles, ensuring alignment with the snapping regions' boundaries. The process invol... | def remesh(mesh1, mesh2, snapping_region1, snapping_region2, smoothing_factor=1, osculating_circle_angle_subtended=pi/4):
point_cloud = PointCloud([(mesh1, snapping_region1), (mesh2, snapping_region2)], smoothing_factor, osculating_circle_angle_subtended)
boundaries = UpdateablePriorityQueue()
new_mesh = M... |
def start_maple_phase(self, cmd_split):
cmd_type = cmd_split[0]
maple_exe = cmd_split[1]
num_maples = int(cmd_split[2])
sdfs_tmp_filename_prefix = cmd_split[3]
sdfs_src_dir = cmd_split[4]
while (len(self.mapleJuiceQueue) > 0):
continue
self.mapleJui... | The code runs a distributed system node, initializing threads for group communication (grouptalk), listening, file operations (fileOp_listen/master), and MapleJuice task handling. It processes user commands like 'gossip', 'alltoall', 'list', 'leave', and 'my_id' to control membership, status, and tasks. The node can vo... | def run(self):
thread.start_new_thread(self.grouptalk, ())
thread.start_new_thread(self.listen, ())
#thread.start_new_thread(self.fileOp, ())
thread.start_new_thread(self.fileOp_listen, ())
thread.start_new_thread(self.fileOp_master, ())
## New thread to receive MapleJuic... |
def update_base_forms(self) -> bool:
new_forms_found: bool = False
current_base_forms = self._get_form_dict()
for base_form in current_base_forms:
# if there is no corresponding imaged folder in the generated images folder
if base_form not in self._trained_forms:
... | The main task of the code is to process form images by moving them to a test directory, train a TensorFlow Lite model using these test data, and then restore the files. It checks for new forms, generates fake images if needed, and handles exceptions during model execution. | def run(self) -> None:
try:
current_img_data: List[str] = []
for form_img in self._form_img:
form_name = form_img.replace(".jpg", "")
current_img_data.append(form_name)
self._test_forms = current_img_data
found_new_forms: bool = s... |
def update_base_forms(self) -> bool:
new_forms_found: bool = False
current_base_forms = self._get_form_dict()
for base_form in current_base_forms:
if base_form not in self._trained_forms:
new_forms_found = True
self._base_forms = current_base_forms
sel... | The code runs a server loop to monitor and process new forms: it checks for updates, generates fake images, trains a model, updates a classifier, and classifies pending forms. The loop sleeps for 1 second and terminates on errors. | def run(self) -> None:
server_running: bool = True
while server_running:
try:
found_new_forms: bool = self.update_base_forms()
new_pending_forms: List[int] = self.get_pending_forms()
if found_new_forms:
self.create_fake_ima... |
def eliminate_implications(s):
"""Change implications into equivalent form with only &, |, and ~ as logical operators."""
s = expr(s)
if not s.args or is_symbol(s.op):
return s # Atoms are unchanged.
args = list(map(eliminate_implications, s.args))
a, b = args[0], args[-1]
if s.op == '=... | The function `to_cnf` converts a propositional logical sentence into **conjunctive normal form (CNF)**. It parses the input string, eliminates implications, moves negations inward, and distributes AND over OR to achieve CNF. This standardizes logical expressions into a conjunction of disjunctions (e.g., `(~B & ~C)` fro... | def to_cnf(s):
"""
Convert a propositional logical sentence to conjunctive normal form.
That is, to the form ((A | ~B | ...) & (B | C | ...) & ...)
>>> to_cnf('~(B | C)')
(~B & ~C)
"""
s = expr(s)
if isinstance(s, str):
s = expr(s)
s = eliminate_implications(s)
s = move_n... |
def pl_true(exp, model={}):
"""Return True if the propositional logic expression is true in the model,
and False if it is false. If the model does not specify the value for
every proposition, this may return None to indicate 'not obvious';
this may happen even when the expression is tautological.
>>... | This function implements the DPLL algorithm for propositional logic satisfiability. It recursively checks if a logical sentence is true under a given model, using pure symbol and unit clause optimizations. If the sentence is unsatisfiable, it returns False; if satisfiable, it returns True with a valid model. The algori... | def DPLL(sentence, symbols, model) -> tuple[bool, dict|None]:
if pl_true(sentence, model) == False:
return False, None
if pl_true(sentence, model) == True:
return True, model
p, value = find_pure_symbol(sentence, symbols, model)
if p:
return DPLL(sentence, [s for s in s... |
def stand(conn):
none = NO_ANGLE
behavior = [
[45, none, 45, none, 45, none, 45, none],
[30, none, 45, none, 45, none, 45, none],
[30, 50, 45, none, 45, none, 45, none],
[45, 50, 45, none, 45, none, 45, none],
[45, 50, 30, none, 45, none, 45, none],
... | This code parses command-line arguments for a Bluetooth server address, port, and running time, then connects to the server using RFCOMM protocol. If successful, it executes `stand()`, `walk()` for the specified duration, and `quit()` functions to control a connected device. | def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-s', '--server', help='server address',
default='B8:27:EB:75:E6:45')
parser.add_argument('-p', '--port', help='server port',
... |
def sit(ant):
moveAll(ant, 0)
def stand(ant):
moveInner(ant, 0)
moveOuter(ant, 60)
def rotate(ant, rot="CW"):
sit(ant)
sleep(0.5)
angle = 90 if rot == "CW" else -90
moveInner(ant, angle)
sleep(0.5)
stand(ant)
sleep(0.5)
moveInner(ant, 0) | The main task of the code is to control a robot (via RealAnt class) by performing sequential actions: sitting, standing, and rotating, using a configurable COM port. It parses user-specified port input, establishes a connection, executes movement commands with delays, then disconnects. The script demonstrates basic rob... | def main():
# Allow user to specify a non-default com port
parser = OptionParser()
parser.add_option('-p', '--port', dest='port',
help='com port',
default='/dev/ttyACM0')
(opts, _) = parser.parse_args()
ant = RealAnt(opts.port)
ant.connect()
si... |
def _start_disassociator(interface_name: str,
sender_l4_base: UDP,
sender_func: Callable,
termination_event: TEvent
) -> None:
"""Starts a thread that attempts to constantly disassociate the connection between the co... | The function `_transmission_routine` periodically sends command datagrams at a specified rate, applying modifications from a queue to each command. It maintains a sequence number, handles persistent state, and adjusts transmission timing to meet the desired rate. The routine terminates when a termination event is trigg... | def _transmission_routine(interface_name: str,
sends_per_second: int,
command_request_queue: MPQueue,
termination_event: MPEvent,
sender_l4_base: UDP,
sender_func: Callable,
... |
def load_user_embedding(self, ufile):
with open(ufile) as infile:
for line in infile.readlines():
arr = line.strip().split(' ')
i = int(arr[0])
for j in range(len(arr[1:])):
self.user_embedding[i][j] = float(arr[j + 1])
def load_ite... | The code initializes a metapath-based random walk generator for heterogeneous graphs. It loads user, item, and type embeddings from files, builds relationship dictionaries, and performs random walks according to specified metapaths. The results are written to an output file, enabling graph traversal for tasks like reco... | def __init__(self, **kargs):
self.metapath = kargs.get('metapath')
self.walk_num = kargs.get('walk_num')
self.K = kargs.get('K')
self.um_dict = dict()
self.mu_dict = dict()
self.mt_dict = dict()
self.tm_dict = dict()
self.uo_dict = dict()
self.ou_d... |
def processTree(tree):
while tree.label == 'S' or tree.label == 'ROOT':
tree = tree.children[0]
return tree
def getFirstVerb(VP):
while len(VP.children) != 0:
VP = VP.children[0]
return str(VP)
def typeOfNoun(words):
for word in words:
if word.upos == "PROPN":
return 1
... | The code generates a question by combining the first verb, noun phrase (NPP), and remaining verb phrase (VP) elements. It checks if the first verb is "be" and categorizes the NPP's noun type (proper or common). If the noun is proper, it returns a question with the original NPP; if common, it capitalizes the first lette... | def makeBinQ(NPP, VPP):
VP = processTree(nlp(VPP).sentences[0].constituency)
firstVerb = getFirstVerb(VP).capitalize()
restVP = VP.children[1:] if len(VP.children) > 1 else []
firstVerbProcessed = (nlp(firstVerb)).sentences[0].words[0]
firstVerbLemma = firstVerbProcessed.lemma
# determine... |
def negative_word_limit(text, negative_words, limit): #gets a list of negative words and a limit and returns a list of words to censor
words_to_censor = negative_words.copy()
empty_list = [] # to be returned if limit is not met
count = 0
for word in negative_words:
if count >= limit:
... | The main task of the code is to censor specific words in an email text. It combines proprietary terms, limited negative words (appearing more than twice), and surrounding contextual words, then applies a censorship function to redact these terms from the email content, ensuring sensitive information is removed. | def main():
# print(censor_specific_word(email_one, 'learning algorithms'))
# print(censor_list_of_words(email_two, proprietary_terms, True))
# negative_words_to_censor = negative_word_limit(email_three, negative_words, 2)
# words_to_censor = negative_words + proprietary_terms
# print(censor_list_of... |
def extract_meta(meta_path: str) -> Tuple[Dict[str, List[str]], List[str]]:
"""
Extracts meta data.
:param meta_path: Metadata path (JSON file).
:return: Tuple; (ordering map, start nodes).
"""
with open(meta_path, 'r') as f:
meta = json.load(f)
ordering_map = get_ordering_map(meta)... | The function `learn_structure` learns a structural model from input data (`df_path`) and metadata (`meta_path`), identifying parent-child relationships. It performs multiple regressions (default: 10) with L1 regularization to detect significant interactions, filtering coefficients based on thresholds. The result is a d... | def learn_structure(df_path: str, meta_path: str, n_way=3,
ignore_neg_gt=-0.1, ignore_pos_lt=0.1,
n_regressions=10, solver='liblinear', penalty='l1', C=0.2,
robust_threshold=0.9) -> Dict[str, List[str]]:
"""
Kicks off the learning process.
:param ... |
def youtube_search_keyword(query, max_results):
"""Fetching the latest videos for a search query using Youtube Data API.
Args:
query (str): search query.
max_results(int): Maximum no of results we want in response from the Y
Youtube Data API.
Returns:
results (list): Li... | The function retrieves the most recent uploaded video's timestamp by searching YouTube for 'today news', extracting publication dates from search results, and comparing them to determine the latest datetime. It returns this datetime object if results exist, otherwise returns None. | def get_time_of_most_recent_uploaded_video():
"""Returns time of most recent uploaded video.
Returns:
resent_date_time (datetime): Returns datetime object.
"""
resent_date_time = ''
search_results = youtube_search_keyword('today news', 10)
if search_results == {}:
return
f... |
def info(msg):
print(msg)
logging.info(msg)
def _train_ranking_model(self, epoch, **kwargs):
self.model.eval()
self.rank_model.train()
def print_log():
msg = 'Epoch {}, Batch {}, lr = {:.5f}, {:.3f} seconds/batch'.format(epoch, bid, curr_lr, 1.0 / time_meter.avg)
... | The code trains a model with two phases: initial training and metric encoder training. It iterates through epochs, training the model normally until a specified epoch, then training the metric encoder. After each training phase, it evaluates the model, saves checkpoints, and updates the best results if the current eval... | def train(self):
best_T2M_results = None
best_T2V_results = None
info('Eval Initially at Epoch {}'.format(0))
# best_T2M_results = self._eval_ranking_model(epoch=0)
for epoch in range(1, self.args['train']['max_num_epochs']+1):
info('Start Epoch {}'.format(epoch))
... |
def login(driver: ChromeDriver, site: str) -> None:
driver.get(site)
driver.set_window_size(1419, 1602)
sleep(3)
logout = driver.find_elements(By.LINK_TEXT, "Log out")
if not logout:
print("DBG1: Logging in")
# we are NOT logged in
# logout[0].click()
driver.find_elem... | The function retrieves and sorts available time slots for a specific date and group by logging into a site, navigating to the relevant group, adjusting the displayed date to match the desired time, and fetching the available slots. | def get_slots_for_datetime(driver: ChromeDriver, desired_time: datetime) -> List[Slot]:
site = cfg["CR_SITE"]
assert site is not None
login(driver, site)
group = get_group_for_time(desired_time)
navigate_to_group(driver, group)
page_date = get_curr_date(driver).date()
desired_day: date = ... |
def make_driver():
# chrome_options = Options()
# chrome_options.add_argument("--disable-extensions")
# chrome_options.add_argument("--disable-gpu")
# chrome_options.add_argument("--no-sandbox") # linux only
# chrome_options.add_argument("--headless")
# chrome_options.headless = True # also work... | The main task of the code is to reserve a court slot for a specified time within the next three days. It validates the input time, checks slot availability using a web driver, and reserves the slot if available. If the slot is not available, it notifies the user. The process includes parsing dates, ensuring time constr... | def main(time_slot):
# Validate time slot
assert time_slot is not None
desired_time: datetime = datetime.strptime(time_slot, "%Y-%m-%d_%H:%M")
desired_day: date = desired_time.date()
assert desired_day >= date.today() and desired_day <= date.today() + timedelta(
days=3
), f"{desired_day}... |
def get_assesment_id(file_name):
split = file_name.split('-')
print(split)
for sp in split:
if str(sp).lower().startswith(Constants.QUIZ):
return str(sp).lower()
return ""
def extract_data_from_csv(path):
rows = []
with open(path, newline='', errors='ignore') as csv_file:
... | The main task of the code is to parse an assessment CSV file, extract course instance, question, and student data, and create corresponding graph nodes (course instance, questions, assessment, students) along with relationships between them in a graph database. It processes each record to generate structured entities a... | def insert_course_instance_assessment_question(assessment_file):
name = os.path.basename(assessment_file)
name, ext = name.split(Constants.DOT)
assessment_id = get_assesment_id(name)
assessment_data = extract_data_from_csv(assessment_file)
print('assessment_id = ' + assessment_id)
all_questions ... |
def extract_data_from_csv(path):
rows = []
with open(path, newline='', errors='ignore') as csv_file:
data = csv.DictReader(csv_file)
for row in data:
rows.append(row)
return rows
def get_meta_data(grades):
for grade in grades:
for key, val in grade.items():
... | This function processes student grades from a CSV file by extracting metadata and student scores, then inserts this data into a knowledge graph. It avoids irrelevant columns, maps student names to IDs, and creates relationships between students, assessments (via Canvas IDs), and their scores. The metadata is first inse... | def student_submission_assessment(grades_file):
grades = extract_data_from_csv(grades_file)
meta_data = get_meta_data(grades) # second row of the grades data contains metadata
insert_assessment_data(meta_data) # inserts metadata into the knowledge graph
avoid_list = ['Student', 'SIS Login ID', 'Sectio... |
def searchlist(ctt):
match = list()
for blood in Blood.objects.all():
if checkMatch(blood,ctt):
#matching result
match.append(blood)
if match:
#if only one item no need to sort
if (len(match) > 1):
#match = sortByVolumn(match)
match =... | The main task of the code is to handle a blood search request by processing user input, filtering results via `searchlist()`, applying optional sorting (by type, expiration date, or volume) based on query parameters, and rendering the sorted results on a webpage template. | def searchBlood(request):
if request.method == 'GET':
#ctt user input custom-control
ctt = request.GET.get('searchResult',False)
if ctt:
match = searchlist(ctt)
sortBy = request.GET.get("sortBy", None)
if sortBy in ["sortbytype", "sortbyexpdate", "sortbyvo... |
def _get_initial_clus(self):
self.initial_atoms, self.elements = self._generate_clus(self.counter)
return self.initial_atoms, self.elements
def _get_fingerprints(self, atoms):
fps = Generate_acsf_descriptor(self.atoms)
fp_length = fps.shape[-1]
#print("self.acsf, sel... | The code resets the environment's state for a new episode by initializing atoms, counters, minima tracking, and observation history. It copies initial atomic configurations, sets up energy/position tracking, initializes data structures for storing simulation progress, and prepares the environment for a fresh run. | def reset(self):
#Copy the initial atom and reset the calculator
self.new_initial_atoms, self.elements = self._get_initial_clus()
self.atoms = self.new_initial_atoms.copy()
self.atoms.set_calculator(EMT())
self.episode_reward = 0
self.total_steps = self.times... |
def _get_initial_clus(self):
self.initial_atoms, self.elements = self._generate_clus(self.counter)
return self.initial_atoms, self.elements
def _get_fingerprints(self, atoms):
fps = Generate_acsf_descriptor(self.atoms)
fp_length = fps.shape[-1]
#print("self.acsf, sel... | This code initializes a reinforcement learning environment for optimizing atomic cluster configurations. It sets up parameters, directories, initial atomic structures, observation/action spaces, and tracking variables for episodes, minima, and convergence. The environment uses EMT calculator for energy/forces, prepares... | def __init__(self,
eleNames=None,
eleNums=None,
clus_seed=None,
save_dir=None,
observation_fingerprints = True,
observation_forces=True,
observation_positions = True,
descriptors = No... |
def log_size(leaf_list):
""""
Logs how many members are contained in all the leaves, used to debug and to check for missing elements.
:param leaf_list: list of leaves(class Node)
"""
tot = 0
for leaf in leaf_list:
for member in leaf.members:
tot +=1
logg... | The code implements the Kapra algorithm for anonymizing time-series data, ensuring groups meet k-anonymity and pattern-based criteria. It performs three phases: building a tree structure, recycling suboptimal nodes, and forming groups. The output includes anonymized datasets, performance metrics, and reports, adhering ... | def kapra_main(k_value=None,p_value=None,paa_value=None,max_level=5,dataset_path=None,nrows=None,verbosity_level = "TRACE"):
"""
Starts the Kapra algorithm described in the paper " Supporting Pattern-Preserving Anonymiziation for Time-Series Data" by Shou et al. 2013.
Kapra is divided in three phases... |
def tos_to_dscp_value(tos):
return int(('{0:08b}'.format(tos))[:6], 2)
def is_iot_client(connection):
if connection.get_dscp_value() == DSCP_NON_IOT:
print(str(connection.get_tuple()) + ' NON-IOT')
return False
for entity in CACHE_CLIENTS['entities']:
if entity['ip'] == connection.ge... | The code processes network packets to identify IoT client connections. It creates a connection object from IP addresses and TOS/DSCP values, checks if the connection is an IoT client and not in a cache, then triggers an IoT-specific action for new connections. The task involves packet analysis, IoT detection, and manag... | def handle_pkt(pkt):
if IP in pkt:
connection = Connection(pkt[IP].src, pkt[IP].dst, tos_to_dscp_value(pkt[IP].tos))
print('got a packet: ' + str(connection.get_tuple()))
if is_iot_client(connection) and connection.get_tuple() not in CACHE_CONNECTION:
print(str(connection.get_tup... |
def get_result(shot: tuple):
print(COLUMNS[shot[0]], shot[1]+1)
result = input("miss, hit or sunk?m/h/s: ")
while not result in ["m", "h", "s"]:
result = input("invalid outcome!\nm/h/s?")
return OUTCOMES[result]
def handle_result(self, pos: tuple, result: int):
x, y =... | The code simulates a turn-based game where a bot and player alternately shoot at each other's boards. The bot uses random strategies from available options or a queue, while the player inputs coordinates. The game continues until all opponent ships are sunk, with the outcome (win/loss) displayed based on remaining ship... | def play(self, rules:tuple = (4,3,2,1)):
refill = self.my_board.fill(rules)
while refill:
refill = self.my_board.fill(rules)
starting = 0 #random.randint(0, 1)
if starting == 0:
print("I BEGIN")
else:
print("YOU BEGIN")
print("GIVE ANY ... |
def fail(msg):
print(msg)
sys.exit(1)
def plot_y_vs_x(all_results, x_col, y_col):
fig, ax = plt.subplots()
ax.set_xlabel(col_title(x_col))
ax.set_ylabel(col_title(y_col))
ax.set_title("Relative throughput")
ax.grid(True)
if do_log(x_col):
ax.set_xscale("log")
if do_log(y_col... | The main task of the code is to generate plots from CSV results files based on user-specified parameters. It accepts input paths, plot types (y vs x or bars per algorithm), column selections, and x-values. The script reads results, processes them according to the chosen plot type, generates a figure, and saves it to th... | def main():
parser = argparse.ArgumentParser(description="Plot results")
parser.add_argument("results_path", type=str, help="Path to results")
parser.add_argument("out_path", type=str, help="Path to output file")
parser.add_argument("--y_vs_x", action="store_true", help="Plot column y vs column x")
... |
def t_term(self):
"""
this generates the electron hopping term
Sum c_{i+1}+ * c_{i} + h.c.
"""
dim = len(self.configs())
t_mat = spr.coo_matrix((dim, dim))
for i in range(self.length - 1):
term = self.hop_e(sites=(i + 1, i))
term += term.T
... | This function constructs a Hamiltonian by summing terms scaled by parameters t, delta, mu, tau, v, and eta. If `fixed_ne` is False, it includes all terms; otherwise, it excludes the pairing term (delta_term) while retaining others like kinetic (t_term), chemical potential (mu_term), and interaction terms. | def ham(self, t, delta, mu, tau=0., v=0., eta=0.):
"""
this puts together all terms of the Hamiltonian
when fixed_ne is True it drops the pairing term
"""
if not self.fixed_ne:
return (t * self.t_term() + delta * self.delta_term() +
mu * self.mu_te... |
def pathSolution(self, parent, j):
# Base Case : If j is source
if parent[j] == -1:
self.shortest_Path.append(j)
return
self.pathSolution(parent, parent[j])
self.shortest_Path.append(j)
def printSolution(self, dist, parent):
src = self.starting_point
... | The function `getSolutions` handles different query modes to return specific graph traversal results. For `mode=1`, it retrieves the shortest path; `mode=2` outputs the full solution path; `mode=3` identifies nearby nodes within a radius; and `mode=4` computes distances from the start node to all others. It delegates t... | def getSolutions(self, mode, D):
if mode == 1: # returns shortest path
self.pathSolution(self.parent, self.end_point)
return self.shortest_Path
if mode == 2: # returns full Solution
self.printSolution(D, self.parent)
if mode == 3: # returns nearby nodes
... |
def search(self, interval):
current = self.root
while True:
status = interval.compare(current.value)
if status == -1:
current = current.left
elif status == 1:
current = current.right
else:
return current
d... | This code deletes a specified key from a tree structure by first locating the minimum node associated with the key, determining the node that needs updating (its parent or itself), recursively removing the key from the tree, and then updating the maximum height or property of the relevant node to maintain tree integrit... | def delete(self, key):
minimumnode = self.search(key)
if self.findMin(minimumnode).parent is not None:
nodetoupdate = self.findMin(minimumnode).parent
else:
nodetoupdate = self.findMin(minimumnode)
self.root = self._delete(self.root, key)
self.updateMaxhi... |
def isRed(self, node):
if node is None:
return False
return node.color
def moveRedLeft(self, node):
self.flipColors(node)
if self.isRed(node.right.left):
node.right = self.rotateRight(node.right)
node = self.rotateLeft(node)
return node
def bal... | This code deletes the minimum element from a red-black tree. It checks if the left child is null, handles red-black tree properties by moving red nodes left when needed, recursively deletes the minimum from the left subtree, and balances the tree to maintain structural integrity post-deletion. | def deleteMin(self, node):
if node.left is None:
return None
if not self.isRed(node.left) and not self.isRed(node.left.left):
node = self.moveRedLeft(node)
node.left = self.deleteMin(node.left)
return self.balance(node) |
def isRed(self, node):
if node is None:
return False
return node.color
def moveRedLeft(self, node):
self.flipColors(node)
if self.isRed(node.right.left):
node.right = self.rotateRight(node.right)
node = self.rotateLeft(node)
return node
def rot... | This function deletes a node with the specified key from a red-black tree while maintaining balance. It handles cases where the key matches the node's key, adjusts tree structure via rotations (rotateRight, moveRedLeft/moveRedRight), and recursively deletes from left/right subtrees. After deletion, it balances the tree... | def _delete(self, node, key):
if key.compare(node.key) == 0:
if not self.isRed(node.left) and not self.isRed(node.left.left):
node = self.moveRedLeft(node)
node.left = self._delete(node.left, key)
else:
if self.isRed(node.left):
node =... |
def isRed(self, node):
if node is None:
return False
return node.color
def _delete(self, node, key):
if key.compare(node.key) == 0:
if not self.isRed(node.left) and not self.isRed(node.left.left):
node = self.moveRedLeft(node)
node.left = self.... | The code deletes a key from a red-black tree, adjusting the root's color to maintain the tree's properties. It ensures the root is black after deletion by temporarily setting it to red before the operation and reverting it post-deletion if the tree isn't empty. | def delete(self, key):
if not self.isRed(self.root.left) and not self.isRed(self.root.right):
self.root.color = True
self.root = self._delete(self.root, key)
if not self.isEmpty():
self.root.color = False |
def get_fat_percentage(self):
# Set a constant to remove from LBM
if self.sex == 'female' and self.age <= 49:
const = 9.25
elif self.sex == 'female' and self.age > 49:
const = 7.25
else:
const = 0.8
# Calculate body fat percentage
LBM ... | This function calculates the protein percentage by subtracting the rounded-down percentages of fat, water, and bone mass from 100%. It first deducts the fat percentage (floored), then subtracts the water percentage (floored), and finally subtracts the bone mass percentage (calculated as bone mass/weight * 100, then flo... | def get_protein_percentage(self):
proteinPercentage = 100 - (floor(self.get_fat_percentage() * 100) / 100)
proteinPercentage -= floor(self.get_water_percentage() * 100) / 100
proteinPercentage -= floor((self.get_bone_mass() / self.weight * 100) * 100) / 100
return proteinPercentage |
def get_fat_percentage(self):
# Set a constant to remove from LBM
if self.sex == 'female' and self.age <= 49:
const = 9.25
elif self.sex == 'female' and self.age > 49:
const = 7.25
else:
const = 0.8
# Calculate body fat percentage
LBM ... | This code determines a body type classification by evaluating fat percentage and muscle mass against predefined scales. It calculates a factor based on fat percentage ranges and combines it with muscle mass comparisons to return a numerical body type code, using weighted values for final classification. | def get_body_type(self):
if self.get_fat_percentage() > self.get_fat_percentage_scale()[2]:
factor = 0
elif self.get_fat_percentage() < self.get_fat_percentage_scale()[1]:
factor = 2
else:
factor = 1
if self.get_muscle_mass() > self.get_muscle_mass_sc... |
def load_mnist_aug(self):
print('loading mnist and augmenting ...')
data_dir = os.path.join('./data', 'mnist')
fd = open(os.path.join(data_dir,'train-images-idx3-ubyte'))
loaded = np.fromfile(file=fd,dtype=np.uint8)
trX = loaded[16:].reshape((60000,28,28,1)).astype(np.float)
num_samples = 5000... | Your return This code initializes a neural network model (likely a GAN) with parameters for image generation, specifying input/output dimensions, batch size, and network architectures. It sets up batch normalization layers, handles dataset loading (e.g., MNIST or custom images), and configures data preprocessing. The `... | def __init__(self, sess, input_height=108, input_width=108, crop=True,
batch_size=64, sample_num = 64, output_height=64, output_width=64,
y_dim=None, z_dim=100, gf_dim=64, df_dim=64,
gfc_dim=1024, dfc_dim=1024, c_dim=3, dataset_name='default', aug=False, alpha_max=20,
max_to_keep=1,
... |
def gen_random(mode, size):
if mode=='normal01': return np.random.normal(0,1,size=size)
if mode=='uniform_signed': return np.random.uniform(-1,1,size=size)
if mode=='uniform_unsigned': return np.random.uniform(0,1,size=size)
def load(self, checkpoint_dir):
#import re
print(" [*] Reading checkpoints.... | This code trains a Generative Adversarial Network (GAN) using TensorFlow. It initializes optimizers for the discriminator and generator, loads data (MNIST or custom), trains via alternating updates to D and G networks, logs losses with TensorBoard, generates samples periodically, and saves checkpoints. The training loo... | def train(self, config):
d_optim = tf.train.AdamOptimizer(config.learning_rate, beta1=config.beta1) \
.minimize(self.d_loss, var_list=self.d_vars)
g_optim = tf.train.AdamOptimizer(config.learning_rate, beta1=config.beta1) \
.minimize(self.g_loss, var_list=self.g_vars)
try:
... |
def add_song(self,song):
"""
adds a new song instance
:param song: song to add
"""
self.get_songs().append(song)
def populate_random(self,cnt,titles,artists):
"""
adds random song to the repo
:param cnt: number of songs to add
"""
newsongs ... | The main task of the code is to load songs from a specified file into a repository. It reads each line, converts it into a `Song` object, and adds it to the repository. Errors during processing are collected and raised as a `ValueError` if any occur. If the file is not found, it generates 10 random songs with predefine... | def load_from_file(self,path):
"""
loads songs from file into the repo
:param path:
:param e_handler:
:return:
"""
errors = []
line_counter = 1
try:
with open(path,"r") as f:
for line in f:
try:
... |
def text_similarity(inp_obj1, inp_obj2):
return inp_obj1.similarity(inp_obj2)
def bag_of_words(sen1, sen2):
sen1 = sen1.replace(".","")
sen2 = sen2.replace(".","")
words1 = word_tokenize(sen1)
lemma1 = []
for w in words1:
lemma1.append(lemmatizer.lemmatize(w))
words2 = word_tokeniz... | The code reads training and test data containing sentence pairs and their gold tags, extracts multiple linguistic features (text similarity, bag-of-words, parse similarity, semantic similarity, synset similarity), scales these features, trains an ensemble classifier (Random Forest + AdaBoost) on the training data, and ... | def main(args):
# Reading the train file
with open(args.pairfile,'r') as f:
sentences = []
ids = []
first_sents = []
second_sents = []
true_score = []
next(f) #Skipping the first header line in the input file
for line in f.readlines():
line_spl... |
def _check_start_game(self, mouse_position):
if self.start_button.rect.collidepoint(mouse_position) and not self.stats.active:
pygame.mouse.set_visible(False)
self.stats.reset_stats()
self.stats.active = True
self.settings.default_settings()
self.score... | The main task of the code is to handle peripheral events in a Pygame application. It processes events like window closure, mouse clicks, and key presses. When the window is closed, it quits Pygame and exits the program. For mouse clicks, it retrieves the position and triggers the _check_start_game method. Key presses a... | def _check_events(self):
"""Respond to peripheral events."""
# Loop to check for Pygame events.
for event in pygame.event.get():
# Check if the program window is closed.
if event.type == pygame.QUIT:
# Deactivate the Pygame library.
pygame... |
def _check_wave_borders(self):
for invader in self.invaders.sprites():
if invader.check_borders():
self._change_wave_direction()
break
def _check_invader_win(self):
screen_rect = self.screen.get_rect()
for invader in self.invaders.sprites():
... | This method updates the position of invaders by checking wave boundaries, updating their movement, and verifying if they have reached a winning condition. It also detects collisions between the player and invaders, triggering a game-over response if contact is made. | def _update_invaders(self):
"""Update the position of the invaders"""
self._check_wave_borders()
self.invaders.update()
self._check_invader_win()
if pygame.sprite.spritecollideany(self.player, self.invaders):
self._game_over() |
def _check_events(self):
"""Respond to peripheral events."""
# Loop to check for Pygame events.
for event in pygame.event.get():
# Check if the program window is closed.
if event.type == pygame.QUIT:
# Deactivate the Pygame library.
pygame... | The code defines the main game loop, continuously checking events, updating the player, projectiles, and invaders when active, and rendering the screen to maintain gameplay and visuals. | def run_game(self):
"""The main loop for the game."""
# Loop that runs while the game is active.
while True:
# Watch for peripheral events.
self._check_events()
if self.stats.active:
# Update player position.
self.player.updat... |
def filter_short_sessions(df, min_len=2):
session_len = df.groupby('sessionId', sort=False).size()
long_sessions = session_len[session_len >= min_len].index
df_long = df[df.sessionId.isin(long_sessions)]
return df_long
def truncate_long_sessions(df, max_len=20, is_sorted=False):
if not is_sorted:
... | The code preprocesses a dataset for session-based recommendation systems by reading and cleaning data, generating timestamps, filtering short/long sessions and infrequent items, splitting data temporally into train/test sets, and saving processed datasets. It ensures data is sorted, truncated, and validated for model t... | def preprocess_diginetica(dataset_dir, csv_file):
print(f'reading {csv_file}...')
df = pd.read_csv(
csv_file,
usecols=[0, 2, 3, 4],
delimiter=';',
parse_dates=['eventdate'],
infer_datetime_format=True,
)
print('start preprocessing')
# timeframe (time since the... |
def filter_short_sessions(df, min_len=2):
session_len = df.groupby('sessionId', sort=False).size()
long_sessions = session_len[session_len >= min_len].index
df_long = df[df.sessionId.isin(long_sessions)]
return df_long
def filter_infreq_items(df, min_support=5):
item_support = df.groupby('itemId', s... | This function preprocesses the Yoochoose dataset by reading and cleaning the input CSV, filtering infrequent items and short sessions, splitting data temporally into training and test sets, further dividing training data into validation splits, and saving processed datasets to the specified directory for recommendation... | def preprocess_yoochoose(dataset_dir, csv_file):
print(f'reading {csv_file}...')
df = pd.read_csv(
csv_file,
usecols=[0, 1, 2, 3],
delimiter=',',
parse_dates=['timestamp'],
infer_datetime_format=True,
)
print('start preprocessing')
df['timestamp'] = df.timesta... |
def update_id(df, field):
labels, uniques = pd.factorize(df[field])
kwargs = {field: labels}
if field == 'itemId':
oid2aid = {oid:aid for oid, aid in enumerate(uniques)}
with open('oid2aid.pkl', 'wb') as f:
pkl.dump(oid2aid, f)
df = df.assign(**kwargs)
return df
def group... | The main task of the code is to preprocess a user-item interaction dataset (e.g., Gowalla/LastFM) by cleaning, transforming, and splitting data into training/validation/test sets. It reads a CSV file, processes timestamps, deduplicates sessions, filters items, truncates long sessions, and splits data for machine learni... | def preprocess_gowalla_lastfm(dataset_dir, csv_file, usecols, interval, n):
print(f'reading {csv_file}...')
df = pd.read_csv(
csv_file,
sep='\t',
header=None,
names=['userId', 'timestamp', 'itemId'],
usecols=usecols,
parse_dates=['timestamp'],
infer_dateti... |
def load_demodata(self, demodata_path):
demodata = np.load(demodata_path, allow_pickle=True)
self.obs = demodata["obs"]
self.acs = demodata["acs"]
def _flatten_demodata(self):
self.obs = self._flatten_array(self.obs)
self.acs = self._flatten_array(self.acs)
def _shuffle_demodata(... | The code initializes a demonstration data processor by loading data from a specified path and preparing it according to the given mode. It handles three modes: "full sequence" (no modification), "partial sequence" (flattens data), and "random" (shuffles data). It also initializes an index counter and records the data s... | def __init__(self, demodata_path, mode="random"):
self.load_demodata(demodata_path)
self.mode = mode
if self.mode == "full sequence":
pass
elif self.mode == "partial sequence":
self._flatten_demodata()
elif self.mode == "random":
self._shuffle... |
def train_recommender(self):
if hasattr(self.rec_model, 'bert'):
if os.environ["CUDA_VISIBLE_DEVICES"] == '-1':
bert_param = list(self.rec_model.bert.named_parameters())
else:
bert_param = list(self.rec_model.module.bert.named_parameters())
ber... | The `fit` method trains distinct models based on their existence: it calls `train_recommender()` if `rec_model` exists, `train_policy()` if `policy_model` exists, and `train_conversation()` if `conv_model` exists. The function orchestrates model-specific training processes conditionally, ensuring each available model i... | def fit(self):
if hasattr(self, 'rec_model'):
self.train_recommender()
if hasattr(self, 'policy_model'):
self.train_policy()
if hasattr(self, 'conv_model'):
self.train_conversation() |
def pretrain(self):
self.init_optim(self.pretrain_optim_opt, self.model.parameters())
for epoch in range(self.pretrain_epoch):
self.evaluator.reset_metrics()
logger.info(f'[Pretrain epoch {str(epoch)}]')
for batch in self.train_dataloader.get_pretrain_data(self.pretr... | The main task of the code is to execute a training pipeline consisting of three stages: pretraining, training a recommendation system, and training a conversational model. The `fit` method sequentially calls these functions to initialize model parameters, optimize recommendation capabilities, and refine conversational ... | def fit(self):
self.pretrain()
self.train_recommender()
self.train_conversation() |
def magic_set_environment_vars(code):
global BLOCKCHAIN
global REDIS
global TIMESTAMPING
global LOGGING_LEVEL
output = []
for line in code.split("\n"):
line = line.strip().upper()
# For reference later
line_end = line[line.find("=")+1:]
logging.debug(line)
... | The function `run` processes input code by checking its first line for specific magic commands. If the code starts with `%ENV`, it sets environment variables; `%CONSULT` triggers Redis-based file consultation; `%PYTHON` executes Python code. Otherwise, it runs Prolog code. The function uses regex to identify these comm... | def run(code):
logging.debug(f"\n{code=}")
first_line = code.split("\n")[0].strip().upper()
logging.debug(first_line)
# Check if the cell is marked by %ENV
# If it is, set environment variables
if re.match(r"%\s*ENV.*", first_line):
return magic_set_environment_vars(code)
# ... |
def load(self, driver: Firefox):
self.set_parameters()
self.load_previous_listings()
self.driver = driver
self.driver.get(self.search_url)
time.sleep(3)
self.soup = BeautifulSoup(self.driver.page_source)
def parse(self):
listings = self.soup.find_all(attrs=self.li... | The main task of the code is to execute a sequence of operations: load data using the provided driver, parse the data, and then exit. If any exception occurs during these steps, it catches and returns the error. The method ensures structured processing and error handling for the data workflow. | def run(self, driver):
try:
self.load(driver)
self.parse()
self.exit()
except Exception as e:
return e |
def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
def ensureDir(dir_path):
d = os.path.dirname(dir_path)
if not os.path.exists(d):
os.makedirs(d)
def golem_linear(model: nn.... | The main task of the code is to evaluate multiple causal discovery models (Notears, GOLEM, DAG-GNN, GRANDAG) on various datasets (real, synthetic, testing) across multiple trials. It loads/generated data, trains models to estimate causal graphs, computes accuracy against true graphs, and aggregates performance metrics ... | def main(trials,seed):
tot_perf={}
reweight_str=f"_reweight_{args.temperature}" if not IF_baseline else ""
device=torch.device(args.device)
args.device=device
for trial in range(trials):
print('==' * 20)
import notears.utils as ut
cur_seed=trial+seed
global COUNT
... |
def updateLine(self):
self.pline=pg.LineSegmentROI(positions=(200,250))
self.selectors[0].addItem(self.pline)
self.pline.sigRegionChanged.connect(self.update_line_length)
self.update_line_length()
def updatePolyLine(self):
self.pgn=pg.PolyLineROI(positions=[[0, 0], [27, 0], [0, 2... | This code manages UI interactions for selecting geometric shapes (Line, Polygon, Angle, Ellipse). When a button is checked, it displays a corresponding label and triggers an update method. If unchecked, it hides the label, removes a shape from a selector, and prints the selection status. The function handles four disti... | def btnstate(self,b):
if b.text() == "Line":
if b.isChecked() == True:
self.b1Label.setHidden(False)
print (b.text()+" is selected")
self.updateLine()
else:
self.b1Label.setHidden(True)
self.selectors[0].removeItem(self.pline)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.