dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_table_id_field(self, table: str, do_error=False) -> str:
"""
Takes a table and returns the name of the field/column marked as a `PRIMARY KEY`. (This function assumes that there is only ONE field marked as a `PRIMARY KEY`).
Parameters
----------
table : str
Na... | This function retrieves a specific database entry by ID from a given table. It validates the table's existence, constructs an SQL query to fetch the entry, checks for exactly one result, and returns a DatabaseEntry object. Errors are raised for invalid tables, duplicate IDs, or missing entries. | def get_entry_by_id(self, table, ID) -> DatabaseEntry:
"""
Get table entry by id.
Parameters
----------
table : str
Name of the table.
ID :
The entry id.
"""
id_field = self.get_table_id_field(table, do_error=True)
if n... |
def get_table_raw(self, name: str, get_only = None) -> list:
"""
Returns all entries in a table as a list of tuples.
Parameters
----------
name : str
Name of the table.
get_only : list, optional
Can be set to a list of column/field names, ... | The function retrieves all entries from a specified database table, optionally filtering columns via `get_only`, and returns them as a generator of `DatabaseEntry` objects. It uses `get_table_raw` to fetch raw data, then converts it into structured entries using column names. Note: inefficient for large databases due t... | def get_table(self, name: str, get_only=None) -> list:
"""
Returns all entries in a table as a table (generator of DatabaseEntry). This function loops over all entries in the table, so it is not the best in very big databases.
Parameters
----------
name : str
Name of... |
def get_table_names(self) -> list:
"""Returns the names of all tables in the database."""
res = self.conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
names = []
for name in res:
names.append(name[0])
return(names)
def get_table_raw(self, name: str, ... | The code defines the equality operator (`__eq__`) to compare two objects by checking if they have identical table structures. It first verifies that both objects have the same table names. If so, it iterates through each table, comparing their raw data and column definitions. If any mismatch is found, it returns `False... | def __eq__(self, other: object) -> bool:
tables = self.get_table_names()
if tables != other.get_table_names():
return(False)
for table in tables:
if self.get_table_raw(table) != other.get_table_raw(table):
return(False)
elif self.get_table_col... |
def is_table(self, table_name: str) -> bool:
"""
Check if database has a table with a certain name.
Parameters
----------
table_name : str
Name to check.
"""
if table_name in self.get_table_names():
return True
return Fal... | This function adds an entry to a database table, either via a DatabaseEntry object or a dictionary with a specified table name. It validates entry fields, fills missing values with null if requested, inserts the data, and returns the generated primary key ID. It also handles error checking for table existence, field mi... | def add_entry(self, entry, table = None, fill_null=False, verbose=False) -> None:
"""
Add an entry to the database by passing a DatabaseEntry, or with a dictionary and specifying a table name.
Returns the id of the added DatabaseEntry in the table, or `None` if table does not contain a primary... |
def get_table_id_field(self, table: str, do_error=False) -> str:
"""
Takes a table and returns the name of the field/column marked as a `PRIMARY KEY`. (This function assumes that there is only ONE field marked as a `PRIMARY KEY`).
Parameters
----------
table : str
Na... | This function updates a database entry using either a DatabaseEntry object or a dictionary. It validates the table name, checks field compatibility with the table schema, handles null values, and executes an SQL UPDATE query. If using a dictionary, the table name must be provided. The `part` parameter allows partial up... | def update_entry(self, entry: dict, table=None, part=False, fill_null=False, verbose=False) -> None:
"""
Update entry in database with a DatabaseEntry, or with a dictionary + the name of the table you want to update.
Parameters
----------
entry : DatabaseEntry/dict
D... |
def advance(self):
# print('Advancing through tokens list...')
self.token_index += 1
if self.token_index < len(self.tokens):
self.current_token = self.tokens[self.token_index]
def Field(self):
print('Adding Field')
# Compound node
# Branching based on Variabl... | This function parses the left-hand side (LHS) of an assignment or expression by handling three cases: 1) 'output' keyword, 2) Field node with brackets, or 3) Var node without brackets. It constructs a syntax tree node with appropriate children based on token types, increments a node counter, and returns the correspondi... | def LHS(self):
print('Adding LHS')
# Compound node
# Branching based on types
# 1 - output
# 2 - Field
# 3 - Var
# Children structure:
# If branch 1: simply the keyword token
# If branch 2: the Field node
# If branch 3: the Var node
... |
def query_webservice_user(webservice_user):
#query the server
conn = pymssql.connect('a2bserver.database.windows.net', 'A2B_Admin', 'v9jn9cQ9dF7W', 'a2bcargomation_db')
cursor = conn.cursor(as_dict=True)
cursor.execute("SELECT TOP (1) * FROM [dbo].[user_webservice] WHERE [user_id] = %s", webservice_user... | The code processes uploaded files (PDFs or images) to extract invoice data by classifying pages, splitting documents, applying recognition models, and compiling results with metadata. It handles encryption, page-specific processing, and combines multi-page outputs, then prepares structured payloads for further handling... | def predict(file_bytes, filename, process_id, user_id, uploaded_by, date_uploaded, shipment_num, file_url=""):
predictions = {}
shared_invoice = {}
classifier_count = collections.defaultdict(list)
user_query = query_webservice_user(user_id)
ext = file_ext(filename)
if ext == "pdf":
ima... |
def validMoves(board: np.array):
result = [idx for idx, value in enumerate(board[0]) if value == 0]
return np.array(result)
def scoreBoard(board, depth):
player_score = scorePlayerBoard(board)
score = player_score - depth/1000
if isWin(board):
score = 4
if isLoss(board):
score = ... | This code implements the alpha-beta pruning algorithm for game tree search, optimizing decision-making by recursively evaluating node values while pruning branches that don't affect the final outcome. It tracks move importance in 'history' by incrementing counts when pruning occurs, with depth-dependent weights. The fu... | def alphaBeta(node, depth, alpha, beta, history=None, max_depth=DEPTH):
if depth == max_depth:
history = {move: 0 for move in validMoves(node.board)}
if depth == 0 or node.isTerminal():
return scoreBoard(node.board, depth)
if node.isMaximizingPlayer():
value = -inf
for chil... |
def make_queens(board):
queens = []
for j in range(QUEENS):
for i in range(QUEENS):
if board[j][i] == 1:
queens.append([j, i])
return queens
def find_best_board(queens):
min_attack = 100
best_queens = copy_list(queens)
queens_c = copy_list(queens)
for i i... | The code implements a gradient descent algorithm to solve the N-Queens problem by iteratively minimizing attacking queen pairs. It generates initial queen positions, evaluates improvements, updates the board until no further reduction in conflicts is possible, and returns True if a conflict-free solution is achieved, o... | def gradient_search(board):
current_queens = make_queens(board)
while True:
best_board = find_best_board(current_queens)
best_queens = make_queens(best_board)
if count_attack(current_queens) == count_attack(best_queens):
break
current_queens = make_queens(best_board)
... |
def removePun(message):
"""Function which removes the following punctuations (“,”,“.”,“?”,“!”,
“;”,“:”)"""
newMessage = ""
for i in message:
if i not in (",",".","?","!",";",":"):
newMessage += i
return newMessage
def encodeM(lst):
if lst == []:
return []
else:
... | The main task of the code is to process an input string by removing punctuation, encoding it into a list of elements using `encodeM`, decoding it back with `decodeM`, and printing the original string, cleaned version, encoded list, decoded list, and the encoded message joined by spaces. The process demonstrates string ... | def main(s):
slst = removePun(s)
eList = encodeM(stringList(slst))
dList = decodeM(eList)
print(f"Given string => {s}")
print(f"Punctuation removed => {slst}")
print(f"List Encoded => {eList}")
print(f"List Decoded => {dList}")
print("Encoded Message", ' '.join(eList)) |
def _check_fleet_edges(self):
"""Respond appropriately if any aliens have reached an edge"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""Respond to the ship being hit by an al... | The function `_update_aliens` updates alien positions, checks if the alien fleet hits screen edges, detects collisions between the player's ship and aliens (triggering a ship-hit response), and verifies if any aliens reach the screen's bottom, initiating appropriate game logic for these events. | def _update_aliens(self):
"""Check if the fleet is at an edge, then
update the positions of all aliens in the fleet"""
self._check_fleet_edges()
self.aliens.update()
# This takes two arguments, a sprite and a group
if pygame.sprite.spritecollideany(self.ship, self.aliens... |
def _check_events(self):
"""A helper method to check for game events. Helper methods have
a single leading _ to indicate that it is a helper. These are not
usually called through an instance."""
# Watch for keyboard and mouse events
# event.get() returns a list of events
... | The main task of the code is to initialize the game loop by loading the theme song, maintaining the game's frame rate, handling events, updating game elements (ship, bullets, aliens) when active, and rendering the screen. It ensures continuous gameplay with music playback and dynamic updates based on game state. | def main(self):
"""Start the main loop of the game"""
# Load and play the theme song
self.pygame.mixer.music.load(self.sound.theme_song)
self.pygame.mixer.music.set_volume(self.settings.music_volume)
self.pygame.mixer.music.play(-1)
while self.game_running:
s... |
def _line_by_line(self):
return '\n'.join([self._string[i:i + self._size]
for i in range(0, self._len, self._size)])
def get_head(self):
""" Return the point where your snake head is, or None if not found."""
points = set()
points.update(self._find_all(Element('... | The main task of the code is to generate a human-readable string representation of a game state, combining the board layout, snake head position, apple locations, stones, and walls using formatted string interpolation. The method aggregates these elements into a structured output for display or logging purposes. | def to_string(self):
return ("Board:\n{brd}\nSnake head at: {shd}\nApples at: {apl}\nStones at: {bad}\nWalls at: {wal}\n"
.format(brd=self._line_by_line(), shd=self.get_head(),
apl=self.get_apples(), bad=self.get_stones(),
wal=self.get_walls())
... |
def load_run(entity_run_file: str) -> Dict[str, Dict[str, float]]:
ranking: Dict[str, Dict[str, float]] = {}
with open(entity_run_file, 'r') as f:
for line in f:
line_parts = line.split()
query_id = line_parts[0]
doc_id = line_parts[2]
doc_score = float(li... | The main task of the code is to rank aspects using precomputed entity rankings. It loads input data and an entity run file, ranks aspects based on top-K entities, and saves the resulting rankings to an output file. The script uses command-line arguments for data paths, entity rankings, output directory, and the number ... | def main():
parser = argparse.ArgumentParser("Rank aspects using entity ranking.")
parser.add_argument("--data", help="Data file.", required=True, type=str)
parser.add_argument("--entity-run", help="Entity run file.", required=True, type=str)
parser.add_argument("--save", help="Output directory.", requi... |
def get_candidate_entity_set(example: AspectLinkExample) -> Set[str]:
candidate_aspects: List[Aspect] = example.candidate_aspects
entities: List[str] = []
for aspect in candidate_aspects:
entities.extend(utils.get_entity_ids_only(aspect.aspect_content.entities))
return set(entities)
def score_en... | This function ranks entities based on their contextual relevance using precomputed embeddings. It processes each example in the input file, scores candidate entities against context entities, sorts them by score, and formats results into run file strings for output. | def rank_entities(
data_file: str,
context_type: str,
entity_embeddings: Dict[str, List[float]]
) -> List[str]:
total = totals[os.path.basename(data_file)]
run_file_strings: List[str] = []
for example in tqdm(utils.aspect_link_examples(data_file), total=total):
query_id: str... |
def op_val(self, a, b, op):
if op == '+=':
a[0] += b[0]*pow(10, b[1]-a[1])
self.fix_val(a)
elif op == '-=':
a[0] -= b[0]*pow(10, b[1]-a[1])
self.fix_val(a)
elif op == '>=':
c = a[1]*1000 + a[0]
d = b[1]*1000 + b[0]
... | The code simulates automatic gameplay by accumulating resources (a) over 'sec' seconds, then using them to upgrade attributes and potentially defeat enemies. It repeatedly checks if resources meet upgrade costs, deducts costs, levels up attributes, and triggers enemy upgrades if a victory condition is met. The loop con... | def auto_play(self, sec):
a = self.elem[self.assetall_key]
b = self.elem[self.asset_key]
self.elem['play_sec'] += sec
for i in range(sec):
self.op_val(a, b, '+=')
cont = True
while cont:
cont = False
for key in self.attr_name:
... |
def solve_sudoku(board, find_ans_count=1):
"""
find the ans of sudoku
param find_ans_count: int, the ans count you want
"""
gv.find_ans_count = find_ans_count
gv.ans = []
gv.call_count = 0
gv.call_level = 0
gv.call_level_max = 0
t1 = time.time()
__solve_sudoku(board)
t2... | The function `test_sudoku` tests a Sudoku solver by solving the given board, measuring execution time, and tracking recursive calls. It prints the number of valid solutions, execution duration, and recursion depth. For each solution, it verifies validity and prints the grid. The main task is to evaluate the solver's pe... | def test_sudoku(board, find_ans_count=1):
"""
test sudoku, including solve, verify and print
"""
ans, exec_sec, call_count, call_level_max = solve_sudoku(board, find_ans_count)
print(f'ans count={len(ans)}, exec sec={exec_sec:.2f}, call count={call_count}, call_level_max={call_level_max}')
... |
def _add_intercept(self, X: pd.DataFrame) -> pd.DataFrame:
"""Add an intercept column of ones to the feature matrix.
Params:
X (pd.DataFrame): The feature matrix.
Returns:
pd.DataFrame: The feature matrix with an intercept column.
"""
if 'intercept' not... | The code implements stochastic gradient descent (SGD) to train a logistic regression model. It initializes weights, computes log loss with regularization, updates weights using mini-batches and gradients, and optionally tracks metrics like accuracy or ROC AUC. The model iteratively minimizes loss by adjusting weights v... | def fit(self, X: pd.DataFrame, y: pd.Series, verbose=False):
"""Fit the logistic regression model on the provided data.
Params:
X (pd.DataFrame): The feature matrix.
y (pd.Series): The target vector (0 or 1).
verbose (bool): Flag to print intermediate results (defaul... |
def find_unknown_scramble(self, length):
if self.known_scrambles.get(length) is None:
self.known_scrambles[length] = []
if len(self.known_scrambles.get(length)) is 18**length:
return None
return self.find_unknown_scramble_recursively(length, [])
def try_to_solve(self, cub... | The code trains a system to solve Rubik's cube scrambles of varying lengths by iterating through scramble lengths, generating random cubes, applying unknown scrambles, attempting solutions, and recording successful solves. It tracks success rates per length and overall, while persisting known scrambles to avoid retrain... | def train(self, start_length=TRAIN_START_LENGTH, end_length=TRAIN_UNTIL_LENGTH, cases=TRAIN_CASES, optimal=False):
successful_trainings = 0
print("Start training...")
for i in range(start_length, end_length + 1):
print("Training scrambles with length " + str(i) + "...")
s... |
def get_available_moves():
valid_moves = []
for valid_move in ["r", "l", "f", "b", "u", "d"]:
valid_moves.append(valid_move)
valid_moves.append(valid_move + "'")
valid_moves.append(valid_move + "2")
return valid_moves
def inverse_move(move):
if move is None:
return None
... | The code generates a random Rubik's cube scramble of specified length, ensuring no consecutive inverse moves, and returns a shortened version. | def get_random_scramble_by_length(length):
if length is None or type(length) is not int or length <= 0:
raise Exception("Length must be valid int")
scramble = []
for i in range(0, length):
moves = []
moves.extend(get_available_moves())
if len(scramble) > 0:
moves.... |
def __reset_args(self):
self._prefer_compressed_address = True
self._words = None
self._passphrase = ''
self._seed = None
self.__set_private_key(None)
self._master_chain_code = None
def __validate_wallet_args(self, mnemonic: str = None, language: str = 'english', strength... | The main task of the code is to initialize a wallet object by validating input parameters and constructing it based on provided data (e.g., mnemonic, seed, private key, or WIF). It handles different creation paths, sets network and derivation settings, and defaults to generating a new wallet if no explicit data is prov... | def __init__(self, mnemonic: str = None, language: str = 'english', strength: int = 128, passphrase: str = '', private_key: bytes = None, chain_code: bytes = None, seed: bytes = None, main_net: bool = True, derivation_path: DerivationPath = None, fingerprint_parent_key: bytes = None, wif: str = None) -> None:
s... |
def extract_preprocessed_recording(timeseries, sorting_params, preprocess_params):
sampling_frequency = sorting_params.sampling_frequency
num_channels = timeseries.shape[0]
timeseries_f = preprocess_timeseries(timeseries, preprocess_params, sampling_frequency)
geom = sorting_params.get_geometry(num_chan... | The pipeline processes a timeseries by preprocessing, sorting spikes using the MS4 algorithm, post-processing the sorted data, and exporting parameters for Phy, a spike sorting tool. It handles input/output operations and applies specified parameters at each stage to analyze neural recordings. | def pipeline(timeseries, io, preprocess_params, sort_params, postprocess_params):
recording_f = extract_preprocessed_recording(timeseries, sort_params, preprocess_params)
sorter = sort_recording_ms4(recording_f, sort_params, io)
postprocess_recording(recording_f, sorter, io, preprocess_params, sort_params, ... |
def open_browser():
global driver
options = Options()
# options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(r'C:\drivers\chromedriver', options=options)
driver.maximize_window()
driver.get('https://www.google.com')
sleep(2)
driver.find_element(By.XPATH, '//div[tex... | The main task of the code is to search for a given text, open a browser, and scrape a specified number of business entries. It takes user input for the search term and number of actions, performs the search, iterates to scrape new businesses, checks for errors during scraping, and terminates the browser session. The co... | def main():
# params = sys.argv[1:]
# if len(params) != 1:
# print('')
# print('#####################################################################')
# print('### ERR: Invalid Search - Search should have exactly 1 parameter. ###')
# print('####################################################################... |
def _is_dets_and_embeds_ok(self, seq_path, seq_det_df_path):
# Verify the processed detections file
node_embeds_path = osp.join(seq_path, 'processed_data/embeddings', self.config.det_file,
self.config.node_embeddings_dir)
reid_embeds_path = osp.join(seq_path, ... | The function either loads preprocessed detection data from a specified path if it exists and is valid, or processes raw detections using a feature embedding model and stores the result. It returns a DataFrame containing detection data along with sequence information. | def load_or_process_detections(self):
"""
Tries to load a set of processed detections if it's safe to do so. otherwise, it processes them and stores the
result
"""
# Paths
seq_path = osp.join(self.dataset_path, self.seq_name)
seq_det_df_path = osp.join(seq_path, ... |
def gen_noise(dim=224, nex = 1):
""" Generate some noise to initialize
"""
input_img_data = tf.random.uniform((nex, dim, dim, 3))
return tf.Variable(tf.cast(input_img_data, tf.float32))
def get_opt_function():
""" This function returns the optimizer function. This is just necessary because of tensorflow weirdness.... | The function optimizes images to maximize activation of specific filters in a neural network model, using gradient ascent with an Adam optimizer. It generates initial noise, iteratively refines images through optimization steps, applies upsampling, and converts color channels. The process returns optimized images and l... | def optimize_filter(
submodel,
layer_name,
filter_index,
filters_shape,
steps=20,
lr=0.01,
layer_dims=2,
n_upsample=1,
sigma=0,
upscaling_factor=1.1,
soft_norm_std=15,
single_receptive_field=True,
norm_f = "soft_norm",
normalize_grads = True
):
""" This pulls together the steps for optimizing the image, ... |
def get_name(self, token):
if token.is_name():
return token.value
raise Exception(f"Expected TokenType.NAME\nGot {token.type}")
def get_duration(self):
token = self.tokenizer.next_token()
if not token.is_takes():
raise Exception(f"Expected TokenType.TAKES\nGot {to... | The code's main task is to generate a Task object using the next available token from a tokenizer. If no token exists, it returns None; otherwise, it constructs a Task instance by retrieving the token's name, duration, and dependencies through helper methods. | def get_task(self):
token = self.tokenizer.next_token()
if token is None:
return None
else:
return Task(self.get_name(token), self.get_duration(), self.get_dependencies()) |
def perform_and_not_query(operand_1, operand_2, dictionary, postings_fo):
"""
Returns the QueryResult containing doc IDs that are in the postings list of
operand_1 but not operand_2.
list_1 AND NOT list_2 - All elements of list_1 that are not present in list_2
"""
(list_1, skip_1) = get_query_... | The function evaluates a Reverse Polish Notation (RPN) search query to retrieve unique document IDs matching the query. It processes tokens using a stack, handling logical operators (AND, OR, NOT) and special cases like 'AND NOT' or 'NOT NOT'. Helper functions perform specific operations, and the result is returned as ... | def perform_search_query(query, dictionary, postings_fo):
"""
Returns list of unique document IDs that match the input search query
in Reverse Polish Notation.
"""
stack = []
i = 0
while i < len(query):
token = query[i]
# TODO: optimisation using De Morgan's rule, merge sma... |
def center_to_corner_box3d(centers,
dims,
angles=None,
origin=(0.5, 1.0, 0.5),
axis=1):
"""Convert kitti locations, dimensions and angles to corners.
Args:
centers (np.ndarray): Locations in kitt... | This function checks which 3D points lie inside rotated 3D bounding boxes (rbbox) and returns indices of points within each box. It converts rbbox centers/dimensions to corners, generates convex surfaces, and uses JIT-compiled checks to determine point inclusion. | def points_in_rbbox(points, rbbox, z_axis=2, origin=(0.5, 0.5, 0)):
"""Check points in rotated bbox and return indices.
Note:
This function is for counterclockwise boxes.
Args:
points (np.ndarray, shape=[N, 3+dim]): Points to query.
rbbox (np.ndarray, shape=[M, 7]): Boxes3d with ro... |
def build_dataset(cfg, default_args=None):
# from mmdet3d.datasets.dataset_wrappers import CBGSDataset
from mmdet.datasets.dataset_wrappers import (ClassBalancedDataset,
ConcatDataset, RepeatDataset)
if isinstance(cfg, (list, tuple)):
dataset = Concat... | The code generates a ground truth (GT) database from 3D annotated datasets (e.g., Kitti, NuScenes, Waymo) by extracting point cloud data, bounding boxes, and metadata (e.g., object names, positions, masks). It processes each sample, saves object-specific point clouds and image patches, and stores structured information... | def create_groundtruth_database(dataset_class_name,
data_path,
info_prefix,
info_path=None,
mask_anno_path=None,
used_classes=None,
... |
def create_nuscenes_infos(root_path,
info_prefix,
version='v1.0-trainval',
max_sweeps=10):
"""Create info file of nuscene dataset.
Given the raw data, generate its related info file in pkl format.
Args:
root_path (str): ... | This function prepares the nuScenes dataset by generating '.pkl' info files, 2D annotations, and a groundtruth database. It handles dataset versions (train/val/test), creates info files with specified prefixes, exports 2D annotations for training/validation splits, and constructs the groundtruth database using the prov... | def nuscenes_data_prep(root_path,
info_prefix,
version,
dataset_name,
out_dir,
max_sweeps=10):
"""Prepare data related to nuScenes dataset.
Related data consists of '.pkl' files recording basic in... |
def nostr(x):
return anone(x) or ablank(x)
def astr(x):
return isinstance(x, str) or isinstance(x, str)
def verbose():
try:
return args and args.verbose
except NameError:
return False
except AttributeError:
return False
def prcmd(cmd):
print('system(%s)' % ', '.join(['"%s... | The function `ppcmd` processes an input command by ensuring it is a list (wrapping a string in a list if necessary), checks for emptiness, and optionally prints the command if verbose mode is enabled, then returns the processed command. | def ppcmd(cmd):
assert(not nostr(cmd))
# cmd = [] if anone(cmd) else cmd
cmd = [cmd] if astr(cmd) else cmd
if verbose():
prcmd(cmd)
return cmd |
def flatten_once(xs):
return [item for sublist in xs for item in iterable(sublist)]
def is_iterable(x):
try:
if is_str(x):
return False
xit = iter(x)
return True
except TypeError as te:
return False | This function recursively flattens a nested iterable structure by repeatedly applying a single-level flattening operation until no more nested iterables remain, provided the 'recursive' parameter is True. If 'recursive' is False, it only performs a single-level flattening. | def flatten(xs, recursive=True):
ys = flatten_once(xs)
if recursive:
for y in ys:
if is_iterable(y):
return flatten(ys, recursive=True)
return ys |
def nostr(x):
return anone(x) or ablank(x)
def ppcmd(cmd):
assert(not nostr(cmd))
# cmd = [] if anone(cmd) else cmd
cmd = [cmd] if astr(cmd) else cmd
if verbose():
prcmd(cmd)
return cmd
def astr(x):
return isinstance(x, str) or isinstance(x, str)
def no(xs):
return (not xs) or (l... | The function executes a system command, checks for errors, and returns the output. If the command is empty, it returns an empty string. It runs the command, captures output and errors, and if errors occur, writes them to stderr and exits with a specified code. Otherwise, it returns the command's output. | def syscmd(cmd, exitcode=1):
if nostr(cmd):
return ''
out, err = command(ppcmd(cmd))
if astr(err) and not no(err):
sys.stderr.write(err)
sys.exit(exitcode)
return out |
def nostr(x):
return anone(x) or ablank(x)
def syscmd(cmd, exitcode=1):
if nostr(cmd):
return ''
out, err = command(ppcmd(cmd))
if astr(err) and not no(err):
sys.stderr.write(err)
sys.exit(exitcode)
return out
def ppcmd(cmd):
assert(not nostr(cmd))
# cmd = [] if anone... | The function executes two commands in a pipeline. If either input is not a string, it runs the other command directly. Otherwise, it chains the output of the first command as input to the second, captures the result, handles errors by writing them to stderr and exiting if necessary, then returns the output of the pipel... | def pipecmds(lhs, rhs):
if nostr(lhs):
return syscmd(rhs)
if nostr(rhs):
return syscmd(lhs)
p1 = subprocess.Popen(ppcmd(lhs), stdout=subprocess.PIPE)
p2 = subprocess.Popen(ppcmd(rhs), stdin=p1.stdout, stdout=subprocess.PIPE)
out, err = p2.communicate()
if astr(err) and not no(err... |
def get_zillow_data():
'''
This function reads in zillow data from the Codeup database, writes data to
a csv file if a local file does not exist, and returns a df.
'''
if os.path.isfile('zillow.csv'):
# If csv file exists read in data from csv file.
df = pd.read_csv('zillow.... | The main task of the code is to acquire, prepare, split, and scale Zillow housing data into train, validate, and test datasets. It combines functions to clean data, split it into subsets, and apply scaling for modeling. The process ensures data readiness for analysis or machine learning by returning structured, normali... | def wrangle_zillow():
'''
Combines all previously defined functions in the module to return
train, validate, and test datasets.
'''
# Acquire
df = get_zillow_data()
# Prepare ###
df = prepare(df)
### Split ###
train, validate, test = split_data(df)
### Scale ###
train, v... |
def showFive(list1, i):
listLen = len(list1)
if listLen == 0:
i = 0
else:
i = i % listLen
clear()
j = i
print("--- Artist Search Result---")
print(" id | name | nationality | number of songs")
while j<i+5 and j<listLen:
print(list1[j][0:-1])
j+=1... | This function allows scrolling through a list of artists (5 items at a time) using 'w' (up) or 's' (down). It lets users select an artist by ID (input '1'), validates the ID, and navigates to artist info. If any action leads to returning to the main menu, it returns True. Input other than 'w', 's', or '1' also returns ... | def artistScrolling(uid,list1, i, conn):
c = conn.cursor()
if i < 0:
i = 0
if i+5 > len(list1):
i = len(list1)-5
showFive(list1, i)
action = input("Enter:\nw to scroll up\ns to scroll down\n1 to select an artist\nanything else to return to the main menu: ").lower()
if action=='w'... |
def init_weights(self, shape: tuple, weights: tuple = None):
if weights:
w, b = weights
w = np.array(w)
b = np.array(b)
else:
w = np.zeros(shape)
b = np.zeros(shape[1])
self.weights['w'] = w
self.weights['b'] = b
def _optimize_(... | The code trains a neural network model by initializing weights, performing forward propagation, computing the cost function, and executing backpropagation via `_optimize_`. It evaluates model performance on training and test datasets, predicts outcomes using trained weights, and calculates accuracy as 100% minus the me... | def train(self, x_train_t, y_train_t, x_test_t, y_test_t, sample_weights: tuple = None):
"""
:param x_train_t: train data of size (number of examples, number of features)
:param y_train_t: train result data of size (number of examples, 1)
:param x_test_t: train data of size (number of e... |
def Fitness(populus,max):# fitness computed by getting most played genes
fitness=0
print("Calculating Fitness: ")
p1 = 0
p2 = 0
r=0
mutant = 0
while(r<int(round(max/8))):
for c in range(len(populus[0])):
if(populus[r][c] == populus[r+1][c]):
p1 += 1
... | This code implements a Genetic Algorithm (GA) to iteratively reduce a population size by computing fitness values per generation until only three individuals remain. It records generation numbers and fitness scores, processes final results, writes them to a text file, and plots the fitness of the best individual agains... | def GA(population,max):#Genetic Algorithm
generation=[]
i=0
fitness=[]
final=[]
while(len(population)>3):#fitness computed until population is left with 3 indviduals
i+=1
generation.append(i)
fitness.append(Fitness(population,len(population)))
cvs=[]
final=(finalForm... |
def make_mst(self):
"""
make_mst: mst will follow the same structure of edges
"""
if self.m == self.n - 1:
self.mst = self.edges
return
self.mst = {i + 1: {} for i in range(self.n)}
priority_queue = sorted(self.edges_general, key=lambda x: x[2])
... | The main task of the code is to process multiple queries by first constructing a minimum spanning tree (MST), generating ancestor relationships, and mapping node depths. It then answers each query using these precomputed structures, returning results along with timing metrics for each step (MST creation, ancestor retri... | def itineraries_v2(self, queries):
t1 = time.perf_counter()
self.make_mst()
t2 = time.perf_counter()
self.get_ancestors()
t3 = time.perf_counter()
self.get_depth_map()
t4 = time.perf_counter()
arr = []
for i in queries:
arr.append(self.... |
def kdtree(points, depth = 0 ): # Build the kd tree and map all points starting with x axis and then y axis and going back and forth
n = len(points)
if n<=0:
return None
axis = depth % k
sorted_points = sorted(points, key = lambda point: point[axis])
... | The code counts the number of drones that are not in conflict with any other drone, using a KD-tree for efficient nearest neighbor search. It checks if the distance from each drone to the closest point in the tree exceeds the squared conflict radius, incrementing the count if true. The result is the number of drones no... | def count_conflicts(drones, conflict_radius):
drone_conflicts = 0
tree = kdtree(positions)
for drone in drones:
if distance(drone , kdtree_closest_point(tree, drone)) > conflict_radius**2:
drone_conflicts = drone_conflicts+1
return drone_conflicts |
def node_info(node_str):
"""Extract node info from node string
Node string is under the form:
[[/]partition/]addr[%iface][:port]
:arg str node_str: Node string
:return: Node info as :class:`tuple` (name, partition, address, iface, port)
"""
(name, partition, address, iface, port) = NOD... | The main task of the code is to collect and return detailed information about virtual server chains, including partition, virtual server name, IP, port, SSL profiles, associated rules, pool names, and member nodes. It processes each virtual server entry, extracts configuration data, resolves related resources like SSL ... | def list_virtual_server_chains(self):
"""Return virtual server chains
"""
vservers = []
for vserver, data in self.virtual_servers.items():
vpartition, vname = '', vserver
if '/' in vserver:
vpartition, vname = vserver.split('/', 1)
(_, ... |
def normalize(cities):
"""
Normalize list of city coordinates
:param cities: list of tuples, containing x and y coordinate
:return: normalized list of city coordinates
"""
max_x = max(cities,key=itemgetter(0))[0]
max_y = max(cities,key=itemgetter(1))[1]
m = max(max_x, max_y)
return ... | The code implements a Self-Organizing Map (SOM) algorithm. It reads and normalizes input data, initializes neurons, and trains the SOM using specified parameters (iterations, learning rate, neighborhood function, radius). The goal is to map high-dimensional data onto a lower-dimensional grid of neurons, capturing data ... | def main():
data_set, n_neurons, iterations, k, plot_k, neighborhood, learning_rate\
, radius = get_input()
cities = read_data(data_set)
scaling, cities = normalize(cities)
neuron_count = len(cities) * n_neurons
neurons = init_neurons(neuron_count)
# TODO maybe distance param?
som(... |
def Connect(driverOverride, server, host, port, dbname, username, password):
if server == 'mssql':
driver = '{SQL Server}'
if driverOverride != '':
driver = driverOverride
if (port != '1433'):
thePort = ',' + port
else:
thePort = ''
... | The main task of the code is to parse command-line arguments for database connection parameters, generate PlantUML code to visualize database schemas, and output the result to a file or console. It connects to a MSSQL database, retrieves table structures, and emits PUMl definitions for tables and relationships, handlin... | def main(argv) -> None:
server = 'mssql'
host = 'localhost'
port = '1433'
dbname = ''
schema = ''
filename = ''
conn = None
fileHandle = None
username = ''
password=''
driver = ''
try:
opts, args = getopt.getopt(argv, 'S:d:s:h:p:o:u:P:D:', ['server=','database=',... |
def fillImage(image, tile_size=8):
rows = len(image)
cols = len(image[0])
rows_needed = rows//tile_size
cols_needed = cols//tile_size
#fill columns
for row in image:
for col in range(cols_needed): row.append([0,0,0,0])
#fill rows
empty_row = []
for col in range(cols+cols_need... | The code converts an image into a compressed tile-based format. It processes the image by filling gaps, converting it to hex, creating a color dictionary, and compressing it into tiles. The output includes a bitmap, tileset array, compression factor, and color palette for efficient storage or transmission of the image ... | def convert(image, tile_size=8):
fillImage(image)
image = convertImageToHex(image)
colors = createColorDict(image)
compressed_factor = pixelsPerChar(len(colors)+1)
tiled_image = convertToTiles(image, colors, tile_size)
compressed_tiles = compressTiles(tiled_image, colors)
tiledict = createTi... |
def init():
"""
Create the collections and search indexes that are mirrored from firebase
"""
client = MongoClient(CONNECTION_STRING)
for c in ["users", "rewards"]:
try:
client.wanderlist.create_collection(c)
except CollectionInvalid as e:
print(e)
... | The main task of the code is to synchronize a database with Firebase, using either transactional or non-transactional methods based on the `USE_TRANSACTION` flag. It initializes the process, updates wanderlist thumbnails, and prints a confirmation message. | def sync_all():
init()
if USE_TRANSACTION:
sync_transacted()
else:
sync_notransaction()
scheduled.update_wanderlist_thumbs()
print("Synchronised DB from Firebase") |
def load_credentials(
self
) -> bool:
'''
Load credentials from the provided filepath if
the file exists
'''
if not os.path.exists(self.__creds_filepath):
raise Exception(
f"Could not find saved credentials at path: '{self.__creds_filepath... | The main task of the code is to handle the login process for a user, either by retrieving stored credentials or using a webdriver to interact with a website. It switches to an iframe, accepts terms, inputs login details, submits the form, waits, and returns a cookie jar. The function manages both credential retrieval a... | def __login(
self,
max_wait_time: int
) -> RequestsCookieJar:
'''
Internal login routine, to be wrapped in try/except
to capture and return specific exceptions concerning
timeouts
'''
# Attempt to load stored credentials and use those if
# ava... |
def initialize_image(model):
f = 2**(model.decoder.num_resolutions - 1)
toksX, toksY = PARAMS.size[0] // f, PARAMS.size[1] // f
sideX, sideY = toksX * f, toksY * f
def encode(img):
pil_image = img.convert('RGB').resize((sideX, sideY), Image.LANCZOS)
pil_tensor = TF.to_tensor(pil_image)
... | (The code generates images using a VQGAN model guided by CLIP text embeddings. It initializes a latent code 'z', sets up CLIP for prompt encoding, and optimizes 'z' via gradient descent to match prompts. Augmentation, learning rate scheduling, and constraints on latent space values (z_min/z_max) ensure image quality an... | def main():
model = load_vqgan_model(PARAMS.vqgan_config, PARAMS.vqgan_checkpoint, PARAMS.models_dir).to(DEVICE)
perceptor = clip.load(PARAMS.clip_model, device=DEVICE, root=PARAMS.models_dir)[0].eval().requires_grad_(False).to(DEVICE)
cut_size = perceptor.visual.input_resolution
make_cutouts = MakeCut... |
def _clean_text(text):
text = CLEAN_LF_RE.sub("\n", text)
text = CLEAN_TAB_RE.sub(' ', text)
return text.strip()
def _score_node(el):
score = _class_weight(el)
name = el.tag.lower()
if name == 'div':
score += 5
elif name in ('pre', 'blockquote'):
score += 3
elif name in (... | The code scores paragraphs and their ancestor elements based on text length and link density. It iterates through all 'p'/'pre' elements, calculates scores using text length and _score_text, adds scores to parent/grandparent nodes, and adjusts scores with link density. | def _score_paragraphs(self):
min_len = self.config.get('body_minimum_length', 0)
scores = self._scores
ordered = []
for el in self._root.iterdescendants('p', 'pre'):
parent_el = el.getparent()
if parent_el is None:
continue
grand_paren... |
def _class_weight(el):
weight = 0
for feature in (el.get('class', None), el.get('id', None)):
if feature:
if NEGATIVE_RE.search(feature):
weight -= 25
if POSITIVE_RE.search(feature):
weight += 25
return weight
def _get_link_density(el):
lin... | The code identifies and excludes elements based on criteria like class weight, link density, text length, and child element counts. It iterates through headers and other tags, applying thresholds to determine if elements should be excluded, adding their 'x' attribute to a set. Rules include checking li/a ratios, image-... | def _collect_exclude_elements(self, element):
for el in element.iter("h1", "h2", "h3", "h4", "h5", "h6"):
if _class_weight(el) < 0 or _get_link_density(el) > 0.33:
self._excludes.add(el.get('x', u''))
min_len = self.config.get('body_minimum_length', 0)
done = self._d... |
def _prepare(self, doc):
self._doc = doc.copy()
self._root = self._doc.root
self._doc.add_xpath()
self._scores = {}
self._excludes = set()
self._done = set()
def _remove_unlikely_candidates(self):
except_tags = (u'html', u'body')
for el in self._root.iter... | The code processes a document by preparing it, removing unlikely candidates, adjusting inappropriate elements, scoring paragraphs, reducing candidates based on scores, and dropping text elements that don't meet criteria. The main task is to clean/structure the document by evaluating and eliminating non-viable content. | def run(self, doc):
self._prepare(doc)
self._remove_unlikely_candidates()
self._inappropriate_div_to_p()
self._score_paragraphs()
scores = self._reduce_candidates()
if scores:
drop_list = []
for score in scores:
self._collect_exclud... |
def threshhold_and_dialate(img):
thresh = threshold_triangle(img)
binary = img > thresh
removed_loners = filter_isolated_cells(binary, struct=np.ones((3,3)))
return dilation(removed_loners, disk(30))
def random_coordinates(img, n, window_size):
dialation = threshhold_and_dialate(img)
img = Image... | The code computes the average number of components per patch size squared for varying patch sizes (10 to 32) using random coordinates and dilation. It iterates over patch sizes, calculates normalized component counts, aggregates results, and plots the mean component count against patch sizes to visualize trends. | def display_component_count():
result = np.array([])
n=3
patches_n = 8192
dilation = threshhold_and_dialate(X[n])
for j in range(1):
comp_count = []
count = 0
for i in range(10,33,2):
print(str(j) + ", " + str(i))
count +=2
rs = random_... |
def __request_cert(self, params):
"""Request a certificate"""
response = requests.put(f"{self._api_url}/creds", params=params)
if not self.__validate_response(response):
return
self._cert = json.loads(response.text)["cert"]
self.__save_cert()
def __create_cert_auth_... | The main task of the code is to request a certificate and generate an authentication token using provided parameters. It handles errors such as incorrect credentials (via BadStatusCodeError) or other exceptions by printing error messages and returning False, while returning True on successful execution. | def __request_cert_auth(self, params):
"""Requests certificate and creates auth token"""
try:
self.__request_cert(params)
self.__create_cert_auth_token()
except BadStatusCodeError:
self.__print("Incorrect credentials")
return False
except E... |
def __check_for_auth(self, action=""):
if not self._auth:
self.__print_setup_authentication(action)
return False
return True
def __print(self, *args, sep="", end="\n", file=None):
if not self._quiet:
for arg in args:
print(arg, sep=sep, end=end... | The code downloads files from a server via API by querying URLs for each file in the provided list, handling authentication, filtering, and user confirmation. It collects URLs, validates responses, and downloads files to a specified path, optionally replacing existing files. It returns the list of downloaded file paths... | def download_files(self, files, path="/var/tmp/", replace=False):
"""Download a list a files
Args:
files (list): A list of files obtained via search()
path (str, optional): The download path. Defaults to "/var/tmp/".
replace (bool, optional): Whether to redownload an... |
def __check_for_auth(self, action=""):
if not self._auth:
self.__print_setup_authentication(action)
return False
return True
def __search_for_urls(self, filter_arg):
"""uses the alternative api /downloads method
to search the inventory table and return
the... | This method enables downloading files directly from a search query using specified filters, with options to set the download path and replace existing files. It checks authentication, retrieves URLs, confirms downloads if required, and handles errors, returning a list of downloaded file paths. | def download_search(self, filter_arg, path="/var/tmp/", replace=False):
"""Download files straight from a search without placing an order
Args:
filter_arg (dict): The filter argument. For information on how to construct this see download-README.md
path (str, optional): The downl... |
def __check_for_auth(self, action=""):
if not self._auth:
self.__print_setup_authentication(action)
return False
return True
def __print(self, *args, sep="", end="\n", file=None):
if not self._quiet:
for arg in args:
print(arg, sep=sep, end=end... | The main task of the code is to place an order for dataset files based on a filter argument, retrieve download URLs, and download the files to a specified path. It checks authentication, validates input, handles errors, and confirms downloads if required. The function returns a list of downloaded file paths. | def download_with_order(self, filter_arg, path="/var/tmp", replace=False):
"""Place an order and download files based on a query.
filter_arg (dict): The filter argument. For information on how to construct this see download-README.md
path (str, optional): The download path. Defaults to '/var/tm... |
def renew_cert(self, quiet=False):
"""Renews the certificate"""
if not self._cert:
if not quiet:
self.__print("No certificate to renew")
return False
if not quiet:
self.__print("Renewing existing certificate...")
params = {
... | The function sets up certificate authentication by requesting a certificate token using provided or prompted credentials, renewing it if necessary, and returns whether the certificate is valid. It handles user authentication, certificate generation, and validation, providing feedback through print statements. | def setup_cert_auth(self, username=None, password=None):
"""Given username and password request a cert token and generate a
certificate
Args:
username (str, optional): Username, if None it will prompt. Defaults to None.
password (str, optional): Password, if None it w... |
def renew_cert(self, quiet=False):
"""Renews the certificate"""
if not self._cert:
if not quiet:
self.__print("No certificate to renew")
return False
if not quiet:
self.__print("Renewing existing certificate...")
params = {
... | The main task of the code is to generate a certificate with two-factor authentication (2FA) permissions using provided or prompted username, password, and 2FA code. It checks if a valid certificate already exists, renews it if possible, and returns a boolean indicating success. If certificate creation fails, it logs th... | def setup_two_factor_auth(self, username=None, password=None, authcode=None):
"""Given a username, password, and 2 factor authentication code,
generate a certificate with two factor auth permissions
Args:
username (str, optional): Username, if None it will prompt. Defaults to Non... |
def reset(self):
self.rst.on() ## Pull the reset pin high to release the ILI9225C from the reset status
time.sleep_ms(1)
self.rst.off() ## Pull the reset pin low to reset ILI9225
time.sleep_ms(10)
self.rst.on() ## Pull the reset pin high to release the ILI9225C from the reset ... | This code initializes an ILI9225 LCD display by configuring hardware pins (SPI, CS, DC, RST), validating rotation settings, performing a hardware reset, setting display orientation, and preparing the display for use through setup and clear operations. | def __init__(self, spi, cs, dc, rst,
width=ILI9225_LCD_WIDTH, height=ILI9225_LCD_HEIGHT, rotation=0, led=255):
_spi = spi
self.spi = spi
_cs = cs
_dc = dc
_rst = rst
self.width = width
self._maxX = width
self.height = height
self.... |
def possible_moves(self):
moves = []
# Looping over every row.
for row in range(len(self.board)):
# Looping over every square in the row.
for col in range(len(self.board[row])):
piece_color = self.board[row][col][0] # Getting the piece color for every sq... | This code determines valid moves by eliminating those that leave the player's king in check. It checks for checkmate or stalemate conditions if no valid moves remain, updates game status flags, and returns the filtered list of valid moves. | def valid_moves(self):
# Getting all possible moves.
moves = self.possible_moves()
# Looping throw every move to check if it's valid or not.
# If it's not valid, delete this move from the moves list.
for move in range(len(moves)-1, -1, -1):
self.make_move(moves[move]... |
def foldercompression():
global dirpath
# dump tree
progress["maximum"] = 5000
progress["value"] = 0
# create tree with all info from all files
getallinfo(dirpath)
tree, encodingTree = constructHuffmanTree(allinfo, progress)
f = open(destination_path, 'w', encoding='utf-8')
json.du... | The code compresses input data using Huffman coding, updates a progress bar, saves the encoded data and Huffman tree to a file, and notifies the user of completion. It reads input from entries, constructs a compression tree, encodes data, calculates compression rate, and writes results to a specified destination file. | def compression(progress):
# progress bar
global destination_path
progress.grid(row=2, column=2, sticky='ew', padx=5)
progress.pack()
progress["value"] = 0
progress.update()
progress["maximum"] = 5000
# get the values from the entries
destination_path = e[1].get()
if dirpath != ... |
def getAllLinesForYear(directory):
allLines = []
print(directory)
for textFile in os.listdir(directory):
if textFile.endswith(".txt"):
bookDirectory = directory +"/"+textFile
bookLines = readFile(bookDirectory)
allLines = allLines +bookLines
return allLines
de... | The function generates n-gram frequency dictionaries (for n=1 to 5) from text data in yearly subdirectories. It processes books in the specified year range, extracts words, creates n-gram counts, and organizes results by year in a nested dictionary structure. | def returnDictionaries(directory, startYear,endYear):
print("returnDictionaries: "+directory)
dictionaries = {}
for year in range(startYear,endYear+1):
yearDict = {}
currDirectory = directory+"/"+str(year)
allBookLines = getAllLinesForYear(currDirectory)
for i in range(1,6):
... |
def menu_formatter(title, list, exit: bool):
are_commands = True if type(list[0]) == Command else False
print(title)
print("------")
for i in range(len(list)):
if are_commands:
print(f"{i+1}) {list[i].description}")
else:
print(f"{i+1}) {list[i]}")
print(... | The main task of the code is to display a main menu with unique categories from commands, handle user input to navigate sub-menus or trigger updates, and manage the Amate update process. It filters duplicate categories, adjusts input ranges based on Amate's installation status, and directs users to sub-menus or the upd... | def main_menu():
# take categories
categories = [cmd.category for cmd in all_commands]
unique_elements = []
for element in categories:
if element not in unique_elements:
unique_elements.append(element)
categories = unique_elements
n_categories = len(categories)
updater_in... |
def perform_scalar_operation(self, scalar, operator):
'''Performs a scalar operation (+|-|*) with each array element
Returns:
Array: The modified array object after performing the scalar operation
'''
if operator == "+":
for index in range(len(self.values... | This method performs mathematical operations on an array with another value (scalar or array) using the specified operator. It checks data type compatibility, shape similarity, and delegates operations to scalar or array-specific methods, raising errors for invalid types or shapes. | def perform_mathematical_operation(self, other, operator):
'''Returns the resulting array after performing a mathematical operation on it.
Returns:
Array: The resulting array after performing the mathematical operation
'''
if isinstance(self.data_type, bool):
... |
def init_mlflow_run(config, exp_name, parent_run_id):
mlflow.set_tracking_uri(config["MLFLOW"]["MLFLOW_TRACKING_URI"])
mlflow.set_experiment(exp_name)
if mlflow.active_run() is None:
mlflow.start_run(run_id=parent_run_id)
def get_fold_data(X, y, train_idxs, test_idxs):
train_x = X[train_idxs]
... | The code performs hyperparameter optimization for a classifier using cross-validation on a training fold, trains the model with the best parameters, evaluates it on the test fold, logs metrics and parameters via MLflow, and returns the fold's performance score. It includes fuzzification of labels, logging, and nested M... | def perform_inner_fold(train, test, it, logging_lvl):
logging.basicConfig(level=logging_lvl)
if track_mlflow:
init_mlflow_run(config, exp_name, parent_run_id)
with ExitStack() as stack:
if track_mlflow:
stack.enter_context(mlflow.... |
def check_progress(self,
page: Union[int, str],
mark_as_complete: bool = False) -> Optional[int]:
"""Checks the progress of the download.
Args:
page (int): Page number.
mark_as_complete (bool, optional): Whether to mark the page as
... | The function parses a page by checking progress status, fetching observations, handling UUID duplicates, downloading associated photos, and updating progress tracking. It returns 1 for completed/in-progress pages, None for marked-complete/pending cases, or 2 if the page matches `stop_at_page`, while managing resume poi... | def _parse(self,
page,
year: Optional[int] = None) -> Optional[Union[bool, int]]:
"""Parses the page.
Args:
page (int): Page number.
year (int, optional): Year to filter by.
Returns:
Returns 1 if the page is complete or in-progr... |
def get_num_pages(self, on_year: Optional[int] = None) -> tuple:
"""Returns the number of pages.
Returns:
tuple: A tuple of (number of pages, number of observations).
"""
url = 'https://api.inaturalist.org/v2/observations'
params = {'taxon_id': self.taxon_id}
... | The code runs a scraper to download images, handling large datasets by iterating yearly if observations exceed 10,000. It creates an output directory, processes pages range-wise, and adjusts parameters like start/end years. It uses signal handling for interruptions and stops based on response codes or `one_page_only` f... | def run(self) -> None:
"""Runs the scraper."""
signal.signal(signal.SIGINT, self._keyboard_interrupt_handler)
if not self.output_dir:
self.output_dir = f'downloaded_images_{self.taxon_id}'
if not self.upload_to_s3:
Path(self.output_dir).mkdir(exist_ok=True, pare... |
def assert_files_exist(researchIntEmbeddingFileName):
embeddingFileFound = True
mappingFileFound = True
if not os.path.exists(researchIntEmbeddingFileName):
embeddingFileFound = False
if not os.path.exists("indices_to_researchInterest.json"):
mappingFileFound = False
if not os.path.e... | The function updates research interest-to-index mappings and embeddings by identifying newly added research interests from input data. It checks file existence, loads existing mappings, tracks added/removed interests, generates new indices for additions, updates embeddings using a model, and writes revised mappings to ... | def update_mapping_data(data, modelName, embeddingFileName):
#check if all files needed are available
if not assert_files_exist(embeddingFileName):
return
#load the existing data
#update research interest mapping data
#index -> research interest mapping
idToResearchIntDict = read_fr... |
def _get_file_by_hash(hash):
return qb.torrents_info(torrent_hashes=hash)
def rename_file_for_plex(cfg, dl_dir, file_name):
new_file_name = ""
# remove spaces from file name
formatted_movie = file_name.replace(" ", ".")
FILE_EXTENSIONS = ('avi', 'mp4', 'mkv', 'srt')
if file_name[-3:] in FILE_EXT... | This function processes a downloaded file by retrieving its metadata via hash, checks for tags, renames the file for Plex compatibility, moves it to designated directories (movie, TV, or private) based on its tag, and handles errors by logging and notifying users. It ensures proper organization and cleanup of media fil... | def _process_file(cfg, hash):
dl_dir = cfg["disk"]["dl_path"]
movie_dir = cfg["disk"]["movie_path"]
tv_dir = cfg["disk"]["tv_path"]
private_dir = cfg["disk"]["private_path"]
try:
tor = _get_file_by_hash(hash)[0]
name = tor["name"].encode("ascii", "ignore").decode("utf-8")
tag... |
def get_runner(self):
print('get_runner')
_, window = self.get_view_and_window()
runner = None
if window.id() in self.get_window_dict() and 'runner' in self.get_window_dict()[window.id()]:
runner = self.get_window_dict()[window.id()]['runner']
return runner
def set_next_step(self, message):
view, _ = sel... | The main task of the code is to execute a given command using an existing process (runner) if it is still active. It updates the status, sends the command to the runner, captures and prints the output/error, and handles cases where the runner is closed or nonexistent by logging an error message. | def run_command(self, command):
runner = self.get_runner()
if not runner is None and runner.poll() is None:
self.set_next_step('')
self.set_status('')
self.update_progress(self.default_prompt + ' : running ' + command)
out, err = runner.communicate(input=command.encode())
print(out)
print(err)
e... |
def update_progress(self, message):
self.get_progress().set_message(message)
self.get_progress().start()
def get_runner(self):
print('get_runner')
_, window = self.get_view_and_window()
runner = None
if window.id() in self.get_window_dict() and 'runner' in self.get_window_dict()[window.id()]:
runner = se... | This method executes a command in the background using subprocess.Popen, monitors its output for specific status updates or errors, updates UI progress/status accordingly, and invokes a callback upon completion. It handles exceptions like missing commands, manages process polling, decodes stdout, and ensures cleanup by... | def run_in_background(self, command, executable, wd, callback=None):
message = self.default_prompt + ' : starting'
self.update_progress(message)
runner = self.get_runner()
try:
self.update_progress(message)
runner = subprocess.Popen( command ,
shell = True,
executable=executable,
s... |
def get_runner(self):
print('get_runner')
_, window = self.get_view_and_window()
runner = None
if window.id() in self.get_window_dict() and 'runner' in self.get_window_dict()[window.id()]:
runner = self.get_window_dict()[window.id()]['runner']
return runner
def run_command(self, command):
runner = self.g... | The main task of the code is to stop a running process by sending a 'q' command, waiting up to 10 seconds for it to terminate naturally, and forcefully killing it if it remains active. It also stops associated progress tracking. | def stop_runner(self):
runner = self.get_runner()
if runner is None:
print("stop_runner: None runner")
return
self.run_command('q')
return_code = None
i = 0
while return_code is None and i < 100:
i = i + 1
return_code = runner.poll()
time.sleep(1/10.0)
if return_code is None :
runner.ki... |
def add_data_to_file(folder_path, duration):
with open(CORE_FILE_PATH, mode='a', newline='') as csv_file:
fieldnames = ['folder_path', 'duration']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writerow({
'folder_path': folder_path,
'duration': str(d... | The function `add_data` validates user inputs for a folder path and duration, then adds valid data to a file, clears displayed data from a GUI tree view, and reloads a core file to reflect updates. | def add_data():
folder_path = selected_label.cget('text')
duration = dur_entry.get()
if folder_path == "" or folder_path == "(None Selected)" or folder_path == None:
return
if duration == None or duration == '' or not duration.isnumeric():
return
add_data_to_file(folder_path=folder_p... |
def create_core_file():
with open(CORE_FILE_PATH, mode='w', newline='') as csv_file:
fieldnames = ['folder_path', 'duration']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
remove_all_data_from_tree()
def add_data_to_file(folder_path, duration):
with op... | The main task of the code is to remove a selected item from a treeview widget, update the records list with remaining items, and synchronize data by creating/updating a core file and adding records to specified files using folder paths and durations. | def remove_data():
if treeview.selection() == () or treeview.selection() == None or len(treeview.selection()) == 0:
return
iid = treeview.selection()[0]
if iid == None or iid == "":
return
treeview.delete(iid)
records = []
for child in treeview.get_children():
records += ... |
def check_core_file_exists(): return os.path.isfile(CORE_FILE_PATH)
def check_file_validity():
isFileValid = True
with open(CORE_FILE_PATH) as core_file:
core_reader = csv.DictReader(
core_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in core_reader:
... | The main task of the code is to process a CSV core file, validate its entries, and delete specified folders based on their duration values. It checks if the core file exists and is valid, then reads each row to verify folder paths and durations. Valid entries trigger folder deletion via `delete_operation`, while invali... | def start_script():
if check_core_file_exists() and check_file_validity():
with open(CORE_FILE_PATH) as core_file:
core_reader = csv.DictReader(
core_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL
)
for row in core_reader:
if... |
def getSoup(url):
response = requests.get(url)
soup=BeautifulSoup(response.text,'html.parser')
return soup
def compare_rule_name(rule_name):
cleaned_rule_name = re.sub(r'[^a-zA-Z0-9]+', '', rule_name)
if len(cleaned_rule_name) > 0:
with open('USCA_SECOND_LR.txt', 'r', encoding='utf-8') as re... | The function extracts content from HTML tables on a webpage by retrieving image alt text and paragraph text, formats them into HTML, handles exceptions, compares the rule name, and passes processed data to a final procedure for further processing. | def single_page_rules(url,rule_name):
new_soup = getSoup(url)
table_content = new_soup.find_all('table', {'style': 'width: 99%'})
html_content = ''
for i in table_content:
try:
img_tag = i.find('img')
paragraph_tag = i.find('td', class_='subpage_text')
if img_... |
def there_is_a_solution(self, event = None): # check if there is a solution for the problem
if len(self.target_vertices) == 3 and len(self.graph_edges) != 0:
# find the vertices of the ambulance, the patient and the hospital
ambulance_vertex = self.graph_vertices.index(list(self.target_... | This function computes the shortest paths from an ambulance to a patient and from the patient to a hospital using an integer programming (IP) model. It sets up decision variables, constraints, and cost matrices based on the graph structure and optimization criterion (time/length). It solves two IP problems, extracts th... | def find_shortest_path_with_IP(self, event = None): # find the shortest path using the IP model
if self.there_is_a_solution():
self.IP_solve_mode = True
self.enter_solve_mode()
# find the vertices of the ambulance, the patient and the hospital
ambulance_vertex = ... |
def there_is_a_solution(self, event = None): # check if there is a solution for the problem
if len(self.target_vertices) == 3 and len(self.graph_edges) != 0:
# find the vertices of the ambulance, the patient and the hospital
ambulance_vertex = self.graph_vertices.index(list(self.target_... | The code finds the shortest paths from ambulance to patient and patient to hospital using the A* algorithm, based on either time or length optimization. It identifies graph vertices, computes edge costs, constructs adjacency lists, executes A* for both paths, calculates total costs, converts them to absolute units (met... | def find_shortest_path_with_Astar(self, event = None):
if self.there_is_a_solution():
self.IP_solve_mode = False
self.enter_solve_mode()
# find the vertices of the ambulance, the patient and the hospital
ambulance_vertex = self.graph_vertices.index(list(self.targe... |
def add_unit_time_weight_image(self, new_time_weight_name):
self.has_time_weight_image = True
self.time_weight_name = new_time_weight_name
self.time_weight_image = Image.open(os.getcwd() + "/images/time_weights_images/" + self.time_weight_name + ".png")
self.time_weight_image = self.time... | This function handles middle-click events on units to toggle time weight or target vertex images based on current modes. If in 'add_time_weights_mode' and clicking an edge unit (kind=3), it adds/removes a time weight image. If in 'add_target_vertices_mode' and clicking a vertex unit (kind=2), it adds/removes a target v... | def middle_click_unit(self, event = None):
if not networks_list[self.instance].entered_solve_mode:
if networks_list[self.instance].add_time_weights_mode == "stop" and self.kind == 3: # if the add_time_weights_mode is enabled and middle-clicking on an edge unit
if self.time_weight_na... |
def get_num_flags(self):
flags = 0
for i in range(1, self.row_count+1):
for j in range(1, self.col_count+1):
if self.board[i][j].value == 'F':
flags += 1
return flags
def reveal(self, x, y):
if (x < 1) or (x > self.row_count) or (y < 1) or ... | The code checks if all bombs are correctly flagged by comparing the number of flags to the total bomb count. If true, it marks the game as over, reveals all unrevealed tiles, and triggers the win condition. | def check_status(self):
if self.get_num_flags() == self.total_bomb_count:
self.game_over_state = True
#now open up the remaining tiles
for i in range(1, self.row_count + 1):
for j in range(1, self.col_count + 1):
tile = self.board[i][j]
... |
def find_8neighbors(self, i, j):
"""returns a list of all tiles which neighbor tile (i,j)"""
ret = []
for iii in range(-1, 2):
for jjj in range(-1, 2):
valid_tile = True
"""catch weird cases"""
if i+iii < 1 or i+iii > self.row_count:
... | This function performs logical deduction on a Minesweeper board to automatically flag or reveal tiles based on known values and surrounding flagged tiles. It iteratively checks revealed tiles: if a tile's value matches the number of remaining unknown surrounding tiles, it flags them; if the number of flagged surroundin... | def trivial_parse(self):
""" Parse through entire board. If a known tile has the same number of
surrounding flagged tiles as its value, reveal all surrounding tiles.
If a known tile has the same number of remaining mines as unknown surrounding
tiles, flag all surrounding tiles. Loop unti... |
def make_board(self):
if len(self.board) != 0:
del self.board[:]
tmp = []
init_prob = self.total_bomb_count/(self.row_count*self.col_count)
for i in range(0, self.row_count + 1):
del tmp[:]
for j in range(0, self.col_count + 1):
tmp.ap... | The code implements an AI for playing Minesweeper. It initializes the game board, updates probabilities using heuristic methods, and iteratively reveals cells based on calculated risks. The AI employs average probability analysis to make decisions, looping until the game ends. It cleans up the board and returns 1 if th... | def AI_game(self):
# print("\n-------------------- MINESWEEPER --------------------\n")
# print(" GAME START")
# print(" Board Size:", (self.row_count * self.col_count))
# print(" Mine Number:", self.total_bomb_count)
# print(" Mine Density:", (self.total_bomb... |
def _reset_orderbook(self, market: str) -> None:
if market in self._orderbooks:
del self._orderbooks[market]
if market in self._orderbook_timestamps:
del self._orderbook_timestamps[market]
def get_orderbook(self, market: str) -> Dict[str, List[Tuple[float, float]]]:
subsc... | This function processes orderbook messages by updating the stored orderbook data for a specific market. It checks if the subscription exists, resets the orderbook if the message indicates a partial update, updates bid/ask prices and sizes, verifies data integrity via checksum, and triggers resubscription or update even... | def _handle_orderbook_message(self, message: Dict) -> None:
market = message['market']
subscription = {'channel': 'orderbook', 'market': market}
if subscription not in self._subscriptions:
return
data = message['data']
if data['action'] == 'partial':
self.... |
def _handle_orderbook_message(self, message: Dict) -> None:
market = message['market']
subscription = {'channel': 'orderbook', 'market': market}
if subscription not in self._subscriptions:
return
data = message['data']
if data['action'] == 'partial':
self.... | This method processes WebSocket messages by parsing JSON data, handling specific message types (e.g., reconnecting on 'info' code 20001 or raising errors), and routing valid messages to channel-specific handlers like orderbook, trades, or ticker based on the 'channel' field. | def _on_message(self, ws, raw_message: str) -> None:
message = json.loads(raw_message)
message_type = message['type']
if message_type in {'subscribed', 'unsubscribed'}:
return
elif message_type == 'info':
if message['code'] == 20001:
return self.re... |
def parse_field_descriptor(desc: str) -> str:
args = desc.strip("L")[:-1] if desc.startswith("L") else translate(desc)
return args
def parse_descriptor(desc: str) -> tuple:
match = re.match(r"\(([^)]*)\)(.*)", desc)
if match:
args_str = match.group(1)
args = []
for arg in re... | This function processes a Java class file's data structure by replacing index-based references in the constant pool with actual string values, such as class names, method names, and field descriptors. It also parses method and field descriptors into structured formats, enhances readability by decoding UTF-8 byte string... | def clean(self, clazz: dict) -> dict:
class_name_index = clazz['this_class']
clazz.pop('this_class')
clazz['name'] = clazz['constant_pool'][clazz['constant_pool'][class_name_index - 1]['name_index'] -1]['bytes'].decode('utf-8')
super_name_index = clazz['super_class']
clazz.pop('s... |
def find_matching_master_build(github_service, commit_id, dic_of_master_builds, pr_id):
pr_list = []
while(True):
pr_number = github_service.get_pr_number(commit_id)
if pr_number is not None:
pr_list.append(pr_number)
else:
pr_list.append(pr_id)
if commit_... | The function identifies failed CI/CD targets in a GitHub pull request against the 'master' branch. It retrieves failed jobs, compares them with master branch builds, and determines root causes by matching PR and master job data. It returns a structured result of root failure targets or None if the PR targets a non-mast... | def get_failed_targets(pull_request_id):
github_service = GithubService(pull_request_id)
sha = github_service.get_latest_commit(pull_request_id)
base_branch = github_service.get_pr_base_branch(pull_request_id)
if base_branch == 'master':
failed_jobs = github_service.get_failed_jobs(sha)
... |
def setSocket(IP, port):
localSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
localSocket.bind((IP, port))
localSocket.listen(10)
return localSocket
def buildConnect(fileName):
global connectedNodeNum
global sleep_time
nodes = decodeConfig(fileName)
for i in range(len(nodes)):... | The code initializes a network node with a specified IP and port, loads configuration from a file, establishes connections with other nodes, and runs a continuous message reception loop in a separate thread. It processes command-line arguments for node configuration, sets up socket communication, and handles incoming d... | def main():
global localIP
global local_node
global p
global sleep_time
p = Process()
if len(sys.argv) != 4:
print("invalid input")
return False
localIP = "127.0.0.1"
local_node = sys.argv[1]
local_node = local_node[-1]
portNum = int(sys.argv[2])
fileName =... |
def isdir(self, path: Union[str, Path]) -> bool:
"""Check if path is directory.
Args:
path (Union[str, Path]): Target path.
Returns:
bool: True if directory else False.
"""
return stat.S_ISDIR(self._lstat(path))
def isfile(self, path: Union[str, Path]) -... | This function writes text data to a remote file via SFTP, handling encoding, append mode, and file existence checks. It validates the target path, raises errors for directories or existing files (unless forced), and uses SSH2 flags to control file creation/writing. Data is encoded and written to the remote file using a... | def write_text(
self,
data: str,
file: Union[Path, str],
append: bool = False,
encoding: str = "utf-8",
force: bool = False,
) -> None:
"""Write text to a remote file.
Args:
data (str): Content to write to a file.
file (Union[P... |
def ismounted(self, mount) -> bool:
"""Check if path is mountpoint.
Args:
path (Union[str, Path]): Target path.
Returns:
bool: True if mountpoint else False.
"""
try:
self.run(["mountpoint", mount])
except OSError:
return ... | This function mounts a remote filesystem by checking if the target is already a mountpoint, unmounting it if 'force' is True, creating the target directory if 'mkdir' is True, and executing the mount command with the provided source and target paths. | def mount(
self,
source: str,
target: Union[Path, str],
force: bool = False,
mkdir: bool = False,
) -> None:
"""Mounts a filesystem in remote machine.
Args:
source (str): Source filesystem.
target (Union[Path, str]): Target filesystem.... |
def get_age_ratio(amt, newdf, time):
#newdf = florida.copy()
#amt='Hospitalized'
freq='7D'
grpvar='Age_group'
df = get_groupby_rolling_df(newdf, grpvar, freq, amt, time)
df[amt] = df['rolling sum']
daily = get_rolling_df(newdf, time=time, freq=7, var=amt)
daily[amt].fillna(0, inplace=Tru... | This function calculates age-adjusted Hospitalization Fatality Rate (HFR) or Case Fatality Rate (CFR) by applying age group ratios to mean rates, then plots the aggregated results over a specified time range (April 2020 to December 2020) on a given axis. It uses conditional logic to handle HFR/CFR differently, computes... | def get_from_mean(newdf, amt, ax, time):
min_date = "2020-04-01"
max_date = "2020-12-01"
grpvar = 'Age_group'
age_ratio = get_age_ratio(amt, newdf, time)
if amt=='Hospitalized': # HFR
hfr_age = get_mean_hfr_age(newdf[newdf[amt] ==1].copy(), time)
age_ratio['mean_HFR'] = age_ratio.ap... |
def get_combined_df(florida, min_date, max_date,
grpvar='Age_group', freq='7D', amt='Died', timevar='Case_',
verbose=False):
# get HFRs in aggregate and per age group
hfr_df, age_hfr = get_HFR(florida, grpvar, freq, timevar, numfreq=7)
if verbose:
print('==... | The code analyzes time-series data (e.g., disease cases) by fitting cubic splines to model trends, performing block bootstrapping to estimate uncertainty, and summarizing key metrics like daily estimates and decreases of interest. It returns aggregated results, optionally including bootstrap replicates, for public heal... | def analyze_data(florida, TAG, return_replicates=False):
## GET HFRS
combined_df = get_combined_df(florida, MIN_DATE, MAX_DATE,
grpvar='Age_group', freq='7D', amt='Died', timevar='Case_',
verbose=verbose)
## CUBIC SPLINES
# fit cubic spl... |
def get_combined_df(florida, min_date, max_date,
grpvar='Age_group', freq='7D', amt='Died', timevar='Case_',
verbose=False):
# get HFRs in aggregate and per age group
hfr_df, age_hfr = get_HFR(florida, grpvar, freq, timevar, numfreq=7)
if hfr_df is None or age_hfr i... | The main task of the code is to analyze epidemiological data by fitting cubic splines to estimate trends, performing block bootstrapping to assess uncertainty, and summarizing key estimates (e.g., daily and decrease metrics) within specified date ranges. The function processes input data, computes residuals, generates ... | def analyze_data(florida, TAG, return_replicates=False, timevar='Case_'):
## GET HFRS
combined_df = get_combined_df(florida, MIN_DATE, MAX_DATE,
grpvar='Age_group', freq='7D', amt='Died', timevar=timevar,
verbose=verbose)
if combined_df is None:
... |
def extractLinkAndDate(url):
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
"""
table.fcLeaderboard
tr <---- column names
tr <---- event info
td <--- event name and link just need link for now
td
td ... | Your return
The code retrieves and structures data about an upcoming fight event. It extracts event details (link, date) from a URL, fetches the event's HTML content, parses the title, and scrapes matchup data. It processes weight classes, generates fighter objects, and compiles all information into a dictionary (`fi... | def getUpcomingFightEvent(): #returns a dictionary of the next upcoming fight event
fightEventData = {'eventData':{}}
for k,v in extractLinkAndDate(EVENTS_URL2).items():
fightEventData['eventData'][k] = v
#use link to get more info about event
source = getPageSource(fightEventData['eventData'][... |
def update_annotation_data(self):
# get spots from active image
spot_pos = self.get_spots()
# get new img id
img_id_new = self.get_img_id()
# get normalization values
normalization_values = self.get_normalization_values()
# get active tiles
active_tiles... | The main task of the code is to update and normalize image annotation data for spot detection. It processes each image directory and file, ensuring consistent foreground/background channel normalization values are calculated or retrieved. These values are then applied to corresponding entries in the annotation data, fo... | def extract_spots(self):
# update annotation data
self.update_annotation_data()
self.dump_data(spot_type="true")
# check image normalization data
df = self.annotation_data["true"].copy()
for img_dir in df.img_dir.unique():
for img_file in df.loc[df["img_dir"]... |
def load_annotation_data(self, annotation_dir=None, annotation_file=None):
# load annotation data from file
try:
with open(Path(annotation_dir) / annotation_file, 'rb') as f:
annotation_data = pickle.load(f)
self.annotation_data["true"] = annotation_data
... | The main task of the code is to load and visualize image data from an HDF5 file, incorporating foreground and background channels, while integrating annotation data for spot detection. It initializes or updates data directories, processes image slices, applies blurring, adds images to a viewer with specified colormaps,... | def load_img(self):
# check for new start (self.annotation_file still None)
if isinstance(self.annotation_file, type(None)):
self.annotation_dir = self.new_args["annotation_dir"]
self.annotation_file = self.new_args["annotation_file"]
self.img_dir = self.new_args["img... |
def get_between_char(text, char_start, char_end):
start = -1
for index in range(len(text)):
if text[index] == char_start:
if start == -1:
start = index
elif text[index] == char_end:
if start != -1:
end = index
return text... | The code parses a text array to extract player names, match metadata, and sets. It processes metadata into parameters, splits text into sets, and constructs a `TennisMatch` object with players and settings. Each set is parsed using `read_set`, and the match is populated with these sets. The function returns the fully c... | def read_match(text_array):
end = 0
player1_text, more = get_between_char(text_array[end:], '[', ']')
end += more
player2_text, more = get_between_char(text_array[end:], '[', ']')
end += more
match_metadata, more = get_between_char(text_array[end:], '(', ')')
end += more
player1 = re... |
def test_tiles_functions(to_save: bool = False) -> None:
"""Show the butterfly image, its split to tiles and the reassembled
image from tiles back to image."""
butterfly_image = cv2.imread(BUTTERFLY_IMAGE, 0)
plt.subplot(1, 3, 1)
plt.title('original image')
plt.imshow(butterfly_image, cmap='gray... | The main task of the code is to test and visualize Harris corner detection on a checkerboard and giraffe image. It calculates response images, detects corners using a custom Harris detector, and generates plots to compare results. The `to_save` parameter controls whether output images are saved. | def main(to_save: bool = False) -> None:
test_tiles_functions(to_save)
# Read checkerboard image as grayscale
checkerboard = cv2.imread(CHECKERBOARD_IMAGE, 0)
# Read giraffe image
giraffe = cv2.imread(GIRAFFE_IMAGE)
# checkerboard response image
checkerboard_response_image = calculate_respo... |
def get_worker_info_and_status_path():
shared_path, config = load_config()
status_file_path = os.path.join(shared_path, args.worker, "status.txt")
return status_file_path, config
def do_alloc(status_file_path: str, config: dict, run: bool):
if get_arg_time() < 0:
print("Bad job duration")
... | The main task of the code is to handle worker management commands. Depending on the `args.command` value, it executes actions like allocating workers (`alloc`/`run`), killing workers (`kill`), or listing worker information (`info`). It retrieves configuration paths and settings via `get_worker_info_and_status_path()` o... | def main():
if args.command == "alloc":
path, config = get_worker_info_and_status_path()
do_alloc(path, config, False)
elif args.command == "kill":
path, config = get_worker_info_and_status_path()
do_kill(path, config)
elif args.command == "run":
path, config = get_wo... |
def cal_class_priors(self, y):
classes_num = [0] * (self.classes_num + 1)
for i in y:
classes_num[i] += 1
n = len(y)
return [classes_num[i] / n for i in range(len(classes_num))]
def cal_means_variances(self, X, Y): # calculates means of gaussian p(t|c)
means = np.zero... | This code trains a classifier by estimating parameters from input data X and target labels Y. It determines the number of classes, calculates class priors, and computes either Gaussian distribution parameters (means/stds) or decision thresholds/conditional probabilities based on the specified model type ("gaussian" or ... | def fit(self, X, Y):
self.classes_num = max(Y)
self.class_priors = self.cal_class_priors(Y)
if self.kind == "gaussian":
self.means, self.stds = self.cal_means_variances(X, Y)
else:
self.thresholds, self.conditional_probs = self.cal_thresholds_conditional_probs(X, ... |
def check_huge_pages(num_numa_nodes: int, post_fix: str = "") -> List[int]:
num_huge_pages = []
for nid in range(num_numa_nodes):
cmd = ["cat", get_huge_page_sysfs(nid)]
output_lines = run_proc_simple(cmd).splitlines()
nr_pages = 0
if len(output_lines) > 0:
items = ou... | The main task of the code is to check and configure system NUMA and huge page settings. It prints CPU and memory information, checks current huge page status, and conditionally sets up or resets huge pages based on command-line arguments, ensuring system resource configuration alignment with specified parameters. | def main(args):
num_numa_nodes = print_cpu_info(do_print=False)
print_mem_info(num_numa_nodes)
check_huge_pages(num_numa_nodes, "current")
if args.setup:
setup_huge_pages(num_numa_nodes)
if args.reset:
reset_huge_pages([0 for _ in range(num_numa_nodes)]) |
def create_spreadsheet():
print("Method ran")
book = openpyxl.load_workbook(file_name)
# Get the first sheet and give it a name
sheet_1 = book.active
sheet_1.title = "Sheet1"
sheet_1["A2"].value = "Date"
sheet_1["B2"].value = "Units Produced"
sheet_1["C2"].value = "Units Sold"
sheet... | The main task of the code is to create a spreadsheet, update two specific sheets with data, clear designated fields, and save the modified workbook under a specified filename. | def updateSheets():
create_spreadsheet()
updateSheet_1()
updateSheet_2()
emptyFeilds()
book.save(file_name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.