dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def irt(data, val_data, lr, iterations):
""" Train IRT model.
You may optionally replace the function arguments to receive a matrix.
:param data: A dictionary {user_id: list, question_id: list,
is_correct: list}
:param val_data: A dictionary {user_id: list, question_id: list,
is_correct: list}
... | The code trains an Item Response Theory (IRT) model on a dataset, tunes hyperparameters (learning rate, iterations), and evaluates performance using validation and test data. It tracks training/validation accuracy, negative log-likelihood, and log-likelihood over iterations, visualizing these metrics. After training, i... | def main():
train_data = load_train_csv("../data")
# You may optionally use the sparse matrix.
sparse_matrix = load_train_sparse("../data")
# print(sparse_matrix.shape)
# print(sparse_matrix)
val_data = load_valid_csv("../data")
# print(len(val_data["user_id"]))
test_data = load_public_t... |
def split_data(data):
number = {
"user_id": [],
"question_id": [],
"is_correct": []
}
algebra = {
"user_id": [],
"question_id": [],
"is_correct": []
}
geometry = {
"user_id": [],
"question_id": [],
"is_correct": []
}
sta... | The code trains and evaluates a model on categorized datasets (Algebra, Number, etc.) by splitting data, training separate models for each category, and combining results. It uses `train_category` to learn parameters (theta, beta, k) and evaluates test accuracy with `new_eval`. Finally, it aggregates all categories for... | def main():
train_data = load_train_csv("../data")
# You may optionally use the sparse matrix.
sparse_matrix = load_train_sparse("../data")
# print(sparse_matrix.shape)
# print(sparse_matrix)
val_data = load_valid_csv("../data")
# print(len(val_data["user_id"]))
test_data = load_public_t... |
def decrease_width(params: Parameters, num_pixels):
img = params.image.copy() # copiaza imaginea originala
for i in range(num_pixels):
print('Eliminam drumul vertical numarul %i dintr-un total de %d.' % (i + 1, num_pixels))
# calculeaza energia dupa ecuatia (1) din articol
... | The function `resize_image` adjusts images based on the `resize_option` parameter: it reduces width, height, amplifies content, or deletes objects. For 'micsoreazaLatime'/'micsoreazaInaltime', it resizes dimensions; 'amplificaContinut' enlarges content; 'eliminaObiect' selects a region and removes it. Invalid options t... | def resize_image(params: Parameters):
if params.resize_option == 'micsoreazaLatime':
# redimensioneaza imaginea pe latime
resized_image = decrease_width(params, params.num_pixels_width)
return resized_image
elif params.resize_option == 'micsoreazaInaltime':
resized_image = decr... |
def fill_frames(self):
for i in range(self.num_site):
self.grow_circle(i)
def generate_result(self):
for num in range(1, self.ar_chunk + 1):
k = (num + (self.ar) - 1) // (self.ar)
x = num % (self.ar)
if x == 0:
x = self.ar
j... | The main task of the code is to process data through three sequential steps: first filling frames (likely preparing data structures or visual elements), then generating an intermediate result, and finally producing a completed output. This method orchestrates data preparation, result computation, and final output gener... | def solve_proposed(self):
self.fill_frames()
self.generate_result()
self.generate_final_result() |
def find_optimum_radii(self):
for num in range(1, self.num_site_sqr+1):
j = num % self.num_site
if j == 0:
j = self.num_site
i = (num + self.num_site - 1) // self.num_site
self.find_avg_radii(i-1, j-1)
def find_optimum_radii_final(self):
f... | The main task of the code is to compute optimal radii in two stages (`find_optimum_radii` and `find_optimum_radii_final`), populate data structures (`fill_frames`), and generate a final result (`generate_result`). This sequence optimizes parameters, structures data, and produces an output, likely for a modeling or simu... | def solve_proposed(self):
self.find_optimum_radii()
self.find_optimum_radii_final()
self.fill_frames()
self.generate_result() |
def save_individual_pages_to_disk(diary, EXTRACTED_PAGES_DIR):
file_name, extension = os.path.splitext(os.path.basename(diary))
save_dir = os.path.join(EXTRACTED_PAGES_DIR, file_name)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
images_paths = []
if extension == ".png":
ima... | The code extracts answer areas from each page of a TIFF file by processing images through grayscale conversion, Gaussian blurring, thresholding, contour detection, corner identification, and perspective transformation to obtain a bird's-eye view. It saves each extracted area as an image and returns a list of their file... | def extract_answer_area_from_page(source_file, EXTRACTED_PAGES_DIR, EXTRACTED_AREAS_DIR, print_corner_markers=False, page_limit=0):
"""Extracts as single images the answer areas of each page of source_fle (a tiff file)
Returns a list with the path to each area file.abs
Run the full pipeline:
- Loa... |
def cosine_similarity(self,x,y):
x = x.div(torch.norm(x, p=2, dim=1, keepdim=True) + 1e-8)
y = y.div(torch.norm(y, p=2, dim=1, keepdim=True) + 1e-8)
cos_dis = torch.mm(x, torch.transpose(y, 0, 1))
return cos_dis
def filter_feature(self, x, edge_index, edge_attr, batch, bern_mask):
... | The code performs a forward pass in a graph neural network, computing cosine similarity between input features and a reference, applying a linear layer with sigmoid to generate a Bernoulli mask, using this mask to pool graph features, and calculating KL divergence and orthogonal losses for training. It returns pooled f... | def forward(self,x, edge_index, edge_attr, batch):
similarity = self.cosine_similarity(x, self.ref)
score = self.lin1(similarity).squeeze()
score = torch.sigmoid(score)
bern_mask = torch.bernoulli(score)
pool_x, pool_edge_index, pool_edge_attr, pool_batch, mask_index = self.fil... |
def check_if_row_column_constraints_met(currState):
# rowTotal = [sum(x) for x in currState.board]
# colTotal = map(sum,zip(*currState.board))
if currState.rowPieceCounter == rowConstraint and currState.columnPieceCounter == columnConstraint:
return True
return False
def check_if_piece_con... | The algorithm_GAC function solves a constraint satisfaction problem by recursively applying backtracking with Generalized Arc Consistency (GAC). It selects variables using the Minimum Remaining Values (MRV) heuristic, tests possible placements, prunes invalid states via preprocessing, and enforces constraints. If a val... | def algorithm_GAC(currState):
# Exit Condition
# If all variables are assigned
if check_if_row_column_constraints_met(currState) and check_if_piece_constraints_met(currState) and check_if_grid_full(currState):
return currState
# Pick an unassigned variable
chosenShip = return_MRV_va... |
def check_if_game_over(currState):
# Black won
if currState.redPieceCount == 0:
currState.gameOver = True
return [True, 1]
# Red won
elif currState.blackPieceCount == 0:
currState.gameOver = True
return [True, 0]
# Both pieces still available
else:
return... | The code implements the Minimax algorithm to determine the optimal move in a game by recursively evaluating all possible states. It alternates between maximizing (current player) and minimizing (opponent) evaluations, considering depth limits and game-over conditions. The function explores moves, sorts them by length, ... | def mini_max_algorithm(currState, depth, currPlayer):
if depth == 0 or check_if_game_over(currState)[0]:
return None, evaluate_state(currState)
bestMove = copy.deepcopy(currState)
if currPlayer:
maxEvaluation = -inf
moves = get_all_possible_moves(currState)
moves.sort(key=lam... |
def check_if_game_over(currState):
# Black won
if currState.redPieceCount == 0:
currState.gameOver = True
return [True, 1]
# Red won
elif currState.blackPieceCount == 0:
currState.gameOver = True
return [True, 0]
# Both pieces still available
else:
return... | This function implements the alpha-beta pruning algorithm to determine the optimal move for a player in a game state, considering a given depth. It evaluates all possible moves recursively, updates the best move based on the evaluation, and prunes branches that cannot improve the current best outcome, thus optimizing t... | def alpha_beta(currState, depth, currPlayer, alpha, beta):
if depth == 0 or check_if_game_over(currState)[0]:
return None, evaluate_state(currState)
bestMove = copy.deepcopy(currState)
if currPlayer:
maxEvaluation = -inf
moves = get_all_possible_moves(currState)
#moves.sort(k... |
def move_player(self, direction):
"""
Method to move the player in a given direction. The direction should be a string. Supports moving "back".
"""
direction = direction.strip()
if direction == "back":
self.player.move_back()
else:
previous_room =... | This function processes player commands in a text-based adventure game by routing verbs to corresponding actions, such as moving, taking, using items, quitting, or managing inventory. It handles synonyms for commands, triggers game-specific functions, and manages save/load operations. | def handle_command(self, verb, obj):
if verb == "move" or verb == 'go':
self.move_player(obj)
elif verb == "take" or verb == "pick up" or verb == "grab":
self.take_item(obj)
elif verb == "use" or verb == "examine" or verb == "show" or \
verb == "turn on" o... |
def get_end_time(self):
end = time.time()
return end - self.start_time
def update_wait_time(self, wait_time):
init_time = self.get_init_times_before_wait()
if wait_time < init_time:
self.current_status_value.setText(
"wait time is bigger than animation time")
... | The code handles the 'D' key press event to update a list of wait times, updates the UI status text, and triggers local saving when the wait limit is reached, while also catching exceptions to display a dialog. | def keyPressEvent(self, event):
if type(event) == QKeyEvent:
# 65, 68 = (a,d)
# print(event.key())
if event.key() == 68 and len(self.wait_times) < self.wait_limit:
try:
t = self.get_end_time()
self.current_status_value.s... |
def create_obstacle(shape, generation_seed=None):
rng = random.Random(generation_seed)
lines, columns = shape
nb_rectangles = rng.randint(3, 6)
grid = init_grid(shape)
for _ in range(nb_rectangles):
add_rectangle(grid, rect(rng, lines, columns))
return grid
def spawn_start_goal(grid, s... | The function generates a grid of specified type ("free", "obstacle", or "maze") with given dimensions. For "obstacle" grids, it ensures a valid path exists between randomly spawned start/goal positions. It returns the grid, start, and goal coordinates, using seeds for reproducibility. | def generate_grid(shape, *, grid_type="free", generation_seed=None, spawn_seed=None):
"""
Generate a grid
shape : (lines, columns)
grid_type : {"free", "obstacle", "maze")
return : grid, start, goal
"""
if grid_type == "obstacle":
while True:
grid = create_obstacle(s... |
def train(args):
data_map = {
"train": {
"path_src": os.path.join(args.output_dir, "data", "src-train.txt"),
"path_tgt": os.path.join(args.output_dir, "data", "tgt-train.txt"),
"transforms": ["sentencepiece", "filtertoolong"],
"weight": 1
},
"v... | The main task of the code is to process data, train a model if specified, average the last models if requested, and evaluate the model based on command-line arguments. It orchestrates a machine learning pipeline by conditionally executing these steps using flags in `args` to control training, model averaging, and evalu... | def main(args):
processData(args, True)
if args.do_train:
train(args)
if args.model_prefix and args.average_last:
average_models(args)
if args.do_eval:
evaluate(args) |
def chat_with_agent(self, user_input: str, greeting: bool = False) -> str:
"""Greet user with message and listen to response."""
if user_input:
logger.info('Agent heard "%s"', user_input)
prediction = self.predict_intent(user_input)
logger.info('Intent: %s', predictio... | The code manages a conversation loop, initiating with a random greeting if specified. It continuously interacts with the user via `chat_with_agent`, listening for input and updating status. The loop terminates when the user becomes inactive, controlled by `active_listening` and `user_status` checks. | def run_conversation(self, greeting: bool = False) -> None:
"""Run conversation."""
if greeting:
greetings = [
'Hello, Deep Thought.',
'Hey there.',
'Are you there, Deep Thought?',
'Say "Hello", Deep Thought.',
'... |
def depth_first_search(self , start , limit):
"""
Function that implements depth first search to find final state.
:param start: int
Starting position of the search
:param limit: int
Maximum number of iterations the loop does before terminating and giving up on fi... | The `get_tours` method performs depth-first search (DFS) on a chessboard to find valid knight's tours starting from each position (0 to `self.__size - 1`). It iterates through all starting points, executes DFS with a configurable limit, and prints results if a tour is found. It optionally visualizes the board, validate... | def get_tours(self):
"""
Method that runs depth first search on all possible positions on chessboard
"""
limit = config.get('limit')
for i in range(0 , self.__size):
out = self.depth_first_search(i , limit)
if out:
print('Start: ' + str(i... |
def extract_spans_extraction(task, seq, io_format):
if task == "uabsa":
if io_format == "extraction":
return extract_uabsa_from_extration(seq)
elif io_format == "extraction-universal":
return extract_uabsa_from_extraction_universal(seq, io_format)
else:
ra... | This function computes F1 scores for sequence prediction tasks, primarily focusing on extraction-based paradigms. It compares predicted sequences (pred_seqs) against ground truth sequences (gold_seqs), extracts spans using task-specific rules, and calculates raw F1 scores. It then applies edit-distance-based fixes to p... | def compute_scores(pred_seqs, gold_seqs, sents, paradigm, task, verbose=False):
"""
compute metrics for multiple tasks
"""
assert len(pred_seqs) == len(gold_seqs)
num_samples = len(gold_seqs)
all_labels, all_predictions = [], []
for i in range(num_samples):
if "extraction" in parad... |
def _init_defaults(self):
field_list = GlobalConfig.__fields__.keys()
properties = self.validator.schema.get("properties", {})
field_dict = {
field: properties.get(field).get("default") for field in field_list
}
if self._defaults is None:
return field_dict... | This method initializes the configuration by either loading an existing configuration file if it exists or creating a new default configuration. It first retrieves default settings, checks for an existing config file, and processes it if found; otherwise, it generates the default config. | def _init_config(self):
default_config = self._init_defaults()
if os.path.exists(self.config_path):
self._process_existing_config(default_config)
else:
self._create_default_config(default_config) |
def _init_config_schema(self):
if not os.path.exists(self.schema_path):
os.makedirs(os.path.dirname(self.schema_path), exist_ok=True)
shutil.copy(OUR_SCHEMA_PATH, self.schema_path)
def _init_validator(self) -> Validator:
with open(OUR_SCHEMA_PATH, encoding="utf-8") as f:
... | The main task of this code is to initialize a configuration manager that logs, caches, and validates configuration settings. It sets up logging, stores default values, tracks the last read time of the config file, and initializes schema validation rules. The `_init_config` method likely loads and parses the configurati... | def __init__(
self,
log: Logger,
defaults: dict,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
self.log = log
self._defaults = defaults
self._last_read: Optional[int] = None
"""When the server last read the config file. If the... |
def find_description(node):
for child in ast.iter_child_nodes(node):
if isinstance(child, ast.arguments):
continue
else:
name = get_string_constant_from_expr(child)
if name is not None:
return name
break
return get_description_from_... | This code traverses an AST to analyze functions, extracting descriptions and API calls. It prints functions with descriptions (30-100 chars) and 2-5 API calls, updating a map with stats. It handles imports, tracks class names, and recursively processes child nodes for comprehensive code analysis. | def find_functions(node, context):
api_map = context.api_map
if isinstance(node, ast.FunctionDef):
function_name = context.get_function_name(node.name)
d = find_description(node)
a = find_api_calls(node, context)
if 30 < len(d) < 100 and 2 < len(a) < 5:
print("Functio... |
def calcHeight(self, node):
if not node:
return -1
return node.height
def settleViolation(self, data, node):
balance = self.calcBalanced(node)
# Case 1: if the value in balance is greater than 1 it should be rotated to the right..
# This is a doubly left heavy situat... | This code inserts a new node into a binary tree, recursively placing the data in the left or right subtree based on value comparison. It updates the node's height and calls a balancing method to resolve any structural violations, ensuring the tree remains balanced. | def insertNode(self, data, node):
if not node:
return Node(data)
if data < node.data:
node.leftChild = self.insertNode(data, node.leftChild)
else:
node.rightChild = self.insertNode(data, node.rightChild)
node.height = max(self.calcHeight(node.leftChil... |
def _crop(self, image):
array = np.array(image, dtype=np.uint8)
array = cv2.cvtColor(array, cv2.COLOR_RGBA2GRAY)
retval, array = self._threshold(array)
x_min, x_max = self._object_range(array, 0)
y_min, y_max = self._object_range(array, 1)
return image.crop((x_min - 1, y_... | The main task of the code is to convert an input image into a circular shape. It first rescales the image to a square by adjusting its dimensions to the minimum of height and width, then crops it. Next, it encloses the image within a margin, trims it further with an expanded margin, and returns the resulting circular i... | def _circle(self, image):
# rescale
edge = min(image.height, image.width)
rescaled = image.resize((edge, edge))#, Image.LANCZOS)
rescaled = self._crop(rescaled)
# circle
margin = 1
enclosed = self._enclose(rescaled, margin)
trimmed = self._trim_circle(enc... |
def _character_to_image(self, character, font):
image = Image.new(RGBA, (font.size, font.size), TRANSPARENT)
draw = ImageDraw.Draw(image)
draw.text((0, 0), character, font=font, fill=self.color)
image = self._crop(image)
return image
def _concat_chars(self, chars):
height... | This function converts a string into a single image by rendering each character using the specified font, concatenating individual character images into a cohesive string image, and then cropping the final image to refine its appearance. | def _string_to_image(self, string, font):
char_images = []
for char in string:
char_image = self._character_to_image(char, font)
char_images.append(char_image)
string_image = self._concat_chars(char_images)
string_image = self._crop(string_image)
return st... |
def list_rule(rule_list, sub_list=None):
print("[+] LIST OF RULES:")
if sub_list is None or len(sub_list) == 0:
sub_list = rule_list
for rule in sub_list:
print(f'{rule_list.index(rule):>2} - {rule}')
def swap_rule_index(rule_list: list, selected_rule: Rule):
"""Swaps the positions of two objects in a list."""
... | The main task of the code is to provide a menu-driven interface for managing Squid proxy rules (rule_list) and access control lists (acl_list). It allows users to list, swap, create, update, or delete rules, validate ACL associations, and ensures rule-acl consistency. The loop persists until a valid choice is made or a... | def RULE_MENU(rule_list, acl_list):
# EXTRACTED_ACL_LIST = extract_squid_element(config_file)
# EXTRACTED_RULE_LIST = extract_squid_rule(config_file)
while True:
print('\n[*] RULE MANAGEMENT:')
print(f'{" ":>4}1. List rule')
print(f'{" ":>4}2. Swap rule index')
print(f'{" ":>4}3. Create new rule')
print(f'... |
def init():
## This function starts the Ray Cluster Head/Worker nodes ##
rayclusterip="YOUR_RAY_CLUSTER_IP"
if ray.is_initialized() == False:
print("Ray is not up!! We are starting it up right with the correct address")
ray.init(address="ray://" + rayclusterip + ":10001") #############... | The code performs inventory optimization for a specified location by loading sales data, generating demand forecasts using a pre-trained DeepAR model, and executing an optimization simulation. It processes input parameters, filters location-specific data, creates forecast scenarios, and returns optimized inventory resu... | def run(Inputs):
init()
input_location= json.loads(Inputs)['Inputs']['Location']
params = get_params(input_location)
samples = 20
sim_duration = 21
training_dataset = 'training_sales_data_2'
ws = get_ws()
dataset = Dataset.get_by_name(ws, name='training_sales_data_2', version='la... |
def th_filter(rnum,this_tmp,last_tmp):
fmax = 0.0 # max for this units
fmin = 200.0 # max for this units
maxat = 0 # max at this 0-4 location for the current unit averaged
minat = 0 # min at this 0-4 location for the current unit averaged
fl.tmp[rnum][fl.ucnt[rnum]] = this_tmp # store 0-4
... | This function processes incoming JSON data from a sensor, checks if the temperature has significantly changed, updates global state variables with new sensor values (temperature, humidity, RSSI, battery), increments counters, and optionally displays debug info. If temperature hasn't changed enough, it exits early. | def recv_json(th_json): # th_json{} received from app.py
rnum = th_json["rnum"]
# -- filter 5 samples and test if this avgd sample's temp that changed
chgd,newtemp = th_filter(rnum,th_json["temp"],gc.th_info["temp"][rnum])
if (chgd == 0): # temp did not change or not timeout
return()
# ----... |
def decode_temp_in_c(encoded_data):
return format((encoded_data / 10000), FORMAT_PRECISION)
def decode_temp_in_f(encoded_data):
return format((((encoded_data / 10000) * 1.8) + 32), FORMAT_PRECISION)
def decode_humidity(encoded_data):
return format(((encoded_data % 1000) / 10), FORMAT_PRECISION)
def build_re... | The code processes BLE advertisements from Govee devices by checking the MAC address prefix, extracting manufacturer data, decoding temperature, humidity, and battery levels, and storing these values along with RSSI in a dictionary for device tracking. | def on_advertisement(advertisement):
log.debug(advertisement)
if advertisement.address.address.startswith(GOVEE_BT_mac_OUI_PREFIX):
mac = advertisement.address.address
if mac not in govee_devices:
govee_devices[mac] = {}
if H5075_UPDATE_UUID16 in advertisement.uuid16s:
... |
def initialPopulation(popSize, cityList):
population = []
for i in range(0, popSize):
population.append(createRoute(cityList))
return population
def rankRoutes(population):
fitnessResults = {}
# calcula o valor de Fitness de cada rota
for i in range(0,len(population)):
fitnessRe... | The main task of the code is to implement a genetic algorithm to solve a route optimization problem (likely the Traveling Salesman Problem). It initializes a population, evolves it over multiple generations using elitism and mutation, and outputs the initial and final best routes along with their distances. The algorit... | def geneticAlgorithm(problemName, population, popSize, eliteSize, mutationRate, generations):
print("\n\nProblema " + problemName)
pop = initialPopulation(popSize, population)
print("Distancia inicial: " + str(1 / rankRoutes(pop)[0][1]))
bestRouteIndex = rankRoutes(pop)[0][0]
bestRoute = pop[bestRou... |
def initialPopulation(popSize, cityList):
population = []
for i in range(0, popSize):
population.append(createRoute(cityList))
return population
def rankRoutes(population):
fitnessResults = {}
# calcula o valor de Fitness de cada rota
for i in range(0,len(population)):
fitnessRe... | This function implements a genetic algorithm to solve a routing problem, tracking the best route's distance over generations. It initializes a population, iteratively evolves it through selection, crossover, and mutation, and records progress. Finally, it plots the distance improvement and saves the graph. | def geneticAlgorithmPlot(problemName, population, popSize, eliteSize, mutationRate, generations):
print("\n\nProblema " + problemName)
pop = initialPopulation(popSize, population)
print("Distancia inicial: " + str(1 / rankRoutes(pop)[0][1]))
bestRouteIndex = rankRoutes(pop)[0][0]
bestRoute = pop[bes... |
def default(val, def_val):
return def_val if val is None else val
def get_default_aug(image_size, channels = 3):
is_rgb = channels == 3
is_greyscale = channels == 1
rgb_or_greyscale = is_rgb or is_greyscale
return torch.nn.Sequential(
RandomApply(
T.ColorJitter(0.8, 0.8, 0.8, 0.... | This code initializes a self-supervised learning model for contrastive representation learning, commonly used in methods like SimCLR. It sets up two data augmentation pipelines, constructs an encoder network with a projection head, and an MLP predictor. The model is configured to learn by contrasting two augmented view... | def __init__(
self,
net,
image_size,
channels = 3,
hidden_layer = -2,
projection_size = 256,
projection_hidden_size = 4096,
augment_fn = None,
augment_fn2 = None
):
super().__init__()
self.net = net
# default SimCLR aug... |
def getname(filename):
#function to make repeatable
#get the number of lines, then get a random number between 0 and it
numoflines = file_len(filename)
randomnum = random.randint(0,numoflines)
#open the file, read it, print only the generated line number
file = open(filename)
... | The main task of the code is to generate a fictional character by combining randomized first and last names, assigning rolled statistical attributes, and creating associated elements like backstory, cyberware, and weapons through function calls. It uses text files for name data and predefined stat categories to produce... | def genCharacter():
print ("Name is: " +getname("firstnames.txt") + " " + getname("surnames.txt"))
for x in range(0,len(statsValues)):
statsValues[x] = rollStat(statsLongNames[x])
rollBackstory()
rollCyberWare()
rollWeapons() |
def rollToX(x):
#returns a number between 0 and x
rollresult = random.randint(0,x)
return rollresult
def GetAllSpells(spells, relations):
#get all of the spells, using other functions
GetSpells(spells, 3)
GetSpells(relations[0], 1)
GetSpells(relations[1], 1)
GetSpells(relations[2], 1)
availa... | The main task of the code is to generate a warband by selecting a wizard class (randomly or specified), gathering associated spells and relations, creating a name, generating soldiers, and outputting structured data (JSON) containing the warband's name, class, spells, soldiers, and gold. | def GenWarband():
#generates the warband; main script here
global startingGold
startingGold = 500
global spellList
spellList = [ ]
#random only if type not specified
if options.wizardtype == "random":
playerClass = arrayWizardType[rollToX(9)]
else:
wt = options.wizardtype.ca... |
def get_query_header(table_name):
if table_name == 'activity-log':
query_header = "INSERT INTO tbl_activity_log (log_key, reference_number, transaction_timestamp, log_level, session_id, correlation_id, activity, source, destination, status) VALUES \n"
elif table_name == 'audit-log':
query_header... | This function generates SQL queries for a specified table, splitting them into multiple files with a size limit. It writes query headers once per file, appends query bodies, and manages file boundaries by closing and restarting files when the max size is reached or at the end of the data. Different table names trigger ... | def write_into_multiple_files(length, max_file_size, table_name):
if table_name == 'activity-log':
filename = 'sql/activity-log-data'
elif table_name == 'audit-log':
filename = 'sql/audit-log-data'
else:
filename = 'deez'
file_index = 1
max_file_size *= 1024 * 1024
h... |
def abnormal_returns(self, firm_event_data: pd.DataFrame, price_col: str,
date_col: str) -> np.ndarray:
"""TODO."""
event_data = self._data_plus_market(firm_data=firm_event_data,
data_col=price_col,
... | This function computes statistical aggregations of abnormal returns, including Cumulative Abnormal Return (CAR), its standard error (SCAR), and tests (rank/sign). It uses specified event windows to calculate parametric metrics and non-parametric tests on excess returns, returning a dictionary with these statistics for ... | def abnormal_return_aggregations(self, window_start: int, window_end: int,
*args, **kwargs) -> dict:
"""TODO."""
abnormal_returns = self.abnormal_returns(*args, **kwargs)
abnormal_returns_variance = self.abnormal_returns_variance(*args,
... |
def construct_pattern(self, partial_data_file):
"""
This method constructs a list from the partial data file.
The list is used as a pattern for searching.
:param partial_data_file: The partial ebola file
:return:
Modifies the contents of self._pattern & self._pattern_... | The task processes two files to identify patterns in complex Ebola data using string-matching algorithms. It constructs a pattern from partial data, reads complex data, selects KMP or BM algorithms based on pattern length, mines the data for results, and writes outputs (local, indicator, start date, and runtime) to a f... | def task2(self, complex_ebola_file, partial_data_file):
"""
The is calls the other functions to complete task2
:param complex_ebola_file: The path to the complex-sample data
:param partial_data_file: The file containing the partial data
:return:
Write a file task2_res... |
def should_eat(self):
return self.can_eat() and self.eat_timer>=self.eat_time
def should_smoke(self):
return self.can_smoke() and self.smoke_timer>=self.smoke_time
def should_apply(self):
return self.can_apply() and self.apply_timer>=self.apply_time
def should_sip(self):
return self.can_... | This function increments four timers by a given value and checks if any of the associated conditions (eat, smoke, apply, sip) should be triggered, returning True if any condition is met, otherwise False. | def inc_time(self, time_inc):
self.eat_timer+=time_inc
self.smoke_timer+=time_inc
self.apply_timer+=time_inc
self.sip_timer+=time_inc
if self.should_eat():
return True
if self.should_smoke():
return True
if self.should_apply():
... |
def can_action(self):
if self.bal <= 0:
self.prompt()
def __init__(self):
self.reset = False
self.quit = False
self.time_inc = .1
self.time=0
self.bal = 0
self.target = Target()
self.cmd_list = ["dstab", "wait", "quit", "reset"]
def inc_time(se... | The code's main task is to execute a fight loop, repeatedly checking if actions can be taken. If reset is triggered, it reinitializes the instance and prints a message; if quit is triggered, it exits. The loop increments time each iteration until `can_action()` becomes True, managing game state transitions and time pro... | def fight(self):
while not self.can_action():
if self.reset:
self.__init__()
print("reset all afflictions")
continue
if self.quit:
return
self.inc_time() |
def build_board():
for each in Board:
Board.remove(each)
for each in EnteredWords:
EnteredWords.remove(each)
random.shuffle(Dice)
for x in range(0,16):
Board.append(random.choice(Dice[x]))
def print_board():
print("["+Board[0]+"] ["+Board[1]+"] ["+Board[2]+"] ["+Board[3]+"]\n")
print("["+Board[4]+"] ["+... | The code calculates a score based on valid words entered by the user, displays the game board, and provides feedback messages depending on the total score. It increments the score for each valid word, then prints a tailored message indicating the user's performance. | def run():
Score = 0
build_board()
print_board()
for each in EnteredWords:
Score = Score + check_word(each)
if Score > 1:
print("Your total score is "+str(Score)+" points!\n")
elif Score == 1:
print("Your total score is "+str(Score)+" point!\nBetter luck next time!\n")
else:
print("Your total score was "... |
def subtract_linear_background(self, I):
linear_background = self.linear_background_fit(I)
subtracted_linear = I - linear_background
return subtracted_linear
def Subtract_Fermi(self, I):
return I - self.Fermi_step(I)
def XMCD(self, I_m, I_p):
return I_m-I_p | This code initializes a class to process XMCD data by reading a CSV file, applying linear and Fermi step background corrections to intensity measurements, and computing the XMCD signal. It sets energy thresholds, loads data columns, and prepares processed signals for analysis. | def __init__(self, name):
data_path = '/Users/annabelladrewanowski/Documents/UZH/Masterarbeit/Analysis/XTreme/processed data/XMCD grazing/'
self.filename = name
data_names = ['Energy', 'minus1', 'plus1', 'plus2', 'minus2', 'minus3', 'plus3', 'I_cp', 'I_cm', 'cp_Hm', 'cm_Hm',
... |
def log_info(self, msg):
self.logger.info(msg, extra={'file': f'{self.file_name} - '})
def valid_file(self):
if not os.path.isfile(self.path_file):
msg = f'Path: "{self.path_file}" is not a file.'
self.log_error(msg)
raise NotFileException(msg)
def load_json(self):
... | The code processes a file by validating it, loading JSON data, converting it to XML, adding metadata, encrypting the XML, sending it, and moving the original JSON file. It logs progress and handles unexpected errors by logging the exception and performing cleanup. | def execute(self):
self.log_info(f'Processing file.')
try:
self.valid_file()
self.load_json()
self.convert_to_xml()
self.add_metadata()
self.encrypt()
self.send_xml()
self.move_json()
except Excep... |
def get_root_element_file(file_path: str) -> ET:
tree = ET.parse(file_path)
return tree.getroot()
def get_propriety_if_exist(node: ET, key):
if node.get(key):
return node.get(key).lstrip()
return None
def get_teachers(root_element: ET) -> List[dict]:
teachers = []
for node in root_elemen... | This function converts an XML file into a structured dictionary by parsing specific elements and attributes. It extracts metadata like document type, version, institution name, school year, and other educational data (teachers, classrooms, lessons, days, terms, groups) using helper functions. The parsed data is organiz... | def xml_file_to_json_data(file_path: str):
root = get_root_element_file(file_path)
data = {
'document_type': get_propriety_if_exist(root, 'document_type'),
'version': get_propriety_if_exist(root, 'version'),
'edu_institution_name': root.find('edu_institution_name').text.lstrip(),
... |
def get_propriety_if_exist(node: ET, key):
if node.get(key):
return node.get(key).lstrip()
return None
def get_teachers(root_element: ET) -> List[dict]:
teachers = []
for node in root_element.findall("teachers/teacher"):
teacher = {
TeacherKey.ID: int(node.get('id').lstrip())... | This function converts an XML string into a structured Python dictionary. It parses the input XML, extracts specific elements and attributes, and organizes them into a dictionary with predefined keys, including document metadata, educational institution details, and data from helper functions like get_teachers and get_... | def xml_str_to_json_data(str_data: str):
root = ET.fromstring(str_data)
data = {
'document_type': get_propriety_if_exist(root, 'document_type'),
'version': get_propriety_if_exist(root, 'version'),
'edu_institution_name': root.find('edu_institution_name').text.lstrip(),
'school_y... |
def _memory_widget(self, profile: str) -> Markup:
"""Generate memory widget Markup string from hardware data.
:return: HTML Markup string with widget
:rtype: Markup
"""
table_data: list = list()
# noinspection PyPep8Naming
WIDGET = "memory"
user_profile =... | This function retrieves and returns HTML markup for specific system monitoring widgets (e.g., memory, CPU, GPU) based on the provided widget name and profile. If the widget name is invalid, it generates an error card listing available widget options. | def get_widget(self, widget_name: str, profile: str = "Default") -> Markup:
"""Get widget HTML Markup string with name and profile.
:param widget_name: Name of the widget.
:param profile: Name of the dashboard profile.
:return: Markup string with entire widget card
:rtype: Marku... |
def _remove_decimal(s):
i = s.find('.')
if i == -1:
return s, 0
dot_position = len(s) - s.find('.') - 1
return s.replace('.', ''), dot_position
def _add(input1, input2):
n1 = _split_number(input1)
n2 = _split_number(input2)
_equalize_decimal_digits(n1, n2)
dec_result = _add_numb... | This function multiplies two numbers, handling decimal points by first removing them, performing digit-by-digit multiplication with carry management, summing intermediate results, and reconstructing the final value with the correct decimal placement based on the original inputs. | def _multiply(input1, input2):
n1, dot1 = _remove_decimal(input1)
n2, dot2 = _remove_decimal(input2)
lines = []
carry = 0
for x in range(0, len(n1)):
c1pos = len(n1) - x - 1
i1 = ord(n1[c1pos]) - _ZERO_CHAR
line = '' + str('0' * x)
for j in range(0, len(n2)):
... |
def _generate_test():
operand = arithmetics.OPERANDS[_r() % 2] # Python can't do multiplication
random1 = _random_sign() * (_r() + _r() / _DECIMAL_LIMIT)
random2 = _random_sign() * (_r() + _r() / _DECIMAL_LIMIT)
return _test(operand, random1, random2)
def _test(operand, random1, random2):
random1st... | The main task of the code is to execute arithmetic tests (random, static, and precomputed), track failures, and report results. It runs 1000 random tests, processes predefined static tests, validates precomputed answers, and logs failed cases. The output summarizes total tests executed, failures, and lists specific fai... | def _run_tests():
failed_tests = []
tests_ran = 0
# Randomly generated tests.
for x in range(0, 1000):
tests_ran += 1
test_result, random1, random2, operand = _generate_test()
if not test_result:
failed_tests.append([random1, operand, random2])
for t in _STATIC_... |
def _is_positive(s):
return not _is_negative(s)
def _add(input1, input2):
n1 = _split_number(input1)
n2 = _split_number(input2)
_equalize_decimal_digits(n1, n2)
dec_result = _add_numbers(n1.decimal_part, n2.decimal_part)
if len(dec_result) > len(n1.decimal_part):
dec_result = dec_result... | The code performs arithmetic operations (addition, subtraction, multiplication) on two numbers provided as strings, considering their signs (positive/negative). It uses helper functions (_add, _subtract, _multiply) and sign-handling utilities (_make_positive, _make_negative) to compute results correctly for all combina... | def calculate(operand, input1, input2):
"""Adds, subtracts or multiples 2 numbers in string format.
:param operand: +, - or *
:param input1: First number
:param input2: Second number
:return: Result of the arithmetics operation
"""
if operand == OPERAND_ADD:
if _is_positive(input1) ... |
def check_key(key: Union[str, tuple], pat: str) -> bool:
"""
Check whether `key` contains pattern.
Parameters
----------
key : Union[str, tuple]
Input key. If a `tuple` then the first element will be used to check.
pat : str
Pattern to check.
Returns
-------
bool
... | This function optimizes a Dask array task graph by fusing operations, inlining fast functions, and applying key renaming/rewriting. It uses Dask's optimization framework, preserves specified keys, and applies inline patterns to further simplify the graph. The result is an optimized Dask graph with transformed task keys... | def custom_arr_optimize(
dsk: dict,
keys: list,
fast_funcs: list = FAST_FUNCTIONS,
inline_patterns=[],
rename_dict: Optional[dict] = None,
rewrite_dict: Optional[dict] = None,
keep_patterns=[],
) -> dict:
"""
Customized implementation of array optimization function.
Parameters
... |
def instantiate(self):
"""
Return a new instance of the stored py:class:`Task` class, or ``None``
in case instantiation fails.
"""
try:
return self.task_cls()
except Exception as exc:
logging.exception("Task[%s][%s] instantiation failed.",
... | The `run` method executes a stored task, logs exceptions silently, and resolves the task's future with its return value or exception. It sets the task status to "PROCESSING," instantiates the task, and executes it with provided arguments. On success, it logs completion and returns the result; on failure, it logs the er... | def run(self):
"""
Execute the stored task, silencing and logging any exceptions it might
raise. The py:attr:`~PackagedTask.result` future will be resolved with
the return value (or exception object if it fails) of the task.
A callback or errback function can additionally be inv... |
def get_containing_voxel_ijk(self, x, y, z):
"""
Internal function to get the meshgrid indices for the center of a voxel
that contains the given position.
Note that pyMCDS stores meshgrids as 'cartesian'
(indexing='xy' in np.meshgrid) which means that we will have
... | This function calculates and returns the concentrations of all chemical species at a specified 3D point by identifying the containing voxel, then extracting concentrations from a 3D array using substrate names. It first maps the input coordinates to voxel indices, initializes a concentration array, and iterates over ea... | def get_concentrations_at(self, x, y, z):
"""
Return concentrations of each chemical species inside a particular voxel
that contains the point described in the arguments.
Parameters
----------
x : float
x-position for the point of interest
y :... |
def get_mesh_spacing(self):
"""
Returns the space in between voxel centers for the mesh in terms of the
mesh's spatial units. Assumes that voxel centers fall on integer values.
Returns
-------
dx : float
Distance between voxel centers in the same units as the... | The function retrieves a DataFrame of cells located within the same voxel as the specified 3D point (x, y, z). It calculates the voxel's boundaries using mesh spacing, filters cells whose positions fall within these bounds, and returns the subset as a DataFrame. | def get_cell_df_at(self, x, y, z):
"""
Returns a dataframe for cells in the same voxel as the position given by
x, y, and z.
Parameters
----------
x : float
x-position for the point of interest
y : float
y_position for the point of interes... |
def _is_keypoint(self, octave: int, scale: int, i: int, j: int) -> bool:
"""Check if a pixel is a keypoint (local maximum)."""
center_pixel = self.dog_images[octave][scale][i][j]
if abs(center_pixel) < self.kp_find_threshold:
return False
count_fails = 0
for x in n... | The code identifies keypoints in a stack of Difference of Gaussian (DoG) images across multiple octaves and scales. It iterates through each pixel, checks if it meets keypoint criteria using `_is_keypoint`, adjusts its position with `_check_new_pos`, and generates keypoint objects with `_create_kp`. Results are stored ... | def find_keypoints(self) -> ndarray:
"""Find the keypoints in the difference of gaussian images.
Args:
dog_images (ndarray): Stack of difference of gaussian images
for each octave and scale.
"""
keypoints_cv = []
keypoints_raw = []
for octave in r... |
def is_local_maximum(self, octave: int, scale: int, i: int, j: int):
"""Verify if a given pixel is a maxima -> Let's filter it
Args:
dog_images (ndarray): Difference of gaussian images for octave and scale
octave (int): Identification of the octave in the pyramid of gaussian
... | The function filters keypoints by checking if they are local maxima in the difference of Gaussian (DoG) images using the Hessian matrix. It calculates orientation, response, and generates descriptors for valid keypoints, returning filtered keypoints and their feature vectors for further processing in computer vision ta... | def filter_keypoints(self) -> ndarray:
"""Filter keypoints using the hessian matrix.
Args:
dog_images (ndarray): Stack of difference of gaussian images
for each octave and scale.
keypoints (ndarray): Keypoints found in the differ... |
def generate_base_image(self, image: np.ndarray) -> np.ndarray:
"""Upsamples the input image by 2 in both directions
and applies Gaussian blur to generate a base image.
Args:
image: The input image to generate the base image from.
sigma: The desired standard deviation of... | The code detects and filters keypoints in an image using a scale-space approach. It generates a base image, applies Gaussian blurring, computes Difference of Gaussians (DoG) images, identifies potential keypoints, filters them for stability, and converts the results into KeyPoint objects for output. This process is typ... | def detect(self, image: ndarray) -> list[KeyPoint]:
self.generate_base_image(image)
self.gaussian_images()
self.compute_dog_images()
self.find_keypoints()
self.filter_keypoints()
return self.convert_keypoints() |
def _get_iner_point(self):
min_q = self.vlist[0]
for v in self.vlist[1:]:
if min_q.v[1] > v.v[1] or (min_q.v[1] == v.v[1] and min_q.v[0] > v.v[0]):
min_q = v
return min_q
def chull(self):
q = self._get_iner_point()
if q in self.vlist:... | The code generates a plot visualizing the convex hull of a set of points, including an inner point, their center, and annotated indices. It removes and re-adds the inner point, sorts the list, computes the convex hull, and displays the hull outline, points, center, and minimum enclosing plane value. | def rplot(self):
q = self._get_iner_point()
if q in self.vlist:
self.vlist.remove(q)
_SentralVertex.center = q.v
self.vlist.sort()
_SentralVertex.center = np.zeros((2))
self.vlist.append(q)
plt.figure()
plt.grid()
allcord = n... |
def make_vertical_inner_link(adj_table, subdivision):
'''
find the vertical and horizontal connections
eg. subdivision = 2
00 ... Layer 0
01 02 03 ... Layer 1
04 05 06 07 08 ... Layer 2
09 10 11 12 13 14 15 ... Layer 3
Vertical Connection... | The code constructs an adjacency table for a subdivided icosahedron, linking points based on internal and edge connections. It initializes a table, processes vertical/horizontal inner and edge links, completes the table, and returns a NumPy array of size 20*(4^subdivision) x 3, where each row lists the three connected ... | def make_adjacency_table(subdivision):
'''
the main progress of building a adjacency table
by divide the connections into two types:
1) insdide the triangle
2) on the edge of the triangle
Args:
subdividion(int) : how many points on the icosahedron projection
Return:
adj_... |
def make_pooling_table(subdivision):
'''
make the pooling table for the icosahedron points
Args:
subdivision(int) : how many subpixels in the triangle of each face
Returns:
pooling_table(list) : list contain each pooling indecies for every subdivision case
... | The main task of the code is to construct essential tables for neural network operations, including a pooling table, adjacency table, and upsample table. It generates these tables using specific functions and combines them to create the upsample table, which likely supports tasks like feature mapping or data reconstruc... | def main():
'''
Construct necessary tables
'''
#if not os.path.exist('./tables'):
#os.mkdir('./tables')
#for i in range(1, 9):
#conv_table = make_conv_table(i)
#np.save('./tables/conv_table_'+str(i)+'.npy', conv_table)
pooling_table = make_pooling_table(1)
#np.save('.... |
def split(self):
# Splitting the dataset into trainingSet & testSet
self.x_train, self.x_test,self.y_train, self.y_test = train_test_split(self.import_Index()[0], self.import_Index()[1], test_size=0.2, random_state=0)
def train(self):
self.regressor = LinearRegression()
self.regressor.fi... | The code visualizes actual vs. predicted values using scatter plots, calculates average accuracy by comparing test and predicted values as percentages, and displays the results with a labeled plot titled with the computed accuracy. | def Visualize(self):
self.split()
self.train()
average = []
total = 0
plt.scatter(range(len(self.y_test)), self.y_test, color='red')
plt.scatter(range(len(self.y_test)), self.prediction(), color='blue')
for i in range(len(self.y_test)):
if self.y_test... |
def n_greater_than(self, row_zb: int, col_zb: int) -> int:
"""
Number of other cells that this cell is less than.
"""
return len(list(self.iter_cells_greater_than(row_zb, col_zb)))
def n_less_than(self, row_zb: int, col_zb: int) -> int:
"""
Number of other cells that this... | This function eliminates impossible digit possibilities in a grid based on inequalities. It iterates through cells, using counts of greater/lesser cells to restrict valid values (e.g., if a cell is greater than two others, it can't be 1 or 2). It also compares current cell values against cells it's relatively greater/l... | def _eliminate_inequalities(self) -> bool:
"""
Eliminate possibilities in a simple way based on inequalities.
Returns: improved?
"""
source_b = "eliminate_inequalities, basic"
source_r = "eliminate_inequalities, relative"
improved = False
for row in range... |
def _eliminate_simple(self) -> bool:
"""
Where a cell is known, eliminate other possibilities in its row, cell,
and 3x3 box.
Returns: improved?
"""
log.debug("Eliminating, simple...")
source = "eliminate_simple"
improved = False
for row in range(s... | This code eliminates impossible options in a constraint satisfaction problem by iteratively applying simple elimination, inequality checks, and possibility constraints. It then tests group-based row/column eliminations for varying group sizes, returning whether any improvements were made to prune invalid solutions. | def eliminate(self) -> bool:
"""
Eliminates the impossible.
Returns: improved?
"""
improved = self._eliminate_simple()
improved = self._eliminate_inequalities() or improved
improved = self._find_only_possibilities() or improved
if improved:
re... |
def possible_digits(self, row_zb: int, col_zb: int) -> List[int]:
"""
Returns possible digits, in ZERO-BASED format, for a given cell.
They are always returned in ascending order.
"""
return list(
d for d, v in enumerate(self.possible[row_zb][col_zb]) if v
)
d... | The main task of the code is to identify and apply "hidden subsets" and "naked subsets" strategies in Sudoku solving. It scans rows, columns, and boxes for groups of cells containing exactly the same set of possible digits (of size `groupsize`). If found, it eliminates other digits from those cells and from all other c... | def _eliminate_groupwise_rows_cols(self, groupsize: int) -> bool:
"""
Scan through all numbers in groups of n. If there are exactly n
possible cells for each of those n numbers in a row/column/box, and
those possibilities are all the same, eliminate other possible digits
for thos... |
def minimax(self, board: list, depth: int, alpha: int, beta: int,
maximizingPlayer: bool) -> tuple:
valid_columns = self.get_valid_columns(board)
terminal = self.is_terminal(board)
if depth == 0 or terminal:
if terminal:
if self.validate_winning_move... | The main task of the code is to determine the AI's optimal move using the minimax algorithm with alpha-beta pruning. It evaluates valid columns, selects the best move based on calculated scores, validates the chosen column, and updates the game state by checking for a winner. The function ensures the AI chooses a legal... | def ai_move(self, board: list):
if not globals.game_over:
(column, score) = self.minimax(board, gb.GAME_BOARD_ROWS - 1,
self.NEG_INFINITY,self.INFINITY, True)
# If the game board is not full.
valid_columns = self.get_valid_columns(board)
if len(va... |
def print_board(board):
for i in range(0, 9, 3):
print(board[i], board[i + 1], board[i + 2])
def evaluate(board):
# Evaluate the current state of the board
# Positive value for AI's advantage, negative for human's advantage
# 0 for a draw
lines = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], #... | This code implements a Tic-Tac-Toe game where a human player competes against an AI. The board is initialized with empty cells, and the game loop alternates between human and AI moves. The human inputs their move, which is validated and placed on the board. The AI determines its move using the best_move() function. Aft... | def main():
board = [EMPTY] * 9
while True:
print_board(board)
move = int(input("Enter your move (0-8): "))
if board[move] != EMPTY:
print("Invalid move. Try again.")
continue
board[move] = HUMAN
if evaluate(board) == -1:
print("You wi... |
def title_from_filename(filename):
title = os.path.splitext(filename)[0]
# Most tags and group names come after the year (which is often in parens
# or brackets)
# Using the year when searching IMDb will help, so try to find it.
year_match1 = re.match(
r"(.*?\w+.*?)(?:([\[(])|(\W))(.*?)((... | The main task of the code is to parse movie data from a filename by extracting a title and tags, retrieve movie information using the title, and format the data for storage if valid information is obtained. It processes the movie details, directory, filename, metadata file name, and tags to structure the output. | def parse_movie(self, search_dir, filename, metadata_file_name, is_trailer=False):
(title, tags) = title_from_filename(filename)
movie_info = self.get_movie_info(title, is_trailer=is_trailer)
if movie_info is not None:
self.format_movie_data(
movie_info, search_dir,... |
def rpc_req_generic(self, req_type, **kwargs):
"""Send specified RPC request and accept returned value
Args:
req_type (str):
**kwargs: key=value pairs sent directly as part of RPC request
Returns:
dict: key=value pairs representing all fields of RPC return va... | The main task of the code is to search for movies in the Mind database using title keywords and an optional release year, filter results, and return the most relevant movie collection data. It handles pagination, error checking, and enriches results with additional content details before returning the best match. | def search_movie(self, title_keywords, year=None):
"""Search for movie in Mind database given title (or title keywords)
and possibly year of movie
Args:
title_keywords (str): Can be space-separated title OR title keywords
year (str): year of movie's release
Retu... |
def fetch_from_whats_on_netflix(enhance) -> typing.List[MovieInfo]:
# curl equivalent of the request made by browser.
"""
curl 'https://www.whats-on-netflix.com/wp-content/plugins/whats-on-netflix/json/movie.json'
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:72.0) Gecko/2010010... | The function retrieves Netflix movie data using different sources based on the 'legacy' flag. If 'legacy' is True, it combines results from 'fetch_from_whats_on_netflix' and 'fetch_from_finder' (both using 'enhance'), then merges them. If 'legacy' is False, it directly fetches data from 'fetch_from_reelgood' with 'enha... | def get_netflix_all(legacy, enhance):
if legacy:
movies1: typing.List[MovieInfo] = fetch_from_whats_on_netflix(enhance)
movies2: typing.List[MovieInfo] = fetch_from_finder(NETFLIX, enhance)
return merge_netflix(movies1, movies2)
else:
return fetch_from_reelgood(NETFLIX, enhance) |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--provider', choices=['netflix', 'amazon'], default='netflix')
parser.add_argument('--lang', help='Comma separated language filter', default='')
parser.add_argument('--year', help='Release year filter', type=int)
parser.add_ar... | The main task of the code is to retrieve movie data from Netflix or Amazon (via different APIs based on legacy flag), filter by language and release year, sort by year or IMDb rating, and output a formatted table of movie details including title, year, rating, languages, and IMDb IDs. | def main():
args = parse_args()
if args.provider == 'netflix':
movies = get_netflix_all(args.legacy, args.enhance)
elif args.provider == 'amazon':
if args.legacy:
movies = fetch_from_finder(AMAZON_PRIME, args.enhance)
else:
movies = fetch_from_reelgood(AMAZON_... |
def build_wire(part, offset=0.0):
"""Build a wire part.
Parameters
----------
part :
offset :
(Default value = 0.0)
Returns
-------
"""
assert isinstance(part, part_3d.WirePart)
doc = FreeCAD.ActiveDocument
zBottom = part.z0
width = part.thickness
sketch ... | The main task of the code is to generate a non-destructive offset of a FreeCAD object based on its type and specified offset value. It identifies whether the object is a special part (e.g., WirePart, SAGPart) or standard, then applies appropriate offset methods like Part::Offset, build_wire, or build_sag. For small off... | def gen_offset(opts, obj, offsetVal):
"""Generates an offset non-destructively.
Parameters
----------
opts : dict
Options dict in the QMT Geometry3D.__init__ input format.
obj : FreeCAD.App.Document
A FreeCAD object.
offsetVal :
Returns
-------
"""
doc = Fre... |
def movement_detection(acc_group_by_axis):
"""
:param acc_group_by_axis:
:return:
"""
detection = []
acc_by_tuples = transpose(acc_group_by_axis)
for acc in zip(acc_by_tuples):
if np.absolute(acc[0][1]) > 0.5 or np.absolute(acc[0][2]) > 0.5:
# if np.absolute(acc[0][0]) > ... | The code detects movement from linear acceleration data, calculates velocity and displacement, inverts displacement components to derive coordinates, and returns [x, y] coordinates if movement is detected; otherwise, returns None. | def calculate_position(linear_acc, period):
movement = False
movement_detected = movement_detection(linear_acc)
for i in movement_detected:
if i == 1:
movement = True
break
if not movement:
return None
#########################################################... |
def recommend_by_same_artist(track_index, count, prioritisePopular, include_fields):
songs_by_same_artist = get_by_same_artist(track_index, count*2)
songs_by_same_artist = sort_by_popularity(songs_by_same_artist, prioritisePopular)[:count]
return recommendations_as_list(songs_by_same_artist, include_fields)... | The function generates hybrid music recommendations by combining tracks suggested through multiple criteria: same artist, lyrical similarity, energy, mood, release time proximity, and random selection. It compiles these diverse recommendations into a dictionary with labeled categories, providing a comprehensive set of ... | def hybrid_recommend(track_index, count=6, prioritisePopular=True):
include_fields = ['track_name', 'track_artist']
all_recommendations = dict()
all_recommendations['by same artist'] = recommend_by_same_artist(track_index, count, prioritisePopular, include_fields)
all_recommendations['lyrically similar'... |
def is_available(self, item: Union[dict, pd.Series], verbose: bool = False):
try:
description = self._get_entity(item).describe_export(
self._get_item_entry(item, "category")
)
if verbose:
print(description)
return True
exce... | The code retrieves data from the Zooniverse Panoptes database based on a provided item, optionally regenerating the data if needed. It returns the data as a pandas DataFrame or raw HTTP response, with options to handle large datasets in chunks, convert to pandas, and control generation waits. | def retrieve(
self,
item: Union[dict, pd.Series],
generate: bool = False,
wait: bool = False,
convert_to_pandas: bool = True,
chunked_retrieve: bool = False,
chunk_size: int = int(1e5),
**read_csv_args,
) -> Union[requests.Response, pd.DataFrame, None]... |
def ensure_connected(id):
if id == state['id']:
raise "Shouldn't try to connect to itself"
(host, port, stub) = state['nodes'][id]
if not stub:
channel = grpc.insecure_channel(f"{host}:{port}")
stub = pb2_grpc.RaftNodeStub(channel)
state['nodes'][id] = (host, port, stub)
def ... | This function handles a candidate node's RequestVote RPC call to a target node. It ensures connectivity, sends a vote request, updates the node's term and role if the response indicates a higher term, increments vote count on success, and triggers election finalization if enough votes are received. It also handles conn... | def request_vote_worker_thread(id_to_request):
ensure_connected(id_to_request)
(_, _, stub) = state['nodes'][id_to_request]
try:
resp = stub.RequestVote(pb2.NodeArgs(term=state['term'], node_id=state['id']), timeout=0.1)
with state_lock:
# if requested node replied for too long,... |
def record_time(self, raised_time=None):
raised_time = raised_time or self.now()
self.history.append(self.last_raised_time)
self.history = self.history[-10:]
self.last_raised_time = raised_time
def update_lights(self):
if self.lid.raised:
self.set_color("off")
... | The main task of the code is to execute a looped sequence of operations: checking the lid state, triggering the alarm, recording time, updating lights, and handling button inputs, all intended to be repeatedly called in an infinite loop to manage the device's functionality. | def __call__(self):
"""
Nothing in the "Timer" class actually operates on a timer.
This object is intended to be called in a loop forever, and
this function does all the things.
"""
if self.lid():
self.alarm(alarm_state=False)
self.record_time()
... |
def GetMaxScanIndex():
global CurrentScanIndex
CurrentScanIndex = 0
try:
with open(rawfilename,"r") as filedata:
csvreader = csv.reader(filedata)
for row in csvreader:
if(len(row) == 7 and CurrentScanIndex<int(row[6])):
CurrentScanIndex = i... | The code performs periodic server scans, alternating between fast (CSV-based) and slow (MASTERSERVER) scans. It runs for a set duration or indefinitely, logging scan mode and writing results to CSV. After every FastScansTillSlow fast scans, it switches to a slower scan, then pauses for `delay` minutes before repeating. | def Iterator(delay=5,FastScansTillSlow=15):
global internalmode
global WriterTimeFormat
internalmode = ""
WriterTimeFormat = '%Y-%m-%d-%H:%M:%S'
end = time() + config['timer']*60
InternalPoint = FastScansTillSlow
while time() < end or config['runforever']:
if InternalPoint >= FastSca... |
def getinfo(config, name, notnull=False):
try:
info = config.getElementsByTagName(name)[0].childNodes[0].data
return info.strip()
except:
if notnull:
print('Missing ' + config.nodeName + ' ' + name +'. Abort.')
exit()
else:
return None
def sh_e... | This function generates a shell script (`.sh`) from an XML configuration, handling environment setup, workload execution, and injection commands. It creates indentation for nested commands, starts/stops a `dool` process (if enabled), and structures loops with `done` statements. The script includes sleep intervals and e... | def gen_single_sh(config, output, nodool):
name = getinfo(config, 'name', True)
f = open(os.path.join(output, name+'.sh'), 'w')
f.writelines(['#!/bin/bash/\n\n'])
# environment (for db env anomalies)
envs = config.getElementsByTagName('env')
if len(envs) > 0:
ntabs_env = sh_env(envs[0],... |
def _gray_scale(self, img):
altura = img.shape[0]
largura = img.shape[1]
gray_img = np.zeros(img.shape)
for i in range(0, altura):
for j in range(0, largura):
R = img[i, j][0]
G = img[i, j][1]
B = img[i, j][2]
... | This code computes the normalized cross-correlation between an image and a mask, identifying the two most correlated pixel positions. It slides the mask over the image, calculates correlation values, tracks the highest values, and returns the image with these positions highlighted for analysis. | def correlacao_normalizada(self, np_img, np_masc):
height = np_img.shape[0]
width = np_img.shape[1]
m = np_masc.shape[0]
n = np_masc.shape[1]
npg_img = self._gray_scale(np_img)
npg_masc = self._gray_scale(np_masc)
media_masc = self._media_pearso... |
def Decimal_Selection():
T=txtDisplay.get()
for o in T:
if o=="+":
Decimal_Add()
elif o=="-":
Decimal_Sub()
elif o=="*":
Decimal_Mul()
elif o=="/":
Decimal_Div()
def Binary_Selection():
T=txtDisplay.get()
for o in T:
... | This code defines a function 'selection' that retrieves a user input value (x) and routes it to specific functions based on the selected number system (Decimal, Binary, Octal, or Hexa_Decimal). Its main task is to act as a dispatcher, directing the program flow to the appropriate conversion or processing function depen... | def selection():
x=v.get()
if x=="Decimal":
Decimal_Selection()
elif x=="Binary":
Binary_Selection()
elif x=="Octal":
Octal_Selection()
elif x=="Hexa_Decimal":
Hexa_Decimal_Selection() |
def get_instructors():
conn = init_connection()
cur = conn.cursor()
cur.execute('SELECT * FROM instructors')
instructors = cur.fetchall()
return instructors
def show_instructors(instructors):
st.write('## User Information')
df = pd.DataFrame(instructors, columns=['ID', 'User ID', 'Name', 'C... | The code defines a Streamlit function for managing instructor data via a sidebar menu. It allows users to view, add, delete, modify instructors, or access a revision form by selecting options from the menu. Each choice triggers corresponding functions to handle data operations, enabling CRUD (Create, Read, Update, Dele... | def management():
menu = ['View Instructor', 'Add Instructor', 'Delete Instructor',
'Modify Instructor', 'Revision']
choice = st.sidebar.selectbox('Please select the following functions below', menu)
if choice == 'View Instructor':
instructors = get_instructors()
show_instructor... |
def is_initial_state(game_state: list[list[str]]) -> bool:
for row in game_state:
for cell in row:
if cell != empty_cell:
return False
return True
def select_random_corner():
return [choice([(0, 0), (0, 2), (2, 0), (2, 2)])]
def extract_lines(game_board: list[list[str]]) ... | The function `get_actions` determines the optimal next move in a game (likely Tic-Tac-Toe) by prioritizing: 1) winning immediately, 2) blocking the opponent's win, 3) defending against forks, 4) creating forks, and 5) selecting any remaining valid move. It analyzes the game state, extracts lines, and applies strategic ... | def get_actions(game_state: list[list[str]], current_player: str):
opponent_player = 'O' if current_player == 'X' else 'X'
if is_initial_state(game_state):
return select_random_corner()
row_lines, column_lines, diagonal_line, anti_diagonal_line = extract_lines(game_state)
potential_actions = ... |
def select_symbol(self):
self.view.display_symbol_choice()
symbol_chosen = False
while not symbol_chosen:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type ==... | The code manages a game loop by alternating between player and AI turns, checking for game over conditions, processing user input, and updating the game board display. It starts with symbol selection, handles mouse clicks for player moves, triggers AI moves when applicable, and redraws the board continuously until the ... | def start_game(self):
self.select_symbol() # Start with symbol choice screen
while True:
if self.is_game_over():
self.wait_for_new_game()
if self.is_players_turn():
self.process_mouse_click()
elif self.is_ai_turn():
se... |
def __openSocket(self, timeout):
self.__socket = None
try:
self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__socket.setblocking(1)
self.__socket.connect((self.host, self.port))
except socket.error as msg:
logger.error("socket... | The main task of the code is to initialize a detector by establishing a connection to a camera server, sending control commands (stop/start), configuring exposure parameters, setting a region of interest (ROI), and defining data paths. It returns True if the connection and setup succeed, otherwise False. | def initialize(self, timeout=5):
"""
Open connection to camserver.
Args:
timeout: Timeout in seconds
Returns:
True if connection was established successfully else False.
"""
self.__openSocket(timeout)
if not self.__socket:
r... |
def link_detections(self, frame_index):
live_tracks = self.live_tracks
current_points = self.get_frame_points(frame_index)
for miss_count in range(0, ALLOWED_MISSES):
VideoProcessor.matching(live_tracks, current_points, miss_count, 1 - IOU_OVERLAP)
new_live_tracks = []
... | The main task of the code is to process video data by linking object detections across frames, generating tracking records, saving them as a CSV file, and exporting the results to a video file. It creates directories for images and ground truth data, iterates through frames to link detections, draws tracks, and writes ... | def process(self):
sub_dataset_dir = os.path.join(DATASET_DIR, 'sample{}'.format(self.VIDEO_INDEX))
img_dir = os.path.join(sub_dataset_dir, 'img1')
gt_dir = os.path.join(sub_dataset_dir, 'gt')
os.makedirs(img_dir, exist_ok=True)
os.makedirs(gt_dir, exist_ok=True)
# print... |
def clockwiseSort(points):
# get mean x coord, mean y coord
xavg = sum(p[0] for p in points) / len(points)
yavg = sum(p[1] for p in points) / len(points)
angle = lambda p: ((math.atan2(p[1] - yavg, p[0] - xavg) + 2*math.pi) % (2*math.pi))
points.sort(key = angle)
def merge(left, right):
mergedHull = []
#Find t... | This code computes the convex hull of a set of points using a divide-and-conquer approach. It recursively splits points into halves, computes their convex hulls, and merges them. The initial clockwise sorting and base case handling (for ≤3 points) ensure proper hull construction. However, the merge logic is incomplete,... | def computeHull(points):
clockwiseSort(points)
print("AFTER CLOCKWISE")
j = 0
for i in points:
j+=1
print(i, " - ", j)
#base case of three points
if(len(points) <= 3):
return points
#separate the current points into two halves until the base case is reached
left_convex = computeHull(points[0:int(len(poi... |
def test_url(self,url):
path = urlparse(url).path
# will return tuple ("/eg/eg/eg",".pdf")
# extracting extension from url
ext = posixpath.splitext(path)[1].lower()
#lock.acquire(2)
IGNORED_EXTENSIONS = ignored_extensions.IGNORED_EXTENSIONS
#lock.release()
... | The main task of the code is to send an HTTP GET request to a specified URL using a session, handle connection errors with a retry mechanism, and pass the response to a parsing function if successful. It checks URL validity, uses a custom User-Agent, and employs a lock for thread safety. If errors occur, it logs messag... | def do_req(self,url,session,lock,try_once=True):
allow_url = self.test_url(url)
if allow_url:
try:
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'
response = session.get(url,timeout=5,headers... |
def move_x(self):
if pyxel.btn(pyxel.KEY_RIGHT):
if self.x < 230:
self.running_animations(self.vx, \
["small_mario_run_right_1", "small_mario_run_right_2", "small_mario_run_right_3"],\
["big_mario_run_right_1", "big_mario_run_right... | The code's main task is to update an object's state by moving it horizontally and vertically, handling shooting mechanics, updating a debugger, checking collisions with the map, and printing the current coordinates. It orchestrates movement, interaction, and debugging for a game entity like Mario. | def update(self):
self.move_x()
self.move_y()
self.mario_shoot()
self.debugger.update()
self.map.collision_handler(self)
print(f"{self.x}, {self.y}") |
def read_shape_points(folder):
filenames = glob.glob(folder+'*.csv')
metrics = None
jpg_files = []
#print(filenames)
for i, filename in enumerate(filenames):
metric, jpg_file = read_single_csv(filename)
if i == 0:
metrics = metric[np.newaxis, :]
else:
... | The code processes grasp data to predict and explain grasp success. It reads training/query data, predicts grasp success based on a threshold, selects alternative grasps using SHAP-based explanations, generates text explanations via templates, and visualizes the query and alternative grasps. The goal is to provide inte... | def main():
parser = argparse.ArgumentParser(description='explainable grasp metrics')
parser.add_argument('-t', type=str, default='train_files/', help='the folder of training csv and images')
parser.add_argument('-q', type=str, default='test_files/35_2.csv', help='the query csv of shape points')
parser.... |
def read_queue():
if os.path.exists(get_queue_path()):
try:
with open(get_queue_path(), "r") as queue:
return json.load(queue)[QUEUE_KEY]
except (json.JSONDecodeError, FileNotFoundError, KeyError):
write_queue([])
return read_queue()
return []
... | The function compares a local file with its latest TFS server version using 'diff'. If changes exist, it checks out the file; if none, it undoes checkout. It processes queued files by simulating modifications and clears the queue. If the file doesn't exist on TFS, it attempts to add it, queuing the file if connection f... | def run_tfs_command(file_path):
queue = read_queue()
# Perform a comparison between the local file and the latest server version
tf_diff_command = ["diff", "/version:T", file_path]
tf_diff_output = execute_tfs(tf_diff_command)
if tf_diff_output.returncode == 0:
changed_lines = [
... |
def capture(self, piece: Piece, move):
"""Moves Pieces and Captures if necessary
:param piece: Piece
:param move: list"""
banish = [20, 20]
if self.getPiece(move) is not None:
self.getPiece(move).position = banish
# En Passant
elif piece.piece[0] == 'P... | The code moves a chess piece, updates the board, handles en passant captures by checking if a pawn's move allows an opponent's pawn to capture it, and checks for checkmate or stalemate by verifying if the opposing king is in check or has no legal moves. | def move(self, piece: Piece, move):
"""Moves a piece and updates board for next move. checks for checkmate or stalemate.
:param piece: Piece
:param move: list"""
previousPos = piece.position
self.capture(piece, move)
self.possibleMoves()
# add en passant moves
... |
def get_transponation_steps(source_key, target_key):
"""Gets the number of half tones to transpose
>>> get_transponation_steps('D', 'C')
-2
"""
source_index = get_index_from_key(source_key)
target_index = get_index_from_key(target_key)
return target_index - source_index
def transpose_line(so... | The function `transpose_file` transposes musical notation in a file from a specified source key (`from_key`) to a target key (`to_key`). It calculates the transposition interval using `get_transponation_steps`, reads each line of the input file, and applies the key change to chord symbols and notation via `transpose_li... | def transpose_file(file_name, from_key, to_key):
"""Transposes a file from a key to another.
>>> transpose_file('example.txt', 'D', 'E')
'Rocking start, jazzy ending\\n| E | A B | Cm7#11/D# |\\n'
"""
direction = get_transponation_steps(from_key, to_key)
result = ''
try:
for line in o... |
def make_user(self, uid, key):
uid0, uid1 = uid
key0, key1 = key
return self.make_cmd("user", [uid0, uid1, key0, key1])
def gen_uid(self):
uid0 = rand_sint()
uid1 = rand_sint()
return uid0, uid1
def gen_key(self):
key0 = rand_sint()
key1 = rand_sint()
return key0, key1 | The main task of the code is to generate a user with a randomly created unique ID (UID) and key. It achieves this by calling `self.make_user()` and passing arguments generated by `self.gen_uid()` and `self.gen_key()`, ensuring the creation of a user with dynamically assigned identifiers. | def make_user_rand(self):
return self.make_user(self.gen_uid(), self.gen_key()) |
def rand_sint(below=2**31):
raw = rand_uint(below)
if rand_bool():
raw = -raw
return raw
def single_request_expect(self, cmds, expect_out, expect_mid=[]):
# HACK: Append dump commands
expect_out = list(expect_out)
for i in range(len(expect_out)):
cmds.append("!")
cmds.append("~")
r = self.single_req... | The `havoc` method generates randomized test cases for a command-processing system, using different variants (0–6) to simulate operations like integer generation, arithmetic, and data manipulation. Each variant constructs a command sequence with random values, executes it, and verifies results against expected outputs ... | def havoc(self):
self.action_title = "havoc"
# TODO(orcanojr): Fix these for junior
if self.variant_id == 0:
self.action_title = "havoc <integer>"
val = rand_sint()
cmds = [str(val)]
self.single_request_expect(cmds, [int(val)])
elif self.variant_id == 1:
self.action_title = "havoc ~"
count = ... |
def _set_predicted_value_evaluation(self):
'''Sets function that will be used for selecting one algorithm amongst
an array of predicted algorithms according to the value of user defined
:py:attr:`~predictor.config.Config.algorithm_type_predicted` and
:py:attr:`~predictor.config.Config.ac... | The code initializes a configuration class by setting default parameters, loading user-defined settings from a YAML file, and deriving necessary values. It configures data paths for actual time/pdI data, predicted model outputs, plots, and machine learning models. The class prepares data frames, initializes evaluation ... | def __init__(self, config_file_path = None):
'''
Initializes user defined parameters to their default values and sets
derived parameters according to values of user defined parameters.
:param config_file_path: Full path to a file containing configuration
in YAML format. File... |
def install_express_cli():
if not os.path.isdir(globals.EXPRESS_CLI_INSTALL_DIR):
cmd = "git clone {} {}".format(globals.EXPRESS_CLI_URL, globals.EXPRESS_CLI_INSTALL_DIR)
sys.stdout.write("--> cloning repository ({})\n".format(cmd))
exit_status, stdout = ssh_utils.run_cmd(cmd)
if not... | The code initializes the Express-CLI tool by creating necessary directories, installing the CLI, validating its installation, and building a configuration file using provided credentials and parameters. It ensures prerequisites are met for Express-CLI operation, returning True on success or False/exit on failures. | def init(url, username, password, tenant, region):
sys.stdout.write("\n[Initialize Express-CLI (branch = {})]\n".format(globals.ctx['platform9']['express_cli_branch']))
# validate express base directory exists
if not os.path.isdir(globals.EXPRESS_BASE_DIR):
try:
os.mkdir(globals.EXPRESS... |
def launch_batch_instances(self, action):
# valid action JSON
required_keys = ['num_instances','plan','facility','operating_system','hostname_base','network_mode','ip_addresses','k8s_vlan_tag']
for key_name in required_keys:
if not key_name in action:
sys.stdout.write... | The main task of the code is to execute actions defined in a JSON spec file, sequentially launching cloud instances or building Kubernetes clusters on Platform9. It validates input parameters, manages instance booting/networking, and integrates with PMK to onboard clusters, handling both assimilated and launched instan... | def run_action(self, spec_file):
if not os.path.isfile(spec_file):
sys.stdout.write("ERROR: failed to open spec file: {}".format(spec_file))
return(None)
with open(spec_file) as json_file:
spec_actions = json.load(json_file)
required_keys = ['actions']
... |
def getSmemData(self):
columns = ['pid', 'rss', 'pss', 'uss']
result = execCommand("smem", ["-t", "-n", "-H", "-c", ' '.join(columns)])
result = result.decode("utf-8")
smemData = self.parseSmemOutput(result)
# Multiply RSS, PSS, USS by 1024 because they are given in KB by smem
... | The main task of the code is to retrieve system data, map process IDs to their corresponding command-line arguments, and format the combined data for structured output. It first fetches raw data, extracts process IDs, retrieves command-line information, then merges and formats the data for use. | def getData(self):
data = self.getSmemData()
pidToCmd = self.getCmdLineData([d[0] for d in data])
return self.formatData(data, pidToCmd) |
def get_distance_to_edge(location, edge, data_limits, direction = "closest"):
"""
Computes distance from location to the edge in the specified direction, or if
no direction is given, to the closest point on the edge. If location is above
the edge, distance is negative and direction is flipped. (This re... | The function `add_distance_to_edge` computes the distance from buoy locations in `swift_df` to the ice edge defined in `edge_df`, adding columns `dist_(label)` and `dir_(label)` to `swift_df`. It calculates distances either as the shortest ("closest") or in a specified direction (from `in_direction`), adjusting for com... | def add_distance_to_edge(swift_df, edge_df, data_limits, in_direction, label,
time_col = 'timestamp', make_plots = False,
xlim = None, ylim = None, lon_col = 'lon'):
"""
Computes distance to the ice edge. Distance will be in the same unit as the columns "x", "... |
def get_terms_and_times():
"""Gets the times for each term (aka. teaching period)"""
def extract_term(text: str) -> str:
return text.split()[-1]
def extract_term_times(text: str) -> dict:
from_week, from_date, to_week, to_date = text.split(",")
return {
"from_week": fro... | (The code scrapes data for all campus regions in the current term, combines it with metadata, and saves each region's data as a JSON file in the specified output bucket. It retrieves term information, iterates through predefined regions, scrapes region-specific data, and writes structured JSON files containing both scr... | def scrape(output_bucket: str = None):
"""Scrape data for every campus region for the current term"""
writer = get_writer(output_bucket)
logger.info(f"Fetching term metadata")
times = get_terms_and_times()
term = get_current_term(times)
meta = get_metadata(times[term], term)
for region in R... |
def _check_start_point(self, start_point):
if not self._position:
return self._set_aborted(self._result.INVALID_GOAL,
'Joint states not received')
elif sum(self._calc_array_diff(start_point, self._position)) > 3.14*10/180:
return self._set_abo... | This method executes a trajectory by interpolating between joint positions over time. It validates the trajectory, logs execution start, calculates time intervals between points, uses linear interpolation to move joints, updates feedback, and logs completion for each segment. The loop ensures precise timing at 125Hz, c... | def _on_trajectory_action(self, goal):
self._joint_names = goal.trajectory.joint_names
trajectory_points = goal.trajectory.points
num_points = len(trajectory_points)
# rospy.loginfo(self._joint_names)
# rospy.loginfo(trajectory_points)
rospy.loginfo([x.time_from_start.to_... |
def dirPathList(self, filepath):
k = []
l = filepath
if l.rfind('/') == (len(l)-1):
l = l[:-1]
if l.rfind('/') != -1:
last = l.rfind('/')
while l.rfind('/') != 0:
k.insert(0, l[:last+1])
l = l[:last]
last... | This code identifies duplicate files by checking if a given file path exists in a directory structure. It modifies a directory path list, checks for duplicates using helper methods, and compiles a list of duplicate file paths. If duplicates are found, it returns True with the list; otherwise, it returns False with an e... | def getDuplicateFileList(self, filepath):
oc = self.oc
l1 = self.dirPathList(filepath)
l1List = list(l1)
l1List[0] = l1List[0] + 1
l1List[1].append(filepath)
l1 = tuple(l1List)
l2 = []
for x in l1[1]:
if self.checkDuplicate(x):
... |
def checkDuplicateExist(self, filepath):
oc = self.oc
try:
y = oc.list(self.duplicatePath(filepath))
list1 = []
l3 = []
for z in y:
l1 = z.get_name().rfind('_') + 1
if z.is_dir():
num1 = int(z.get_name()[... | The function checks for duplicate data in a file. If duplicates exist, it returns True along with the minimum value's row (from column 1) and the maximum value from column 2. If no duplicates, it generates a new file path and returns False with default values. | def getDuplicateAttributes(self, filepath):
isExist, dataList, _ = self.checkDuplicateExist(filepath)
if isExist:
C = self.column(dataList, 1)
D = self.column(dataList, 2)
val1 = C.index(min(C))
val2 = max(D)
list3 = dataList[val1]
... |
def fileExists(self, oc, filepath):
try:
oc.file_info(filepath)
return True
except Exception as e:
if str(e)[-3:] == "404":
return False
def dirPathList(self, filepath):
k = []
l = filepath
if l.rfind('/') == (len(l)-1):
... | This code creates a file or folder at a specified path, checking if it already exists. If not, it constructs the directory structure by iterating through path components, creating missing directories, and placing the file contents. It handles both file and folder creation, returning success or existence messages. | def createFile(self, filepath, type1, filecontents):
if (not self.fileExists(self.oc, filepath)):
oc = self.oc
if type1=='file':
str1 = filecontents
str2 = bytes(str1, 'UTF-8')
list1 = self.dirPathList(filepath)[1]
list1.reverse()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.