dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def find_u2_location_in_read(self, read: SeqIO, u2: str) -> (int, bool):
# TODO: what should be the maximum dist to find the universal?
max_distance = 6
best_location = 0
best_distance = float('inf')
is_found_u2 = False
from Levenshtein import distance
for i in ra... | The main task of the code is to process a list of biological reads by validating them against predefined sequence designs, tracking failed reads, and writing successful results to a CSV file. It identifies oligo sequences, checks for universal primer locations, and appends results in batches, while logging progress and... | def reads_results_to_csv(self, reads: List[str],
const_design: pd.DataFrame,
payload_design: pd.DataFrame,
barcodes_design: pd.DataFrame,
output_csv_path: Union[Path, str]) -> None:
res = list()
... |
def retrieve_reads_in_specific_len(self, reads: List[str], length: int) -> List[str]:
reads = [r for r in reads if len(r) == length]
print(f'{len(reads)} reads in len {length}')
return reads
def reads_results_to_csv(self, reads: List[str],
const_design: pd.DataFrame,... | The function analyzes sequencing reads using two approaches: 1) Filtering reads to a specific length (575) and saving results to CSV, or 2) Extracting reads longer than a threshold with a defined start position (universal2), applying Levenshtein distance, and saving processed data. It processes input read data alongsid... | def analyze_data_with_the_chosen_approach(self, algo_approach: str,
reads: List[str],
const_design_pd: Union[TextFileReader, DataFrame],
payload_design_pd: Union[TextFileReader, Data... |
def create_folders(self) -> None:
uts.is_dir_exists(self.output_hist_folder)
uts.is_dir_exists(self.output_folder)
uts.is_dir_exists(self.output_heatmap_folder)
uts.is_dir_exists(self.output_graphs_folder)
uts.is_dir_exists(self.output_csv_folder)
uts.is_dir_exists(self.o... | This code processes sequencing data by analyzing read lengths, comparing them to a design, and generating statistical outputs. It creates folders, uploads design data, processes FASTQ reads, generates histograms, analyzes data with a chosen algorithm, identifies common sequences per barcode, counts reads per barcode, a... | def run(self, is_use_only_good_reads_with_correct_len=False):
self.create_folders()
# upload design
const_design_pd, payload_design_pd, barcodes_design_pd = self.upload_design()
# reads
reads = uts.open_fastq(input_file=self.input_file)
# reads len showed in histogram
... |
def read_group(file):
g2s = {}
s2g = {}
for line in read_tsv(file, "\t"):
if line[1] not in g2s:
g2s[line[1]] = set()
g2s[line[1]].add(line[0])
s2g[line[0]] = line[1]
return g2s, s2g
def read_otu(file):
head = []
r = {}
for line in open(file):
... | This function calculates core and pan OTUs for each group in the input data. It reads OTU and group information, computes core (common) and pan (shared) OTUs per group, stores results in dictionaries, prints statistics, generates dual-axis plots for visualization, and returns the core and pan OTU dictionaries. | def core_pan_otu(otu, group, prefix):
g2s, s2g = read_group(group)
data, all_sample = read_otu(otu)
dcore = {}
dpan = {}
for i in g2s:
samples = list(g2s[i])
cores, pans = stat_core_pan(data, samples)
dcore[i] = cores
dpan[i] = pans
print("Group %s\tPan OTU\... |
def initialize_with_zeros(dim):
w = np.zeros((dim, 1))
b = 0
return w, b
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
costs = []
for i in range(num_iterations):
# Cost and gradient calculation
grads, cost = propagate(w, b, X, Y)
# ... | The main task of the code is to train a logistic regression model using gradient descent on training data, evaluate its performance on training and test sets by calculating prediction accuracy, and return a dictionary containing model parameters, costs, and evaluation metrics. The function initializes parameters, optim... | def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
# initialize parameters with zeros
w, b = initialize_with_zeros(X_train.shape[0])
# Gradient descent
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, pr... |
def initialize_parameters(input_layer, hidden_layer, output_layer):
# initialize 1st layer output and input with random values
W1 = np.random.randn(hidden_layer, input_layer) * 0.01
# initialize 1st layer output bias
b1 = np.zeros((hidden_layer, 1))
# initialize 2nd layer output and input with rando... | The code implements a neural network model with one hidden layer. It trains the model using gradient descent over specified iterations, computes costs, and updates parameters. After training, it predicts on train/test data, calculates accuracy, and returns parameters along with cost history for analysis. | def nn_model(X_train, Y_train, X_test, Y_test, n_h, num_iterations = 1000, learning_rate = 0.05, print_cost=False):
n_x = X_train.shape[0]
n_y = Y_train.shape[0]
# Initialize parameters with nputs: "n_x, n_h, n_y"
parameters = initialize_parameters(n_x, n_h, n_y)
# Retrieve W1, b1, W2, b2
... |
def isAttacked(pos):
global turn
swapTurn()
moves = getAllPossibleMoves()
swapTurn()
for move in moves:
if move.end == pos:
return True
return False
def getKingsideCastleMoves(pos):
moves = []
if board[pos[0]][pos[1] + 1] == '--' and board[pos[0]][pos[1] + 2] == '... | The function `getCastleMoves` generates valid castling moves for the current player based on the board position. It checks if the king is under attack, then verifies castle rights (kingside/queenside) for the current turn. Valid moves are collected from helper functions and returned as a list. | def getCastleMoves(pos):
moves = []
if isAttacked(pos):
return
if (turn == 'w' and currentCastleRights.wks) or (turn == 'b' and currentCastleRights.bks):
for move in getKingsideCastleMoves(pos):
moves.append(move)
if (turn == 'w' and currentCastleRights.wqs) or (turn == 'b'... |
def is_jump(move):
return abs(move.startRow - move.endRow) == 2 or abs(move.startCol - move.endCol) == 2
def get_valid_moves(loc):
valid_moves = []
dest = [(loc[0] + 2, loc[1] + 2), (loc[0] - 2, loc[1] - 2), (loc[0] + 2, loc[1] - 2), (loc[0] - 2, loc[1] + 2)]
for d in dest:
move = Move(loc[0], ... | This function executes a move in a checkers game, handles piece captures, updates the game state, and checks for double jumps. It updates the board, increments capture counters, toggles player turns, and recursively processes subsequent moves if a double jump occurs, then updates the display and game status. | def make_move(move):
global turn, status_text, red_captures, black_captures
dest_square = b.sq[move.endRow][move.endCol]
loc_square = b.sq[move.startRow][move.startCol]
middle_square = b.sq[(move.startRow + move.endRow) // 2][(move.startCol + move.endCol) // 2]
if is_jump(move):
# remo... |
def get_valid_moves(loc):
valid_moves = []
dest = [(loc[0] + 2, loc[1] + 2), (loc[0] - 2, loc[1] - 2), (loc[0] + 2, loc[1] - 2), (loc[0] - 2, loc[1] + 2)]
for d in dest:
move = Move(loc[0], loc[1], d[0], d[1])
if is_valid_selection(d):
if is_valid_move(move):
val... | The code identifies and visually highlights all valid moves for a selected game piece, including subsequent jump moves. It first retrieves valid moves, marks each end position in green, and if a move is a jump, recursively finds and highlights additional jumps from the new position, ensuring all potential move options ... | def draw_valid_moves(selected):
valid_moves = get_valid_moves(selected)
for move in valid_moves:
highlight_square(move.endRow, move.endCol, (0, 255, 0))
if is_jump(move):
valid_moves = get_valid_moves(move.end)
for move in valid_moves:
if is_jump(move):
... |
def checkForPinsAndChecks():
global pins, checks, inCheck
pins = []
checks = []
inCheck = False
if turn == 'w':
enemyColor = 'b'
allyColor = 'w'
startRow = wKingPos[0]
startCol = wKingPos[1]
else:
enemyColor = 'w'
allyColor = 'b'
startRow... | The function `getValidMoves` generates all valid chess moves for the current player, considering checks, pins, and castling. It checks if the king is in check, filters moves to avoid leaving the king in check, and handles castling rights. If in check, it either blocks the check or moves the king, depending on the numbe... | def getValidMoves():
global checkMate, staleMate, turn, inCheck, pins, checks, currentCastleRights
currentCastleRightsSave = CastleRights(currentCastleRights.wks, currentCastleRights.bks,
currentCastleRights.wqs, currentCastleRights.bqs)
inCheck, pins, checks = c... |
def get_all_valid_moves(color):
valid_moves = []
for r in range(b.w):
for c in range(b.h):
if b.sq[r][c].piece is not None and b.sq[r][c].piece.color == color:
moves = get_valid_moves((r, c))
for move in moves:
valid_moves.append(move)
... | The main task of the code is to select and execute a random valid move for the current player, prioritizing jumps if available. It checks all valid moves, filters jumps, randomly chooses one if jumps exist, otherwise selects any valid move, and updates the game state accordingly. | def make_random_move():
global must_jump
jumps = []
moves = get_all_valid_moves(turn)
for move in get_all_valid_moves(turn):
if is_jump(move) and is_valid_move(move):
jumps.append(move)
if len(jumps) > 0:
rand_move = random.choice(jumps)
make_move(rand_move)
... |
def drawSquares():
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
if (r + c) % 2 == 0:
pygame.draw.rect(display, pygame.Color("white"),
(SQUARE_SIZE * c, SQUARE_SIZE * r, SQUARE_SIZE, SQUARE_SIZE))
else:
pygame... | The function `updateDisplay()` renders the chessboard and pieces, highlights the selected square with a semi-transparent blue overlay, and visually marks valid moves with yellow overlays. It updates the display to reflect the current game state, including piece selection and possible moves, using Pygame's blitting func... | def updateDisplay():
global turn
drawSquares()
drawPieces()
if selected != ():
s = pygame.Surface((SQUARE_SIZE, SQUARE_SIZE))
s.set_alpha(100)
s.fill(pygame.Color("blue"))
display.blit(s, (clickCol * SQUARE_SIZE, clickRow * SQUARE_SIZE))
s.fill(pygame.Color("yel... |
def evalPos():
global turn
wKs = bKs = wQs = bQs = wNs = bNs = wBs = bBs = wRs = bRs = wPs = bPs = 0
pawns = knights = bishops = queens = kings = rooks = 0
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
if board[r][c][0] == 'w':
if board[r][c][1] == "P":
... | This function implements a quiescence search in a game-playing algorithm, using alpha-beta pruning. It evaluates the current position, updates alpha/beta bounds, and recursively explores capture moves to refine the score. It increments a position counter, applies moves, and undoes them to explore variations, returning ... | def quiesce(alpha, beta):
global positions
stand_pat = evalPos()
if stand_pat >= beta:
return beta
if alpha < stand_pat:
alpha = stand_pat
captures = getCaptures(getValidMoves())
sortMoves(captures)
for capture in captures:
positions += 1
makeMove(captur... |
def is_terminal():
return get_all_valid_moves(turn) == 0 or get_all_valid_moves(BLACK if turn == RED else RED) == 0
def evaluate():
valid_moves = get_all_valid_moves(turn)
if len(valid_moves) == 0:
return -math.inf
valid_moves = get_all_valid_moves(BLACK if turn == RED else RED)
if len(va... | The code implements the negamax algorithm with alpha-beta pruning to determine the optimal move in a two-player game. It recursively evaluates all valid moves at the current depth, updates the best move based on maximizing the score, and prunes unpromising branches. The function tracks game state variables (positions, ... | def negamax(depth, alpha, beta):
global positions, turn, red_captures, black_captures
if depth == 0 or is_terminal():
return evaluate(), None
value = -math.inf
valid_moves = get_all_valid_moves(turn)
if len(valid_moves) > 0:
best_move = random.choice(valid_moves)
for move in... |
def quiesce(alpha, beta):
global positions
stand_pat = evalPos()
if stand_pat >= beta:
return beta
if alpha < stand_pat:
alpha = stand_pat
captures = getCaptures(getValidMoves())
sortMoves(captures)
for capture in captures:
positions += 1
makeMove(captur... | This function implements the negaMax algorithm with alpha-beta pruning and transposition table lookup for efficient game tree search. It evaluates valid moves recursively, prioritizes them, and selects the best move by maximizing the score while avoiding redundant computations. The algorithm checks for game-ending cond... | def negaMax(depth, alpha, beta):
global turn, positions
value = -math.inf
if depth == 0:
return quiesce(alpha, beta), None
validMoves = getValidMoves()
if len(validMoves) == 0:
if inCheck():
return -math.inf
else:
return 0
swapTurn()
if le... |
def quiesce(alpha, beta):
global positions
stand_pat = evalPos()
if stand_pat >= beta:
return beta
if alpha < stand_pat:
alpha = stand_pat
captures = getCaptures(getValidMoves())
sortMoves(captures)
for capture in captures:
positions += 1
makeMove(captur... | The code implements the Principal Variation Search (PVS) algorithm with alpha-beta pruning to evaluate the best move score at a given depth in a game tree. It recursively explores valid moves, starting with a "first move" and iteratively refining the alpha-beta bounds. The function uses quiescence search at depth 0 to ... | def PVS(depth, alpha, beta):
global positions
if depth == 0:
return quiesce(alpha, beta)
validMoves = getValidMoves()
firstMove = validMoves[len(validMoves) - 1]
makeMove(firstMove)
bestScore = -PVS(depth - 1, -beta, -alpha)
undoMove()
if bestScore > alpha:
if bestSc... |
def rho_AvgSa_Sa(self, bgmpe, scenario, Ts, Tc_avg):
"""
The correlation between Spectra acceleration and AvgSA
:param Ts: these are all periods we are interested in
:param T_r: these are the periods for which avgSa is calculated
:param M:
:param Rjb:
:param Fau... | Your return
The code generates a conditional or unconditional target spectrum for ground motion selection, calculating its mean, standard deviation, and covariance based on input parameters like site, rupture, and distance characteristics. It uses a specified correlation model (e.g., Baker-Jayaram) to compute spectra... | def create(self, site_param={'vs30': 520}, rup_param={'rake': 0.0, 'mag': [7.2, 6.5]},
dist_param={'rjb': [20, 5]}, Hcont=[0.6, 0.4], T_Tgt_range=[0.01, 4],
im_T_star=1.0, epsilon=None, cond=1, useVar=1, corr_func='baker_jayaram'):
"""
Creates the target spectrum (condition... |
def findAllPoints(self, img):
redMask = cv2.inRange(img, np.array([0, 0, 20]), np.array([20, 20, 255]))
greenMask = cv2.inRange(img, np.array([0, 20, 0]), np.array([20, 255, 20]))
blueMask = cv2.inRange(img, np.array([10, 0, 0]), np.array([255, 20, 20]))
yellowMask = cv2.inRange(img, np.... | This code processes an image to detect colored points, calculates their positions, converts pixel coordinates to real-world measurements, determines joint angles, updates the last joint position, and publishes the calculated angles along with centers and vectors for further use in a robotic or control system. | def callback2(self, data):
# Receive the image
try:
self.cv_image2 = self.bridge.imgmsg_to_cv2(data, "bgr8")
except CvBridgeError as e:
print(e)
self.redC2, self.greenC2, self.blueC2, self.yellowC2 = self.findAllPoints(self.cv_image2)
self.combinecenters()... |
def findAllPoints(self, img):
redMask = cv2.inRange(img, np.array([0, 0, 20]), np.array([20, 20, 255]))
greenMask = cv2.inRange(img, np.array([0, 20, 0]), np.array([20, 255, 20]))
blueMask = cv2.inRange(img, np.array([10, 0, 0]), np.array([255, 20, 20]))
yellowMask = cv2.inRange(img, np.... | This code processes an image to detect colored points, converts pixel positions to meters, calculates joint angles from these positions, updates the last joint state, and publishes the resulting angles for robotic control or tracking. | def callback2(self, data):
# Receive the image
try:
self.cv_image2 = self.bridge.imgmsg_to_cv2(data, "bgr8")
except CvBridgeError as e:
print(e)
self.redC2, self.greenC2, self.blueC2, self.yellowC2 = self.findAllPoints(self.cv_image2)
self.combinecenters()... |
def calculate_pv_capacity_profile_based_on_tmy_weather(selected_shape: gpd.GeoDataFrame, buildings: gpd.GeoDataFrame,
building_specific_weather: bool = False,
debug: bool = True):
"""
Build PV capacity ... | This function generates photovoltaic (PV) capacity factor profiles for a specified year or typical meteorological year (TMY) using DWD TRY weather data. It processes input building and geographic data, checks data availability (compressed/uncompressed), and creates annual PV profiles saved as CSV files in a temporary d... | def build_pv_capacity_profile_for_year(selected_shape: gpd.GeoDataFrame, buildings: gpd.GeoDataFrame, year: int | None,
debug: bool = True):
"""
Build PV capacity factor profiles for a single year for all given buildings from the DWD TRY data. The profiles are
saved in... |
def get_dic(cnvcall, star_combinations):
"""
Return the variant table to use for each CNV/hybrid group
"""
if cnvcall in ["star5", "star13", "star5_star68", "star13_star68"]:
return star_combinations.dhap
elif cnvcall in [
"cn2",
"star13intron1",
"dup_star13",
... | The main task of the code is to determine a STAR allele call by integrating copy number variation (CNV) data and small variant information. It checks predefined CNV-to-genotype mappings, processes variant observations, and applies heuristic matching rules. For ambiguous cases (e.g., CNV levels 3-6), it attempts variant... | def match_star(
var_observed,
cnvcall,
spacer_cn,
star_combinations,
exon9,
var42126938_G_haplotype,
var42127803_diff_haplotype,
):
"""
Return the star allele call based on the called cnv/hybrid group and small variants
"""
star_call = namedtuple("star_call", "call_info varia... |
def refresh_overall():
overall = overall_states()
df = pd.DataFrame(overall, columns=["State Name", "State Abbr.", "Capital", "Establised", "Population", "Total Area", "Land Area", "Water Area"])
df.to_csv("Overall_data.csv")
def refresh_state(abbr):
historical_pop, head = poptrend(abbr)
state = pd.... | This code provides a command-line interface to interact with state data, allowing users to refresh databases, view state information, analyze population trends, and generate racial population statistics. It handles user inputs like 'refresh', 'info', 'poptrend', and 'popstats', validates state abbreviations, loads/save... | def main():
global states_abbr
global states_name
choice = "1"
while choice != "exit":
print("Enter Your command (help for instructions):")
choice = input()
if choice == "refresh":
print("Enter 1 to refresh the database of all states")
print("Enter 2 to re... |
def get_device():
# get CPU, GPU, or MPS device for training/running model
device = (
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
print(f"Using {device} device")
return device
def get_model(device, dataset, ... | The function classifies an input image using a specified model and dataset. It loads the model, preprocesses the image as a grayscale tensor, runs inference without gradients, and returns sorted predictions based on the dataset's label mapping. | def classify_image(image, dataset, model_name):
device = get_device()
model = get_model(device, dataset, model_name)
image_tensor = read_image(image, ImageReadMode.GRAY)
image_tensor = image_tensor.unsqueeze(1)
image_tensor = image_tensor.float()
with torch.no_grad():
image_tensor = imag... |
def get_device():
# get CPU, GPU, or MPS device for training/running model
device = (
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
print(f"Using {device} device")
return device
def get_testing_data(dataset_st... | The function classifies a specific training image from a dataset using a pre-trained model. It retrieves the image, prepares it for the model, performs prediction without gradients, saves the image as a PNG, and returns sorted predicted labels. | def classify_training_image_index(index, dataset, model_name, filename):
device = get_device()
testing_data = get_testing_data(dataset)
input_tensor = testing_data[index][0]
input_tensor = input_tensor.unsqueeze(1)
model = get_model(device, dataset, model_name) # make sure this loads the state dict... |
def parse_arguments():
"""Parsing command line
"""
parser = argparse.ArgumentParser(
description="Uses VARNA to plot the fast-paths predicted by RAFFT. !! It creates a temporary directory in the current folder!!")
parser.add_argument('rafft_out', help="rafft_output")
parser.add_argument('--o... | The main task of the code is to generate and visualize RNA folding paths from RAFFT output by creating annotated composite images. It processes structural data, generates individual structure diagrams using VARNA, arranges them on a canvas, calculates energy differences between consecutive steps, and draws connecting p... | def main():
args = parse_arguments()
fast_paths, seq = parse_rafft_output(args.rafft_out)
# draw structures
out_dir = "./tmp_rafft_fig"
system(f"mkdir -p {out_dir}")
varna_jar = "{}/VARNAv3-93.jar".format(
dirname(realpath(__file__))) if args.varna_jar is None else args.varna_jar
v... |
def set_limit(self, limit):
self._check_unreachable_limit_error(limit)
self._limit = limit
def reset(self):
self._first_iteration = True
self._index = self._start
def _set_lambda_check_bounds(self):
if self._step > 0:
self._lambda_check_bounds = lambda: self._index < ... | This code initializes an object with parameters for a sequence generator, setting a start value, step size, and limit. It validates the step size (non-zero), configures internal state, resets the sequence, and prepares a bounds-checking function to ensure generated values stay within the specified limit. | def __init__(self, limit, step=1, start=0):
if step == 0:
raise ValueError("Incrementing by 0 does not make sense.")
self._step = step
self._start = start
self.set_limit(limit)
self.reset()
self._set_lambda_check_bounds() |
def chooseMaze(window, font):
drawMazeOptions(window, font)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
... | The function `aiMode` selects a maze and search algorithm (BFS, DFS, greedy, or A*), computes the solution path, and visually animates the agent's movement through the maze step-by-step in real-time, updating the display with each move until the goal is reached. | def aiMode(window, font):
mazeName = chooseMaze(window, font)
if mazeName == 0:
return
maze = globals()[mazeName]
method = chooseSearch(window, font)
mazeSolSizeName = mazeName + "SolSize"
mazeSolSize = globals()[mazeSolSizeName]
if method == "bfs":
seq = bfs(start, goal, ... |
def checkOption(pos):
x = pos[0]
y = pos[1]
if x >= OPTIONS_X and x <= OPTIONS_X + OP_WIDTH:
if y >= OPTION1_Y and y <= OPTION1_Y + OP_HEIGHT:
return 1
elif y >= OPTION2_Y and y <= OPTION2_Y + OP_HEIGHT:
return 2
elif y >= OPTION3_Y and y <= OPTION3_Y + OP_H... | This code initializes a Pygame window for a maze generator, sets up display parameters, and handles user interactions. It displays a menu allowing users to switch between human-controlled and AI-controlled maze modes or exit. The main loop processes events like mouse clicks, triggers corresponding modes, and maintains ... | def main():
pygame.init()
pygame.mixer.init()
pygame.display.set_caption("Python Maze Generator")
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.SysFont(FONT, 30)
width = mazeSize*BLOCK
height = mazeSize*BLOCK
if width > 600:
width = 600
if height >... |
def atom_features(atom,
explicit_H=True,
use_chirality=True,
default_atoms=None):
if not default_atoms:
default_atoms = ATOMS
results = \
one_of_k_encoding_unk(atom.GetSymbol(), default_atoms) + \
one_of_k_encoding_unk(atom.GetDegree(... | This function converts a molecule into a graph representation by extracting atom and bond features, along with their connections. It stacks atom features, processes bond features (or returns zeros if none), and collects bond indices to form edges. The result is a MolGraph object encapsulating the molecule's structural ... | def get_graph_from_mol(mol):
af = np.stack([atom_features(a) for i, a in enumerate(mol.GetAtoms())])
bf = np.stack([bond_features(b) for b in mol.GetBonds()]) \
if len(mol.GetBonds()) else np.zeros(shape=[0, num_bond_features()], dtype=np.int)
us = np.array([b.GetBeginAtomIdx() for b in mol.GetBonds... |
def atom_features(atom,
explicit_H=True,
use_chirality=True,
default_atoms=None):
if not default_atoms:
default_atoms = ATOMS
results = \
one_of_k_encoding_unk(atom.GetSymbol(), default_atoms) + \
one_of_k_encoding_unk(atom.GetDegree(... | This function converts a SMILES string into a molecular graph representation by extracting atom and bond features, along with their connectivity. It uses RDKit to parse the SMILES, generates feature arrays for atoms and bonds, and constructs a MolGraph object containing these features and bond indices for graph-based m... | def get_graph_from_smiles(smiles):
mol = Chem.MolFromSmiles(smiles)
af = np.stack([atom_features(a) for i, a in enumerate(mol.GetAtoms())])
bf = np.stack([bond_features(b) for b in mol.GetBonds()]) \
if len(mol.GetBonds()) else np.zeros(shape=[0, num_bond_features()], dtype=np.int)
us = np.array... |
def check_around_3(cut_point_img, cut_point, point, p=1):
# check if there is a cut_point which is not cut_point above around it
h, w = cut_point_img.shape
r, c = point
left_r, right_r = max(0, r-p), min(h-1, r+p)
left_c, right_c = max(0, c-p), min(w-1, c+p)
for i in range(left_r, right_r+1):
for j in range(lef... | This function identifies neighboring pixels around a given point that can be reclassified into the current part by comparing orientation differences and label compatibility, ensuring directional consistency and optimal grouping in image segmentation. | def find_next_pixel_2(parts, current_part, img_label, cut_point_img, cut_point, current_p, orientation, current_label, p=1, threshold=20):
h, w = img_label.shape
r, c = current_p
left_r, right_r = max(0, r-p), min(h-1, r+p)
left_c, right_c = max(0, c-p), min(w-1, c+p)
points = []
for i in range(left_r, right_r+1... |
def get_label_connect(connect_list, c_label):
connect_labels = []
c_label_connect = list(connect_list[c_label-1])
for label in c_label_connect:
connect_labels.append(label)
# print("1: ", connect_labels)
for i in range(len(connect_list)):
if (i == c_label-1):
continue
if (c_label in connect_list[i]):
c... | This function merges parts in a structure by identifying and combining parts with similar orientations (below a threshold) and same direction. It iterates through connected labels, calculates orientation differences, selects the best match, merges them, updates data structures, and recursively repeats the process to en... | def merge_pwso(orientation, aver_orientation, cut_points, new_cut_points, connect_list, parts, c_part, c_label, threshold, pre_c_label=-1):
connect_labels = get_label_connect(connect_list, c_label)
aver_orient_label = c_label
if (pre_c_label != -1):
aver_orient_label = pre_c_label
best_part = None
min_diff = 36... |
def generate_word(data_path, input, page_infos):
combined = None
combined_floor = None
combined_ori = None
last_width = 0
for char in input:
code = ord(char)
# print(code)
# print(char)
label, connect_list, avg_ori = load_infos(data_path, code)
img = cv.imrea... | The main task of the code is to process an input string character by character, generating words and handling spacing/newlines for text layout. It accumulates characters into a word, triggers `generate_word()` when encountering spaces, newlines, or end-of-input, and uses `put_space()`/`new_line()` to manage page layout... | def generate_sentence(data_path, input, page_infos):
word = ''
for char in input:
if char == ' ':
if word != '':
generate_word(data_path, word, page_infos)
word = ''
# put space
put_space(page_infos)
elif char == ' ':
... |
def get_aver_orientation(parts, orientation):
aver_orientation = []
for part in parts:
aver = count_orientation(part, orientation)
aver_orientation.append(aver)
return aver_orientation
def find_corresponding_part(cut_point, parts):
for part in parts:
if (part[0] == cut_point):
return part
return None
def ... | The main task of the code is to merge image parts with similar orientations by adjusting cut points. It calculates an average orientation for parts, iterates through cut points, and uses a threshold to determine if parts should be merged. The function modifies `new_cut_points` and `parts` by merging compatible segments... | def merge_parts_with_similar_orientation(cut_point_img, connect_list, img_label, cut_points, parts, orientation, threshold=30):
aver_orientation = get_aver_orientation(parts, orientation)
# print(aver_orientation)
new_cut_points = cut_points.copy()
n = 0
for cut_point in cut_points:
c_part = find_corresponding_p... |
def generate_sentence(data_path, input, page_infos):
word = ''
for char in input:
if char == ' ':
if word != '':
generate_word(data_path, word, page_infos)
word = ''
# put space
put_space(page_infos)
elif char == ' ':
... | The main task of the code is to generate text on a page by reading lines from a text file, processing each non-empty line to render text using `generate_sentence`, and creating new pages for empty lines via `new_line`, finally saving the resulting page image. | def generate_text(data_path, text_path, page_infos):
# init page
size = (3508, 2480)
page_infos['page'] = np.zeros(size, dtype=np.uint8)
page_infos['page'].fill(255)
with open(text_path, 'r') as fin:
rows = fin.readlines()
for row in rows:
# row = row.strip()
... |
def _cache_reload() -> Graph:
"""
Clear and rewrite graph to cache.
:return: graph
:rtype: rdflib.Graph
"""
logging.debug("_cache_reload()")
_cache_clear()
graph = _build_graph()
_cache_write(graph)
return graph
def _cache_load() -> Graph:
"""
Load graph from cache, re... | The function retrieves a concept scheme from a given URI using a cached or reloaded graph. It returns a dictionary with the concept scheme data if successful, or an error message if an exception occurs. The 'reload' parameter determines whether to reload the graph. | def get_concept_scheme(uri: str, reload: bool = False) -> dict:
"""
Get a concept scheme from its URI.
:param uri: URI of concept scheme
:param reload: If the graph should be reloaded
:return: dictionary representation of concept scheme
:rtype: dict
"""
if reload:
graph = _cache... |
def _cache_reload() -> Graph:
"""
Clear and rewrite graph to cache.
:return: graph
:rtype: rdflib.Graph
"""
logging.debug("_cache_reload()")
_cache_clear()
graph = _build_graph()
_cache_write(graph)
return graph
def _cache_load() -> Graph:
"""
Load graph from cache, re... | The main task of the code is to retrieve and return concepts associated with a given concept scheme URI from a graph database. It loads the graph (cached or reloaded), queries for concepts linked to the scheme via SKOS.inScheme, and returns a structured dictionary with the results or an error message if the scheme does... | def get_concept_scheme_concepts(uri: str, reload: bool = False) -> dict:
"""
Get concepts for a given concept scheme from its URI.
:param uri: URI of concept scheme
:param reload: If the graph should be reloaded
:return: dictionary representation of concept scheme
:rtype: dict
"""
if re... |
def _cache_reload() -> Graph:
"""
Clear and rewrite graph to cache.
:return: graph
:rtype: rdflib.Graph
"""
logging.debug("_cache_reload()")
_cache_clear()
graph = _build_graph()
_cache_write(graph)
return graph
def _cache_load() -> Graph:
"""
Load graph from cache, re... | The main task of the code is to execute a SPARQL query on an RDF graph, process the results based on the type of retrieved resources (SKOS Concept or ConceptScheme), and return structured dictionary responses with error handling. It loads/caches the graph, executes the query, checks result bindings, determines resource... | def sparql_query(query: str, reload: bool = False) -> dict:
"""
Perform a SPARQL query.
:param query: the SPARQL query
:param reload: If the graph should be reloaded
:return: dictionary of query result
:rtype: dict
"""
if reload:
graph = _cache_reload()
else:
graph =... |
def _cache_reload() -> Graph:
"""
Clear and rewrite graph to cache.
:return: graph
:rtype: rdflib.Graph
"""
logging.debug("_cache_reload()")
_cache_clear()
graph = _build_graph()
_cache_write(graph)
return graph
def _cache_load() -> Graph:
"""
Load graph from cache, re... | The main task of the code is to retrieve a concept's information from a given URI using a graph database, either reloading the graph data or using a cached version. It returns the concept details in a dictionary format with error handling, including an "error" flag and the result or error reason if an exception occurs. | def get_concept_from_uri(uri: str, reload: bool = False) -> dict:
"""
Get a concept from its URI.
:param uri: URI of concept
:param reload: If the graph should be reloaded
:return: dictionary representation of concept
:rtype: dict
"""
if reload:
graph = _cache_reload()
else:... |
def evaluate_hand(self, hand: List[Card]):
# TODO: Four of a kind
all_cards = hand + self.community_cards
best_cards = []
evaluators = [
Evaluator.royal_flush,
Evaluator.straight_flush,
Evaluator.four_kind,
Evaluator.full_house,
... | This code determines the winner(s) of a poker round by evaluating players' hands, resolving ties, distributing the shared pot, and resetting the game state. It updates the small blind position, filters active players, compares hand strengths, identifies winning players, calculates payouts, and broadcasts results before... | def post_round(self):
self.small_blind_index = (self.small_blind_index + 1) % len(self.player_list)
self.caller_list = [player for player in self.player_list if player not in self.fold_list]
# The game actually finished after all phases
if len(self.fold_list) != len(self.player_list) - ... |
def broadcast(self, message):
sio.emit("message", message, room=self.room_id)
def take_card(self) -> Optional[Card]:
if len(self.deck):
return self.deck.pop()
else:
return None
def post_round(self):
self.small_blind_index = (self.small_blind_index + 1) % len(self.... | This method handles the start of a game phase by broadcasting the phase name and managing community cards. It adds 3 cards for FLOP, 1 for TURN/RIVER, and triggers post-round actions. It also sets 'first' to True for the PRE_FLOP phase. | def phase_start(self):
self.broadcast("Starting phase " + self.phase.name.capitalize().replace("_", " "))
if self.phase == Phases.PRE_FLOP:
self.first = True
elif self.phase == Phases.FLOP:
# Flop deals 3 cards
self.community_cards.append(self.take_card())
... |
def deck_generator():
deck = []
for suit in [suit for suit in dir(CardSuits) if not suit.startswith("__")]:
for rank in [rank for rank in dir(CardRanks) if not rank.startswith("__")]:
deck.append(Card(CardRanks[rank], CardSuits[suit]))
# TODO: Use a non-crackable shuffle function inste... | The `initialize_round` method resets a Poker game by removing players with zero balance, ensuring at least two active players, initializing the deck, dealing cards, setting game phases (e.g., pre-flop), and broadcasting a new round start. It also manages player states, call values, and community cards, though some task... | def initialize_round(self):
"""
Initializes the Poker game, resets the pot to 0
:return: An error string, or None if no error occurred.
"""
for player in self.player_list[:]:
if player.balance == 0:
self.player_list.remove(player)
# T... |
def get_shellcode_len(map_file):
'''
Gets the length of the shellcode by analyzing map_file (map produced by VS 2013)
'''
try:
with open(map_file, 'r') as f:
lib_object = None
shellcode_len = None
for line in f:
parts = line.split()
... | The code extracts shellcode from an EXE file using a map file, processes relocations, fixes null bytes in the shellcode, and outputs the cleaned shellcode as a C array. It checks input validity, retrieves shellcode length, analyzes relocations, applies fixes if needed, and prints the final result. | def main():
print("Shellcode Extractor by %s (%d)\n" % (author, year))
if len(sys.argv) != 3:
print('Usage:\n' +
' %s <exe file> <map file>\n' % os.path.basename(sys.argv[0]))
return
exe_file = sys.argv[1]
map_file = sys.argv[2]
print('Extracting shellcode length fr... |
def get_edge_mask(self,
src_nid,
tgt_nid,
ghetero,
feat_nids,
prune_max_degree=-1,
k_core=8,
prune_graph=True,
with_path_loss=True):
... | The code generates path explanations for predicted links in a heterogenous graph by extracting a k-hop subgraph around source/target nodes, learning edge masks, and retrieving paths. It prunes the graph based on degree/k-core, computes paths with specified constraints, and maps subgraph paths back to original node IDs.... | def explain(self,
src_nid,
tgt_nid,
ghetero,
num_hops=5,
prune_max_degree=-1,
k_core=2,
num_paths=1,
max_path_length=5,
prune_graph=True,
with_path_loss=T... |
def get_sql(filename):
fd = open(filename, encoding="utf-8")
sql_file = fd.read()
fd.close()
return sql_file
def find_word_with_start_index(folder_name, sql_file):
index = sql_file.find(folder_name)
result = ''
while True:
if sql_file[index] is '\"':
break
result ... | The code generates a heatmap comparing execution times of SQL queries using different data formats (virtual_table, parquet, df, csv, csv.gz) in a specified benchmark folder. It processes queries, loads data, executes queries for each format, collects execution times, and visualizes the results as an annotated heatmap. | def heat_map(folder_name: str):
file_name = ''
lst = []
directory = './benchmark/' + folder_name + '/query_with_join/'
queries = Path(directory).glob('*')
data_formats = ['virtual_table', 'parquet', 'df', 'csv', 'csv.gz']
for query in queries:
sql_file = get_sql(query)
file_name ... |
def to_lid_pt(y, x):
px, py = -x * UP.lidar_zoom + UP.lidar_car_x, -y * UP.lidar_zoom + UP.lidar_car_y
if px > 0 and py > 0 and px < UP.lidar_x and py < UP.lidar_y:
return int(px), int(py)
return -1, -1
def draw_path(y, x, color, img, calibration, top_down, lid_color=None):
# TODO: Remove big box.
uv_mode... | This function visualizes a model's predictions on a top-down image. It draws lead vehicles, predicted paths (lpath/rpath/cpath), and a user steering path based on curvature. The function overlays these elements onto the top-down image using color-coded paths, with varying opacity and positions derived from input parame... | def plot_model(m, VM, v_ego, curvature, imgw, calibration, top_down, d_poly, top_down_color=216):
if calibration is None or top_down is None:
return
for lead in [m.lead, m.lead_future]:
if lead.prob < 0.5:
continue
lead_dist_from_radar = lead.dist - RADAR_TO_CAMERA
_, py_top = to_lid_pt(lead... |
def __get_multiple_scans(self, start_step=START_STEP, stop_step=STOP_STEP, cluster_count=1,
scan_interval=0, number_of_scans=0):
self.__port_lock.acquire()
try:
cmd = 'MD%04d%04d%02d%01d%02d\n' % (start_step, stop_step, cluster_count, scan_interval, number_of_sca... | The scanning_loop method repeatedly performs scans while the scanner is active and scanning is allowed. It acquires a port lock, processes multiple scans, checks for interruptions, toggles the laser state, and releases the lock if stopped. The loop pauses briefly between iterations to manage scan rate and concurrency. | def scanning_loop(self):
while self.__is_active:
if self.__scanning_allowed:
self.__port_lock.acquire()
for scan in self.__get_multiple_scans():
self.__set_scan(scan)
if not self.__scanning_allowed or not self.__is_active:
... |
def best_split(self, dataset, num_samples, num_features):
# dictionary baray zakhire kardan behtarin split ke daray key hay: 1.feature_index 2.threshold 3.dataset_left 4.dataset_right 5.info_gain
best_split = {}
max_info_gain = -1000
# ro index hame feature ha for mizanim
... | This function recursively constructs a decision tree by splitting the dataset based on the best feature and threshold. It checks stopping conditions (min samples, max depth), computes the best split, and recursively builds left/right subtrees. If no valid split is found, it creates a leaf node with the calculated outco... | def build_tree(self, dataset, current_depth=0):
#tabe besorat bazgashti derakht tasmim ra misazad
X, Y = dataset[:,:-1], dataset[:,-1] # feature ha va on meghdar outcome ra az dade ha joda mikonad
num_samples, num_features = np.shape(X) # avali teada kol nemone ha va dovomi tedad vijgi ... |
def feature_extraction(self, input_layer, current_scale, index):
filter_size = 3
filter_0 = tf.Variable(initial_value=self.filter_initializer(shape=(filter_size, filter_size, 1, 64)),
name="0_" + str(index) + "f")
bias_0 = tf.get_variable(shape=[1], initializer=s... | The code implements a LapSRN model for image super-resolution, recursively upsampling input images through multiple scales. It iteratively extracts features, applies upsampling, combines results via addition, and applies activation functions. Outputs at each scale are stored in a list and transposed to NCHW format, ret... | def LapSRN_model(self):
"""
Implementation of LapSRN
Returns
----------
Model
"""
outputs = list()
prev_fe_layer = self.LR_input
prev_re_layer = self.LR_input
for n in range(0, self.num_of_components):
current_scale = pow(2, ... |
def level_one():
"""grade k-2 logic here, return simulation output"""
sim_data = sim_one()
# only 2 players, just display 2 move counts
data_frame = Frame(root, bg="white")
Label(data_frame, text="Number of players: " + str(sim_data["num_players"])).pack()
Label(data_frame, text="Player 1 moves:... | The code defines a function `gradeCallback` that determines and executes a specific level function (`level_one`, `level_two`, or `level_three`) based on the user-selected grade range (K-2, 3-5, 6-8). It first hides the submit button and uses `grade.get()` to identify the selected grade, triggering the corresponding lev... | def gradeCallback():
submit_button.forget()
"""Called when user selects grade (initial screen)
StringVar: grade.get()"""
# print('Grade is ' + grade.get())
# determine simulation function
if grade.get() == "K-2":
level_one()
elif grade.get() == "3-5":
level_two()
elif gra... |
def __prepare(self, start_point, z_value=None, power=None, speed=None):
if speed is None:
speed = self.default_speed
if power is None:
power = self.default_power
self.code += '\nG1 F{}'.format(self.move_speed)
self.__move(*start_point)
if z_value is not No... | This code draws a path by sequentially moving to each point in the provided list. It initializes settings with the last point using `__prepare`, then iterates through all points to move to each coordinate via `__move`, finally signaling path completion with `__element_finished`.) | def draw_path(self, points, **kwargs):
self.__prepare(points[-1], **kwargs)
for p in points:
self.__move(*p)
self.__element_finished() |
def __prepare(self, start_point, z_value=None, power=None, speed=None):
if speed is None:
speed = self.default_speed
if power is None:
power = self.default_power
self.code += '\nG1 F{}'.format(self.move_speed)
self.__move(*start_point)
if z_value is not No... | The code draws a circle by positioning and moving along key points relative to the center (x,y) with radius r, using helper methods for preparation, movement, and finalization. It calls __prepare to set initial parameters, __move_g2 to navigate to critical circle coordinates, and __element_finished to conclude the draw... | def draw_circle(self, x, y, r, **kwargs):
self.__prepare([x-r, y], **kwargs)
self.__move_g2(x, y+r, r)
self.__move_g2(x+r, y, r)
self.__move_g2(x, y-r, r)
self.__move_g2(x-r, y, r)
self.__element_finished() |
def __prepare(self, start_point, z_value=None, power=None, speed=None):
if speed is None:
speed = self.default_speed
if power is None:
power = self.default_power
self.code += '\nG1 F{}'.format(self.move_speed)
self.__move(*start_point)
if z_value is not No... | This method draws a line between two points (x1,y1) and (x2,y2), handling optional z-coordinates (z1/z2) for 3D lines. It prepares the starting point, moves to the endpoint, and finalizes the drawing element, using keyword arguments for additional properties. | def draw_line(self, x1, y1, x2, y2, z1=None, z2=None, **kwargs):
if z1 is None:
if 'z_value' in kwargs:
z1 = kwargs.pop('z_value')
if z2 is None:
z2 = z1
a, b = (x1, y1) if z1 is None else (x1, y1, z1), (x2, y2) if z2 is None else (x2, y2, z2)
self... |
def __parse_move_line(self, line):
"""G02 X88.704067 Y251.364508 Z-0.125000 I0.032899 J0.064154"""
parts = re.sub('\(.*?\)', '', line).split()
x, y = None, None
for part in parts[:0:-1]:
axis = part.upper()[0]
value = float(part[1:])
if axis in ['Z', '... | The main task of the code is to parse G-code generated by Inkscape's "Path to GCode" extension, extract path coordinates, scale and reposition them to fit a specified width while maintaining proportions, and append the transformed G-code commands to `self.code`. It handles multiple paths, calculates bounding boxes, app... | def load_from_inkscape_gcode(self, filename, w, cx, cy, **kwargs):
"""
Loads path created in inkscape using (Extensions > Gcode tools > Path to GCode)
"""
lines = [x.strip() for x in open(filename).read().split('\n')]
xs, ys = [], []
shapes = dict()
current_pa... |
def __render_keys(self, workplane, d):
if bool(d["locations"]):
print("Key locations:")
for key in self.__generated["keys"]:
keyloc = key[1]
keypos = key[2]
if bool(d["keyswitchCuts"]):
self.__keyswitch_cut_at_keyloc(workplane, keyloc.x, k... | The code renders a 3D model of a PCB or similar object by combining multiple components (keys, drills, outlines, LCD, encoders, etc.) using CadQuery. It uses a dictionary `d` to control rendering parameters, conditionally adding elements based on flags. The workplane is built incrementally via private methods, then com... | def render(self, **kwargs):
d = {
"locations": False,
"keyswitchCuts": False,
"keyswitchOutlines": False,
"drills": False,
"drillPads": False,
"outline": False,
"spacer": False,
"esdOutline": False,
"lcd... |
def playerShoot(self):
if self.player.nextShootableFrame < self.frameCounter:
keys = pygame.key.get_pressed()
bulletDirection = Pos(0, 0)
if keys[pygame.K_UP]:
bulletDirection.y -= 1
if keys[pygame.K_DOWN]:
bulletDirection.y += 1
... | The code's main task is to update a game state by handling player/enemy movements, shooting mechanics, bullet management, AI behaviors, resource updates, and rendering. It spawns enemies periodically, checks for frame intervals, and ensures smooth game progression by calling various update and draw functions. | def run(self):
self.player.move()
self.playerShoot()
self.cowShoot()
self.bulletAi()
self.removeExpiredBullets()
self.allyAi()
self.enemyAi()
self.updateMilk()
self.openShopIfClose()
if self.frameCounter % 30 == 0 and len(self.enemies) < 30... |
def _creatingItemSets(self):
"""
Scans the uncertain transactional dataset
"""
self._Database = []
if isinstance(self._iFile, _ab._pd.DataFrame):
uncertain, data = [], []
if self._iFile.empty:
print("its empty..")
i = self._... | The main task of the code is to mine frequent patterns from uncertain databases using the UF algorithm. It constructs a tree structure, filters out non-frequent patterns by comparing their support against a minimum threshold, and generates final frequent patterns through recursive traversal. The process involves creati... | def startMine(self):
"""Main method where the patterns are mined by constructing tree and remove the remove the false patterns
by counting the original support of a patterns
"""
global minSup
self._startTime = _ab._time.time()
self._creatingItemSets()
self._mi... |
def _creatingItemSets(self):
"""
Scans the dataset
"""
self._Database = []
if isinstance(self._iFile, _ab._pd.DataFrame):
uncertain, data = [], []
if self._iFile.empty:
print("its empty..")
i = self._iFile.columns.values.tol... | The code's main task is to mine frequent patterns from an uncertain database using the PUF algorithm. It constructs a tree, generates candidate patterns, checks their support against a minimum threshold, removes false positives by validating original support, and saves valid patterns. The process involves intersecting ... | def startMine(self):
"""Main method where the patterns are mined by constructing tree and remove the remove the false patterns
by counting the original support of a patterns
"""
global _minSup
self._startTime = _ab._time.time()
self._creatingItemSets()
self._m... |
def reverse(self):
"""Reverse the graph."""
self._graph = self._graph.reverse()
def complement(self):
"""Change each base of nodes in the graph as complimentary base."""
complement_dict = { "A": "T",
"T": "A",
"G": "C",
... | The code's main task is to reverse and complement a graph's edges, then swap the source and sink nodes to create a plausible reversed-complemented graph structure, likely for bioinformatics or network analysis applications. | def reverse_complement(self):
"""Reverse and complement the graph and swap source and sink to make it plausible."""
self.reverse()
self.complement()
self.swap_source_sink() |
def __download_df(self, symbol):
"""
Private downloads data from Coingecko database for the crypto(symbol)
Parameters
----------
arg1 : str
crypto Symbol
Returns
-------
Pandas DataFrame
downloaded data as dataframe
... | The function retrieves historical and current cryptocurrency prices for specified time intervals relative to a given datetime, returning them as a tuple. It adjusts the input datetime, fetches data, checks for availability, and calculates prices at the alert time, 2hr, 4hr, 1D, 1W ahead, and current price, returning 'N... | def get_prices(self, symbol, dtime):
"""
Returns tuple of prices for the crypto (symbol) and dtime as Alert time (Alert Price, 2hr, 4hr, 1D, 1W)
Parameters
----------
arg1 : str
crypto Symbol
arg2 : datetime
Alert or created datetime objec... |
def open_resize_image(resive_factor):
"""Opens image and resive it to given factor"""
return cv2.resize(
cv2.imread(ARGS["image"], 1),
(0, 0),
fx=resive_factor,
fy=resive_factor,
)
def find_screen(img_res):
"""Tries to find the multimeter screen based on its color,
... | The code processes an image to extract and display numerical values from a screen capture. It resizes the image, crops a region of interest, applies thresholding and morphological operations to isolate digits, and identifies digit contours. The extracted values are printed and saved, with optional debug visualizations ... | def main():
"""Control program flow"""
img_res = open_resize_image(RFACTOR)
if not SCREENPOINT:
screen_transform = find_screen(img_res)
else:
screen_transform = ask_screen_points(img_res)
(y_image_shape, x_image_shape) = (
screen_transform.shape[0],
screen_transform.s... |
def _load_local_player(self) -> int:
"""
Returns the local player object out of uWorld.UGameInstance.
Used to get the players coordinates before reading any actors
:rtype: int
:return: Memory address of the local player object
"""
game_instance = self.rm.read_ptr(... | The main task of this code is to initialize memory reading for the "SoTGame.exe" process, locate critical game objects like uWorld, gName, gObject, and uLevel, establish base addresses for these objects, retrieve the local player's coordinates, and set up data structures to track game state information such as actors, ... | def __init__(self):
"""
Upon initialization of this object, we want to find the base address
for the SoTGame.exe, then begin to load in the static addresses for the
uWorld, gName, gObject, and uLevel objects.
We also poll the local_player object to get a first round of coords.
... |
def connect(self):
"""
Connects to the IRC server and joins the given channel.
This also will request tags in messages.
"""
self.sock = socket.socket()
self.sock.connect(self.addr)
self.send("PASS {}".format(self.password))
self.send("NICK {}".format(self... | The main task of the code is to continuously listen for incoming messages by maintaining a connection, processing each received message (or PING) through respective handlers, printing non-null results, and repeating this process every second in an infinite loop. | def _listen(self):
"""
Main listen loop.
First ensures the client is connected. Following that it will
receive messages every second and call the handler function.
"""
if not self.is_connected:
self.connect()
while True:
data = self.recv... |
def abort_with_error(err):
logging.critical(err)
raise Exception(err)
def show_info(win, file_name, insert=''):
"""
Clear way to show info message into screen.
:param win:
:return:
"""
msg = read_text_from_file(file_name, insert=insert)
msg = visual.TextStim(win, color='grey', text=m... | The main task of the code is to conduct a visual perception experiment using PsychoPy, presenting square or circle stimuli with adaptive stimulus onset asynchrony (SOA) adjustments based on participant responses. It collects participant data (ID, gender, age), runs training and experimental trials, logs responses and t... | def main():
global PART_ID # PART_ID is used in case of error on @atexit, that's why it must be global
# === Dialog popup ===
info = {'IDENTYFIKATOR': '', u'P\u0141EC': ['M', "K"], 'WIEK': '20'}
dictDlg = gui.DlgFromDict(dictionary=info, title='Czas detekcji wzrokowej')
if not dictDlg.OK:
a... |
def get_not_jokers_cards(hand: str) -> list:
"""Get the cards that are not jokers."""
return re.findall("[^J]", hand)
def get_best_not_joker_card(hand: str) -> str:
"""Get the best card that is not a joker."""
not_jokers_cards = get_not_jokers_cards(hand)
return max(not_jokers_cards, key=lambda x: c... | This function replaces jokers ("J") in a poker hand with the optimal non-joker cards to create the strongest possible hand. It identifies the number of jokers, checks the hand's value (e.g., full house, three of a kind), and substitutes jokers with the most frequent or highest-value card to maximize the hand's strength... | def convert_joker_best_possible_card(hand: str) -> str:
"""Convert the joker to the best possible card."""
number_of_jokers = hand.count("J")
not_jokers_cards = get_not_jokers_cards(hand)
if number_of_jokers == 0 or number_of_jokers == 5: # no jokers or five of a kind
return hand
elif numbe... |
def create_board(self):
"""creates a list of lists representing the board and all it's disc
in their location. returns the board"""
one_row = []
board = []
for row in range(self.__height):
for col in range(self.__width):
cell_disc = self.cell_content((... | The function identifies and returns the coordinates of four connected discs forming a winning line in a Connect Four-like game, checking rows, columns, and both diagonal directions (down-right and up-right) to determine the win's location. | def win_streak(self):
"""returns the locations of the 4 winning discs"""
board = self.create_board()
winner = str(self.is_win())
if winner:
return self.check_win_row(board, winner) or self.check_win_col(
board, winner) or self.check_win_down_right(board, winne... |
def _create_cells(self):
for _ in range(self._num_cols):
cells = []
for _ in range(self._num_rows):
cells.append(Cell(self._win))
self._cells.append(cells)
for i in range(self._num_cols):
for j in range(self._num_rows):
self... | This code initializes a maze generator by setting up grid dimensions, cell sizes, and a window. It creates a 2D grid of cells, uses a seed for randomization, and generates a maze by recursively breaking walls to form paths. Finally, it sets entrance and exit points, preparing the maze for visualization or traversal. | def __init__(self, x1, y1, num_cols: int, num_rows: int, cell_size_x, cell_size_y, win: Window = None, seed=None):
self._x1 = x1
self._y1 = y1
self._win = win
self._num_cols = num_cols
self._num_rows = num_rows
self._cell_size_x = cell_size_x
self._cell_size_y = ... |
def _sample(obss, acts, qs, max_pts, is_reweight):
# Step 1: Compute probabilities
#print(qs)
#ps = np.max(np.array(qs), axis=1) - np.min(np.array(qs), axis=1)
#print(ps)
#ps = ps / np.sum(ps)
print(qs)
ps = calc_ps(qs)
print(ps)
# Step 2: Sample points
if is_reweight:
#... | The code implements the DAgger algorithm for imitation learning, iteratively training a student policy using data from a teacher policy. It collects expert trajectories, trains the student on a subset of data, generates student policy trajectories, queries the teacher for corrected actions, and augments the dataset. Th... | def train_dagger(env, teacher, student, state_transformer, max_iters, n_batch_rollouts, max_samples, train_frac, is_reweight, n_test_rollouts, id):
# Step 0: Setup
obss, acts, qs = [], [], []
students = []
#wrapped_student = TransformerPolicy(student, state_transformer)
# Step 1: Generate some ... |
def getMin(system, jobs_obj):
min = system['opt_solution']
if min < system['maxspan']:
min = system['maxspan']
if len(jobs_obj['jobs']) > 0:
if min < jobs_obj['jobs'][0]['time']:
min = jobs_obj['jobs'][0]['time']
possible_maximum_sum_of_jobs_in_other_machines = 0
for i i... | This function implements a branch-and-bound algorithm to find an optimal solution for a scheduling/assignment problem. It recursively explores job-machine assignments, prunes suboptimal paths by comparing against the current best solution, and uses symmetry checks to avoid redundant computations. The function tracks vi... | def BnB_findSolution(node: dict, jobs_obj):
global BEST_CURRENT_SOLUTION, NUMBER_OF_NODES_VISITED
NUMBER_OF_NODES_VISITED += 1
node_index = NUMBER_OF_NODES_VISITED
min = getMin(node, jobs_obj)
if min >= BEST_CURRENT_SOLUTION['maxspan']:
return
max = getMaxAndCheckBestSolution(node, jobs_... |
def getJobsObj(jobs_as_string):
jobsObj = getJobsObjAsListFromString(jobs_as_string)
return jobsObj
def getNewFreeSystem():
system = {'machines' : [], 'maxspan' : 0, 'free_space_in_other_machines': K_NUMBER*(NUMBER_OF_MACHINES-1)}
for j in range(1, NUMBER_OF_MACHINES+1):
system['machines'].appen... | The code's main task is to solve a scheduling optimization problem using a branch-and-bound (BnB) algorithm. It initializes a solution with the Longest Processing Time (LPT) heuristic, then refines it via BnB to minimize the makespan (maximum machine completion time) under constraints. The function returns the optimal ... | def main(input):
global BEST_CURRENT_SOLUTION, NUMBER_OF_MACHINES, K_NUMBER
NUMBER_OF_MACHINES = input['number_of_machines']
K_NUMBER = input['K']
jobs_obj = getJobsObj(input['jobs_string'])
root = getNewFreeSystem()
root['opt_solution'] = int(np.ceil(jobs_obj['sum_of_all_jobs_times']/NUMBER_OF_... |
def initializePopulation(jobs_obj, free_system):
population = []
machines_indexes = getMachineIndexesString()
interval_start = 0
for _ in range(POPULATION_SIZE):
chromosome_string = ''.join(random.choices(machines_indexes, k = jobs_obj['number_of_jobs']))
chromosome_fitness, maxspan = g... | This function executes a genetic algorithm to optimize job scheduling on a free system by evolving a population of chromosomes over multiple generations. It initializes a population, iteratively applies mutation and crossover to generate offspring, selects the fittest chromosomes, and returns the best solution found. T... | def doGeneticAlgorithm(free_system, jobs_obj):
global TEXT_TO_PRINT
if not os.path.isdir(os.path.dirname(__file__) + r'/' + 'population'):
os.mkdir(os.path.dirname(__file__) + r'/' + 'population')
else:
shutil.rmtree(os.path.dirname(__file__) + r'/' + 'population')
os.mkdir(os.path.d... |
def getJobsObj(jobs_as_string):
jobsObj = getJobsObjAsListFromString(jobs_as_string)
return jobsObj
def getNewFreeSystem():
system = {'machines' : [], 'maxspan' : 0}
for j in range(1, NUMBER_OF_MACHINES+1):
system['machines'].append({'jobs' : [], 'jobs_count': 0, "span" : 0, 'index': j})
ret... | This code performs job scheduling optimization using a genetic algorithm to find the optimal distribution of jobs across multiple machines. It calculates a lower bound for the makespan (total completion time), runs a genetic algorithm to search for the best schedule, and prints the resulting machine allocation. The cor... | def main(input):
global NUMBER_OF_MACHINES, TEXT_TO_PRINT
NUMBER_OF_MACHINES = input['number_of_machines']
jobs_obj = getJobsObj(input['jobs_string'])
free_system = getNewFreeSystem()
free_system['opt_solution'] = int(np.ceil(jobs_obj['sum_of_all_jobs_times']/NUMBER_OF_MACHINES))
best_chromosome... |
def addSensor(self, attribute: addressable.AddressableAttribute, name, device_class=None, unit_of_measurement=None):
address, id = self.get_ids(attribute)
name = self.format_name(name)
sensor = Sensor(self.client, id, name, self.device,
device_class, unit_of_measurement)... | The main task of this code is to initialize a vehicle device by integrating its status data (e.g., battery, charging, climate control) with a home automation system. It sets up sensors, binaries, and switches for monitoring and controlling the vehicle, saves a car image if specified, and logs status keys. The code maps... | def __init__(self, vehicle: weconnect.Vehicle, client, imageSaveFolder=None) -> None:
self.vehicle = vehicle
if imageSaveFolder is not None:
vehicle.updatePictures()
f = FileIO(f"{imageSaveFolder}{vehicle.vin.value}.png", 'w')
self.vehicle.pictures['car'].value.save... |
def loadCookiesFileFile(requestsSession):
if path.isfile(cookiesFilename):
with open(cookiesFilename, 'rb') as f:
cookies = pickle.load(f)
requestsSession.cookies.update(cookies)
def testRequest(requestsSession, url):
try:
DEBUG('test-request:testRequest: request starting... | The code tests a session-based interaction by loading cookies, sending a request to set a name, waiting, retrieving the name, and saving cookies again. It verifies session persistence and cookie handling in a web application. | def testRequests(requestsSession):
loadCookiesFileFile(requestsSession)
testRequest(requestsSession, testUrlPrefix + '/session/set_name/ddd')
time.sleep(3)
testRequest(requestsSession, testUrlPrefix + '/session/get_name')
saveCookiesToFile(requestsSession) |
def get_info():
global name, size, data_hash, count, addr
data, addr = uServerSock.recvfrom(bufsize)
if (check_package(data) == True):
data = data[15:len(data)] #cut the packge for data
data = data.decode()
info = data.split('!') #split the data into pats
name = info[0]
... | The main task of the code is to download a file, generate its hash, compare it with a predefined hash value, and if they mismatch, signal the server to repeat the download process recursively. | def download_file():
global addr
get_info()
get_file()
make_file()
my_hash = get_hash_file()
print("my hash ", my_hash)
print("data ha ", data_hash)
if check_hash(data_hash, my_hash) == False:
uServerSock.sendto("Repeat".encode(), addr)
download_file() |
def get_hash_file():
hash_md5 = hashlib.md5()
with open(file, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def make_package(b_data, number):
crc32_func = crcmod.mkCrcFun(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF)
crc... | The main task of the code is to generate a packaged data transmission containing a file's name, size, and hash value. The function concatenates these elements into a string, encodes it to bytes, packages it with a fixed identifier '00000', and sends the resulting data package for transmission. | def make_info():
info = name + '!' + size + '!' + get_hash_file()
b_data = info.encode()
package = make_package(b_data, '00000')
send_info(package) |
def make_dir():
number = 1
with open(name, "rb") as f:
buf = f.read(bufsize)
while (buf):
package = make_package(buf, str(number))
with open('packages/' + str(number), "wb") as p:
p.write(package)
p.close()
buf = f.read(bufsize)
... | The code's main task is to create directories and information, receive UDP data, check for a 'Repeat' message, and recursively restart the process if triggered, handling timeouts by printing an error. | def start():
make_dir()
make_info()
try:
data, addr = uClientSock.recvfrom(bufsize)
print('got final answer')
except socket.timeout:
print('last_timeout')
if data.decode() == 'Repeat':
start() |
def __read_line(fd):
global line_no_
line_no_ += 1
return fd.readline().strip()
def __get_text(source):
splits = source.split(':')
if len(splits) < 2:
return None
return splits[1].strip()
def _read_edge_weight_section(edge_weight_format, n_cities, fd):
if not n_cities:
raise ... | This function reads a TSP file from a given path and parses its contents into a structured dictionary. It extracts metadata like problem name, type, dimension, and edge weight formats, while also loading coordinate data or distance matrices based on the file's structure. The output dictionary organizes information unde... | def read_TSP_instance(filepath):
"""
Return a dictionary with info and data of tsp file.
----------
Parameters:
filepath: read a tsp file from filepath
----------
Returns:
instance: a tsp instance.
eg.
use instance['INFO'] and info keyword(upper) to get the na... |
def initialize_parameters(layer_dims):
np.random.seed(1)
params = {}
L = len(layer_dims)
for l in range(1, L):
params["W" + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) / np.sqrt(layer_dims[l - 1]) # * 0.01
params["b" + str(l)] = np.zeros((layer_dims[l], 1))
return ... | The code trains a neural network using gradient descent. It initializes parameters, iteratively performs forward propagation, computes the cost, executes backward propagation to calculate gradients, updates parameters with the learning rate, and logs costs every 100 iterations. Finally, it visualizes the cost reduction... | def run_model(X_train, Y_train, layer_dims, num_iterations, learning_rate=0.0075):
np.random.seed(1)
costs = []
# Weights (W) and intercepts (b) for each layer of Neural Network
params = initialize_parameters(layer_dims)
for i in range(0, num_iterations):
AL, caches = forward_propagation(... |
def add_location_features(df):
def count_invalid_chars(x):
if type(x) is float:
return 0
return len(re.findall(r'#|\$|\|%|\?|!|/|;|@|\+|\*|\d|:', x))
df['location'] = df['location'].fillna('')
df['invalid_location_character_count'] = df['location'].map(count_invalid_chars)
... | This function processes a dataset by adding features, encoding text (via embeddings/TF-IDF/BOW), cleaning text, and reducing dimensions. It copies the input DataFrame, applies location/manual features, transforms text based on `text_type`, drops specified columns, and optionally reduces dimensions. The output is a prep... | def process_dataset(df, encoding_type='binary', text_type='embeddings', target_dimensions=None, clean_text=False, use_spacy=True, use_manual_features=True, remove_target=True,tree=False):
df2 = df.copy()
global feature_names
if use_manual_features:
add_location_features(df2)
calculate_keyword_e... |
def aperture2image(Im, inst, algo, zcCol, lutx, luty, projSamples, model):
R = inst.apertureDiameter / 2.0
if (Im.type == 'intra'):
myC = - inst.focalLength * \
(inst.focalLength - inst.offset) / inst.offset / R**2
elif (Im.type == 'extra'):
myC = inst.focalLength * (inst.focalLe... | The main task of the code is to perform image compensation by transforming and interpolating pixel intensities based on a projection model. It validates input dimensions, constructs coordinate mappings, applies morphological operations to refine image regions, interpolates intensity values using a spline, and adjusts t... | def compensate(self, inst, algo, zcCol, oversample, model):
if ((zcCol.ndim == 1) and (len(zcCol) != algo.numTerms)):
raise Exception(
'input:size', 'zcCol in compensate needs to be a %d \
row column vector\n' % algo.numTerms)
sm, sn = self.image.shape
... |
def get_inits(X, device, lr, styles_Y):
gen_img = SynthesizedImage(X.shape).to(device)
gen_img.weight.data.copy_(X.data)
trainer = torch.optim.Adam(gen_img.parameters(), lr=lr)
styles_Y_gram = [gram(Y) for Y in styles_Y]
return gen_img(), styles_Y_gram, trainer
def extract_features(X, content_layers... | The code trains a neural network for style transfer, optimizing content and style features while applying learning rate decay. It computes content, style, and total variation losses, updates model parameters via backpropagation, logs loss values, and saves generated images every 50 epochs. The primary goal is to produc... | def train(X, contents_Y, styles_Y, device, lr, num_epochs, lr_decay_epoch):
X, styles_Y_gram, trainer = get_inits(X, device, lr, styles_Y)
scheduler = torch.optim.lr_scheduler.StepLR(trainer, lr_decay_epoch, 0.8)
for epoch in range(num_epochs):
trainer.zero_grad()
contents_Y_hat, styles_Y_ha... |
def aantalbolletjes():
repeater = "enabled"
while repeater == "enabled":
aantalBolletjesijs = int(input("Hoe veel bolletjes ijs wil je?: "))
if aantal > 0:
repeater = "disabled"
return aantalBolletjesijs
else:
WrongAnswer()
def WatVoorVerpakking():
... | This function handles user input for ordering ice cream balls, updating global totals for balls, containers (bowl or cone), and repetition. It retrieves the number of balls, checks the container type, increments respective counters, and determines if the user wants to order again, with error handling for invalid inputs... | def Particulier():
global aantal
global herhalen
global TotaleBolletjes
global totaalHoorntjes
global TotaalBakjes
global bakjeOfHoorntje
aantal = aantalbolletjes()
bakjeOfHoorntje = WatVoorVerpakking()
if bakjeOfHoorntje != "ERROR":
h... |
def initialize_session_state():
"""
This method sets the variables required for olaf to work in
streamlit session state.
"""
if "is_video_paused" not in st.session_state:
st.session_state["is_video_paused"] = False
if "frame_stopped_at" not in st.session_state:
st.session_state["... | The main task of the code is to handle both batch and single-video processing in a Streamlit application for audio-visual question answering (AVQA). It initializes session state, allows users to select YouTube videos, preprocesses them, plays the video with a custom player component, transcribes user questions from aud... | def main(frontend_dev):
"""
Olaf main application script.
"""
initialize_session_state()
is_batch_input = st.radio("Is batch processing?", ["No", "Yes"], horizontal=True)
is_batch = is_batch_input == "Yes"
# is_batch =False
# Setup for streamlit_player
_SUPPORTED_EVENTS = [
... |
def fetch(entries):
# Getting user input from text entries in GUI window, defaults are set above in [text_list]
search_term = clean_search_text(entries[0][1].get())
start_date = entries[1][1].get()
end_date = entries[2][1].get()
date_error_code = error_check_date(start_date, end_date)
... | The main task of the code is to process user inputs to search for keywords, scrape relevant web content and social media data within specified date ranges, perform NLP analysis on the collected text, and generate visualizations using graph functions. The pipeline includes error handling at each stage, with early termin... | def start_processing(entries):
search_term, start_date, end_date, pubs_per_month, tweets_per_month, number_of_keywords, user_api_key,\
user_service_url, error_code = fetch(entries)
if error_code == -1:
return
dict_of_urls, dict_of_text, error_code = web_scraping_for_keyword(search_term... |
def update_stop_words_with_keyword_permutations(keyword):
keyword_split = keyword.split()
if len(keyword) > len('Smoking Disorder'):
for word in keyword_split:
new_stop_words.extend(['@' + word.upper(),'@' + word.lower()])
new_stop_words.extend(['#' + word.upper(),'#' + word.lowe... | The function processes CSV files containing keyword data within a specified date range, converts them into dictionaries, and generates histograms visualizing the top non-stopwords. It updates stop words with keyword permutations first, then checks for matching files. If found, it creates histograms; if not, it returns ... | def turn_keywords_into_graphs(keyword, start_date, end_date):
update_stop_words_with_keyword_permutations(keyword)
file_list = find_keyword_files(os.path.join(nlp_keyword_path, keyword + '_' + start_date + '_'\
+ end_date + '_' + '*_nlp_keywords.csv'))
if f... |
def initiate_nlp_path():
keywords_path = 'nlp_keywords'
sentiments_path = 'nlp_sentiments'
if not os.path.exists(keywords_path):
os.mkdir(keywords_path)
if not os.path.exists(sentiments_path):
os.mkdir(sentiments_path)
return keywords_path, sentiments_path
def write_results_to_keywor... | The function processes text using NLP to extract keywords and sentiment analysis, then saves results to CSV files. It generates NLP output via an API, writes keywords to a '_nlp_keywords.csv' file, and sentiments to a '_nlp_sentiments.csv' file, using specified paths and parameters like API key, service URL, and keywor... | def get_nlp_keywords_and_sentiment_to_file(file_name, nlp_dictionary, nlp_type, user_api_key, user_service_url, number_of_keywords):
keywords_path, sentiments_path = initiate_nlp_path()
nlp_dict = nlp.generate_nlp_output(nlp_dictionary, nlp_type, user_api_key, user_service_url, number_of_keywords)
write_res... |
def openai_query(prompt, engine, temperature = 0.7, max_tokens = 128, top_p = 1, frequency_penalty = 0, presence_penalty = 0, stop = ["\n"]):
if engine in AVAILABLE_COMPLETION_ENGINES:
print("Using completion engine: " + engine)
response = openai.Completion.create(
engine=engine,
... | The main task of the code is to generate an AI response to a question, classify its content type (fiction/nonfiction), create an image descriptor, generate an image URL, summarize the interaction, and track associated costs. It handles errors, checks for nonresponsive answers, and returns the answer, image, descriptor,... | def construct_answer(question, engine=ENGINE_TO_USE_FOR_CHAT):
base_cost = 0
try:
base_cost, answer = openai_query(question, ENGINE_TO_USE_FOR_CHAT)
except Exception as e:
print("Error in openai_query: " + str(e))
return 0, "I had some issue. Please try again later."
detect_nonr... |
def print_players(self, index):
"""
Helper for display method. Creates and returns a string representing
the players on the space associated with index.
:param index: int [0..24] representing the index of a space in self._board
:return: a string representing the names of players
... | The code's main task is to print a formatted game board state to the console, displaying four columns: space names, property values/rents, owners, and player positions. It iterates through game spaces, gathers data, aligns columns using helper methods, and prints each row. Afterward, it displays each player's current b... | def display(self):
"""
Prints a simple depiction of the current state of the game to the console. Represents
the board as a vertical line with GO at the top. Data on spaces are separated into
multiple columns for readability. Does not align columns.
Column 1: Space names
... |
def get_unique_string(self, d, case):
string = ''
if case == 'partner':
string = d['partner_given_name'].lower() + ' ' + d['partner_family_name'].lower() + ' ' + str(d['partner_aga_id'])
elif case == 'attendee':
string = d['given_name'].lower() + ' ' + d['family_name'].lo... | The code automatically pairs unpaired attendees based on compatibility criteria (gender, rank, and preferences), prioritizing females in 'main' mode and allowing male-male pairs in 'waitlist' mode. It calculates potential matches, iteratively pairs attendees with the most compatible partners, and ensures the required n... | def auto_match_pairs(self, mode='main'):
t = time.time()
n = 0
# Calculate number of matches per player
auto_pair_list = []
if mode == 'main':
for p in self.attendee_list:
if p['signed_up'] and not p['paired'] and not p['signup']['has_partner']:
... |
def clear_all(self):
self.batch_clear(self.get_cell_string(STARTING_ROW, '420'))
def display_emails(self, emails):
str = ''
for e in emails:
str += e + ','
str += '\n'
print(str)
def append_player_info(self, values, player):
values.append(player['given_name'].... | The code updates player data sheets by sorting IAPGC pairs, displaying emails, managing pair lists, and updating spreadsheet cells with player info and statistics. It processes top IAPGC pairs, appends waitlist pairs, auto-matches players, and updates missing lists and stats, ensuring structured data presentation in sp... | def update_player_sheet(self):
self.clear_all()
self.iapgc_pair_list.sort(reverse=True, key=self._sort)
n = 1
n_iapgc = len(self.iapgc_pair_list)
# Get IAPGC emails
print('Emails of all IAPGC players: ')
iapgc_emails = []
for i in range(4):
... |
def decode_set(s):
return {k.decode('utf-8') for k in s}
def get_pid(process_name):
pid = redis.zrange(process_name, -1, -1)
if not pid:
pid = create_pid(process_name)
return pid
else:
return pid[0].decode('utf-8')
def get_pid_info(pid):
ans = redis.hgetall('process:' + str(p... | The function identifies running or initializing processes via Redis, aborts them by updating their status to 'aborted', logs an error message in Redis, and returns the count of processes terminated. It retrieves process names, checks their status, and modifies records accordingly. | def cleanup_pids():
allnames = decode_set(redis.smembers('process_names'))
n = 0
for process_name in allnames:
pid = get_pid(process_name)
if get_pid_info(pid)['status'] in ['running', 'init']:
n += 1
set_pid_status(pid, 'aborted')
msg = 'Process aborted b... |
def bootstrap():
guardian_count = ScratchVar(TealType.uint64)
i = SLOT_TEMP
return Seq([
Assert(Txn.application_args.length() == Int(3)),
Assert(Len(Txn.application_args[0]) %
Int(GUARDIAN_ADDRESS_SIZE) == Int(0)),
guardian_count.store(
Len(Txn.application_... | The main task of the code is to handle different application operations (create, update, delete, no-op) by checking the transaction's application ID and completion type. It executes corresponding functions like `bootstrap()`, `is_creator()`, or method-specific logic (`setvphash()`, `verify()`) based on the transaction'... | def vaa_processor_program():
handle_create = Return(bootstrap())
handle_update = Return(is_creator())
handle_delete = Return(is_creator())
handle_noop = Cond(
[METHOD == Bytes("setvphash"), setvphash()],
[METHOD == Bytes("setauthid"), setauthid()],
[METHOD == Bytes("verify"), ver... |
def getAlgodClient(self) -> AlgodClient:
return AlgodClient(self.ALGOD_TOKEN, self.ALGOD_ADDRESS)
def getTargetAccount(self) -> Account:
return Account.FromMnemonic(self.TARGET_ACCOUNT)
def getBalances(self, client: AlgodClient, account: str) -> Dict[int, int]:
balances: Dict[int, int] = dict()
... | The code initializes an Algorand client, retrieves a target account, checks its balance, funds it if the balance is below 100 million microAlgos, and then prints the updated balance. The main task is to ensure the target account has sufficient funds for transactions by checking and replenishing its balance as needed. | def setup(self):
self.client = self.getAlgodClient()
self.target = self.getTargetAccount()
b = self.getBalances(self.client, self.target.getAddress())
if (b[0] < 100000000):
print("Account needs money... funding it")
self.fundTargetAccount(self.client, s... |
def parse_grid(text: str) -> tuple[Grid, Node, Node]:
'''Parse input text into a grid'''
rows: list[str] = text.split('\n')
grid: list[list[Node]] = []
start: Node = Node((-1, -1), 0, 0, 0, None)
end: Node = Node((-1, -1), 0, 0, 0, None)
for i, row in enumerate(rows):
col = []
f... | The code reads a grid from a file, parses it into a grid and start/end nodes, then uses A* algorithm to find paths from the start to end. It iteratively replaces 'S' with 'a' in the grid text, recalculates paths, and collects results in a set. Finally, it prints the minimum path length from all computed paths, solving ... | def main():
with open('input.txt', 'r') as file:
text: str = file.read()
parsed_grid: tuple[Grid, Node, Node] = parse_grid(text)
grid: Grid = parsed_grid[0]
start: Node = parsed_grid[1]
end: Node = parsed_grid[2]
paths_from_a: set[int | float] = set()
# VERY ... |
def init_grid(file_text: str) -> None:
global grid, start, grid_dimensions
lines = list(map((lambda xs: xs.split('->')), file_text.splitlines()))
# Finding width of the grid
x_values: list[int] = list(map(int, findall('(\d+),', file_text)))
max_x: int = max(x_values)
min_x: int = min(x_values)... | The code simulates sand falling in a grid-based environment. It calculates two values: the number of sand units that fall before blocking (without an infinite floor) and the number before blocking when an infinite floor is added. The function returns these counts as a tuple. | def solve(file_text: str) -> tuple[int, int]:
global grid, grid_dimensions
units_of_sand_1: int = 0
units_of_sand_2: int = 0
init_grid(file_text)
while (x := drop(start, False)) == 1:
units_of_sand_1 += 1
print_grid()
init_grid(file_text)
grid.append([True] * grid_dimensions[... |
def create_folds(self, n_folds, stratified):
"""
Creates the folds for the cross validation.
Parameters
----------
n_folds (Int > 1): The number of folds to be used in the cross validation
stratified (Bool): If True the folds are stratified
"""
if type(n... | This function performs hyperparameter tuning via grid or random search, evaluating model performance across parameter combinations using cross-validation. It generates parameter combinations, splits data into folds, assesses each set's accuracy, and stores results. Options include stratified splitting, parallel process... | def fit(
self,
X,
y,
parameters_grid,
n_folds=1,
stratified=False,
test_size=0.2,
verbose=True,
parallel=False,
random_search=False,
n_random=10,
get_eta=False,
):
"""
Performs the grid search.
P... |
def _flatten(self, d):
"""
Flatten the gradient d.
Parameters
----------
d (list) : direction of descent
Returns
-------
d_flat (np.array) : flattened direction of descent
"""
d_flat = d[0]["weights"].flatten()
d_flat = np.concat... | This function computes the step size for parameter updates in an optimization algorithm. It calculates gradients via forward-backward passes, computes a beta value using specified formulas (FR, HS+, PR+), determines the search direction `d`, performs a line search to find step size `alpha`, and updates model parameters... | def _step(self, X, y):
"""
Compute the step size and update the parameters of the model.
Parameters
----------
X (np.array) : input data
y (np.array) : output data
"""
self._current_params = copy.deepcopy(self.model.get_params())
J, grad_params... |
def _get_non_blocking_server_socket(addr: tuple, max_connections: int) -> socket.socket:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(False)
server.bind(addr)
server.listen(max_connections)
return server
def handle_readables(self, readables, server):
for res... | This code sets up a non-blocking server socket, monitors incoming connections using `select.select`, processes readable sockets via `handle_readables`, and manages resource cleanup on shutdown. It runs in a loop with a 2-second delay to limit CPU usage, logging server status and handling keyboard interrupts gracefully. | def run(self):
server_socket = _get_non_blocking_server_socket(self.server_address, self.MAX_CONNECTIONS)
self.INPUTS.append(server_socket)
rospy.loginfo("Server is running...")
try:
while self.INPUTS:
readables, writables, exceptional = select.select(self.I... |
def evaluate(self, token_class):
# return flag used for error checking
success = True
if self.MODE_SINGLE_LINE_COMMENT and token_class in LINE_BREAK: self.MODE_SINGLE_LINE_COMMENT = False # if a single line comment has been detected PRIOR, disable self.MODE_SINGLE_LINE_COMMENT if a ne... | The main task of the code is to process a list of lexemes by iterating through them, validating each token's type, and printing recognized tokens (excluding line breaks and comments) with their values. It manages line counting for comments, skips invalid tokens, and advances the cursor to process the next token. | def traverse_tokens(self):
# reset cursor
self.cursor = 0
# keep iterating until end of lexeme list
while(self.cursor != self.length):
# get the token
current_token = self.lexemesList[self.cursor]
# stop the loop if an error has ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.