dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getRunningTime():
if platformName=='Windows':
return time.clock()
if pyV == 3:
return time.monotonic()
if platformName=='Linux':
with open('/proc/uptime') as f:
return float(f.read().split()[0])
else:
return time.time()
def deal_rec(l):
for soc... | The main task of the code is to monitor network connections with timeout handling, process incoming data, track statistics (e.g., received/lost packets, timeout thresholds), and dynamically adjust IP settings. It uses I/O multiplexing via `select()` to handle socket readiness, updates performance metrics periodically, ... | def main():
staTime = getRunningTime()
startSign = []
startTime = getRunningTime()
while True:
j =oriTime=overTime= 0
if startSign:
tempM = min(gFile.timeoutList)
wt = gFile.timeoutTime+tempM-getRunningTime()
for i in range(baseNum,bigNum... |
def respond(err, res=None):
if err:
statusCode = 400
body = err
else:
statusCode = 200
body = res
return {
'statusCode': statusCode,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type,Access... | This Lambda function processes image data to generate a knitting pattern. It handles pre-flight requests, decodes base64 images, calculates stitch counts based on user-defined parameters, applies a color palette, and returns a JSON response with the stitch chart, color mappings, and gauge details. | def lambda_handler(event, context):
try:
print('Received event: ' + json.dumps(event))
if event['httpMethod'] and event['httpMethod'] == 'OPTIONS':
print('Received pre-flight request')
response = respond(None,'Success')
print(response)
return response
... |
def compute_gini_index(self, rows):
"""
Calculate impurity score for the given rows,
which shows how impure the a group of rows is. The lower, the puere.
(For example, out of 14 menus, there are 9 pizzas and 5 sushies.
Gini index = 1 - (9/14)^2 - (5/14)^2 = 0.46... | This function identifies the optimal feature-value split in a decision tree node by calculating information gain. It iterates through each feature, evaluates all unique values, partitions data using conditions, skips invalid splits, computes gain using Gini index, and retains the condition with the highest gain to maxi... | def find_best_split(self, rows):
"""
Find the best condition to ask on a node by iterating each feature (e.g. meal, protein2)
and compute the information gain
"""
best_gain = 0
best_condition = None
# Gini index on current node
current_uncertain... |
def find_best_split(self, rows):
"""
Find the best condition to ask on a node by iterating each feature (e.g. meal, protein2)
and compute the information gain
"""
best_gain = 0
best_condition = None
# Gini index on current node
current_uncertain... | The code recursively builds a decision tree by selecting the best split condition for maximum information gain. If no gain or max depth is reached, it creates a leaf node. Otherwise, it partitions data into true/false subsets, recursively constructs child branches, and returns a DecisionNode with the split condition an... | def build_tree(self, rows, current_depth=0):
"""
Build decision tree
"""
# Find the best condition to get the highest gain
gain, condition = self.find_best_split(rows)
# No more gain or reach to the max depth then terminate node growth
if gain == 0 or curren... |
def unary(self):
print("UNARY-STATEMENT")
if self.check_token(TokenType.PLUS) or self.check_token(TokenType.MINUS):
self.next_token()
self.primary()
def check_token(self, kind):
return self.cur_token.kind == kind
def next_token(self):
self.cur_token = self.peek_token
... | The main task of the code is to parse a term expression involving multiplicative operators. It starts by printing "TERM-STATEMENT", parses an initial unary expression, then repeatedly checks for * or / tokens. When found, it consumes the token and parses another unary expression, effectively building a sequence of mult... | def term(self):
print("TERM-STATEMENT")
self.unary()
while self.check_token(TokenType.ASTERISK) or self.check_token(TokenType.SLASH):
self.next_token()
self.unary() |
def term(self):
print("TERM-STATEMENT")
self.unary()
while self.check_token(TokenType.ASTERISK) or self.check_token(TokenType.SLASH):
self.next_token()
self.unary()
def check_token(self, kind):
return self.cur_token.kind == kind
def next_token(self):
self.... | The code parses arithmetic expressions with addition and subtraction. It starts by printing "EXPRESSION-STATEMENT", processes a term, then repeatedly checks for '+' or '-' operators. If found, it advances the token and processes another term, allowing for chained operations like "term + term - term". The loop enables h... | def expression(self):
print("EXPRESSION-STATEMENT")
self.term()
while self.check_token(TokenType.PLUS) or self.check_token(TokenType.MINUS):
self.next_token()
self.term() |
def expression(self):
print("EXPRESSION-STATEMENT")
self.term()
while self.check_token(TokenType.PLUS) or self.check_token(TokenType.MINUS):
self.next_token()
self.term()
def is_comparison_operator(self):
return self.check_token(TokenType.GT) or self.check_token(T... | The code parses a comparison expression by first evaluating an initial expression, then checking for and processing subsequent comparison operators followed by additional expressions in a loop, allowing for chained comparisons like "a > b < c". | def comparison(self):
print("COMPARISON-STATEMENT")
self.expression()
if self.is_comparison_operator():
self.next_token()
self.expression()
while self.is_comparison_operator():
self.next_token()
self.expression() |
def check_token(self, kind):
return self.cur_token.kind == kind
def next_token(self):
self.cur_token = self.peek_token
self.peek_token = self.lexer.get_token()
def expression(self):
print("EXPRESSION-STATEMENT")
self.term()
while self.check_token(TokenType.PLUS) or self.c... | This method parses and processes different programming language statements (PRINT, IF, WHILE, LABEL, GOTO, LET, INPUT) by checking token types, executing corresponding actions, handling nested statements, validating syntax, and managing symbols/labels. It advances tokens, evaluates expressions/comparisons, enforces str... | def statement(self):
if self.check_token(TokenType.PRINT):
print("PRINT-STATEMENT")
self.next_token()
if self.check_token(TokenType.STRING):
self.next_token()
else:
self.expression()
elif self.check_token(TokenType.IF):
... |
def get_player_data(game_id):
sql = f"select * from game where id='{game_id}'"
cursor = config.conn.cursor(dictionary=True)
cursor.execute(sql)
result = cursor.fetchall()
return result
def get_airport_info(ident):
sql = f"select name,ident,latitude_deg,longitude_deg,type from airport where ident... | This code initializes a game instance by retrieving player data, airport information, and game status. It sets the player's starting location, collects resource data, determines the final destination airport, and prepares a status dictionary with player stats, collected resources, and event messages for display. | def __init__(self, game_id):
# Game_id comes from the URL
self.game_id = game_id
self.current_ident = get_player_data(self.game_id)[0]['location']
config.player_name = get_player_data(self.game_id)[0]['screen_name']
self.current_airport = get_airport_info(self.current_ident)[0]
... |
def what_goal_in_airport(self, game_id, destination_ident):
goal_at_current = check_goal(game_id, destination_ident)[0]['goal']
if goal_at_current == 0:
self.status['food_collected'] = True
self.status['event'] = "You found the food resources you needed!"
elif goal_at_c... | The main task of the code is to simulate a player's flight to a destination airport, updating their battery range, location, and game state. It checks for goals at the destination, updates the database, and manages airport removal from available options. Depending on the "day" parameter, it returns either all reachable... | def fly(self, game_id, destination_ident, dist, day):
# travel distance is subtracted from battery range
self.status['battery_range'] -= float(dist)/2
# Check what goal does this destination airport contain and update the player
self.what_goal_in_airport(game_id, destination_ident)
... |
def pre_process(item, s_expression, aoi=None):
assets = OrderedDict()
resolution = get_resolution(item, s_expression)
common_band_names = parse_expression(s_expression)
for index, common_name in enumerate(common_band_names):
_, asset_href = get_asset(item, common_name)
if not asset... | This code processes a TIFF image by applying a mathematical expression (s_expression) to its data blocks, reducing memory usage through block-wise processing. It reads input data, evaluates the expression on each block, writes the result to an output TIFF, and adds overviews and compression for efficient storage and vi... | def apply_s_expression(item, out_tif, s_expression, aoi=None):
# reads an input tif, applies the expression and writes the output tif
# uses blocks to reduce the memory footprint
asset_hrefs = pre_process(item, s_expression, aoi)
ds = gdal.Open(list(asset_hrefs.values())[0])
dst_ds = get_empty_ds(... |
def print_banner():
print("""
_____ _____
| __ \\ ___ | __ \\
| | | |( _ ) | | | | \033[1m Monster Stat Block Generator\033[0m
| | | |/ _ \\/\\ | | |
| |__| | (_> < |__| |
|_____/ \\___/\\/_____/ -By Matt Talbert\n""")
def init_tk():
root = tk.Tk()
frm_main = ttk... | (The code initializes a GUI application using Tkinter, loads data from a CSV file into a dictionary, populates the main window with this data, and starts the GUI event loop. The main tasks include setting up the interface, reading structured data, and rendering it visually for user interaction.) | def main():
print_banner()
root, frm_main = init_tk()
cr_dict = read_cr_table(filename="cr_table.csv")
window_objects = populate_main_window(frm_main, cr_dict)
root.mainloop() |
def get_nodes(self, node_type, node, nodes):
if node['type'] == node_type:
nodes.append(node)
for _node in node['children']:
self.get_nodes(node_type, _node, nodes)
return nodes
def align_image(self, v: int, m: int):
mask = m - 1
aligned_value = (v + mask)... | The code processes animation frames by reading metadata, compressing PNG images into WFLZ format, aligning image dimensions, and writing structured binary data to an `.anb` file. It organizes textures, vertex data, and frame information according to the metadata's hierarchy, ensuring proper alignment and chunking for t... | def __init__(self, folder):
self.directory = Path(folder)
metadata_dir = self.directory.joinpath('metadata.json')
self.metadata = json.loads(metadata_dir.read_text())
self.hash_chunk = b''
self.hash_chunk_size = 0
self.main_body_node_size = 0
self.previous_wflz_si... |
def input_age_range(cc, category_list):
for i, classification in enumerate(cc):
if pgp.remove_classification_number(classification) == "resident_age":
return pgp.age_band_text_to_numbers(category_list[i]["label"])
return [0, 999]
def nests_nicely(c, input_age_range):
if pgp.remove_classi... | The function generates a comprehensive dataset for visualizing input selections by calculating counts and percentages for each category, handling blocked data, age range compatibility, and incorporating total population data when applicable. | def generate_one_dataset(data, total_pops_data, cc, category_list):
"""Generate a full dataset (i.e. the data for all charts) for a given set of input selections.
The dataset also has an element for total population if cc is non-empty.
Parameters
----------
data : list
All datasets with th... |
def is_resident_age(c):
"""Return true if and only if c is a resident_age classification."""
return pgp.remove_classification_number(c) == "resident_age"
def make_c_str(cc, c):
"""Generate a file name for a list of input classifications and an output classification.
Parameters
----------
cc : l... | The code generates files for a specified number of input variables by processing combinations of classifications, reading data from JSON.gz files, and updating a dictionary to count unblocked output variables for each combination. It skips redundant classifications, processes data, and tracks unblocked variables to pop... | def generate_files(num_vars, unblocked_combination_counts):
"""Generate all files with `num_vars` input variables.
The number of unblocked variables will be saved to the dictionary `unblocked_combination_counts`.
Parameters
----------
num_vars : int
The number of input variables
unbloc... |
def read_dictionary(self, org_name):
f_dict = gzip.open("dicts/" + org_name + ".dict.pkl.gz", 'rb')
return cPickle.load(f_dict)
def read_emb_weight(self, org_name):
with open("emb_weights/" + org_name + ".pkl", "rb") as wf:
weights = cPickle.load(wf)
return weights
def in... | This code initializes a TensorFlow model for text processing, setting up GPU configuration, loading word embeddings, and defining placeholders for title/description inputs and masks. It prepares a model architecture for tasks like regression using historical data tracking and embedding databases, likely for NLP applica... | def __init__(self, project_name, max_len=MAX_LEN):
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth=True
self.sess = tf.compat.v1.Session(config=config)
self.tokenizer_cmd = ['perl', 'tokenizer.perl', '-l', 'en', '-q', '-']
self.org_name = datasetDict[... |
def _err(msg):
return {"~err": {"~msg": msg}}
def _query(cmd, db=dict(_db)):
if len(cmd) > 1:
return _err("Query contains more than one key at a level.")
if len(cmd) == 0:
if isinstance(db, list):
return _arr(db)
else:
return _clean(db)
key = cmd.keys()[0]... | This function processes a JSON command string to perform operations like querying, changing, deleting, or adding data. It validates the input structure, identifies the operation type from the top-level key, executes the corresponding function, and returns the result as JSON. Errors in parsing, structure, or unrecognize... | def handle_cmd(cmd):
try:
# Convert to an actual json structure
j_cmd = json.loads(cmd)
# Check that there is the correct number of base keys (can only perform one operation per request)
if len(j_cmd) != 1:
return _err('Invalid number of keys at base level. Expected exact... |
def _geometric_mean(list_preds):
result = np.ones((781, 16))
for predict in list_preds:
result *= predict
result **= 1. / len(list_preds)
return result
def _find_best_coefficients(predicts, alpha=0.001, iterations=10000):
coefficients = [1] * 16
best_coefficients = coefficients[:]
b... | The main task of the code is to generate a submission file by processing model predictions through test-time augmentation (TTA), calculating geometric mean predictions, determining optimal coefficients, mapping predicted labels to class names, and writing the final results as a CSV file with filenames and corresponding... | def generate_submit(predictions, files, output_file):
results = []
for i in range(TTA_COUNT):
results.append(predictions[i::TTA_COUNT])
predictions = _geometric_mean(results)
coefficients = _find_best_coefficients(predictions)
labels_pred, _ = _get_labels_distribution(predictions, coefficie... |
def compare(self, data):
correct = 0
for x,y in data:
activation = self.forward(x)[-1]
results = getMaxPredValue(activation)
if (results == getY(y)):
correct += 1
return correct
def balancedAccuracy(right, wrong):
bA = right / (right + wro... | The main task of the code is to train a model using mini-batch gradient descent with momentum, monitoring balanced accuracy and detecting overfitting by tracking error percentages every 10 epochs. It shuffles data, updates parameters iteratively, and visualizes error trends over training epochs. | def training(self, training_data, epochs, lr, momentum):
batch_size = 35
training_data = list(training_data)
n = len(training_data)
errors = []
js = []
for j in range(epochs):
if j % 10 == 0:
numRight = self.compare(training_data)
... |
def CheckFinish(self, render=False):
# Check if the game has finished and determine the winner
if len(list(self.PossibleMoves())) == 0:
self.Fill(render)
c1, c2 = self.PieceCount()
if c1 > c2:
self.winner = 1
elif c1 < c2:
s... | This code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a player in a game. It recursively evaluates all possible moves up to a given depth, scoring positions based on game outcomes. Alpha-beta pruning optimizes performance by eliminating branches that cannot influence the f... | def minimax(self, depth, max_player, alpha, beta, player):
# Minimax algorithm with alpha-beta pruning for finding the best move
self.CheckFinish()
if self.winner == player:
return None, self.size ** 2 + 1
if self.winner == 3 - player:
return None, -(self.size ** ... |
def CheckFinish(self, render=False):
if (self.players_last_move[1] == (-1,-1) and self.players_last_move[2] == (-1,-1)):
scores = self.CalculateScores()
if scores[1] > scores[2]:
self.winner = 1
else:
self.winner = 2
def score(self, player):
... | This code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move in a game. It recursively evaluates all possible moves, assigns scores based on game states, and prunes branches to improve efficiency. The function alternates between maximizing and minimizing players, using alpha and beta... | def minimax(self, depth, max_player, alpha, beta, player):
# Minimax algorithm with alpha-beta pruning for finding the best move
self.CheckFinish()
if self.winner == player:
return None, 10000
if self.winner == 3 - player:
return None, -10000
if depth == 0... |
def crossover(self, mom: list, dad: list):
child1, child2 = [], []
for i in range(len(mom)):
if random.sample([True, False], 1)[0]:
child1.append(mom[i])
child2.append(dad[i])
else:
child2.append(mom[i])
child1.ap... | This function performs evolutionary optimization by iteratively evolving a population through crossover, mutation, and selection over a specified number of generations. It generates new offspring, replaces the population with selected individuals, and terminates early if a solution with zero fitness is found, while opt... | def run_generations(self, population: list, start, verbose=True):
for i in range(self.__generations):
for _ in range(len(population)):
is_crossover = random.random()
if is_crossover < self.__crossover_p:
mom, dad = random.sample(population, 2)
... |
def create_population(self):
population = []
for _ in range(self.__individuals):
population.append(self.random_genome())
return population
def run_generations(self, population: list, start, verbose=True):
for i in range(self.__generations):
for _ in range(len(... | This code implements a genetic algorithm for solving a SAT problem. It initializes a population, evolves it over generations, selects the fittest individuals, and returns the resulting solutions along with the computation time. The algorithm uses selection, generation runs, and conversion of solutions to dictionaries f... | def sat_algorithm(self, verbose=True):
population = self.create_population()
start = time.clock()
population = self.run_generations(population, start, verbose)
population = self.selection(population)
end = time.clock() - start
results = []
for indivi... |
def _create_clusters(self, centroids):
clusters = [[] for _ in range(self.K)]
for idx, sample in enumerate(self.X):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)
return clusters
def _get_centroids(self, clusters):
cent... | The code implements a K-means clustering algorithm. It initializes centroids randomly, iteratively assigns data points to the nearest centroid, updates centroids based on cluster means, and stops when centroids converge. Finally, it returns cluster labels for the input data. | def predict(self, X):
# Storing the input data
self.X = X
# Getting the number of samples and features
self.n_samples, self.n_features = X.shape
# Initializing centroids
random_sample_idxs = np.random.choice(self.n_samples, self.K, replace=False)
self.cen... |
def get_high_score():
try:
with open('score.dat','rb') as file:
score = pickle.load(file)
except:
score = 0
return score
def pause_game():
pygame.mixer.music.pause()
largeText = pygame.font.SysFont("comicsansms",110)
TextSurf, TextRect = text_objects("Paused", largeTe... | The code defines a game loop for a car-dodging game using Pygame. It handles user input for movement and pausing, updates the player car's position, spawns and moves an obstacle car, checks for collisions, tracks dodged obstacles, updates the score, and saves high scores. The loop continues until the player crashes or ... | def game_loop():
global pause
global otherCar_width
global otherCar_height
pygame.mixer.music.play(-1)
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
# otherCars = 1
otherCarStartX = random.randrange(0, display_width)
otherCarStartY = -600
otherCarSpeed = ... |
def load_open_api(openapi_url: str) -> dict:
""" Loads the openapi schema from the given url """
with request.urlopen(openapi_url) as response:
return json.loads(response.read().decode())
def _get_response_model(path_method: OpenAPIOperation) -> str or None:
""" Returns the response model for the gi... | The code generates an `endpoints.py` file from an OpenAPI schema by parsing paths, methods, parameters, and examples, while excluding specified paths. It modifies the OpenAPI metadata, validates response schemas, and uses a Jinja template to render endpoints with dynamic data, ensuring only valid operations are include... | def parse_open_api(open_api_url: str, ignore: list[str], proxy_path: str):
""" Generates the endpoints.py file from the openapi schema """
print(f"Loading openAPI definition from {open_api_url}") # TODO: Use logger
open_api_json = load_open_api(open_api_url)
open_api = OpenAPI.parse_obj(open_api_json... |
def empty_a_list(self):
self.availability_list = None
self.availability_list = arcade.SpriteList()
def check_dead(self):
for c in self.Char_list.Creature_list:
if c.hp <= 0:
n = self.Char_list.Creature_list.index(c)
order = self.Char_list.order[n]
... | The code handles mouse press events to switch between movement, action, bonus, and next-turn modes in a game. It checks the click position to activate corresponding actions, updates game states, draws available moves/actions, processes character interactions, and transitions turns based on user input and current game c... | def on_mouse_press(self, x, y, button, key_modifiers):
"""
Called when the user presses a mouse button.
"""
if button == arcade.MOUSE_BUTTON_LEFT and self.current_char.sprite.change_x == 0 and self.current_char.sprite.\
change_y == 0 and ((x - (SCREEN_WIDTH // 5 * 3)) ** ... |
def build_KD_tree(params_to_zeros, lookup_mode):
params_to_zeros_table = pandas.read_table(params_to_zeros).dropna().drop_duplicates(subset=[freq_adj0_name, size_adj0_name, size_cov_name], keep=False)
if 'nearest' in lookup_mode:
try:
freq_size_adj0_kdtree = spatial.KDTree(params_to_zeros_ta... | The function processes a gene's data to compute statistical metrics (e.g., burst numbers, rates) and confidence intervals using KD-tree interpolation and bootstrapping. It generates a pandas Series with averages, confidence bounds, and failure rates for parameters like burst size, synthesis rate, and dissociation rate,... | def one_gene(gene, df1_gene, freq_size_adj0_kdtree, param_lookup, add_cov, permutations, interpolation_points, lookup_mode, proc, o):
import warnings, functools
#warnings.filterwarnings("ignore")
freq_adj0_name, size_adj0_name, size_cov_name, open_chance_name, close_chance_name, transcribe_chance_name,... |
def get_tries(bam, fasta_file, g_dict):
fasta_ref = Fasta(fasta_file)
read_trie = pygtrie.StringTrie(separator=':')
conv_trie = pygtrie.StringTrie(separator=':')
mut_trie = pygtrie.StringTrie(separator=':')
t_trie = pygtrie.StringTrie(separator=':')
s_trie = pygtrie.StringTrie(separator=':')
... | The code processes BAM files to analyze genomic conversions and mutations, using trie structures to track molecular data. It updates conversion and strand-specific counts, filters significant mutations, and prepares results for parallel processing by chunking data into a queue. The function returns gene IDs under speci... | def count_conversions(bfile, fasta_file, vcf_file, g_dict, n_cells_top, q):
bam = pysam.AlignmentFile(bfile)
read_trie, mut_trie, conv_trie, t_trie, s_trie, strand_trie = get_tries(bam,fasta_file,g_dict)
good, sig_df, mols_series = find_mutations(conv_trie, mut_trie, g_dict, vcf_file, n_cells_top)
if no... |
def get_process_dict(proc):
processes = {}
for p in proc:
if p.pid != 0: # skip initial process
if psutil.pid_exists(p.pid): # prevents error if process closes between list creation and running this function.
if len(p.children()) == 0: # Filter proces... | The main task of the code is to retrieve and analyze process information by first obtaining a dictionary of processes, handling potential errors during data collection, printing the process dictionary, calculating total processes, and identifying parent processes for a specific process ID (16252). The code ensures grac... | def main():
try:
thisdict = get_process_dict(get_process_list())
except Exception as e:
print(e)
sys.exit()
print(thisdict)
total_processes(thisdict)
parent_processes(thisdict, 16252) |
def _indexSection(self, counter, title=None, anchor=None, toc=True, \
level=1, appendix=False, numbered=True):
counter = str(counter)
if numbered:
if appendix:
autoName = 'Appendix' + self.nbws_cond + counter
autoAnchor = 'rfc.appendix.' ... | This function recursively processes XML <section> elements to generate document sections, handling numbering, anchors, and index entries. It writes section headings, processes child elements like paragraphs and figures, and manages counters for nested sections. In index mode, it builds a document index; otherwise, it r... | def write_section_rec(self, section, count_str="1.", appendix=False,
level=0, numbered=True):
""" Recursively writes <section> elements
We use the self.indexmode flag to determine whether or not we
render actual text at this point or just lookup heade... |
def write_heading(self, text, bullet='', autoAnchor=None, anchor=None,
level=1, breakNeed=0):
""" Writes a section heading """
raise NotImplementedError('write_heading() needs to be overridden')
def write_t_rec(self, t, align='left', autoAnchor=None):
""" Recursively writes... | The code builds an index for an RFC document by parsing XML elements, generating sections (abstract, middle, back), managing reference counters, handling nested references, and appending index items for sections like the abstract, references, appendix, and authors' addresses. It ensures proper anchoring and hierarchica... | def _build_index(self):
self.indexmode = True
# Reset document counters
self.ref_start = 1 # Start of reference counters
self.refs_start = 1 # Start of references sections
self.figure_count = 0
self.table_count = 0
self.eref_count = 0
... |
def pre_indexing(self):
""" First method that is called before traversing the XML RFC tree for indexing"""
raise NotImplementedError('pre_indexing() needs to be overridden')
def _build_index(self):
self.indexmode = True
# Reset document counters
self.ref_start = 1 # ... | The main task of the code is to generate and write an RFC document to a file by processing the content through indexing, formatting, and rendering stages. It handles both ASCII and UTF-8 encodings, applies metadata, constructs internal indexes, formats dates, and writes the final output to the specified file or a tempo... | def write(self, filename, tmpfile=None):
""" Public method to write the RFC document to a file. """
# If the ascii flag is enabled, replace unicode with ascii in the tree
if self.ascii:
xml2rfc.utils.safeReplaceUnicode(self.r)
# Do any pre processing necessary, such as inser... |
def add_hdr():
column_names = ['First','Last', 'Address','City','State','Area Code','Income']
df_csv = pd.read_csv('Exercise_Files/Names.csv', header=None)
df_csv.columns = column_names
return df_csv
def menu():
columns_list = columns()
message = f"""
Columns list: {columns_list}
"""
... | The main task of the code is to filter and return specific data from a DataFrame based on user-selected column and value. It loads data, displays a menu, lets the user choose a column, lists its unique values, selects a specific value, filters the DataFrame where the column matches the selected value, and returns the r... | def print_data():
# df.loc[df['column_name'] == 'property value']
df = add_hdr()
print(menu())
column = select_column()
values = df[column].unique()
message = f'The values of {column} are: {values}'
print(message)
value = select_value()
data = df.loc[df[column] == value]
... |
def find_first_number(line):
first_letter_list = ['o', 't', 'f', 's', 'e', 'n']
for i, character in enumerate(line):
if character.isdigit():
return character
if character in first_letter_list:
number = check_spelled_letter(line + 'xxxxx', character, i)
if numb... | The main task of the code is to extract the first and last numeric characters from a given string (`line`), concatenate them into a two-digit number, and return it. This is commonly used in tasks like parsing calibration numbers from text, where each line contains scattered digits. The function relies on helper functio... | def get_number(line):
first = find_first_number(line)
last = find_last_number(line)
number = create_number(first, last)
return number |
def read_file(filename):
with open(filename, 'r') as of:
lines = of.read().splitlines()
return lines
def get_all_numbers(data):
numbers_list = []
for line in data:
number = get_number(line)
numbers_list.append(number)
return numbers_list
def sum_list_values(values):
total... | The main task of the code is to read data from 'input.txt', extract all numerical values, calculate their sum, and print both the list of numbers and the total sum. The function reads the input file, processes it to identify numbers, computes their cumulative sum, and outputs the results for verification. | def main():
data = read_file('input.txt')
value_list = get_all_numbers(data)
calibration_sum = sum_list_values(value_list)
print(value_list)
print(calibration_sum) |
def get_message_dict(self, message_dict=None):
if message_dict:
new_message_dict = {"v2f": {}, "f2v": {}}
for var in message_dict["v2f"]:
new_message_dict["v2f"][var] = {
factor: (0.5, 0.5) for factor in message_dict["v2f"][var]
}
... | This function performs iterative message passing (sum-product algorithm) to compute marginal probabilities for variables in a probabilistic model. It updates messages between variables, calculates marginal probabilities, and stops early if convergence is detected (two consecutive unchanged probability states). Debug mo... | def marginal_sum_product(self, scope=None, debug=False):
max_iter = 100
if debug:
start_time = time.time()
message_dict = self.get_message_dict()
if debug:
print(
f"Initialize meesage dict (time : {time.time() - start_time}, memory: {sys.getsizeof(... |
def init_artifacts_directory(self):
self.artifacts_path = os.path.join(self.project_path, 'release-artifacts')
if os.path.exists(self.artifacts_path):
shutil.rmtree(self.artifacts_path)
os.makedirs(self.artifacts_path)
def run_unit_tests(self):
with self.stage('Run Unit Tests... | The main task of the code is to execute a build process that initializes an artifacts directory, runs unit tests, builds a Python wheel package, generates documentation, and optionally constructs Docker images and Helm charts based on command-line arguments. | def build(self):
self.init_artifacts_directory()
self.run_unit_tests()
self.build_python_wheel()
self.pkg_docs()
if args.skip_docker is not True:
self.build_docker_image()
if args.skip_helm is not True:
self.build_helm_chart() |
def build(self):
self.init_artifacts_directory()
self.run_unit_tests()
self.build_python_wheel()
self.pkg_docs()
if args.skip_docker is not True:
self.build_docker_image()
if args.skip_helm is not True:
self.build_helm_chart()
def push_docker_image... | The main task of the code is to execute a release process by first building the project, then optionally pushing a Docker image (unless skipped), and finally pushing Git changes related to the release. This ensures the project is built, containerized, and version-controlled for deployment or distribution. | def release(self):
self.build()
if args.skip_docker is not True:
self.push_docker_image()
self.push_release_git_changes() |
def _announce_build_location(self):
if self.project_path_is_current_dir:
print('Building at: ./')
else:
print('Building at: {0}'.format(self.project_path))
def validate(self):
if args.release:
if args.version is None:
raise ValueError('Must set... | The code's main task is to execute a build process by sequentially announcing the build location, validating configurations, preparing resources, conditionally performing a release or build based on `args.release`, tidying up after operations, and generating a report. The method orchestrates these steps to manage softw... | def doIt(self):
self._announce_build_location()
self.validate()
self.prepare()
if args.release == True:
self.release()
else:
self.build()
self.tidy_up()
self.report() |
def save_company_data(url_ = "https://www.moneycontrol.com/stocks/company_info/stock_news.php?", sc_id=[], page_no=1, next=0, years=[]):
for company in sc_id:
df = pd.DataFrame(columns=['company','headline',
'description', 'articleBody'])
for year in years:
... | The code scrapes and saves company data for specified IDs and years, merges all company news data, and cleans the merged news. It iterates through provided company IDs, stores their data, combines news across companies, and performs cleanup to prepare the data for further processing. | def scrap_news(sc_ids=[], years=[]):
for sc_id in sc_ids:
save_company_data(sc_id=[sc_id], years=years)
merge_company_news()
clean_news() |
def make_dataset_v1(df: pd.DataFrame):
x_encoder = OneHotEncoder()
y_encoder = LabelBinarizer()
x, y = x_y_split(df)
y = crop_y_to_binary(y)
attr_info = misc.import_json("./attr_info.json")
nominal = [s["name"] for s in attr_info if s["type"] == "nominal" and s["name"] in x.columns]
numeric... | The code defines a function `make_dataset` that selects and executes one of three version-specific dataset creation methods (`make_dataset_v1`, `make_dataset_v2`, `make_dataset_v3`) based on the input `version` parameter. If the version is invalid, it returns `None`. The primary task is to route dataset processing logi... | def make_dataset(df: pd.DataFrame, version):
if version == 1:
return make_dataset_v1(df)
if version == 2:
return make_dataset_v2(df)
if version == 3:
return make_dataset_v3(df)
return None |
def default(val,d):
if exists(val):
return val
return d() if isfunction(d) else d
def Downsample(dim, dim_out=None, mode='nearest', align_corners=None):
#no strided conv or padding
return nn.Sequential( Rearrange("b c (h p1) (w p2) -> b (c p1 p2) h w", p1=2, p2=2),
nn.... | This code defines a UNet-like neural network architecture for tasks like image generation or segmentation. It initializes convolutional layers, time embeddings via sinusoidal positional encoding, and constructs downsampling/upsampling blocks with ResNet modules, attention mechanisms, and skip connections. The model pro... | def __init__(
self,
dim,
init_dim=None,
out_dim=None,
dim_mults=(1, 2, 4, 8),
channels=3,
self_condition=False,
resnet_block_groups=4,
):
super().__init__()
# determine dimensions
self.channels = channels
self.self_cond... |
def getObjectMimeType(obj):
mime_type = obj.get('additional_mimetype', NOT_SPECIFIED)
if mime_type != NOT_SPECIFIED:
mime_type = mime_type.get('name')
return mime_type
def map_mime_type(mime_type):
if mime_type == '':
return NOT_SPECIFIED
if mime_type == NOT_SPECIFIED:
retu... | The code validates objects in a list against expected MIME types, checking for required scaffold and context files. It reports errors if scaffold files exist without context info, or if the dataset's scaffold tag mismatches actual content. It returns structured error details for file validation and dataset tagging comp... | def test_obj_list(id, version, obj_list, scaffoldTag, bucket):
objectErrors = []
prefix = f"{id}/{version}/files"
foundScaffold = False
foundContextInfo = False
datasetErrors = []
for obj in obj_list:
mime_type = getObjectMimeType(obj)
mapped_mime_type = map_mime_type(mime_type... |
def test(self, monitor_dir, evaluate=True, save_vid=False):
n_episodes = self.num_eval if evaluate else self.num_test
env = gym.make(self.env_name)
if save_vid:
env = wrappers.Monitor(env, monitor_dir, force=True)
else:
env = wrappers.Monitor(env, monitor_dir, for... | The code trains a Q-Network using DDPG with Hindsight Experience Replay (HER), involving replay memory, target network updates, and periodic evaluations. It runs episodes, collects transitions, and updates policy/Q-networks via minibatch sampling. HER generates substitute goals to enhance learning. Models are saved per... | def train(self):
"""Train the Q-Network for a given number of episodes."""
save_graph = True
save_vid = False
replay_memory = ReplayMemory(self.env, self.env_name, self.replay_memory_size)
vid_ckpts = [0, 1/3, 2/3, 1]
vid_ckpts_iter = [int(i * self.num_epochs) for i in v... |
def setup_ui(self):
"""
Removes window border, map button icons and actions. Gets
current username and outstanding tasks and sets greeting.
:return:
"""
self.setWindowFlags(Qt.FramelessWindowHint)
self.setWindowIcon(QIcon(c.OWL))
self.btnLogo.setIcon(QIcon... | The main task of the code is to initialize system operations by setting up the user interface, retrieving metrics, verifying backend status, checking internet connectivity, ensuring software version compliance, and fetching tasks for processing. It orchestrates pre-processing checks and preparations for system function... | def run_operations(self):
self.setup_ui()
self.pull_metrics()
self.check_backend()
self.check_internet()
self.check_version()
self.get_tasks() |
def pre_process_data(self):
"""
Used ot generate the pair quality based on student preference and house properties, amd decision variables for
each student/house pair.
Both are arranged in a dictionary {student ref: {house ref: ...} }
:return: pair_quality_dict, decision_variab... | This code initializes an optimization model for student-house assignment, setting up datasets, decision variables, and constraints (hard/soft) using Gurobi. It processes data, enforces demand, priority, gender split rules, and incorporates supply, Dutch language, and study preference constraints. The objective function... | def __init__(self, student_data, house_data):
# assert(sum(house_data.list_property("room_count")) <= len(student_data.data))
# --> Setting up records
self.student_dataset = student_data
self.house_dataset = house_data
self.decision_variable_dict = {"x": {}, ... |
def add_expense(user):
print("=== Add Expense ===")
categories = database.get_categories()
if not categories:
print("No categories found. Please add a category first.")
return
print("Select a category for the expense:")
for idx, category in enumerate(categories, 1):
print(f"{... | The code presents a user menu for managing expenses, allowing actions like adding expenses, viewing expenses, managing categories, and logging out. It loops until the user selects "Logout," executing corresponding functions based on their choice. | def user_menu(user):
while True:
print("\n=== User Menu ===")
print("1. Add Expense")
print("2. View My Expenses")
print("3. Manage Categories")
print("4. Manage My Expenses")
print("5. Logout")
choice = input("Enter choice: ")
if choice == "1":
... |
def create_account():
username = input("Enter a new username: ")
password = getpass.getpass("Enter a password: ")
if database.add_user(username, password):
print("Account created successfully.")
else:
print("Username already taken. Please try another.")
def login():
username = input(... | The main task of the code is to display a main menu with options for creating an account, logging in, viewing a combined expenses report, or exiting the program. It loops until the user selects "Exit Program," handling each choice by calling corresponding functions like `create_account()`, `login()`, or `view_combined_... | def main_menu():
while True:
print("\n=== Main Menu ===")
print("1. Create an account")
print("2. Log in")
print("3. View Combined Expenses Report")
print("4. Exit Program")
choice = input("Enter choice: ")
if choice == "1":
create_account()
... |
def create_population(size):
population = []
for i in range(size):
board = []
for j in range(BOARD_SIZE):
board.append(random.randint(0, BOARD_SIZE-1))
population.append(board)
return population
def evolve(population):
new_population = []
for i in range(POPULATION... | The code implements a genetic algorithm to find a valid solution (e.g., a solved Sudoku board) by evolving a population over multiple generations. It iteratively selects the fittest individual, checks validity, and returns the solution if found. | def solve():
population = create_population(POPULATION_SIZE)
for generation in range(GENERATIONS):
population = evolve(population)
best_board = None
best_fitness = 0
for board in population:
fitness = calculate_fitness(board)
if fitness > best_fitness:
... |
def _reset_synth(self):
self.fsynth.players_clear()
self.fsynth.fxchain_clear()
self.fsynth.router_default()
self.fsynth.reset()
for opt, val in {**_SYNTH_DEFAULTS, **self.cfg.get('fluidsettings', {})}.items():
self.fluidsetting_set(opt, val)
def _refresh_bankfonts(se... | The code loads a bank from a file or raw YAML, parsing it into nested dicts/lists. It requires a 'patches' element, sets the file as 'currentbank' if loaded from a file, resets the synth, loads soundfonts, applies 'init' settings (sysex, fluidsettings, messages), and returns the YAML stream. If no args are provided, it... | def load_bank(self, bankfile='', raw=''):
"""Load a bank from a file or from raw yaml text
Parses a yaml stream from a string or file and stores as a
nested collection of dict and list objects. The top-level
dict must have at minimum a `patches` element or an error
is raised. If... |
def check_service(
retry=10,
delay=3,
print_attempt=True,
service_name=None,
service_port=None):
config = get_config()
if not service_name:
service_name = config.get(DB_HOST_KEY, 'mariadb')
if not service_port:
service_port = config.get(DB_PORT_KEY, DB_PORT)
is_db_c... | The main task of the code is to verify the health and connectivity of multiple Redis-related services (queue, cache, socket.io) and a general service, then confirm all connections are established successfully by printing "Connections OK". | def main():
check_service()
check_redis_queue()
check_redis_cache()
check_redis_socketio()
print('Connections OK') |
def _review(cursor, query):
try:
print('sync...', end='', flush=True)
sync(cursor)
print('done')
except Exception as e:
print(e)
cursor.execute(query)
rows = cursor.fetchall()
count, total = 0, 0
try:
for row in rows:
word = row[0]
... | (The main task of the code is to define a command-line interface for interacting with a SQLite database, offering multiple modes to query and manage vocabulary words. These modes include reviewing words by randomness, recency, strength, or forgotten status, listing words based on time or status, and syncing data. The c... | def main():
options = {
'sync': sync,
'recite': recite,
'review_random': lambda cursor:
_review(cursor,
"SELECT DISTINCT word FROM recite_info "
"ORDER BY random() LIMIT 50"),
'review_within_1day': lambda cursor:
_review(cursor,
... |
def unpack_inputs(self, inputs):
inp_tensor, msk_tensor, seg_tensor, step = inputs
if self.use_cuda:
msk_tensor = msk_tensor.view(-1, self.max_len).cuda()
inp_tensor = inp_tensor.view(-1, self.max_len).cuda()
seg_tensor = seg_tensor.view(-1, self.max_len).cuda()
... | The code processes input data through a neural network model, incorporating attention mechanisms and user-specific features to generate probabilistic outputs. It combines textual embeddings with relevance scores (Rs) and user metadata to compute a weighted probability distribution over classes, returning log-transforme... | def forward(self, inputs, Rs, user_metadata):
inp_tensor, msk_tensor, seg_tensor, step = self.unpack_inputs(inputs)
# msk_tensor: (B * evi_num, 130)
# seg_tensor: (B * evi_num, 130)
# mask_text: Every sentence starts with 0, followed by
# 1's at positions where tokens are presen... |
def easy_move(sign):
is_finish = False
while not is_finish:
x_coord = random.randint(0, 2)
y_coord = random.randint(0, 2)
if board[x_coord][y_coord] == ' ':
board[x_coord][y_coord] = sign
is_finish = True
else:
continue
def medium_move(sign):
... | The function `player_move` determines the player's action based on their difficulty level ("easy", "medium", "hard", or "user") and the game sign. It prints the selected move level and delegates execution to corresponding functions (`easy_move`, `medium_move`, `hard_move`, or `user_move`) to handle the move logic. | def player_move(player, sign):
if player == "easy":
print('Making move level "easy"')
easy_move(sign)
elif player == "medium":
print("Making move level 'medium'")
medium_move(sign)
elif player == "hard":
print("Making move level 'hard'")
hard_move(sign)
el... |
def open_inv():
moveClick(inv_pic)
print("Inventory opened")
return 0
def GetCord(file_path):
centre=pag.locateCenterOnScreen(file_path, confidence=0.8)
if centre == None:
return None
return (list(centre))
def moveClick(file_name):
cordlist=GetCord(file_name)
random_move(cordlist... | The code's main task is to search for and click the first available seed in a game inventory. It opens the inventory, iterates through provided seed paths, checks each for presence using GetCord(), clicks the first found seed via moveClick(), then closes the inventory. The function returns 0 after a 1-second delay, ind... | def choose_seed(seed_pathes):
open_inv()
time.sleep(0.6)
for seed in seed_pathes:
if GetCord(seed) != None:
print(seed, " found in inventory")
moveClick(seed)
break
else:
print(seed, " not found in inventory")
time.sleep(1)
close_inv()
... |
def GetCord(file_path):
centre=pag.locateCenterOnScreen(file_path, confidence=0.8)
if centre == None:
return None
return (list(centre))
def moveClick(file_name):
cordlist=GetCord(file_name)
random_move(cordlist)
pag.click()
def check_troubles():
if GetCord(chest_pic) != None:
... | The main task of the code is to repeatedly click on plants (via `moveClick`) until their coordinates become invalid (`GetCord` returns None), performing up to 10 clicks per plant before checking for issues (`check_troubles`) to manage potential errors or reset conditions. | def grab_plants():
for plant in plants_pathes:
i = 0
while GetCord(plant) != None:
moveClick(plant)
i += 1
if i == 10:
check_troubles()
i = 0 |
def GetCord(file_path):
centre=pag.locateCenterOnScreen(file_path, confidence=0.8)
if centre == None:
return None
return (list(centre))
def moveClick(file_name):
cordlist=GetCord(file_name)
random_move(cordlist)
pag.click()
def check_seeds():
for ns in no_seed_pathes:
if GetC... | The code automates planting seeds by repeatedly detecting and clicking on holes (via `moveClick`) until no more holes are found. After every 5 clicks, it checks seed status with `check_seeds()`. The loop exits when `GetCord` returns `None`, ensuring controlled planting cycles. | def plant_seeds():
i = 0
while GetCord(hole_pic) != None:
moveClick(hole_pic)
i += 1
if i == 5:
check_seeds()
i = 0 |
def format_example_for_autoais(evidence, claim):
return "premise: {} hypothesis: {}".format(evidence, claim)
def get_entail_label_ids(tokenizer):
pos_id = tokenizer.convert_tokens_to_ids("1")
neg_id = tokenizer.convert_tokens_to_ids("0")
return pos_id, neg_id
def stretch_nli_rerank(example,
... | The code performs inference to assess Argumentation Integrity Score (AIS) between a premise (evidence) and hypothesis (claim) using a HuggingFace model. It tokenizes input text, checks token length against `max_len`, and applies either `stretch_nli_rerank` (for long inputs) or `_autoais_predict` (for shorter inputs) to... | def infer_autoais(example,
tokenizer,
model,
max_len:int = 512):
"""Runs inference for assessing AIS between a premise and hypothesis.
Args:
example: Dict with the example data.
tokenizer: A huggingface tokenizer object.
model: A hug... |
def checkPosInt(n,n0=0):
if (not isinstance(n,int)):
raise TypeError(f"{n} is not an integer.")
elif n < n0:
raise ValueError(f"{n} is an integer < {n0}")
else:
pass
def eulerPhi(n):
'''
The Euler totient function, its primary definition.
'''
coprime = [m for m in ran... | The function `necklacePoly(n, k)` calculates the number of distinct necklaces of length `n` using `k` colors, accounting for rotational symmetry. It applies the formula from combinatorics: summing Euler's totient function φ(d) multiplied by $k^{n/d}$ for all divisors `d` of `n`, then dividing by `n`. This counts unique... | def necklacePoly(n,k=2):
'''
Number-theoretical counting for the number of necklaces of length n
made with k beads. See Wikipedia.
'''
checkPosInt(n), checkPosInt(k,1)
if n == 0:
return 1
else: # n>=1
return sum([eulerPhi(d)*pow(k,n//d) for d in divisors(n)])//n |
def checkPosInt(n,n0=0):
if (not isinstance(n,int)):
raise TypeError(f"{n} is not an integer.")
elif n < n0:
raise ValueError(f"{n} is an integer < {n0}")
else:
pass
def orbit(ar,bracelet=False):
'''
Given an array, generate the orbit.
'''
L = len(ar)
cyclic_orbit... | The code generates all unique necklaces of length `n` with `k` bead colors, considering rotational and reflectional symmetries (if `bracelet=True`). It recursively builds necklaces by extending shorter ones, using orbit representatives to eliminate duplicates. For each shorter necklace, it appends all possible bead col... | def allNecklaces(n,k=2,bracelet=False):
'''
Generate all necklaces with k beads of length n.
'''
checkPosInt(n), checkPosInt(k,1)
if n==0:
return [()] #empty necklace
elif n==1:
return [(i,) for i in range(k)]
elif n>1:
out = set()
shortNecklaces = allNecklac... |
def checkPosInt(n,n0=0):
if (not isinstance(n,int)):
raise TypeError(f"{n} is not an integer.")
elif n < n0:
raise ValueError(f"{n} is an integer < {n0}")
else:
pass
def largestDomain(necklace):
# A necklace is of the form (i1, i2, i3, ...). A domain is a group of neighboring bea... | The function `validSingleTraces(n,k,N)` generates all valid necklaces of length `n` with `k` bead colors, ensuring no more than `N-1` consecutive beads of the same color. It filters out invalid necklaces using a domain check and adds constant-color necklaces (all beads same color) when `n=N`. The result is a sorted lis... | def validSingleTraces(n,k,N):
'''
Generate all necklaces with k beads of length n, and at most N-1 beads of the same color appear in a row.
For n=N we make an exception, since (i,i,...,i) [n copies of letter i] is a valid single-trace operator.
'''
checkPosInt(n), checkPosInt(k,1), checkPosInt(N,2)
... |
def select_species_data(self, species=None, **kwargs):
# def select_species_data(self,species=None,Wave=None, WaveMin=None, WaveMax=None,
# OscillatorStrength=None, OscillatorStrengthMin=None, OscillatorStrengthMax=None,
# Gamma=None, GammaMin=None, GammaMax=N... | This code fits spectral data using a spline continuum model with specified anchor points, iteratively building and refining the model until a Bayesian criterion (e.g., BIC) stops the process. It selects species-specific data, extracts fitting parameters, and applies weighted least-squares fitting. The result is stored ... | def fit(self, species="KI", n_anchors=5, windowsize=3, criteria="BIC", **kwargs):
"""
The main fitting method for the class.
Currently kwargs for select_species_data to make code more pretty
:param species: name of the species
:param n_anchors: number of anchor points for spline ... |
def _load(data):
if isinstance(data, (str, Path)):
return pd.read_excel(data, header=1).iloc[:-1].set_index("Car")
elif isinstance(data, pd.DataFrame):
return data
else:
raise TypeError(f"Unsupported init type: {type(data)}")
def get_total_characteristics(self... | This code initializes a class to process data from a file, extracting key metrics like total characteristics, customers, and options, while setting up parameters for weight calculations, ranking, and optimization. It prepares data structures for further analysis or modeling, likely for resource allocation or decision-m... | def __init__(self, file):
self.df = self._load(file)
self.order_data = self.df.loc["Data Order", :]
self.df = self.df.iloc[:-1]
self.total_chars = self.get_total_characteristics()
self.total_customers = self.get_total_customers()
self.total_options = self.get_options()
... |
def get_start_end_time_local(strava_activity: Dict) -> Tuple[dt.datetime, dt.datetime]:
start_lat = strava_activity['start_latlng'][0]
start_lng = strava_activity['start_latlng'][1]
activity_timezone = get_timezone_at_location(start_lat, start_lng)
start_time = pd.to_datetime(strava_activity['start_date... | The function generates a weather report for a Strava activity by first retrieving the local start and end times of the activity, then fetching corresponding weather data using an API key, and finally compiling the data into a formatted weather report string. | def generate_weather_report_for_activity(strava_activity: Dict, api_key: str) -> str:
start_time_local, end_time_local = get_start_end_time_local(strava_activity)
weather_data = download_weather_data_for_activity(strava_activity=strava_activity, api_key=api_key)
return generate_weather_report_from_weather_d... |
def get_summit_classifications(summits: pd.DataFrame,
classification_columns: List[str]) -> Dict[Any, List[str]]:
"""
Given a table of summits, return a dictionary where the keys are summit ID and the values are a list of
corresponding applicable summit classifications
:p... | The function generates a report on visited summits by processing classification data: mapping codes to names, reducing classifications per configuration, then compiling the report with processed data and settings. | def generate_summit_report(summits: pd.DataFrame, config: ReportConfiguration) -> str:
classification_codes = config.code_mapping
summit_classifications = get_summit_classifications(summits=summits,
classification_columns=list(classification_codes.keys()))... |
def check_return_buy_buy_sell(self, sym1, sym2, sym3):
"""
Function returns the rate of return ignoring all costs.
"""
# Just check if it's a profitable swap, ignore concrete amounts.
current_price1 = self.fetch_current_ticker_price(sym1)
current_price2 = self.fetch_curre... | The code detects and executes triangular arbitrage opportunities using two strategies (BUY_BUY_SELL and BUY_SELL_SELL) by continuously checking market quotients. It calculates potential profits after transaction fees, executes trades when the profit margin exceeds a specified threshold, and repeats until the profit fal... | def execute_triangular_arbitrage(self, sym1, sym2, sym3, transaction_fee, min_profit_percent):
total_val = (self.check_return_buy_buy_sell(sym1, sym2, sym3) - transaction_fee*3)
while(total_val - 1 >= min_profit_percent): # Be sticky! Keep this going, unless the profit falls.
print(f"{datet... |
def append_arff(self, dataset):
if not dataset.endswith('.arff'):
dataset = dataset + '.arff'
return dataset
def get_data(self, dataset):
dataset = self.append_arff(dataset)
if not dataset in self.data_cache:
X, cluster_labels = read_arff(os.path.join(self.path, d... | This function determines if there are bridge nodes in a dataset for a given k value, using cached results to avoid redundant computation. It appends ARFF data, checks cache validity, retrieves cluster labels and local indices, identifies bridges via a helper function, and returns the cached bridge status. | def get_bridge(self, dataset, k):
dataset = self.append_arff(dataset)
if not dataset in self.bridge_cache or not k in self.bridge_cache[dataset]:
_, cluster_labels = self.get_data(dataset)
_, local_indices = self.get_neighbor(dataset, k)
is_bridge = determine_bridges... |
def set_data(self):
data_fn = self.device + '.mat'
if self.where == 'local':
path = ('/Users/Sijie/GoogleDrive/PERMIT/3-Simulation Code' +
'/packet size obfuscation/python_code/other/SmartHomeIoT/' +
'matfiles/Filtered/')
self.data = loadma... | This code initializes a configurable system for data processing, handling both synthetic and real datasets. It sets parameters for input/output sizes, utilization rates (rho), arrival rates, and coefficient of variation. It calculates input/output configurations based on user-defined rules, adjusts alphabet scales, and... | def __init__(self,
synthetic=False, device='SleepCamMerged',
where='local', input_typ='iid',
n_dev=2, n_eps=5, n_rho=6,
pmf='Zipf', scale=0.01,
T=100000, in_tau=1, out_tau=None,
n_reps=10, n_out=5,
... |
def get_current_line(self):
return self.lines[self.index]
def next(self):
self.index += 1
def parse_shape(self, origin, destination):
os.makedirs(self.temp_folder, exist_ok=True)
os.chdir(ffdec_path)
subprocess.run([
'ffdec.bat',
'-zoom',
'10',... | The main task of the code is to parse export data by identifying the type (shape, font, or sprite) from the current line and delegating to the corresponding parsing method (parse_shape, parse_font, or parse_sprite) with the provided origin and destination parameters. | def parse_export(self, origin, destination):
export_type = self.get_current_line().strip()
self.next()
if export_type == 'shape':
self.parse_shape(origin, destination)
elif export_type == 'font':
self.parse_font(origin, destination)
elif export_type == 'sp... |
def get_current_line(self):
return self.lines[self.index]
def next(self):
self.index += 1
def parse_export(self, origin, destination):
export_type = self.get_current_line().strip()
self.next()
if export_type == 'shape':
self.parse_shape(origin, destination)
el... | This code parses a file line by line, extracting origin and destination paths using a regex pattern, then processes each pair with self.parse_export(). It skips empty lines and continues until the file ends. | def parse_origin_file(self):
line_match = re.search('(.*)->(.*)', self.get_current_line())
origin = os.path.join(original_asset_path, line_match.group(1).strip())
destination = os.path.join(game_asset_path, line_match.group(2).strip())
self.next()
while self.index < self.length a... |
def get_root_path(dir, base_dir):
n_bdir = os.path.normpath(base_dir)
n_dir = os.path.normpath(dir)
diff = n_dir.removeprefix(n_bdir)
return diff if diff else '/'
def load_segment_name(dir, base_dir):
segment = get_last_path_segment(dir, base_dir)
logging.info(f'loading segment {segment} name')... | The function processes a directory structure by recursively handling child directories, loading metadata and data entries, validating directory contents, and updating localization information in a database. It hashes paths, checks for required files, and stores entries in sets/hashes, with conditional operations based ... | def process_child(dir, base_dir):
root_path = get_root_path(dir, base_dir)
logging.info(f'processing {root_path}')
load_segment_name(dir, base_dir)
load_key_icon(dir, base_dir)
path_hash = hash(root_path)
logging.debug(f'inserting {root_path} as {path_hash}')
DRY_RUN or db.hset('key_hashes'... |
def load_segment_name(dir, base_dir):
segment = get_last_path_segment(dir, base_dir)
logging.info(f'loading segment {segment} name')
dir_entries = os.listdir(dir)
if not NAME_FILE in dir_entries:
abort(f'entry {dir} has no {NAME_FILE}')
name_file = os.path.join(dir, NAME_FILE)
name_fil... | The code processes the root directory by validating its structure, storing entry hashes, and handling localization data. It checks for required files, skips invalid entries, and recursively processes child directories. If not in dry-run mode, it updates the database with hashes, navigation links, and localized names/ic... | def process_root(dir):
logging.info('processing /')
load_segment_name(dir, base_dir=dir)
path_hash = hash(ROOT)
logging.debug(f'inserting {ROOT} as {path_hash}')
DRY_RUN or db.hset('key_hashes', path_hash, ROOT) # set hash -> path
dir_entries = os.listdir(dir)
dir_entries.remove(NAME_FILE... |
def _checkLambda(lamb, lmin, lmax, lstep):
"""
Helper function that check the lambda parameter limits
"""
if(lamb > lmax):
return lmax
elif(lamb < lmin):
return lamb*lstep*lstep
else:
return lamb
def CheckPars(pars, Pinfo):
"""
Helper function that check... | The code implements a **Levenberg-Marquardt algorithm** for non-linear least-squares fitting. Its main task is to minimize the $\chi^2$ (chi-squared) statistic by iteratively adjusting model parameters to better fit observed data. It uses a damping parameter ($\lambda$) to balance between gradient descent and Gauss-New... | def LevMar(fx, par_in, obs_in, sig_in, pinfo, udat, Niter = 20, init_lambda=10.0, \
lmin = 1.e-4, lmax=1.e4, lstep = 10**0.5, chi2_thres=1.0, \
fx_thres=0.001, auto_derivatives = False, verbose = True, n_reject_max = 6,
svd_thres = 1.e-14):
"""
Levenberg-Marquard based fitting r... |
def _split_data(self):
"""
Split data into training and test sets
Parameters
----------
None
Returns
-------
None
"""
if not self.balance_data:
self.X_train, self.X_test, self.y_... | The main task of the code is to fit a machine learning model (XGBoost, Random Forest, or LightGBM) using specified hyperparameters. It handles data splitting, hyperparameter tuning if needed, trains the model on training data, computes metrics, and saves the trained model and artifacts. The process includes logging ste... | def fit_model(self):
"""
Fit model
Parameters
----------
None
Returns
-------
model : object
Model object
"""
if self.X_train.empty:
self._split_data(... |
def annot_pencil(annotation, res):
if 'commands' not in annotation:
return ''
width,height = res
svg = '<path stroke="#%06x" fill="none" stroke-linejoin="round" stroke-linecap="round" stroke-width="%.2f" d="' % (int(annotation['color']), (float(annotation['thickness'])/100*width))
datapoints = ... | The code generates SVG content based on the annotation type by delegating to specific drawing functions (e.g., pencil, line, ellipse) using the slide's dimensions. It returns the corresponding SVG string or logs an error for unknown types. | def generate_svg(annotation, slide):
width, height = slide['width'], slide['height']
if annotation["type"] == "pencil":
return annot_pencil(annotation, res=(width,height))
elif annotation["type"] == "line":
return annot_line(annotation, res=(width,height))
elif annotation["type"] == "el... |
def is_taskcluster_loaner():
return "TASKCLUSTER_INTERACTIVE" in os.environ
def get_task(branch, revision):
task = get_json(
"https://index.taskcluster.net/v1/task/gecko.v2.%s.revision.%s.firefox.linux64-ccov-debug"
% (branch, revision)
)
return task["taskId"]
def get_last_task():
la... | The main task of the code is to parse command-line arguments for coverage report generation, download coverage artifacts based on task IDs derived from branch/commit or last task, use grcov to generate reports, and output either high-level coverage statistics or HTML reports, with conditional handling for Taskcluster e... | def main():
parser = argparse.ArgumentParser()
if is_taskcluster_loaner():
nargs = "?"
default_src_dir = "/home/worker/workspace/build/src/"
default_branch = os.environ["MH_BRANCH"]
default_commit = os.environ["GECKO_HEAD_REV"]
else:
nargs = None
default_src_... |
def get_closest_enemy_in_radius(self, enemies):
closest_enemy_distance = self.radius
closest_enemy_in_radius = None
closest_aligned_enemy_distance = self.radius
closest_aligned_enemy = None
for enemy in enemies:
enemy_dist = self.calc_curr_distance_to_target(enemy)
relative_angle = sel... | This code manages an entity's firing mechanics by tracking cooldowns, selecting valid targets within range, calculating aim vectors, and spawning projectiles when conditions are met. It updates fire rate accumulation, checks target validity, computes aiming angles, and fires bullets if the cooldown is complete and the ... | def update_firing(self, dt, enemies, projectiles):
# time gap between shots
if self.fire_rate_acc < self.fire_rate:
self.fire_rate_acc += dt
else:
self.can_fire = True
if self.current_target is None or self.current_target.should_die or \
self.distance_to_target > self.radius or ... |
def update_firing(self, dt, enemies, projectiles):
# time gap between shots
if self.fire_rate_acc < self.fire_rate:
self.fire_rate_acc += dt
else:
self.can_fire = True
if self.current_target is None or self.current_target.should_die or \
self.distance_to_target > self.radius or ... | This code updates a turret's behavior based on placement status. When placed, it calculates direction vectors, rotates the turret image to face targets, and manages firing logic. When unplaced, it tracks mouse movement, validates placement positions, and updates visual feedback. The code ensures proper rotation alignme... | def update(self, mouse_pos, dt, enemies, projectiles, all_turrets, map_rect):
if self.placed:
# show attack radius when hovered over
# if self.rect.collidepoint(mouse_pos):
# self.draw_radius = True
# else:
# self.draw_radius = False
self.update_firing(dt, enemies, projectil... |
def logger(msg, data):
logfile = 'tslog.txt'
with open(logfile,'a') as f:
f.write(msg+' '+str(data)+'\n')
def getRosters(allrows):
teams = {}
#scores = []
for i in allrows.keys():
#print('get rosters...',allrows[i][0][0],'\n\n')
#print(i,type(i))
p = []
if allrows[i][0][0] == None:
print('oops')
... | The code scrapes HTML tables from URLs constructed with year, season, and event codes, extracts specific rows, processes data into dictionaries, and generates rosters/rankings using helper functions. It iterates over 14–19 years, two seasons, and event codes, parsing structured data from web pages for analysis. | def main():
for year in range(14,20):
for season in range(2):
for event in eventCodes[season]:
#if season==2:
# years = range(13,19)
#else:
# years = range(14,19)
#for year in years:
testurl = url1 + str(year)+ str(season+1) + '/' + str(event) + url2
print("loading...", testurl)
... |
def check_functions(the_rbt):
FUNC_LIST = ['insert', 'remove', 'search', 'path', 'min', 'max', 'bfs']
log.info(f"{newline}Testing if the class has the required methods. ({FUNC_LIST})")
print(f"{newline}Testing if the class has the required methods. ({FUNC_LIST})")
for func in FUNC_LIST:
if no... | The code tests a red-black tree implementation by verifying required functions, inserting/removing elements, checking path lengths, min/max values, BFS traversal, and structural integrity. It uses predefined lists for operations, logs results, generates histograms, and ensures correctness through multiple validation st... | def test_redblacktree(the_rbt):
# Test if it has the required functions
check_functions(the_rbt)
base_list, remove_list = create_base_and_remove_lists()
log.debug(f'Base List{base_list}')
log.debug(f'Remove List{remove_list}')
# insert_remove_cplist=create_insertremove_cplist(base_list, rem... |
def resolveMac(mac):
global ouiObj
if mac[:8].upper() in ouiObj:
return ouiObj[mac[:8].upper() ]
return "COULDNT-RESOLVE"
def stop():
global alreadyStopping
debug("stoping called")
if not alreadyStopping:
debug("setting stopping to true")
alreadyStopping = True
de... | The code processes network packets to track devices by their MAC addresses, updating metrics like RSSI, first/last seen times, and count of detections. It maintains a dictionary (`deviceDictionary`) storing device information, updating entries when a known MAC is encountered or adding new entries for unknown MACs. Exce... | def packetHandler(pkt):
try:
global currentTime
global deviceDictionary
rssi = pkt.radiotap.dbm_antsignal
mac_address = pkt.wlan.ta
vendor = resolveMac(mac_address)
currentTime = datetime.datetime.now()
if mac_address not in macList:
if mac_add... |
def reward(self):
if self.rewardType == "basic":
return self.reward_basic()
return 0
def clear_reward_bool(self):
for key in self.reward_bool.keys():
self.reward_bool[key] = False
def update_state(self):
if self.stateType == "12bool":
return self.upda... | This function updates reward values based on the snake's progress toward the apple, calculates distances for proximity rewards, generates the reward, updates the game state, and returns the next state, reward, termination status, and score for reinforcement learning training. | def conclude_round(self):
# update reward
self.reward_bool["eat"] = not (self.apple.rect.x == self.last_apple.x \
and self.apple.rect.y == self.last_apple.y)
last_distance = euclidean(
[self.last_snake.x, self.last_snake.y],
[self.last_apple.x, self.last_apple... |
def game_over(self):
self.done = True
def move_apple(self):
avoid = [(rect.x, rect.y) for rect in self.snake.body]\
+ [(rect.x, rect.y) for rect in self.extraWalls]
self.apple.move(avoid)
def conclude_round(self):
# update reward
self.reward_bool["eat"] = not (self.ap... | This method handles a game step for a snake game: processes actions to change direction, moves the snake, checks wall/body collisions, manages apple consumption, updates score, and concludes the round unless in manual control. | def step(self, action=None):
if self.done:
return
if (not self.manualControl) and action != None:
self.snake.changeDirection(action)
self.last_apple = self.apple.rect
self.last_snake = self.snake.head
# move forward
self.snake.addHead(c... |
def define_username(self):
choice_input = 0
while True:
if choice_input == 0:
choice_input = 1
self.name = input("To begin, please enter a Username\n ==> ")
if len(self.name) < 2 or len(self.name) > 8:
print("Usernames must ... | The code initializes a game by welcoming the player, prompting for a username, and offering a tutorial. It handles user input to decide whether to run the tutorial, applies penalties for invalid choices, then proceeds with game setup and initiates the main game loop via `round_repeater`. | def launch_game(self):
print("Welcome... to \'The Skies of Keizhaal\'.")
self.define_username()
print(" " +
"Hello " + str(self.name) + "\n" +
" Would you like to play the Tutorial?\n" +
"(0 for no I've got this, 1 for yes im a bitch... |
def is_complete(self):
return all(var.is_assigned() for var in self.variables)
def select_var(self):
unassigned_vars = [var for var in self.variables if not var.is_assigned()]
return min(unassigned_vars, key=lambda var: len(var.domain))
def arc3(self, var):
queue = [(Xk, var) for Xk in s... | This function performs backtracking with forward checking and arc consistency (AC-3) to solve a constraint satisfaction problem. It selects a variable, assigns values, checks arc consistency, and recursively attempts to solve the problem. If a value leads to a solution, it returns True; otherwise, it restores domains a... | def backtrack_arc(self):
if self.is_complete():
return True
var = self.select_var()
old_domains = {v: v.domain.copy() for v in self.neighbors[var]}
for value in var.domain:
var.set_val(value)
if self.arc3(var):
success = self.backtra... |
def get_selected_camera_shape():
for each_camera_transform in cmds.ls(sl=True): #loop over all cameras that are selected (transform node)
camera_shape = cmds.listRelatives(each_camera_transform,type="camera") #find the shape node
if camera_shape: #only set attr if a camera shape was found
... | This code configures depth of field (DOF) settings for a 3D camera by enabling DOF, adjusting locator scale, and creating two locators between the camera and a target object to define focus distance. It retrieves camera and object data, sets DOF attributes, uses a distance tool to measure positions, and returns the cam... | def basic_depth_of_field_settings():
#get selected camera shape, transform and objec to focus for DOF
shot_camera_shape = get_selected_camera_shape()
shot_camera_transform = get_selected_camera_transform()
object_to_focus = get_object_to_focus()
cmds.setAttr(shot_camera_shape+".depthOfField", True)... |
def update(self):
terminated = [k for k, v in self.active.items() if not v.aborted and not v.blocking and v.terminating]
aborted = [k for k, v in self.active.items() if v.aborted and v.terminating]
def _update(k, op):
tr:Transaction = self.active.get(k, None)
if tr.ro:
... | The code processes a system's state by repeatedly updating active components, checking for changes, and handling dependencies. It iterates through sites, updates their status, and adjusts the system until no changes occur. After stabilizing, it checks for blocked items and potential cycles, updating the system again if... | def tick(self):
changed = True
while changed:
changed = False
self.dep_graph = set()
for _,v in self.active.items():
v.blocking = False
for s in self.sites:
if s.up:
res = s.tick()
cha... |
def input(self, file):
if file.endswith('.DS_Store'):
return
cmds = open(file, 'r').read().split('\n')
for c in cmds:
self.parse(c)
self.transmgr = transmgr.TransMgr()
def mega(self, loc):
from os import listdir
from os.path import isfile, join
... | This code processes user commands in a loop until 'exit' is entered. It handles 'source', 'mega', 'h', and 'res' commands by invoking specific methods or actions, with other commands parsed via self.parse(). The primary task is to act as a command-line interface for managing translation tasks and responding to user inp... | def prompt(self):
cmd = ''
while cmd != 'exit':
cmd = input()
if cmd.startswith('source'):
self.transmgr = transmgr.TransMgr()
self.input(cmd[cmd.find(' '):].strip())
elif cmd.startswith('mega'):
self.mega(cmd[cmd.find('... |
def write(self, tr, data, val, j = None):
if j is None:
tr.seq += 1
j = Job(tr, data,tr.seq,val)
else:
tr = j.tr
data = j.data
val = j.val
ups = []
if not data % 2:
for s in self.sites:
if s.up:
... | This code processes commands to manage transactions in a distributed system. It handles transaction termination ('e'), writes ('w'), site failures ('f'), data dumps ('d'), transaction initiation ('begin'), site recovery ('rec'), and reads ('r'). It checks transaction validity, updates states, and triggers actions like ... | def exec(self, cmd, p1, p2, p3):
if cmd[0] == 'e':
tid = int(p1[1:]) # end p1
tr : Transaction = self.active.get(tid, None)
if tr is not None:
tr.terminating = True
# else:
# print(f"Transaction T{tid} terminated before completion."... |
def test1():
"""Tests for generic sorting and binary search."""
print(80 * "#" + "\nTests for generic sorting and binary search.")
test1_1()
test1_2()
test1_3()
test1_4()
test1_5()
def test2():
print("#" * 80 + "\nSearch for substrings up to length n")
test2_1()
test2_2()
def tes... | The main task of the code is to execute three test functions (test1, test2, test3) sequentially within the main function, likely for testing or validation purposes. Each test function may perform specific checks, operations, or simulations, and the main function orchestrates their execution in order. | def main():
test1()
test2()
test3() |
def face_locations_effective(x):
return (face_recognition.face_locations(resize(x, 256)) or
face_recognition.face_locations(resize(x, 512)) or
face_recognition.face_locations(resize(x, 1024)) or
face_recognition.face_locations(resize(x, 256), model='cnn'))
def plot_face_rect(imag... | This function processes a list of image URLs to extract facial encodings, filtering images based on face count thresholds (min/max). For valid images, it identifies face locations, selects the most relevant face (via 'how' parameter), generates encodings, and returns structured results including face count, encodings, ... | def images_to_encodings(urls: List[str], max_faces=3, min_faces=1, how='center', plot=False):
results = {}
for url in tqdm(urls):
image = face_recognition.load_image_file(requests.get(url, stream=True).raw)
locations = face_locations_effective(image)
if len(locations) > max_faces or len(... |
def new_temp_dir(ctx):
memory_dir = '/dev/shm'
temp_dir = memory_dir if osp.isdir(memory_dir) else None
backup_dir = tempfile.mkdtemp(prefix='inkbot-', suffix='.bak', dir=temp_dir)
try:
yield backup_dir
finally:
ctx.run(list2cmdline(['rm', '-rf', backup_dir]))
def rsync(ctx, src, de... | (The code backs up darknodes and credentials by copying files to a temporary directory, excluding specified paths, replacing directory references in Terraform files, then encrypting and archiving the result into the specified backup file.) | def backup(ctx, backup_file):
'''
Backup darknodes and credentials to <backup-file>
'''
os.stat(osp.dirname(osp.abspath(backup_file))) # validate dir
with new_temp_dir(ctx) as backup_dir:
excludes = [
'.terraform',
'/bin/',
'/darknode-setup',
... |
def install_darknode_cli(ctx, update=False):
'''
Install darknode-cli if not already installed
'''
if osp.exists(osp.join(real_darknode_dir, 'bin')):
if update:
ctx.run('curl https://releases.republicprotocol.com/darknode-cli/update.sh -sSf | sh')
else:
ctx.run('curl http... | The function `restore` recovers darknodes and credentials from a specified backup file. It decrypts and extracts the backup, modifies Terraform configurations to align with the current darknode directory, synchronizes files, and identifies any extra darknodes. It initializes Terraform, handling potential failures, and ... | def restore(ctx, backup_file):
'''
Restore darknodes and credentials from <backup-file>
'''
install_darknode_cli(ctx)
with new_temp_dir(ctx) as backup_dir:
decrypt_extract(ctx, backup_file, backup_dir)
search_replace_tf(backup_dir, re.escape(darknode_dir_var), darknode_dir)
... |
def is_element_present(self, locator_properties, locator_type="id", max_time_out=10):
"""
This method checks for presence of element & return the bollean value
:param locator_properties: it takes locator string as parameter
:param locator_type: it takes locator type as parameter
... | This method performs a mouse click on an element if it is present within a specified timeout. It uses the provided locator type and properties to locate the element. If the element is found, it clicks the element and logs a success message; otherwise, it logs an error indicating the element was not found. | def mouse_click_action_on_element_present(self, locator_properties, locator_type="id", max_time_out=10):
"""
This method is used to perform mouse click action according to the locator type and property
:param locator_properties: it takes locator string as parameter
:param locator_type: ... |
def start_core_service(self):
try:
if isAdmin():
try:
self._logger.info(f"starting {self._settings['roon_service_name']}")
from subprocess import run
commandString = f"net start \"{self._settings['roon_service_name']}\""
... | This code initializes and manages a service by starting a core service, authorizing if credentials are missing, connecting to a Roon core, configuring settings, launching a web server, and maintaining periodic pings to the core. It ensures settings are saved and handles service lifecycle tasks, including thread managem... | def start(self):
try:
'''start service if it is not started'''
self.start_core_service()
# authorize if necessary
try:
if self._settings["core_id"].strip() == "" or self._settings["token"] == "":
self.authorize()
exc... |
def unary(self):
# Optional unary +/-
if self.checkToken(TokenType.PLUS) or self.checkToken(TokenType.MINUS):
self.emitter.emit(self.curToken.text)
self.nextToken()
self.primary()
def checkToken(self, kind):
return kind == self.curToken.kind
def nextToken(self):
... | The `term` method parses a sequence of unary expressions separated by multiplication (`*`) or division (`/`) operators. It starts by parsing a unary expression, then repeatedly checks for `*` or `/` tokens. For each operator found, it emits the token, advances to the next token, and parses another unary expression. Thi... | def term(self):
self.unary()
# Can have 0 or more *// and expressions.
while self.checkToken(TokenType.ASTERISK) or self.checkToken(TokenType.SLASH):
self.emitter.emit(self.curToken.text)
self.nextToken()
self.unary() |
def term(self):
self.unary()
# Can have 0 or more *// and expressions.
while self.checkToken(TokenType.ASTERISK) or self.checkToken(TokenType.SLASH):
self.emitter.emit(self.curToken.text)
self.nextToken()
self.unary()
def checkToken(self, kind):
return... | The main task of the code is to parse arithmetic expressions involving addition and subtraction. It starts by parsing a term, then repeatedly checks for '+' or '-' operators. When found, it emits the operator, advances the token, and parses another term, allowing for multiple operations in sequence. This loop handles z... | def expression(self):
self.term()
# Can have 0 or more +/- and expressions.
while self.checkToken(TokenType.PLUS) or self.checkToken(TokenType.MINUS):
self.emitter.emit(self.curToken.text)
self.nextToken()
self.term() |
def expression(self):
self.term()
# Can have 0 or more +/- and expressions.
while self.checkToken(TokenType.PLUS) or self.checkToken(TokenType.MINUS):
self.emitter.emit(self.curToken.text)
self.nextToken()
self.term()
def isComparisonOperator(self):
re... | The main task of the code is to parse and emit a chain of comparison operations. It first processes an initial expression, then checks for at least one comparison operator, emitting it and parsing another expression. A loop subsequently handles zero or more additional comparison operators and expressions, ensuring sequ... | def comparison(self):
self.expression()
# Must be at least one comparison operator and another expression.
if self.isComparisonOperator():
self.emitter.emit(self.curToken.text)
self.nextToken()
self.expression()
# Can have 0 or more comparison operator... |
def checkToken(self, kind):
return kind == self.curToken.kind
def nextToken(self):
self.curToken = self.peekToken
self.peekToken = self.lexer.getToken()
def comparison(self):
self.expression()
# Must be at least one comparison operator and another expression.
if self.isCo... | This code processes statements in a custom language, generating Python code. It handles PRINT (with string/list/format), IF/THEN/ENDIF, WHILE/REPEAT/ENDWHILE loops, variable declarations (LET), input (INT/STR), list operations (LIST/LISTADD/LISTINPUT), and CREATE commands for image/video processing using OpenCV. It emi... | def statement(self):
if self.checkToken(TokenType.PRINT):
self.nextToken()
if self.checkToken(TokenType.STRING):
self.emitter.emitLine("print(\"" + self.curToken.text + "\")")
self.nextToken()
elif self.checkToken(TokenType.LIST):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.