dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def instrument(self):
instruments = []
if self.Bamboo.isChecked():
instruments.append("Bamboo")
if self.Bass.isChecked():
instruments.append("Bass")
if self.Bell.isChecked():
instruments.append("Bell")
if self.Flute.isChecked():
if ... | The code initializes the UI by connecting buttons to methods: 'addInstruments' triggers `instrument()`, 'addState' triggers `state_list()`, and 'start' triggers `setup()` with parameters like interval, base, rules, and limits to configure the application's behavior. | def initUI(self):
self.addInstruments.clicked.connect(lambda: self.instrument())
self.addState.clicked.connect(lambda: self.state_list())
self.start.clicked.connect(
lambda: self.setup(
interval,
base,
rule,
state1,
... |
def requestData(ticker, period, interval):
"""
Common tickers:
- EURUSD=X
- GBPUSD=X
- AUDUSD=X
- NZDUSD=X
- JPYUSD=X
"""
return yf.download(tickers=ticker, period=period, interval=interval)
def enableEMA(df, period):
# Exponential moving average
ema = EMAIndicator(df['close... | The code processes financial data for AUDUSD=X, applies technical indicators (EMA, Bollinger Bands, Awesome Indicator), generates trading signals, and outputs the DataFrame along with signal summaries and statistical results. | def main():
pd.set_option('display.max_rows', None)
df = requestData("AUDUSD=X", "10d", "30m")
df.columns= df.columns.str.lower()
df = enableEMA(df, 3)
df = enableBollingerBands(df)
df = enableAwesomeIndicator(df)
print(df)
signals = provideSignals(df)
for signal in signals... |
def as_tracker(self):
tracker = Tracker(
im_shape=tuple(self.data_config.frame_shape),
scale=self.data_config.scale
)
tracker.DEBUG_MODE = True
# configure merge capacity
tracker.MERGE_EDGE_CAPACITY = self.tracktour_config.merge_capacity
# if appe... | This code runs a tracking process by loading detections from a CSV file, solving the tracking model with specified parameters, optionally computing additional features like migration and sensitivity if debug mode is enabled, and writing output results if requested. It includes validation checks for flow penalty setting... | def run(self, write_out=True, compute_additional_features=False):
start = time.time()
tracker = self.as_tracker()
if tracker.PENALIZE_FLOW and tracker.FLOW_PENALTY_COEFFICIENT == 0:
raise ValueError("Cannot penalize flow with a coefficient of 0.")
# load detections
... |
def set_map_size(self, map_dim_new):
self.map_dim = map_dim_new
self.h_line = self.map_dim[0]*(block+line) - line
self.v_line = self.map_dim[1]*(block+line) - line
self.map_size = (self.h_line + 2*border, self.v_line + 2*border)
self.screen = pygame.display.set_mode(self.map_size)
self.goal = (self.map_dim[... | This code initializes a grid-based simulation environment for a robot, setting up map dimensions, obstacles, and a robot instance. It configures an 8x8 map, generates border blocks, places random obstacles, initializes sensors, creates a robot object, updates the display, and starts a training session with logging. The... | def __init__(self):
# Set map sizes
self.h_line = self.v_line = self.map_dim = self.map_size = self.screen = self.goal = self.state = None
self.training = True
self.num_actions = 0
self.clock_rate = 5
self.finished = False
self.set_map_size((8, 8))
self.show_animation = False
# Set blocks
self.lake_... |
def load_data(filename):
"""
Load shopping data from a CSV file `filename` and convert into a list of
evidence lists and a list of labels. Return a tuple (evidence, labels).
evidence should be a list of lists, where each list contains the
following values, in order:
- Administrative, an int... | The code's main task is to load shopping data from a spreadsheet, split it into training and test sets, train a model on the training data, predict on the test set, and evaluate the model's performance by calculating accuracy, true positive rate (sensitivity), and true negative rate (specificity), then printing these m... | def main():
# Check command-line arguments
if len(sys.argv) != 2:
sys.exit("Usage: python shopping.py data")
# Load data from spreadsheet and split into train and test sets
evidence, labels = load_data(sys.argv[1])
X_train, X_test, y_train, y_test = train_test_split(
evidence, labe... |
def goalTest(self): # this method checks backtrack algorithms is finished or not
if len(self.finalAssignment) == self.lenAssignment:
return True
else:
return False
def MRV(self): # this method do MRV
done = False
for index, l in enumerate(self... | (The code implements a backtracking algorithm with Minimum Remaining Values (MRV) heuristic to solve a constraint satisfaction problem. It assigns values (0/1) to variables in a grid, using forward checking or MAC (Maintaining Arc Consistency) based on a flag. It checks for failures, backtracks when needed, and maintai... | def backtrack(self): # this method runs backtrack algorithm
if self.goalTest():
return True
a = self.MRV()
b = [0, 1]
for i in b:
self.base[a[0]][a[1]] = str(i)
self.finalAssignment.append([a[0], a[1], str(i)])
self.step += 1
... |
def mutation(self, children):
temp = {}
for key, value in children.items():
rand = random.randint(1, 10)
if rand >= 9:
rand2 = random.randint(0, self.levelLen - 1)
rand3 = random.randint(0, 2)
l = list(key)
l[rand2] ... | The code runs an algorithm for 1,000,000 iterations, generating mutations from child data, tracking minimum, average, and maximum fitness values in lists. When a condition is met, it visualizes the current state, plots fitness trends, and exits. The main task involves iterative optimization with mutation, fitness evalu... | def do_algo(self):
for i in range(1000000):
a = self.mutation(self.get_children())
print(a)
print(self.get_point())
self.minFitness.append(self.get_min_point())
self.avgFitness.append(self.get_point())
self.maxFitness.append(self.get_max_p... |
def nonzero_x_H_x(self, state):
"""
for a given | x > belonging to basis,
find all | x' > such that < x' | H | x > != 0
"""
assert len(state) == self.N*2, state
state_hopped = self.all_hoppings(state)
all_states = [ hopped for (hopped, parity) in state_hopped if ... | The code computes the local energy expectation value for a given quantum state using the Gutzwiller projected wavefunction. It sums over all states $x'$, incorporating Hamiltonian matrix elements $<x|H|x'>$ and Gutzwiller weights $P_G(x)$, with a correction term `fast_update` to account for wavefunction ratios. The res... | def Eloc(self, state):
"""
Evaluated as \sum_{x'} < x |H| x' > <x'|Psi>/<x|Psi>,
###<x|Psi> = <x|P_G|Psi_0> = P_G(x)<x|Psi_0>, where P_G is the Gutzwiller projector
Here x is state
"""
eloc = 0
##basis = self.get_basis()
##assert state in basis, state
... |
def random_init(self):
import random
from itertools import combinations
#up = combinations(range(self.Lsite), self.N)
#up = [ sorted(list(xx)) for xx in up ]
#up_idx = random.randint(0, len(up)-1)
#up_init = up[up_idx]
#down = combinations(range(self.Lsite, self... | The code implements a Metropolis-Hastings algorithm for sampling quantum states, calculating the average energy (E_mean) and acceptance rate. It initializes a state, iteratively proposes new states via `self.jump()`, evaluates acceptance probabilities using `P_accept_fast()`, updates states based on random sampling, an... | def Metropolis(self, nstep):
E_tot = [ ]
num_accept = 0
import random
#state_init = [ xx*2 for xx in range(self.N) ] + [ (yy*2+self.Lsite+1) for yy in range(self.N) ]
#state_init = [ 0, 1, 6, 8, 9, 11, 12, 13, 16, 17]
#state_init = [ 2, 4, 6, 7, 8, 10, 11, 12, 1... |
def _highpass(matrix, wp=6e4, ws=1e4, gpass=3, gstop=20):
"""
Filtering out low frequencies of signal
:param wp: Passband edge frequency [Hz]
:param ws: Stopband edge frequency [Hz]
:param gpass: The maximum loss in the passband [dB]
:param gstop: The minimum attenuation in the stopband [dB]
:return: filtered... | The code reconstructs a USG data set by first applying a high-pass filter to center the data around zero. It then computes the Cross-Power Weighted Image (CPWI), converts it to decibels (dB), and plots the reconstructed image with specified sample and transducer ranges. The process visualizes the filtered and transform... | def run():
"""
Create full reconstruction of a USG data
"""
data_centered_around_0 = _highpass(data)
cpwi = _cpwi(data_centered_around_0)
cpwi = _db_conversion(cpwi)
_plot_reconstruction(cpwi, from_sample=1000, to_sample=-300,
cutoff=-50, from_transducer=0,
... |
def _parse_mmf_header(it, current, recipe):
"""Parses the MMF header and moves to the next line if found."""
current = _skip_empty(it, current)
if _is_mmf_header(current):
current = next(it)
return current
def _parse_title(it, current, recipe):
"""Parses the Title line and moves to the next ... | The main task of the code is to parse a recipe from an iterable of strings (lines) into a structured `Recipe` object. It processes lines to extract and organize components like the header, title, directions (and optionally ingredients) using helper functions. The function iterates through the input lines, applies parsi... | def parse_recipe(lines):
"""Parses a recipe from the given lines.
Parses a single recipe when given an iterable of strings. These lines
should not have a trailing newline character.
Args:
lines: An iterable of strings containing the lines of the recipe.
Returns:
A Recipe correspon... |
def _get_ingredient_heading(line):
"""Returns the heading from a heading line or an empty string if this
is not an ingredient heading line."""
match = _heading_re.match(line)
if not match:
return ""
return match.group(1).strip()
def _is_ingredient(line):
"""Tests whether a line is an ing... | This function parses valid ingredient lines from an iterator, collecting them into a list of tuples (text, is_heading) for a recipe. It processes lines until encountering an invalid line, handling empty lines and ingredient headings, then assigns the parsed ingredients to the recipe's ingredients attribute. The functio... | def _parse_ingredients(it, current, recipe):
"""Parses valid ingredient lines and advances to the first line that
is not a valid ingredient line.
Valid ingredient lines are ingredient heading lines, ingredient lines,
and empty lines.
"""
ingredients = [] # list of tuples (text, is_heading)
... |
def calculate_correlation(self, gene1: int, gene2: int) -> float:
"""Calculates single correlation between given tuple of genes.
:param gene1 first gene index
:param gene2 second gene index
:return correlation between given tuple of genes"""
gene1_values = pd.DataFrame(... | This function computes Pearson's correlation between all gene pairs, adding undirected regulations to a set if their absolute correlation exceeds a given threshold. Valid regulations are filtered and directions are later randomized. It returns suggested undirected constraints for network inference. | def derive_constraints(self, threshold: float) -> Set[reg.Regulation]:
"""Computes Pearson's correlation between each pair of genes, if the absolute value is greater than given
threshold, then suggests such regulation to be added later during the inference.
As the correlation is symmetric, the s... |
def get_r_q(a):
terminal_states = list()
non_terminal_states = list()
for i, row in enumerate(a):
terminal = True
for no in row:
if no != 0:
terminal = False
break
if terminal:
terminal_states.append(i)
a[i][i] = 1
... | The code calculates probabilities from a matrix `m` using matrix operations and rational arithmetic. It handles edge cases (single-row matrices or zero-sum rows) and computes probabilities by inverting a matrix, performing matrix multiplication, and converting results to fractions. It then scales these fractions by the... | def solution(m):
if len(m) == 1:
return [1, 1]
if sum(m[0]) == 0:
probabilites = [0] * len(m)
probabilites[0] = 1
probabilites.append(1)
return probabilites
r, q, one_pos = get_r_q(m)
f = inverted(get_f(q))
fr = matmul(f, r)
probabilites = [Fraction(i).... |
def getError(combination: dict, TBAMatch: pd.Series) -> float:
error = 0
total = 0
errorPercent = 1.0
data = []
for team in combination:
data.append(flatten_dict(combination[team]["data"]))
addedData = data[0]
for field in addedData:
if not field == "teleop_pass":
... | The main task of the code is to evaluate the reliability of scout ratings in scoutingData by comparing them against team combinations and averages from TBAData. It calculates trust scores based on discrepancies between individual scout entries and aggregated team data, then computes an overall trust rating for each sco... | def getScoutRatings(TBAData: pd.DataFrame, scoutingData: list) -> dict:
scouts = []
scoutTrusts = []
scoutTrustRatings = []
TBADict = TBAData.to_dict("records")
for entry in scoutingData:
if not (scouts.__contains__(entry["scout_info"])):
scouts.append(entry["scout_info"])
fo... |
def getScoutRatings(TBAData: pd.DataFrame, scoutingData: list) -> dict:
scouts = []
scoutTrusts = []
scoutTrustRatings = []
TBADict = TBAData.to_dict("records")
for entry in scoutingData:
if not (scouts.__contains__(entry["scout_info"])):
scouts.append(entry["scout_info"])
fo... | The function iteratively calculates and refines scout trust ratings by analyzing data consistency across team combinations and comparative entries. It processes scouting data against TBA match records, evaluates error rates for team combinations, adjusts trust scores based on team averages, and iterates 10 times to con... | def getMarkovianRatings(TBAData: pd.DataFrame, scoutingData: list):
scoutRatings = getScoutRatings(TBAData, scoutingData)
# print("got one time ratings")
for j in range(10):
scouts = scoutRatings["scouts"]
oldTrustRatings = scoutRatings["trustRatings"]
scoutTrusts = []
scoutT... |
def generateOriginalPopulation(self, startingValue: pd.DataFrame) -> list:
population = []
population.append(pd.DataFrame(copy.deepcopy(startingValue)))
while len(population) < self.populationSize:
population.append(self.mutateGenes(startingValue))
return population
def setBe... | The code executes an evolutionary algorithm to optimize a solution by iteratively generating populations, selecting parents, and updating the best solution. It terminates when 25 generations pass without improvement or after 1500 generations, returning the best solution and its error. | def run(self):
np.random.seed(1186244499)
self.population = self.generateOriginalPopulation(self.startingValue)
self.bestSolutionError = -1.0
self.setBestSolution(self.population)
foundSolution = False
self.generationsSinceImprovement = 0
generationNumber = 0
... |
def draw_samples( fold_data, guard_condition ):
"""
Draw subgraph samples for mini batch
Args:
fold_data (pandas.DataFrame): Possible list of subgraphs
guard_condition (int): Mini batch size
"""
x = torch.tensor( () )
y = torch.tensor( (), dtype=torch.long )
edge_index ... | (This function performs mini-batch training of a graph neural network (GNN) model using PyTorch Geometric. It iterates over epochs, draws training samples, computes loss via negative log-likelihood, backpropagates gradients, and updates the model. Training accuracy is logged, while validation accuracy is periodically e... | def stichted_training( device, data_list, model, optimizer, writer
, checkpoint_file, epochs = 200, guard_condition = 50, val_sample_size = 0, val_step = 1 ):
"""
Execute mini batch based training
Args:
device (str): Cuda device
data_list (dict): Dictionary of training a... |
def attribute_based_collection_impl( self, bloomfilter ):
"""
Implementation to calculate the attribute based collection
Args:
bloomfilter (bool): Value if we want to additionally calculate the hashes with a bloomfilter
"""
self.based_collection_impl( True, ... | The function calculates a graph summary using one of four methods (attribute-based, class-based, schemex, or property-type) based on `self.gs_`, then computes features, labels, and weights for graph elements. Weights are inversely proportional to label distribution to ensure even sampling. The `bloomfilter` flag influe... | def calculate_graph_summary( self, bloomfilter ):
"""
Calculate the by the index defined graph summary on the prepared data
Args:
bloomfilter (bool): Value if we want to additionally calculate the hashes with a bloomfilter
"""
# 2. create graph summary over ... |
def make_readings(self):
readings = []
for angles in self.config.search_profile:
self.arduino.send_angles(angles)
readings.append(self.parse_reading(self.mercury.make_read(base_read_power=2800)))
return readings
def find_numerator(self, prob_of_t_given_prior_data):
... | The main task of the code is to compute and update a probability grid using prior data and historical context. It calculates probabilities by dividing numerators (from prior data) by denominators (from the same data), constructs a new probability grid, updates the current grid with these values, appends the updated gri... | def search_algorithm(self):
self.readings = self.make_readings()
prob_of_t_given_prior_data = self.history.most_recent_grid
prob_solution_of_all_numerators = self.find_numerator(prob_of_t_given_prior_data)
prob_solution_of_all_denominators = self.find_denominator(prob_of_t_given_prior_da... |
def startScreen():
while True:
DISPLAY.fill(BLACK)
pressKeyScreen()
if checkForKeyPress():
pygame.event.get() # clear event queue
return
pygame.display.update()
FPSCLOCK.tick(FPS)
def runGame():
# initial score
score = 0
# defining snake ... | The main task of the code is to initialize a Pygame window for a Snake game, set up essential components like the display, clock, and font, and orchestrate the game flow by calling the start screen, game loop, and game over screen functions. It manages the game's lifecycle, including rendering and event handling, using... | def main():
global FPSCLOCK, DISPLAY, BASICFONT
pygame.init()
pygame.display.set_caption('Snake :V')
DISPLAY = pygame.display.set_mode((WIDTH, HEIGHT))
FPSCLOCK = pygame.time.Clock()
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
startScreen()
while True:
runGame()
... |
def flat_in_xeff_conversion_fn(parameters):
"""
To handle the conditional prior stuff
"""
xeff, q, cxd = parameters["chi_eff"], parameters["mass_ratio"], parameters["cxd"]
p = parameters.copy()
s1z_min, s1z_max = s1z_lim(xeff, q)
p["s1z"] = get_s1z_from_limits(s1z_min, s1z_max, cxd)
p["s... | This function converts input gravitational wave parameters into a format compatible with LAL (LIGO Algorithm Library), mapping parameters like mass ratio, chirp mass, and spin components to output parameters such as mass_1, mass_2, spin magnitudes (a_1/a_2), tilt angles, and orbital phase differences. It computes spin ... | def flatxeff_params_to_lal(parameters):
"""
From:
mass_ratio, chirp_mass, chi_eff, cxd, phi_1, phi_2, r1, r2,
luminosity_distance, dec, ra, theta_jn, psi,phase, s1, s2
To:
luminosity_distance, theta_jn, phase, a_1, a_2, tilt_1,
tilt_2, phi_12, phi_jl,
"""
p = parame... |
def _handle_event(self, event_name: str):
"""
Calls _run_handled_event with context-specific
arguments.
"""
self._run_handled_event("game." + event_name)
self._check_class_data()
self.class_data["flowchart"]._check_class_data()
for key, position i... | The main task of the code is to run a user-created game by processing player input, navigating a flowchart-based narrative, and handling commands like "help" or "about". It initializes game data, displays introductory information, and enters a loop where it checks valid choices, triggers events, updates the game state,... | def play_game(self):
"""
Start playing the user-created game.
"""
self._handle_event("intro_msg.before")
print(self.class_data["name"])
print(self.class_data["desc"])
print("Special commands: \"help\", \"about\".")
self._handle_event("intro_msg.after")
... |
def get_eval_dataloader(self, eval_dataset):
sampler = SequentialSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset,
sampler=sampler,
num_workers = 32,
batch_size=self.args.eval_ba... | The code evaluates a model on either the test or dev dataset by computing loss and metrics, logging results, and saving them to files. It processes batches, collects predictions, calculates average loss, and updates metrics for intent and slot tasks. | def evaluate(self, mode):
if mode == "test":
eval_dataset = self.test_dataset
elif mode == "dev":
eval_dataset = self.dev_dataset
else:
raise Exception("Only dev and test dataset available")
logger.info("***** Running evaluation on %s dataset *****", ... |
def get_slot_label(labels, preds, masks, label_set):
y_true = []
y_pred = []
for i in range(len(labels)):
label = labels[i]
pred = preds[i]
mask = masks[i]
true_len = int(mask.sum().item())
pred = pred[:true_len, :true_len]
label = label[:true_len, :true_len]
... | This function computes evaluation metrics for intent and slot prediction tasks. It calculates slot precision, recall, F1-score, intent accuracy, their average, and semantic accuracy. Metrics are derived from predicted vs true labels, with masks applied to ignore padding. Results are returned as a dictionary containing ... | def compute_metrics(args, intent_preds, intent_labels, slot_preds, slot_labels,
masks, slot_label_set=None):
slot_labels, slot_preds = get_slot_label(
slot_labels, slot_preds, masks, slot_label_set)
slot_precision, slot_recall, slot_f1_score = get_slot_metrics(
slot_labels, s... |
def get_train_dataloader(self):
sampler = RandomSampler(self.train_dataset)
train_dataloader = DataLoader(self.train_dataset,
sampler=sampler,
num_workers = 32,
batch_size=self.args.train_ba... | The code trains a model using gradient accumulation, AdamW optimizer with layered weight decay, and linear learning rate scheduling. It logs training details, evaluates on a dev set, and implements early stopping based on validation metrics. The model is saved if early stopping isn't triggered, with training loss track... | def train(self):
train_dataloader = self.get_train_dataloader()
total_steps = len(
train_dataloader) // self.args.gradient_accumulation_steps * self.args.num_train_epochs
param_optimizer = list(self.model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.w... |
def load_data(file_name, res):
# Validate if any file is passed
if file_name == "":
# NOTE: modify the response name here, if you've changed the data source
res = "mpg"
try:
data_set = default_data()
except FileNotFoundError:
data_set = default_data()
... | The code analyzes a dataset by identifying categorical and continuous variables, generating visualizations (heatmaps, violin plots, etc.), calculating correlation metrics for different variable pairs (continuous-continuous, categorical-continuous, categorical-categorical), and performing brute-force analysis to compare... | def main(file_name, response):
data_df = load_data(file_name, response)
print(data_df.head())
x = data_df.drop("target", axis=1)
res_type = response_type(data_df)
print("Response variable is " + res_type)
if res_type == "Boolean":
data_df["target"] = data_df["target"].astype("category"... |
def read_breast_cancer_data():
# downloaded and uploaded 'wdbc.data' inside a public repository
data_url = "https://raw.githubusercontent.com/patilbp/datasets/main/wdbc.data"
# column names were missing in my referenced data, so added separately
columns = [
"id",
"diagnosis",
"r... | The main task of the code is to analyze a dataset (default or provided) for predictive variables, determine response type (Boolean/Continuous), generate visualizations (heatmaps, scatter plots, etc.), calculate statistical metrics (t-value, p-value, mean squared differences), and compile results into a structured HTML ... | def main(file, response):
# finds if any file/csv is passed as input
# if not then sets the default dataset and default response
if file == "":
if response == "":
response = "diagnosis"
# read default dataset passed
read_data = read_breast_cancer_data()
# display response n... |
def replace_nan_value(df):
for col in df.columns:
if pd.api.types.is_numeric_dtype(df[col]) and np.isnan(df[col]).any():
# df[col] = np.fill_na(df[col])
df[col] = df[col].replace(np.nan, 0)
return df
def response_type(df, response):
if df[response].nunique() > 2:
retu... | The main task of the code is to analyze baseball pitcher statistics by connecting to a MariaDB database, process and clean the data, compute correlations between categorical and continuous variables using various plots, generate correlation matrices, apply brute-force analysis for feature importance, train multiple mac... | def main():
# Directory for saving all plots
if not os.path.isdir("plots"):
os.mkdir("plots")
if not os.path.isdir("bruteforce-plots"):
os.mkdir("bruteforce-plots")
# Maria DB Connection Details
db_database = "baseball"
db_host = "localhost:3306"
db_user = "root"
db_pass... |
def exists(self, id: str) -> bool:
"""
Check if entity exists by ID.
Args:
id (str): ID of entity to get,
Returns:
bool: Exists,
"""
return self.entityRepository.exists(id)
def add(self, entity: T) -> T:
"""
Add a new entity T.
... | The main task of the code is to add a new entity `T` if it does not exist (checked via `entity.id`) or update an existing one if it does. The function returns the updated or added entity `T` on success, or `None` otherwise. The update includes soft-deleted records via `includeSoftDeleted=True` to ensure comprehensive m... | def addOrUpdate(self, entity: T) -> T:
"""
Add entity T if none exists, else update existing.
Args:
entity (T): Entity to add or update.
Returns:
T | None: T if success, else None.
"""
if(not self.exists(entity.id)):
return self.add(... |
def set_shared_index_single(pts_lines_mtx):
def set_index_single(index_match,index_line):
pts_lines_mtx[index_match, index_line] = 1
return set_index_single
def set_shared_index_both(pts_lines_mtx):
def set_index_both(index_match,index_line1,index_line2):
pts_lines_mtx[index_match, index_lin... | The main task of the code is to identify the top matching line pairs between two images based on shared points and geometric consistency. It uses RANSAC to refine matches, filters pairs with sufficient inliers, and returns the top two lines with their projected points, inlier counts, and geometric properties for furthe... | def get_top_matching_lines( pts1,pts2,
lines_info_img1,
lines_info_img2,
min_shared_points,
inlier_ratio):
# The parrallel option
# t0=timer()
# pts_lines = np.zeros((len(pts1), len(lines_inf... |
def get_hough_lines(img_size,pts1,pts2,min_hough_points,pixel_res,theta_res,max_distance,num_matching_pts_to_use):
bw_img1 = np.zeros(img_size).astype(np.uint8)
pts1r = np.round(pts1[0:num_matching_pts_to_use, :]).astype(int)
bw_img1[pts1r[:, 1], pts1r[:, 0]] = 255
bw_img2 = np.zeros(img_size).astype(np... | The code estimates the fundamental matrix (F) using line correspondences and RANSAC. It rescales images and points for efficient Hough line detection, finds top matching lines, and computes F_R/F_L with inlier thresholds. The result is adjusted by the rescale factor and returned with debug data. | def separable_F_core(im_size_h_org,im_size_w_org, pts1org, pts2org,inlier_ratio,inlier_threshold,
hough_rescale=-1,
num_matching_pts_to_use=150,
pixel_res=4,
min_hough_points=4,
theta_res=180,
max_distance_pts_line=3,
... |
def _coscine_query(self, coscine_object, method_name, *args, **kwargs):
method = getattr(coscine_object, method_name)
if not callable(method):
return method
else:
try:
return method(*args, **kwargs)
except coscine.CoscineException as e:
... | This function generates a structured project entry containing its ID, path, name, parent ID, resources, and subprojects. It appends this entry to an internal project list, recursively processes subprojects, and returns the project's index in the list while optionally printing verbose output. | def _gen_pr_entry(self, project: coscine.Project, path, parent_project_id=None):
project_dict = {
# 'project': project,
"id": project.id,
"path": path,
"name": project.name,
"parent": parent_project_id,
}
self_idx = len(self._projects)
... |
def _init_dataframe(self, df):
self._interactive_df = qgrid.show_grid(df)
self._displayed_df = self._interactive_df.df
def _init_buttons(self):
df_button = wid.Button(description='Data')
df_button.on_click(self._show_df)
plot_button = wid.Button(description='Ternary Plot')
... | The code initializes a user interface for interacting with a DataFrame, allowing column selection and dynamic display. It copies the input DataFrame, processes column names, sets up widgets for selection and output, and configures event handlers to update the displayed data when columns change. Debug mode is enabled by... | def __init__(self, df, initial_keys=None, debug=True):
self._df = df.copy()
self._df.columns = ["".join(index) for index in self._df.columns]
self._header = wid.HBox()
self._body = wid.VBox()
self.debug = debug
self._output = wid.Output()
self._box = wid.VBox([sel... |
def _init_data_fields(self):
self._projects = []
self._files = []
self._resources = []
self._file_handles = {}
self._log = []
self._errors = []
def _init_coscine_client(self, token):
if isinstance(token, str):
self._client = coscine.Client(token, verbo... | This method downloads data from Coscine by initializing client settings, iterating through projects to generate entries, recording the download timestamp, and exporting results to an HDF file. It accepts authentication tokens and verbosity settings, processes project data, and stores outputs in a structured format for ... | def download_from_coscine(self, token=None, verbose_level=None):
self._init_data_fields()
if token is not None:
self._init_coscine_client(token)
if verbose_level is not None:
self.verbose_level = verbose_level
for pr in self._client.projects():
self._g... |
def read_file(my_file, all_file):
classes = {}
classes = multi_dict(3, str)
clst = []
with open(my_file, 'r') as mf:
mcont = mf.readlines()
with open(all_file, 'r') as af:
acont = af.readlines()
for mline in mcont:
for aline in acont:
clst = aline.split("@ "... | The code manages a course system by allowing users to interactively check status, add/delete classes, update hubs, and view all statuses. It reads from two files, processes user input via a loop, and updates data accordingly. Actions include exiting, checking status, adding personal classes, updating the database, and ... | def main(req):
my_file = "my_course.txt"
all_file = "course.txt"
con = True
cls = read_file(my_file, all_file)
update(req, cls)
while con:
next_act = int(input("\nInput action:\n"
"0. Exit\n"
"1. Check Status\n"
... |
def add_tile(self):
try:
add_field=random.choice(tuple(self.empty))
except IndexError:
print("Gameover")
exit()
key=random.random()
if key<self.PROBABILITY_OF_FOUR:
current_add=4
else:
current_add=2
self.state[ad... | The main task of the code is to run a game loop where tiles are added to the game field, the current state is printed, and the game checks for legal moves. If no valid moves remain, it attempts to make a move, exiting if specified. The loop continues until no legal moves exist, updating empty tile sets for game progres... | def play(self):
while True:
self.add_tile()
self.print_field()
while not self.legal_move:
if self.make_move()=="x":
exit()
self.legal_move=False
self.create_set_of_empty() |
def create_loss_fn(num_classes):
def fn(logits,y,mask):
log_probs=nn.functional.log_softmax(logits, dim=-1)
one_hot_labels = nn.functional.one_hot(y, num_classes=(num_classes+1))
per_example_loss = -(one_hot_labels * log_probs).sum(dim=-1) * mask
total_loss = per_example_loss.sum()
... | The code trains and evaluates a Named Entity Recognition (NER) model using BERT-based architecture. It loads data, initializes model/optimizer, handles checkpoints, and performs training with epoch-wise iterations, validation, and prediction. The model uses BC5CDR processor for tokenization and label mapping, with opti... | def run_main(flags):
# TODO?: interpret directory relative to script
# if flags.output_dir[0] != "/":
# flags.output_dir = os.path.join(os.path.dirname(__file__), flags.output_dir)
device = flags.device
# TODO:
# RuntimeError: Expected all tensors to be on the same device, but found at le... |
def _capture(cam: Picamera2, base: Path) -> None:
"""Capture a new image, and save it to a file that with the ID of the last
captured image, incremented by 1.
:param cam: Picamera2 object
:param base: Directory where images are contained
"""
path = _build_relpath(base, offset=1)
cam.captu... | The code defines a worker function for a camera thread that captures images during daytime (determined by sunrise/sunset margins), saves them to a specified directory, queues them for upload, and repeats with a delay. It initializes the camera, handles configuration settings, and manages file cleanup. | def worker(config: dict) -> None:
"""Worker for the camera thread. This captures an image, queues it and
sleeps for the time specified in `config`, before starting again.
:param config: Config, usually obtained from super.yml
"""
img_path = config.pop('outdir', IMG_PATH)
if isinstance(img_pat... |
def _create_lyt_trace_bytes(trace: np.ndarray, color_idx: int) -> bytes:
if len(trace) > 0:
trace_looped = cast(np.ndarray, np.vstack((trace, trace[:1])))
heading = angle_from_2d_vector(trace_looped[1:] - trace_looped[:-1])
# NOTE 2 in format
heading = _to_lyt_heading(heading, input_... | This function converts cone trace data into a binary LYT format for track representation. It scales cone positions, generates start/finish/checkpoint blocks based on cone positions, combines them with cone traces, and adds a header for the Live For Speed (LFS) track format. The output is a byte string containing struct... | def _traces_to_lyt_bytes(
cones_per_type: list[FloatArray], offset_in_meters: tuple[float, float]
) -> bytes:
lfs_scale = 16
offset = offset_in_meters * lfs_scale
cones_in_map = [(c * lfs_scale + offset).astype(int) for c in cones_per_type]
cones_bytes = [
_create_lyt_trace_bytes(cones, Co... |
def normed(v):
length = sqrt(norm2(v))
return v[0] / length, v[1] / length
def dot_product(w, v):
return w[0] * v[0] + w[1] * v[1]
def scale(v, s):
return v[0] * s, v[1] * s | The code computes the projection of vector `w` onto vector `v` by normalizing `v`, calculating the dot product of `w` with the normalized `v`, and then scaling the normalized `v` by this dot product to obtain the projection vector. | def proj(w, v):
vn = normed(v)
p = dot_product(w, vn)
return scale(vn, p) |
def subtract(v2, v1):
return tuple(u1 - u2 for u1, u2 in zip(v1, v2))
def proj(w, v):
vn = normed(v)
p = dot_product(w, vn)
return scale(vn, p)
def norm2(v):
return dot_product(v, v) | This function calculates the squared distance from a point `p` to a line segment defined by points `v1` and `v2` using vector projection. It computes the perpendicular distance by subtracting the projection of the vector from `v1` to `p` onto the segment's direction vector, then returns the squared norm of the resultin... | def point_segment_distance2(p, v1, v2):
s = subtract(p, v1)
v = subtract(v2, v1)
n = subtract(s, proj(s, v))
return norm2(n) |
def latcut(network, homes, latsplit = None):
''' Seperate a subset of a network by latitude.
Parameters
----------
network : networkx graph
network to search.
homes : list
subset of overall network.
latsplit : float
latitude to seperate the network subset.
Returns
-------
North : list... | The code divides a network into subsets based on geographic coordinates and courier routes, generating paths for each subset according to input specifications. It splits homes using latitude/longitude cuts, assigns them to couriers, and computes paths with distances. The function returns all paths and their total dista... | def cut(network, homes, inputs):
'''Cuts up a network into smaller subsets. A path for each subset
visiting all subset nodes is created.
Parameters
----------
network : networkx graph
network to search.
homes : list
List of all destinations (as strings) to map.
inputs : list
List... |
def Profile(*Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = {}
matrix = Count(*Motifs)
for symbol in "ACGT":
profile[symbol] = []
for i in range(k):
profile[symbol].append(matrix[symbol][i]/t)
return profile
def ProfileMostProbableKmer(text, k, profile):
n ... | The function `GreedyMotifSearch` identifies the best set of `k`-length motifs across `t` DNA sequences using a greedy algorithm. It initializes `BestMotifs` with the first `k` characters of each sequence. For each possible starting position in the first sequence, it constructs a new motif set by selecting the most prob... | def GreedyMotifSearch(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for i in range(n-k+1):
Motifs = []
Motifs.append(Dna[0][i:i+k])
for j in range(1, t):
P = Profile(*Motifs[0:j])
Motifs.append(Pro... |
def RandomMotifs(Dna, k, t):
rand_motifs = []
for i in range(t):
r = random.randint(0, len(Dna[0])-k)
rand_motifs.append(Dna[i][r:r+k])
return rand_motifs
def ProfileWithPseudocounts(*Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = {}
matrix = CountWithPseudocounts(*Mot... | The main task of the code is to implement the Gibbs sampling algorithm for motif finding. It iteratively refines a set of randomly selected k-mers from DNA sequences by sampling new motifs based on a profile matrix (with pseudocounts), updating the best motifs when a lower score is achieved. The goal is to identify a s... | def GibbsSampler(Dna, k, t, N):
#randomly select k-mers Motifs = (Motif1, …, Motift) in each string from Dna
Motifs = RandomMotifs(Dna, k, t)
#BestMotifs ← Motifs
BestMotifs = Motifs
for i in range(1, N):
#randomly generated integer between 1 and t
r = random.randint(1, t)
#P... |
def RandomMotifs(Dna, k, t):
rand_motifs = []
for i in range(t):
r = random.randint(0, len(Dna[0])-k)
rand_motifs.append(Dna[i][r:r+k])
return rand_motifs
def ProfileWithPseudocounts(*Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = {}
matrix = CountWithPseudocounts(*Mot... | The code implements Randomized Motif Search to identify the best motifs in DNA sequences. It initializes with random motifs, iteratively generates new motifs using a profile with pseudocounts, and updates the best motifs if the new score is lower. The loop terminates when no improvement is found, returning the optimal ... | def RandomizedMotifSearch(Dna, k, t):
M = RandomMotifs(Dna, k, t)
BestMotifs = M
while True:
Profile = ProfileWithPseudocounts(*M)
M = Motifs(Profile, Dna)
if Score(*M) < Score(*BestMotifs):
BestMotifs = M
else:
return BestMotifs |
def ProfileWithPseudocounts(*Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = {}
matrix = CountWithPseudocounts(*Motifs)
for symbol in "ACGT":
profile[symbol] = []
for i in range(k):
profile[symbol].append(matrix[symbol][i]/(t+4))
return profile
def ProfileMostPr... | The function performs Greedy Motif Search with pseudocounts to find the best set of k-length motifs in DNA sequences. It initializes best motifs, iterates over all possible starting positions in the first DNA string, constructs candidate motifs using pseudocount-based profiles, and updates the best motifs if the curren... | def GreedyMotifSearchWithPseudocounts(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for i in range(n-k+1):
Motifs = []
Motifs.append(Dna[0][i:i+k])
for j in range(1, t):
P = ProfileWithPseudocounts(*Motifs[0:j... |
def std_present(std_roll):
curr_students = load_student()
for std in curr_students:
if std.roll_no == std_roll:
return True
return False
def check_std_limit(std_roll):
curr_students = load_student()
for std in curr_students:
if std.roll_no == std_roll and std.num_books_is... | The main task of the code is to issue a book to a student after verifying the student's existence in library records, ensuring they haven't exceeded their book limit, checking the book's availability (ISBN validity and stock), and confirming the student hasn't already borrowed the book. If all conditions are met, it re... | def issue_book_student():
std_roll = input('Enter Student Roll No To Whom Book Has To Be Issued : ')
# check if student present in library records
if std_present(std_roll):
# find student with given data and check if he has reached book limit
if check_std_limit(std_roll):
# getti... |
def find(self, node):
return self.parent(node)
def union(self, node_1, node_2):
node1 = self.find(node_1)
node2 = self.find(node_2)
# print("in union node1:", node1)
# print("in union node2:", node2)
# print("edge dict b4:", self.edge_parent_dict)
# print("edge di... | This function constructs a Minimum Spanning Tree (MST) using Kruskal's algorithm. It processes sorted edges, unions disjoint sets, and checks for cycles. When parameter k > 0, it returns the MST once k nodes are connected, printing node/edge sets and total weight. If k=0, it completes the full MST and outputs results. | def mst(self, sorted_list_of_edges, k=0):
n = len(self.nodes_list)
count = 0
for node in self.nodes_list:
self.edge_parent_dict[node].append(node)
for edge in sorted_list_of_edges:
u = edge[0]
v = edge[1]
# print "node u:", u
#... |
def sort_sequences(self):
self.sequences.sort(key=len, reverse=True)
def update_max_len_lines(self, max_len, lines):
max_len_lines = [x for x in lines if len(x) == max_len]
for currentLine in max_len_lines:
self.print_used_line(currentLine)
grammar_level = self.grammar
... | The main task of the code is to sort sequences, determine the maximum length, update relevant lines based on this length, and print progress markers. It processes sequences by first sorting them, then analyzing their lengths to adjust line counts, ensuring alignment with the longest sequence. The function also outputs ... | def first_step(self):
print('First step')
self.sort_sequences()
print('Using sequences %s' % self.sequences)
print("\n")
max_len = len(self.sequences[0])
used_lines_count = self.update_max_len_lines(max_len, self.sequences)
self.update_other_lines(used_lines_count... |
def first_step(self):
print('First step')
self.sort_sequences()
print('Using sequences %s' % self.sequences)
print("\n")
max_len = len(self.sequences[0])
used_lines_count = self.update_max_len_lines(max_len, self.sequences)
self.update_other_lines(used_lines_count... | The code's main task is to execute a sequence of steps—first, second, and third—then print the results and an example, likely processing data or performing a multi-stage operation with structured output. | def run(self):
self.first_step()
self.second_step()
self.third_step()
self.print_result()
self.print_example() |
def rand(df):
boot = np.random.choice(df.shape[0], df.shape[0], replace=True)
oob = [x for x in [i for i in range(0, df.shape[0])] if x not in boot]
df1=df.iloc[boot]
df2=df.iloc[oob]
defe = df1[df1["label"] == 1]
clean = df1[df1["label"] == 0]
defe1 = df2[df2["label"] == 1]
clean1 = d... | The code performs bootstrapping on a dataset to evaluate feature importance using multiple methods (original, SMOTE, NCL, IKMCCA, etc.) with KNN and permutation importance. It saves results as CSV files for comparative analysis of feature significance across different preprocessing and oversampling techniques. | def fun(file):
df = pd.read_csv('C:/gln/myclassoverlap/Data/new/gooddata/data_clean/'+file)
scaler = StandardScaler()
# scaler1 = StandardScaler()
# scaler2 = StandardScaler()
feature_original=[]
feature_remove=[]
feature_SMOTE=[]
feature_ovim=[]
feature_imov=[]
feature_NCL=[]
... |
def import_cameras_pose(csvfile_path):
'''
Description:
read csv file to import .csv file of camera pose.
The csv file contains: camera_name,x,y,z,roll,pitch,yaw
The input camera pose is in Airsim coordinate system
@para csvfile_path: the path of csv file (type: string)
@return cameras_po... | The code defines an argument parser for a script that handles three main tasks: displaying usage instructions, cleaning output folders, and processing camera poses to capture ground truth (GT) or source view (SV) data for MIV. It checks command-line arguments to determine the operation—printing help, removing files, or... | def argparser():
'''
entry point
'''
if(len(argv) == 1 or argv[1] == "-h"):
print("********** Usage *************")
print("Capture source views for MIV:")
print("- python recorder_for_MIV.py SV {camera_pose_csv} {num_frames}")
print("Capture Ground truth video:")
... |
def generateRoulette(self, generation):
# given a generation of children, calculates their dissonance and forms a roulette based set to breed
breedingSet = []
workSet = []
mostDissonance = 0
leastDissonance = 1000
secondLeastDissonance = 1000
leastDissonantChild... | The code runs a generational evolution process by iteratively selecting breeding individuals via roulette wheel selection, generating new offspring, and evaluating each new generation's "disappointment" (likely a fitness metric). It continues until reaching the total number of generations, then identifies the two least... | def runGenerations(self):
while self.currentGeneration < self.totalGenerations:
breedingSet = self.generateRoulette(self.allGenerations[self.currentGeneration])
self.allGenerations.append(self.generateNewChildren(breedingSet))
# print("Generation " + str(self.currentGeneratio... |
def getCurrValue(self):
"""Returns the dissonance of the current seed"""
return self.determineSeedDissonance(self.currSeed)
def step(self):
"""Runs one step of hill-climbing, generates children and picks the best one, returning it as its value.
Also returns a second value that tells if t... | The code implements a hill-climbing algorithm that iteratively improves a solution by updating the current seed (`self.currSeed`) until it reaches a local maximum (where `self.getCurrValue()` no longer exceeds `self.minValue`) or exhausts the maximum allowed iterations (`self.maxRounds`). At each step, it records the d... | def run(self):
"""Perform the hill-climbing algorithm, starting with the given start state and going until a local maxima is
found or the maximum rounds is reached updating the current seed at each iteration."""
# status = None
while self.getCurrValue() > self.minValue and self.count < ... |
def compute_boundary_points_all_features(self):
'''
Computes all possible boundary points for each attribute in self._features (features to discretize)
:return:
'''
def padded_cutpoints_array(arr, N):
cutpoints = self.feature_boundary_points(arr)
padding =... | The code's main task is to preprocess data for discretization by storing input data and class labels, identifying columns to ignore, computing boundary points for features, generating bin descriptions, and establishing a one-hot encoding schema for categorical data transformation. It prepares the dataset for subsequent... | def fit(self, X, y):
self._data_raw = X # copy of original input data
self._class_labels = y.reshape(-1, 1) # make sure class labels is a column vector
self._classes = np.unique(self._class_labels)
if len(self._col_idx) != self._data_raw.shape[1]: # some columns will not be discreti... |
def get_api(self, api_version):
api = [p.capitalize() for p in api_version.split('/', 1)]
if len(api) == 1:
api.insert(0, 'Core')
return getattr(client, f'{api[0]}{api[1]}Api', None)()
def get_method(api, *items):
return getattr(api, '_'.join(items))
def _under_score(name):... | The code applies configuration changes to Kubernetes resources by retrieving their current state, applying deltas, retrying on conflicts, and handling deletions. It uses the Kubernetes client library, manages exceptions, and ensures deletions are executed with proper parameters, including dry-run support. | def apply(self):
retry_list = []
for (api_version, kind, name), target in self.items.items():
api = self.get_api(api_version)
current = None
try:
reader = self.get_method(
api, 'read', 'namespaced', _under_score(kind))
... |
def _set_status(self, status: str):
self._db_iterator.set_status(self.vm.item, status)
status = list(self._smples.keys())[list(self._smples.values()).index(self.radio_btns.value_selected)]
self._update_by_status(status, 0)
def _on_ref_required(self):
ra, dec = self.vm.item._ra, self.vm.i... | The code initializes an interactive visualization interface using matplotlib, setting up a grid of subplots for displaying data, checkboxes, radio buttons, sliders, and navigation buttons. It integrates with a database iterator to handle data items, allowing users to toggle visibility, adjust opacities, select display ... | def __init__(self, db_iter: DbIterator, tree: SiteTree):
self._tree = tree
self._db_iterator = db_iter
plt.ion()
self._fig: Figure = plt.figure()
self._fig.subplots_adjust(bottom=0.02)
self._ax_main = plt.subplot2grid((4, 3), (0, 0), colspan=2, rowspan=3, fig=self._fig)... |
def build_model(self, error_function):
self.logits = self.neural_net()
self.prediction = self.out_act_fn(self.logits)
self.acc = self.accuracy()
self.acc_op = self.acc
self.error_descr = error_function
if error_function is "mse":
self.mse_op = self.mse()
... | This code initializes a neural network model with customizable input/output tensors, hidden layers, activation functions, and loss functions. It sets up weights, biases, and computes metrics like accuracy, gradient norms, Hessian eigenvalues, and ReLU saturation. The model can be built explicitly or within an implicit ... | def __init__(self, input_tensor, output_tensor,
num_input=1, num_hidden=[], num_classes=1, act_fn=tf.nn.sigmoid, out_act_fn=tf.nn.sigmoid,
error_function="mse", compute_acuracy=True, compute_grad_norm=False, compute_eigens=False,
compute_saturation=False, implicit_loop... |
def _read_construct(line):
if "~" in line:
split_line = line.split("~", -1)
weight = split_line.pop(-1)
try:
weight = float(weight)
except ValueError:
raise ValueError('Weight must be a float value not "{}"'.format(weight))
line = "~".join(split_line)
... | The function `_compile_fields` generates code to validate and transform input data according to a schema. It processes fields and their validators, handling nested structures, lists, and dynamic ("**") fields. It constructs code snippets to enforce validation rules, manage input/output mappings, and raise errors for mi... | def _compile_fields(schema, fields, counter=1, path=()):
code = []
field_names = []
include_extra = False
include_extra_validators = None
for field, validators in fields.items():
field = _read_construct(field)
field_names.append(field.name)
if field.name == "**":
... |
def test_jackjill():
data, vocab = get_part1_data('data/jj.txt')
train_y = data[:, 1:]
train_x = data[:, :-1]
reverse_vocab = {idx: word for word, idx in vocab.items()}
model = RNN_Part1(vocab)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)
p = tqdm(range(100))
for epoch in p... | The main task of the code is to execute three test functions sequentially: test_jackjill(), test_short(), and test_long(). Each test is prefixed with a print statement indicating its order ("# test 1", "# test 2", "# test 3"), suggesting the code is designed for testing or demonstration purposes, likely verifying diffe... | def main():
print("# test 1")
test_jackjill()
print("# test 2")
test_short()
print("# test 3")
test_long() |
def get_img_size(line_mode: bool = False) -> Tuple[int, int]:
"""Height is fixed for NN, width is set according to training mode (single words or text lines)."""
if line_mode:
return 256, get_img_height()
return 128, get_img_height()
def validate(model: Model, loader: DataLoaderIAM, line_mode: bool)... | This function trains a neural network model for image recognition, using a DataLoaderIAM to iterate over training data. It performs data augmentation, trains the model in epochs, validates performance with character error rates and word accuracy, and saves the best model parameters. Training stops early if validation p... | def train(model: Model,
loader: DataLoaderIAM,
line_mode: bool,
early_stopping: int = 25) -> None:
"""Trains NN."""
epoch = 0 # number of training epochs since start
summary_char_error_rates = []
summary_word_accuracies = []
preprocessor = Preprocessor(get_img_size(lin... |
def train(model: Model,
loader: DataLoaderIAM,
line_mode: bool,
early_stopping: int = 25) -> None:
"""Trains NN."""
epoch = 0 # number of training epochs since start
summary_char_error_rates = []
summary_word_accuracies = []
preprocessor = Preprocessor(get_img_size(lin... | The code's main task is to perform text recognition using a CTC-based model, supporting training, validation, or inference modes. It processes the IAM dataset, configures decoders (BestPath/BeamSearch/WordBeamSearch), and handles line-mode training with whitespace inclusion. For inference, it loads a pre-trained model ... | def main():
"""Main function."""
parser = argparse.ArgumentParser()
parser.add_argument('--mode', choices=['train', 'validate', 'infer'], default='infer')
parser.add_argument('--decoder', choices=['bestpath', 'beamsearch', 'wordbeamsearch'], default='bestpath')
parser.add_argument('--batch_size', h... |
def get_questions(coding_id):
"""
returns a lsit of questions with fields:
info: the question
details: instructions
type: singleselect, multiselect, ect.
values: a list of {label, value} dicts
values_raw: a comma-seporated list of values
opp_info: informatino from... | The code processes coding data by retrieving questions and coding instances, then generates CSV files for questions, raw data, and inter-rater agreement analysis for a specified coding task (ID 10). | def handle(self, *a, **kw):
coding_id = 10
questions = get_questions(coding_id)
coding_instances = get_serialized_coding_instances(coding_id)
gen_questions_csv(coding_id, questions)
gen_all_raw_csvs(coding_id, questions, coding_instances)
gen_all_agreement_csvs(coding_id,... |
def is_end(self, x: int, y: int) -> bool:
return self.get_value_at(x, y) == 'E'
def visit(self, x: int, y: int):
self.visited[y][x] = True
def print_current_path(self):
if not self.first_print:
LINE_UP = '\033[1A'
LINE_CLEAR = '\x1b[2K'
for _ in range(self.hei... | This code finds the shortest path from a starting point to an endpoint using a greedy algorithm. It iteratively selects the next cell with the minimum unvisited score, updates scores for available moves, and tracks the path until reaching the end. The returned score represents the path length. | def find_path(self):
x, y = self.start
while not self.is_end(x, y):
self.visit(x, y)
self.print_current_path()
# print(f'visiting {x, y}')
for move in self.available_moves(x, y):
# print(f'available move: {move}')
_x, _y = m... |
def get_html(url):
chromedriver_autoinstaller.install()
driver = webdriver.Chrome()
raw_html = driver.get(url)
raw_html = driver.page_source
driver.close()
return raw_html
def remove_extra_info(html):
# Create BeautifulSoup object from the HTML
soup = BeautifulSoup(html, "html.parser")
... | The code fetches HTML from a specified URL, cleans it by removing extra information and blank lines, stores the cleaned HTML in a text file, and prints the result. | def main():
# url = 'https://stackoverflow.com/questions/66955402/getting-all-the-html-code-from-a-website-that-is-using-react'
url = "https://partners.dev.rappi.com/"
raw_html = get_html(url)
cleaned_html = remove_extra_info(raw_html)
cleaned_html = remove_blank_lines(cleaned_html)
store_string... |
def getSources(self, mode):
if not mode in list(self.allmoduleinfo.keys()):
raise Exception("Invalid index of module info")
buildfile = path.join(self.getBuildDir(), self.allmoduleinfo[mode].Build_Make)
with open(buildfile) as f:
text = f.read()
lines = re.finda... | The main task of the code is to replace placeholders in a template string with module-specific information, generating a configured template based on the given mode. It replaces tokens like @module, @name, @srcs, and flags with values from `self.allmoduleinfo` and helper methods, adjusting formatting and combining data... | def replaceTemplate(self, mode, tpl):
tpl = tpl.replace("@module", self.allmoduleinfo[mode].Module_Type)
tpl = tpl.replace("@name", self.allmoduleinfo[mode].Module_Name)
tpl = tpl.replace("@defaults", self.allmoduleinfo[mode].Defaults)
tpl = tpl.replace("@srcs", self.getSources(mode))
... |
def generateMakefile(self, debug=False, make=False):
#windows can help us debug the script and we do not want generate makefile on widnows
if os.name == "nt":
return
verbose = ";" if debug else NOVERBOSE
builddir = self.getBuildDir()
# make quickly, but can't clear o... | The code generates Android.bp files for modules by processing templates and replacing placeholders with module-specific data. It checks if the source path exists, generates Makefiles if enabled, adjusts files, and writes aggregated BP content, overwriting existing files. The main task is to create or update Android.bp ... | def generate(self, to_cmake = True, to_make = False):
if path.exists(self.src) == False:
raise Exception(self.src + " not existed")
if to_cmake:
self.generateMakefile(make = to_make)
self.adjustFiles()
allBPs = {}
# sub-module" .bp
for k in list... |
def ShapeData(df,tag,wtName,zscore=False,display=False):
wtDF = df.loc[df['VARIANT'] == wtName]
# identify trafficking competent
soluble = df.loc[df['TRAFFICKING'] == 1]
insoluble = df.loc[df['TRAFFICKING'] == 0]
# reference each tag by the wt, s.t. more non-traffickers have values larger than wt'... | This function classifies data using a model trained on features derived from input tags, evaluating performance via ROC curves and F1 scores. It supports bootstrapping for statistical analysis, splitting data into training/test sets, and returns metrics like AUC, accuracy, and averaged F1 scores for trafficking/non-tra... | def ProbClassifier(df,tags,display=False,split=True,bootstrap=False):
# organize data relative to WT
wtName = "wt"
zscore = True
for tag in tags:
ShapeData(df,tag,wtName,zscore=zscore,display=display)
dTags = ["d"+t for t in tags]
# partition in test/training set
if bootstrap:
... |
def get_video_to_image_id(image_dir):
'''
Dump a dictionary that get's all the image names given the video name
key - value : gf097t1aaaff - [gf097t1aaaff001.png, gf097t1aaaff002.png, ... , gf097t1aaaff518.png]
'''
# if it exist, do nothing
if os.path.isfile('/mnt/cube/projects/yundong/pain_det... | This function reads and prepares segmented sequences for RNN models by loading input (AAM/feat_4096) and output (AU/PSPI) data, applying padding strategies (zero, repeat edge, discard) for edge cases, and constructing numpy arrays based on configuration parameters like input type, padding method, and AU usage. It retur... | def read_rnn_seg(args):
'''
Read segmented seq for RNN.
'''
rnn_kwargs, imagepath, image_id, subj_id, video_id, AAM_filetype, AAMpath, feat_path, AUpath, PSPIpath = args
rnn_input_segment = None
rnn_output_segment = None
input_path = None
if rnn_kwargs != None:
try:
... |
def load_model_config(name: str) -> dict:
path = model_dir() / f'{name}.yaml'
with path.open() as f:
config = yaml.safe_load(f)
return config
def create_model(config: dict) -> AutoencoderLightning:
num_embeddings = calc_num_embeddings()
logger.info(f'num_embeddings={num_embeddings}')
enc... | The main task of the code is to train an autoencoder model. It loads a configuration file, creates the encoder model based on the specified architecture, and initiates the training process using the training parameters defined in the configuration. The function orchestrates model creation and training for an autoencode... | def train_autoencoder() -> None:
config = load_model_config('autoencoder')
encoder = create_model(config['model'])
do_train_autoencoder(encoder, **config['train']) |
def weights_population(a, sentence):
# This function is used to calculate the weights for the population or an instance of the population.
# Weights are used for selection and what not.
fitness_of_population = [value(0, a[i], sentence)**3 for i in range(len(a))]
total = sum(fitness_of_population)
fi... | The function generates a new generation from an old one by selecting weighted parents, reproducing them, mutating offspring, and replacing the old generation with the mutated children, using the input sentence to influence selection and evolution. | def new_generation(old_generation, sentence):
# This function is used to create the new generation by calling other functions
weights = weights_population(old_generation, sentence)
prv_gen = []
child_gen = []
for i in range(len(old_generation)):
parent = random.choices(old_generation, weight... |
def checkwin(board):
for r in range(Rows):
for c in range(Cols - 3):
if board[r][c] == 0 and board[r][c + 1] == 0 and board[r][c + 2] == 0 and board[r][c + 3] == 0:
return 0
if board[r][c] == 1 and board[r][c + 1] == 1 and board[r][c + 2] == 1 and board[r][c + 3] == 1... | The code implements a Monte Carlo Tree Search (MCTS) algorithm to select the optimal child node from a given parent node. It performs up to `n` iterations of expansion, simulation, and backpropagation. The algorithm prioritizes nodes with higher visit counts or scores, returning the child with the highest score if avai... | def mcts_n(parent_node, n):
initial_node = copy.deepcopy(parent_node)
while n > 0 and checkwin(parent_node.state) == 2 and not checkdraw(parent_node.state):
if parent_node.Poss_Child and random.uniform(0, 1) >= 0:
parent_node = expansion(parent_node)
result = simulation(parent_no... |
def checkwin(board):
for r in range(Rows):
for c in range(Cols - 3):
if board[r][c] == 0 and board[r][c + 1] == 0 and board[r][c + 2] == 0 and board[r][c + 3] == 0:
return 0
if board[r][c] == 1 and board[r][c + 1] == 1 and board[r][c + 2] == 1 and board[r][c + 3] == 1... | This code simulates 10 games between two Monte Carlo Tree Search (MCTS) players with different computational budgets: one using 2000 iterations (MCTS-200) and the other using 6 iterations (MCTS-40). It tracks wins, losses, and draws, measuring performance differences between the two MCTS variants. The results are print... | def MCTS_vs_MCTS():
turn = 0
count = 0
draw = 0
winner2 = 0
num_games = 10
in_time = time.time()
for _ in range(num_games):
print(_)
board = Board.create_board()
current_node = TreeNode(board, None, 0, 0)
current_state = current_node.state
lastmove = 0... |
def checkwin(board):
for r in range(Rows):
for c in range(Cols - 3):
if board[r][c] == 0 and board[r][c + 1] == 0 and board[r][c + 2] == 0 and board[r][c + 3] == 0:
return 0
if board[r][c] == 1 and board[r][c + 1] == 1 and board[r][c + 2] == 1 and board[r][c + 3] == 1... | The code implements a game loop where a human player competes against an AI using Monte Carlo Tree Search (MCTS). It loads a pre-trained Q-table, handles user input for moves, alternates turns, updates the game state, and renders the board. The AI uses the MCTS algorithm with 200 iterations per move, while the human co... | def game_driver(screen, SQAIZE, width, RADIUS):
turn = 0
count = 0
draw = 0
winner2 = 0
num_games = 1
in_time = time.time()
qtable = pickle.load(gzip.open("C:\\Users\\agraw\\PycharmProjects\\AI-Assignment2\\20180827_final_5.dat.gz", "rb"))
board = Board.create_board()
current_node = ... |
def winnerCpy(matrixCpy):
first = True
second = True
for i in range(len(first_player)):
if matrixCpy[first_player[i][0]][first_player[i][1]] != 2:
second = False
break
for i in range(len(second_player)):
if matrixCpy[second_player[i... | This code implements the minimax algorithm for a game, recursively evaluating all possible moves at a given depth. It alternates between maximizing and minimizing players (player 2 and 1), selecting the optimal move by comparing scores from recursive calls. The function returns the best score and corresponding game sta... | def minimax(matrixCpy, depth, max_player):
if depth == 0 or winnerCpy(matrixCpy):
return calculateScore(matrixCpy), matrixCpy
playerIndex = 0
if (max_player):
playerIndex = 2
else:
playerIndex = 1
if max_player:
maxEval = float('-in... |
def parse_args():
parser = ArgumentParser()
parser.add_argument("--use-amp", action="store_true")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
return args.use_amp, args.dry_run
def dry_run(use_amp):
with open(DRY_RUN_SENSES, "r") as file:
sense_ids = f... | The main task of the code is to parse command-line arguments, determine if a dry run is requested, and execute either a dry-run simulation or a full disambiguation process using the `use_amp` parameter. If `is_dry_run` is True, it runs `dry_run(use_amp)` for testing; otherwise, it triggers `disambiguate_all(use_amp)` f... | def main():
use_amp, is_dry_run = parse_args()
if is_dry_run:
dry_run(use_amp)
else:
disambiguate_all(use_amp) |
def load_latest_offset_details():
"""
Load the latest offset details from the "crawl_queue_offsets.json" temporary file in the same directory
Returns:
dict: A dictionary containing the offset details.
If the file is empty or does not exist, returns None.
Raises:
FileNotFoundErr... | This function consumes Oracle crawl tasks from a Kafka topic, processes SQL queries with parameter substitutions using a Zookeeper lock for exclusivity, executes data crawling operations, handles errors, and sends results to another Kafka topic. It ensures single-instance execution via ZK locks, validates message schem... | def crawl_oracle():
"""
This function carries out the crawling tasks for Oracle data by getting crawl task messages from the Kafka
topic 'oracle_crawl_queue_topic'.
It follows the instruction of the crawl task message(i.e. sql query, parameter substitutions),
performs data crawling operations,... |
def explain(
self, node_idx, graph_idx=0, graph_mode=False,
unconstrained=False, model="exp", explainer="LG-IME",
dataset="unknown"
):
"""Explain a single node
"""
# index of the query node in the new adj
if graph_mode:
node_idx_new = n... | The code explains nodes by generating masked adjacency matrices for specified nodes, denoising their neighborhoods, aligning the resulting graphs, and logging alignment results. It processes two nodes, extracts features, aligns their structures, and outputs aligned graphs for analysis. Your return | def explain_nodes(self, node_indices, args, graph_idx=0):
"""
Explain nodes
Args:
- node_indices : Indices of the nodes to be explained
- args : Program arguments (mainly for logging paths)
- graph_idx : Index of the graph to explain the node... |
def explain(
self, node_idx, graph_idx=0, graph_mode=False,
unconstrained=False, model="exp", explainer="LG-IME",
dataset="unknown"
):
"""Explain a single node
"""
# index of the query node in the new adj
if graph_mode:
node_idx_new = n... | The main task of the code is to explain node predictions in a graph neural network (GNN) by generating masked adjacency matrices, denoising subgraphs around target nodes, evaluating explanation quality via metrics like AUC, fidelity, and contrastivity, and returning the masked adjs. It processes multiple nodes, constru... | def explain_nodes_gnn_stats(self, node_indices, args,
graph_idx=0, model="exp"):
masked_adjs = [
self.explain(node_idx, graph_idx=graph_idx, model=model,
explainer=args.explainer, dataset=args.dataset)
for node_idx in node_indices
... |
def get_predictions(output_batch):
return threshold(output_batch.data.cpu()[0])
def error(preds, targets):
return 1 - jaccard(preds, targets)
def jaccard(preds, targets):
# preds = preds.round().int()
# targets = targets.round().int()
preds = threshold(preds)
intersection = preds & targets
... | The code evaluates a model on a test dataset, computing loss, error rate, and Jaccard index (IoU) metrics. It supports test-time augmentation (TTA) for improved predictions and allows limiting evaluation to a subset of batches for debugging. Metrics are averaged over the test set (or specified subset) and returned as l... | def test(model, test_loader, criterion, epoch=1, use_tta=False,debug_max_size=None):
model.eval()
test_loss = 0
test_error = 0
jacc = 0
with torch.no_grad():
for i,(data, target) in enumerate(test_loader):
if debug_max_size and i > debug_max_size:
break
... |
def get_predictions(output_batch):
return threshold(output_batch.data.cpu()[0])
def error(preds, targets):
return 1 - jaccard(preds, targets)
def jaccard(preds, targets):
# preds = preds.round().int()
# targets = targets.round().int()
preds = threshold(preds)
intersection = preds & targets
... | This function visualizes sample predictions from a model on a dataset. It loads a batch, skips to a specified index, processes inputs through the model, and displays original images, ground truth annotations, and predicted annotations. If a loss criterion is provided, it also computes the loss, error rate, and Jaccard ... | def view_sample_predictions(model, loader, n, criterion=None, idx=0):
with torch.no_grad():
loader = iter(loader)
inputs, targets = next(loader)
# skip ahead in the loader
for _ in range(idx):
inputs, targets = next(loader)
data = Variable(input... |
def get_predictions(output_batch):
return threshold(output_batch.data.cpu()[0])
def error(preds, targets):
return 1 - jaccard(preds, targets)
def jaccard(preds, targets):
# preds = preds.round().int()
# targets = targets.round().int()
preds = threshold(preds)
intersection = preds & targets
... | Your return
The function `get_sample_predictions` generates predictions using a model on a specified sample (or first batch) from a data loader. It processes inputs and targets, computes model outputs, and derives predictions. If a loss criterion is provided, it calculates the loss, error, and Jaccard index between p... | def get_sample_predictions(model, loader, n, criterion=None, idx=None):
with torch.no_grad():
if idx:
inputs, targets = loader.dataset[idx]
inputs = inputs.unsqueeze(dim=0)
targets = targets.unsqueeze(dim=0)
else:
inputs, targets = next(iter(loader))
... |
def load_labels(
cache_dir: Union[Path, str]
) -> Tuple[Tuple[str, ...], np.ndarray, List[str], np.ndarray]:
"""
prepare all the labels
"""
# indoor and outdoor relevant
filename_io = download_url(
"https://raw.githubusercontent.com/csailvision/places365/master/IO_places365.txt",
... | The main task of the code is to perform image detection or attribute analysis using a pre-trained model. It loads model parameters, processes image batches, runs inference with hooks, and saves detection results in TSV format. The code splits datasets across multiple processes, handles softmax weights for visualization... | def detection(args: Arguments, proc_id: int, cache_dir: Union[Path, str]):
# load the labels
classes, labels_IO, labels_attribute, W_attribute = load_labels(cache_dir)
model = load_model(cache_dir)
hook = Hooker(model)
# load the transformer
# get the softmax weight
params = list(model.para... |
def check(self):
moves = self.get_opponent_moves()
if self.player == 1:
king = self._white_king
else:
king = self._black_king
for move in moves:
if(move[1][0] == king[0] and move[1][1] == king[1]):
return True
return ... | The code appends valid castling moves to the current moves list by checking if the king and rook haven't moved, ensuring the path between them is empty, and verifying the move doesn't leave the king in check. It handles both players' castling options, checking for attacks on the path and appending valid moves like king... | def get_valid_castling(self, moves):
""" Appends valid castling moves to current valid moves
Castling Rules:
Cannot castle when in check
Cannot castle when result leads to a check
Rook and King never moved at all
Space between Rook and King are empty
... |
def make_move(self, from_dict, to_dict, extra_move=None):
""" normal moves include from and to coord. castling move has an extra normal move """
self.board[ from_dict['y'] ][ from_dict['x'] ] = 0
self.board[ to_dict['y'] ][ to_dict['x'] ] = from_dict['piece']
#if kings move keep track w... | This code validates a list of moves by simulating each move, checking if it results in a check (e.g., king under threat), and removing invalid moves. It iterates backward through the moves list to avoid index errors during removal. For each move, it temporarily applies the move, checks for a check condition, and revert... | def further_validation(self, moves):
for x in range(len(moves)-1, -1, -1):
selected_piece = self.board[moves[x][0][0]][moves[x][0][1]]
target_piece = self.board[moves[x][1][0]][moves[x][1][1]]
selected = {
'piece' : selected_piece,
'y' : moves[... |
def get_valid_moves(self):
moves = []
for y in range(8):
for x in range(8):
if self.board[y][x] != 0:
select = { 'piece': self.board[y][x], 'y': y, 'x': x }
up = (y-1) % 8
down = (y+1) % 8
righ... | The main task of the code is to determine if the current game state is terminal by checking if there are no valid moves remaining. It first validates available moves, checks if the game is in a "check" state, and returns True if no moves are available. If no moves exist regardless of the check state, it confirms the te... | def terminal_test(self):
available_moves = self.get_valid_moves()
available_moves = self.further_validation(available_moves)
if self.check() == True:
if(len(available_moves) == 0):
return True
if(len(available_moves) == 0):
... |
def initial_state():
"""Return the initial state for the perceptron.
This function computes and then returns the initial state of the perceptron.
Feel free to use any data type (dicts, lists, tuples, or custom classes) to
contain the state of the perceptron.
"""
# *** START CODE HERE ***
state = {}
state['be... | The code trains a perceptron using a specified kernel function and learning rate on training data, updates its state iteratively, and saves predictions on test data to a text file. It also generates a contour plot visualizing the decision boundary, saved as a PDF, to analyze model performance. | def train_perceptron(kernel_name, kernel, learning_rate):
"""Train a perceptron with the given kernel.
This function trains a perceptron with a given kernel and then
uses that perceptron to make predictions.
The output predictions are saved to src/perceptron/perceptron_{kernel_name}_predictions.txt.
The output pl... |
def read_data(images_file, labels_file):
x = np.loadtxt(images_file, delimiter=',')
y = np.loadtxt(labels_file, delimiter=',')
return x, y
def one_hot_labels(labels):
one_hot_labels = np.zeros((labels.size, 10))
one_hot_labels[np.arange(labels.size),labels.astype(int)] = 1
return one_hot_labels
... | The code's main task is to train and evaluate neural network models on a dataset. It loads and preprocesses data (normalization, shuffling, splitting into train/dev/test sets), then trains a baseline model and a regularized variant, returning their accuracies. The function handles data preparation, model training with ... | def main(plot=True):
parser = argparse.ArgumentParser(description='Train a nn model.')
parser.add_argument('--num_epochs', type=int, default=30)
args = parser.parse_args()
np.random.seed(100)
train_data, train_labels = read_data('./images_train.csv', './labels_train.csv')
train_labels = one_ho... |
def initialChecks():
global running
#general things to do before running events
if running is not None:
utils.displayErrorMessage('Recording Audio, Stop That First')
return False
utils.displayErrorMessage('')
utils.displayInfoMessage('')
return True
def playtargetaudio(event=None... | The function `playbothaudio` checks if initial conditions are met using `initialChecks()`. If successful, it plays both the target audio via `playtargetaudio()` and the recorded audio via `playrecordedaudio()`, likely for simultaneous playback or comparison. | def playbothaudio(event=None):
if initialChecks():
playtargetaudio()
playrecordedaudio() |
def check_confluent(coeffs):
a = coeffs[0]
b = coeffs[len(coeffs)-1]
if b > a or b < 1:
return False
for i in range(len(coeffs)-1):
if coeffs[i] != a:
return False
return True
def basis_polynomial(fieldgen, Basis_coeffs):
m = len(Basis_coeffs) # basis order
M = 0 ... | The code constructs an On-Line Converter (finite state machine) for number representation conversion using a specified basis and Pisot root. It initializes parameters, validates the basis, computes key values (beta, delta, k), generates basis sequences, and builds a transducer with transient and synchronous states to h... | def __init__(self, Basis_coeffs, c, verbose):
self.Basis_coeffs = Basis_coeffs
if(verbose):
print(f'Initializing basis with coefficients {Basis_coeffs}')
print('Reccurence: B_n = ', end='')
for i in range(len(Basis_coeffs)):
print(f'{Basis_coeffs[i]:+... |
def get_emotion2id(DATASET: str) -> Tuple[dict, dict]:
"""Get a dict that converts string class to numbers."""
if DATASET == "MELD":
# MELD has 7 classes
emotions = [
"neutral",
"joy",
"surprise",
"anger",
"sadness",
"disgu... | This code initializes a dataset class for emotion recognition in conversations using text modality. It sets parameters like dataset name, split (train/test), speaker mode, and model checkpoint (e.g., RoBERTa). It loads utterance transcriptions from a file, maps emotions to IDs, and prepares data for tokenization. The c... | def __init__(
self,
DATASET="IEMOCAP",
SPLIT="train",
speaker_mode="upper",
num_past_utterances=0,
num_future_utterances=0,
model_checkpoint="roberta-large",
ROOT_DIR="multimodal-datasets/",
SEED=0,
):
"""Initialize emotion recognition ... |
def profiler(self):
prof = mtprof.Profile()
self.addCleanup(prof.close)
return prof
def f(duration, ncalls):
consume_cpu(duration, ncalls)
def check_stats(self, stats, nruns=1):
self.check_function_durations(stats, f, nruns, self.DURATION)
st = self.check_function_durations(... | This code tests the enable/disable functionality of a profiler. It initializes a profiler, enables it, runs a function for a specified duration and call count, disables the profiler, generates statistics, and verifies the results against expected values using check_stats. | def test_enable_disable(self):
prof = self.profiler()
prof.enable()
f(self.DURATION, self.NCALLS)
prof.disable()
prof.create_stats()
self.check_stats(prof.stats) |
def profiler(self):
prof = mtprof.Profile()
self.addCleanup(prof.close)
return prof
def f(duration, ncalls):
consume_cpu(duration, ncalls)
def check_stats(self, stats, nruns=1):
self.check_function_durations(stats, f, nruns, self.DURATION)
st = self.check_function_durations(... | This test verifies that a profiler can be enabled and disabled twice consecutively. It runs a function twice—each time for half the duration and number of calls—while toggling the profiler's state. After collecting statistics, it checks if the aggregated results match expectations, ensuring proper profiling behavior ac... | def test_enable_disable_twice(self):
prof = self.profiler()
prof.enable()
f(self.DURATION / 2, self.NCALLS)
prof.disable()
prof.enable()
f(self.DURATION / 2, self.NCALLS)
prof.disable()
prof.create_stats()
self.check_stats(prof.stats, 2) |
def profiler(self):
prof = mtprof.Profile()
self.addCleanup(prof.close)
return prof
def nominal_workload(self, nruns=1):
threads = [threading.Thread(target=func,
args=(self.DURATIONS[func], self.NCALLS))
for func in (g, h)]
f... | This test verifies the functionality of enabling and disabling a profiler. It initializes a profiler, activates it, executes a nominal workload, deactivates the profiler, generates statistics, and checks if the resulting stats match expected outcomes. The main task is to ensure the profiler correctly captures and valid... | def test_enable_disable(self):
prof = self.profiler()
prof.enable()
self.nominal_workload()
prof.disable()
prof.create_stats()
self.check_nominal_stats(prof.stats) |
def _send_protocol(self): # send the current window
numsent = 0
self.timeout_datagram_index = 0
self.timeout_watch_index = 0
while (len(self._datagram_send_list) > 0 and numsent < self._send_window):
r = self._datagram_send_list.popleft()
self.send(r)
... | This code implements a congestion control mechanism for a network protocol, managing data transmission by adjusting the send window size based on network conditions. It handles timeouts by retransmitting pending datagrams if not acknowledged within the timeout period. Upon receiving packets, it processes acknowledgment... | def run(self):
while (self._running):
if (len(self._pending_sent_datagrams) == 0):
try:
self._send_protocol()
if (self._send_window < self._ssthresh):
self._send_window *= 2
else:
... |
def get_item_from_url(url_params, key, default=''):
parsed_loc = parse_url_next(url_params)
if parsed_loc:
return get_item_from_list_dict(parsed_loc, key)
else:
return default
def get_client_id(next_string):
client_id = settings.DEFAULT_CLIENT
if next_string:
try:
... | The function handles Google OAuth2 login by retrieving an auth code from the request, fetching user data, converting the token with a client ID, authenticating the user, and redirecting to a specified URL. It logs errors if token creation fails and redirects to the login page if authentication fails. | def Google_login(request):
state = request.GET.get('state', '/')
auth_code = request.GET.get('code')
redirect_uri = settings.DEPLOYMENT_URL + '/google-login'
next_loc = get_item_from_url(state, 'next', '/home')
logger.info('next ' + next_loc)
invite_token = get_item_from_url(next_loc, 'invite'... |
def get_parser():
parser = argparse.ArgumentParser(
description='Single sequence based RNA Secondary Structural Model predictor')
basic_group = parser.add_argument_group('Basic input/output options')
basic_group.add_argument('--input_fasta_path', type=str, metavar='example.fa', required=True,
... | The code's main task is to execute RNA secondary structure prediction using a pre-trained RSSM model. It handles GPU/CPU configuration, downloads/model updates, loads models, processes input FASTA sequences, performs bulk prediction, and generates output files including dot-bracket structures. The function manages depe... | def run(args=None):
if args is None:
parser = get_parser()
args = parser.parse_args()
# configurations
config = yaml.safe_load(open(os.path.join(basedir, 'RSSMFold', 'rssm_configs', 'single_seq_rssm_config.yml')))
if len(args.use_gpu_device) > 0 and torch.cuda.is_available():
al... |
def get_parser():
parser = argparse.ArgumentParser(
description='MSA based RNA Secondary Structural Model predictor')
basic_group = parser.add_argument_group('Basic input/output options')
basic_group.add_argument('--input_evo_lib_path', type=str, metavar='example.hdf5', required=True,
... | The code performs RNA secondary structure prediction using a pre-trained RSSM model, handling GPU/CPU setup, model loading, input processing, and result generation. It prepares output directories, executes bulk predictions from evolutionary library files, and optionally generates dot-bracket notation from predicted str... | def run(args=None):
if args is None:
parser = get_parser()
args = parser.parse_args()
# configurations
config = yaml.safe_load(open(os.path.join(basedir, 'RSSMFold', 'rssm_configs', 'msa_rssm_config.yml')))
if len(args.use_gpu_device) > 0 and torch.cuda.is_available():
all_devic... |
def check_left_and_right(self, part: Part) -> bool:
left_i = part.start_ind - 1
right_i = part.start_ind + part.length
if self.check_symbol(left_i, part.row) or\
self.check_symbol(right_i, part.row):
return True
return False
def check_up_and_down(self, part: P... | The main task of the code is to determine whether a given `Part` object is considered an engine part by checking its position relative to the engine. It evaluates three directional conditions: left/right, up/down, and diagonals. If any check confirms the part's alignment with the engine's structure, the method returns ... | def is_engine_part(self, part: Part) -> bool:
if self.check_left_and_right(part): return True
if self.check_up_and_down(part): return True
if self.check_diagonals(part): return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.