dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def wait_for_instance(id: int):
logger.info(f"Waiting for instance {id} to start")
retry = 0
while True:
if retry > 10:
raise Exception("Timeout waiting for instance to start")
try:
instances = vast.get_instances()
except:
retry += 1
ti... | The function `run_all` automates deploying and executing tasks on a remote VAST instance. It loads configuration and job scripts, provisions an instance, establishes an SSH connection, runs setup and job commands, then deletes the instance. Key steps include API validation, YAML config parsing, SSH setup with Paramiko,... | def run_all(id: str, config_file: str, job_file: str, log_file: str = "./log-{id}.log"):
vast.check_api_key()
with open(config_file, "r") as f:
config = InstanceConfig(**yaml.load(f, Loader=yaml.FullLoader))
with open(job_file, "r") as f:
job = f.read()
instance_info = vast.create_insta... |
def recv(client):
msg_length = client.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = client.recv(msg_length).decode(FORMAT)
return msg
def drawGameState(screen, gs):
'''
Draw background board
'''
drawBoard(screen)
#Draw pieces
drawPieces(screen, gs.board... | This code implements a local multiplayer chess game with network communication. It initializes a chessboard, handles player input for move selection, validates moves, sends moves to a server, receives updates, updates the game state, and checks for check/checkmate. The game runs in a loop, rendering the board and handl... | def local_multiplayer(screen):
#initializing pygame
screen.fill(GOLD)
gamestate = ChessState()
gameOver = False #flag variable to check game is on or over
clock = pygame.time.Clock()
firstloc = ()
secondloc = ()
checked = False
checkMate = False
validMoves = gamestate.getValidMoves() #check valid moves
m... |
def getAllMoves(self, board):
moves = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j][1] == 'p':
self.getPawnMoves(i, j, moves, board)
elif board[i][j][1] == 'r':
self.getRookMoves(i, j, moves, board)
elif board[i][j][1] == 'h':
self.getKnightMoves(i, j, mo... | This function generates valid moves by checking if each move leaves the current player's king in check. It iterates through all possible moves, applies each temporarily, switches turns, checks for check, removes invalid moves, then reverts changes. The result is a list of moves that do not expose the king to capture. | def getValidMoves(self):
#check checked for black
moves = self.getAllMoves(self.board)
for i in range(len(moves) - 1, -1,-1):
self.movePiece(moves[i])
if self.turn == 'w':
self.turn = 'b'
else:
self.turn = 'w'
if self.check():
moves.remove(moves[i])
if self.turn == 'w':
self.turn = ... |
def getAllMoves(self, board):
moves = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j][1] == 'p':
self.getPawnMoves(i, j, moves, board)
elif board[i][j][1] == 'r':
self.getRookMoves(i, j, moves, board)
elif board[i][j][1] == 'h':
self.getKnightMoves(i, j, mo... | This function generates valid moves by testing each potential move to ensure it doesn't leave the player's king in check. It iterates through all possible moves, temporarily applies each move, checks for check status, removes invalid moves, and restores the board state before returning the filtered list of valid moves. | def getValidMoves(self):
#check checked for black
moves = self.getAllMoves(self.board)
for i in range(len(moves) - 1, -1,-1):
self.movePiece(moves[i])
if self.turn == 'w':
self.turn = 'b'
else:
self.turn = 'w'
if self.check():
moves.remove(moves[i])
if self.turn == 'w':
self.turn = ... |
def getValidMoves(self):
#check checked for black
moves = self.getAllMoves(self.board)
for i in range(len(moves) - 1, -1,-1):
self.movePiece(moves[i])
if self.turn == 'w':
self.turn = 'b'
else:
self.turn = 'w'
if self.check():
moves.remove(moves[i])
if self.turn == 'w':
self.turn = ... | The main task of the code is to generate and visualize valid moves for a selected chess piece on a board. It identifies the piece at the given position, calculates its possible moves using specialized methods, filters these against globally valid moves, and draws red circles on the screen to indicate legal move positio... | def getHint(self, box, screen):
moves = []
piece = self.board[box[0]][box[1]]
validMoves = self.getValidMoves()
if piece[1] == 'p':
self.getPawnMoves(box[0], box[1], moves, self.board)
elif piece[1] == 'r':
self.getRookMoves(box[0], box[1], moves, self.board)
elif piece[1] == 'h':
self.getKnightMov... |
def getValidMoves(self):
#check checked for black
moves = self.getAllMoves(self.board)
for i in range(len(moves) - 1, -1,-1):
self.movePiece(moves[i])
if self.turn == 'w':
self.turn = 'b'
else:
self.turn = 'w'
if self.check():
moves.remove(moves[i])
if self.turn == 'w':
self.turn = ... | The function generates valid moves for a selected chess piece, filters them against the current player's permissible moves, and visually highlights these valid moves on the screen by drawing red circles at their corresponding board positions using Pygame. | def getHint(self, box, screen):
moves = []
piece = self.board[box[0]][box[1]]
validMoves = self.getValidMoves()
if piece[1] == 'p':
self.getPawnMoves(box[0], box[1], moves, self.board)
elif piece[1] == 'r':
self.getRookMoves(box[0], box[1], moves, self.board)
elif piece[1] == 'h':
self.getKnightMov... |
def remove_cheermotes(raw_message):
word_list = raw_message.split(" ")
message = ""
for word in word_list:
if word.lower().startswith(tuple(ttsController.PREFIXES)) and word[-1].isdigit():
continue
message += word + " "
message.strip()
return message
def split_message(sel... | The main task of the code is to handle WebSocket messages by managing subscriptions during a session setup and processing chat notifications. It checks active subscriptions, creates new ones if needed, and queues text-to-speech generation for specific chat events like gifts, subscriptions, and cheers, while handling mo... | def on_message(self, ws, msg):
msg = json.loads(msg)
if msg['metadata']['message_type'] == 'session_welcome':
# session variables
session_id = msg['payload']['session']['id']
init_check = requests.get(ttsController.SUBS_ENDPOINT + '?status=enabled', headers=self.head... |
def merge_nodes_geometrically(nodes, tag):
"""
Merge nodes according to geometrical restrictions
"""
geometry_nodes, merge, tag = merge_nodes_geometrically_recursion(nodes, {}, tag)
geometry_nodes = {k: l for k, l in geometry_nodes.items() if len(l) != 0}
return geometry_nodes, merge, tag
def ge... | The function merges nodes using geometric rules, recursively processing merged areas to combine overlapping or adjacent nodes. It checks if a merge occurred, calculates affected areas, groups nodes within those areas, and repeats the merging process until no further merges are needed, returning the final merged nodes s... | def merge_nodes(nodes):
"""
Merge nodes by geometrical rules
"""
tag = False
geometry_nodes, merge, tag = merge_nodes_geometrically(nodes, tag)
if tag:
areas = get_merged_areas(merge)
area_nodes = get_nodes_in_area(areas, merge, geometry_nodes)
merged_nodes = merge_nodes_... |
def get_linear_equation_parameters(rho, sens_1, spec_1, cov_1, sens_2, spec_2, cov_2):
"""
Get the slope and intercept of the linear equation of the intersection of two planes (equation A3.3)
ZeroDivisionError: planes are parallel
"""
try:
denominator = (cov_1 * (1 - rho) * (1 - spec_1) + co... | The code generates nodes by calculating intersections of lines derived from pairs of predictors, excluding specific lines like the x-axis and hypotenuse. It iterates through all predictor combinations, computes linear equations, filters valid lines, and determines their intersections to construct nodes, ensuring unique... | def get_nodes(rho, predictors, precision):
"""
Get nodes
"""
potential_lines = []
for group in combinations(predictors, 2):
slope, intercept = get_linear_equation_parameters(rho, *predictors[group[0]], *predictors[group[1]])
if slope is not None and intercept is not None:
... |
def get_nodes(rho, predictors, precision):
"""
Get nodes
"""
potential_lines = []
for group in combinations(predictors, 2):
slope, intercept = get_linear_equation_parameters(rho, *predictors[group[0]], *predictors[group[1]])
if slope is not None and intercept is not None:
... | This function calculates the intersection lines and nodes formed by multiple planes (predictors) using a given precision. It processes nodes by unmerging, merging, and sorting them, then derives and organizes intersecting lines. The output includes the computed nodes and sorted line segments representing the geometric ... | def get_predictors_intersection(rho, predictors, precision):
"""
Get lines and nodes of predictors's planes intersection
"""
nodes = get_nodes(rho, predictors, precision)
nodes = unmerge_nodes(nodes)
nodes = merge_nodes(nodes)
lines = get_lines(nodes)
sorted_lines = sort_line_nodes(lines... |
def check_input(self):
if self.game.PLUS_KEY:
if self.__iter_or_expo:
self.iterations += 1
else:
self.exponent += 0.1
if self.game.MINUS_KEY:
if self.__iter_or_expo:
if self.iterations - 1 > 0:
self.i... | The code's main task is to run a demo loop that continuously updates and displays iteration/exponent values on-screen, handling user input to adjust iterations. It renders text with specific formatting, showing controls for increasing/decreasing iterations, and refreshes the display in a loop until `show_demo` is set t... | def draw(self):
self.show_demo = True
while self.show_demo:
self.game.check_events()
self.check_input()
self.draw_text(
f"Iterations: {self.iterations}",
18,
(255, 255, 255),
70,
10,
... |
def _create_cells(self):
self.__cells = [
[
Cell(
[True] * 4,
column_offset,
column_offset + self.__cell_size_x,
row_offset,
row_offset + self.__cell_size_y,
self._... | The code generates and solves a maze by creating cells, breaking walls recursively, setting entrance/exit, and solving the maze. It then enters a loop to handle events, input, and render the maze in real-time until the demo is closed. | def draw(self):
self.show_demo = True
self._create_cells()
self._break_entrance_and_exit()
self._break_walls_r(0, 0)
self._reset_cells_visited()
self.solve()
while self.show_demo:
self.game.check_events()
self.check_input()
self... |
def setup_network(self):
if self.bitcoind is not None and self.cointype == "BTC":
self.start_bitcoind()
self.setup_nodes()
def run_test(self):
raise NotImplementedError
def teardown(self):
for n in self.nodes:
requests.post(n["gateway_url"] + "ob/shutdown")
... | This code defines a main function for a test framework that initializes and runs tests for the OpenBazaar-go application. It parses command-line arguments for binaries, test parameters, and environment settings, sets up a network, executes test cases, and handles failures. The framework cleans up resources afterward, e... | def main(self, options=["--disablewallet", "--testnet", "--disableexchangerates"]):
parser = argparse.ArgumentParser(
description="developertask Test Framework",
usage="python3 test_framework.py [options]"
)
parser.add_argument('-b', '--binary', required=T... |
def update_covid19_data():
"""Update the covid-19 data held in 'covid19_data'.
Access Cov19API and get data before placing it into the global
dictionary, 'covid19_data'.
"""
logging.info('UPDATE DATA: Covid19')
raw_data = get_covid19_data()
if (not raw_data) or (raw_data['totalPages'] =... | The function `do_alarm` activates an alarm by announcing its title, current time, and COVID-19 data. It optionally provides weather or news briefings based on the alarm's settings, then removes the alarm from the list. The task involves logging, data updates, and structured announcements to inform users during an alarm... | def do_alarm(alarm):
"""Activate and announce the alarm, along with selected details.
Arguments:
alarm -- alarm to activate
"""
logging.info('DO ALARM: START')
update_covid19_data()
logging.info('BEGIN GENERAL BRIEFING')
announce(
'It is ' + time.strftime('%H:%M', time.... |
def symbol_search(message: Message) -> None:
"""
Function to Hande search stock menu.
Assign search_type global variable
Redirect:
Main menu
Parameters:
message(Message): The incoming message
Returns:
None
"""
# Get specified user id
user_id = message.from_us... | The function handles user messages by routing them to appropriate actions based on the message text and session data. It identifies the user, updates their message count, and directs the message to functions like search, bookmark management, or menu navigation depending on predefined strings or stored search type in th... | def message_handler(message: Message) -> None:
"""
Function to handle buttons input and text input messages.
Parameters:
message (Message): The input message
Returns:
None
"""
# Get specified user id
user_id = message.from_user.id
session.increase_current_message_id(use... |
def MasukParkir():
platnomor = str(input("Masukkan nomor/plat kendaraan (contoh: D1234AF): "))
waktumasuk = datetime.datetime.now()
kendaraanmasuk.append(
{'nomor_plat': platnomor,
'waktu_masuk': waktumasuk})
print("Waktu masuk:", waktumasuk)
print("Gerbang masuk terbuka. Silakan ma... | The code defines a main menu loop for a parking system, displaying options to enter/exit parking, access admin functions, or quit. It repeatedly prompts the user for input, executes corresponding functions based on the choice, and validates inputs to ensure only valid menu options are processed. | def MenuUtama():
while True:
print("===== MENU AWAL =====")
print("1. Masuk Area Parkir")
print("2. Keluar Area Parkir")
print("3. Admin Parkir")
print("4. Keluar")
pilihanmenu = int(input("Pilih menu (1/2/3/4): "))
if pilihanmenu == 1:
MasukParki... |
def get_map(counter, previous_map):
# check if there is a (new) layer 1 map available
while len(os.listdir('data/map/layer 1')) == 0:
print("waiting for map layer 1")
time.sleep(1)
current_map = len(os.listdir('data/map/layer 1')) - 1
if counter == 0 or current_map != previous_map:
... | The code continuously tracks dynamic objects in a map using sensor data, updating their positions over time. It processes classification data, traces object points, and visualizes their movement paths with time-based filtering to manage visualization duration. | def main():
classification_counter = 0
previous_map = 0
dynamic_objects = []
while True:
data, pixels, opencv_im, previous_map = get_map(classification_counter, previous_map)
# map_rotation = calculate_map_rotation(opencv_im)
map_rotation = 60
classification, object_i... |
def construct_request(ticker, fields=None, date_from=None, date_to=None,
freq=None, static=False, IsExpression=None,
return_names=True):
"""Construct a request string for querying TR DSWS.
tickers - ticker or symbol, or list of symbols
f... | The function `usage_statistics` retrieves and aggregates user usage data over a specified number of months. It defaults to the current month if no date is provided, constructs requests for each month, fetches the data, concatenates results, formats the index as "Month Year," and returns a cleaned DataFrame of statistic... | def usage_statistics(self, date=None, months=1):
""" Request usage statistics
date - if None, stats for the current month will be fetched,
otherwise for the month which contains the specified date.
months - number of consecutive months prior to "date" for which
... |
def construct_request(ticker, fields=None, date_from=None, date_to=None,
freq=None, static=False, IsExpression=None,
return_names=True):
"""Construct a request string for querying TR DSWS.
tickers - ticker or symbol, or list of symbols
f... | The function fetches financial data from Datastream for specified tickers and fields, handling date ranges, frequencies, and static/snapshot requests. It constructs a request, retrieves raw data, parses it into structured DataFrames (with MultiIndex for multiple tickers/dates), and returns results with optional metadat... | def fetch(self, tickers, fields=None, date_from=None, date_to=None,
freq=None, static=False, IsExpression=None, return_metadata=False):
"""Fetch the data from Datastream for a set of tickers and parse results.
tickers - ticker or symbol, or list of symbols
fields - field or... |
def construct_request(ticker, fields=None, date_from=None, date_to=None,
freq=None, static=False, IsExpression=None,
return_names=True):
"""Construct a request string for querying TR DSWS.
tickers - ticker or symbol, or list of symbols
f... | The code retrieves and processes the next scheduled release dates (NDoR) for economic data series, handling up to 12 future releases. It validates input parameters, fetches data via constructed requests, parses responses, restructures the output, converts date fields to datetime objects, and returns structured results ... | def get_next_release_dates(self, mnemonics, n_releases=1):
""" Return the next date of release (NDoR) for a given economic series.
Could return results for up to 12 releases in advance.
Returned fields:
DATE - Date of release (or start of range where the exact
... |
def get_model():
global model_base
model = SentenceTransformer(model_base)
gpu_available = torch.cuda.is_available()
device = torch.device("cuda" if gpu_available else "cpu")
model = model.to(device)
return model
def embeddings(model, sentences):
gpu_available = torch.cuda.is_available()
... | The main task of the code is to check if a user's guess matches a predefined answer using a language model. It constructs prompts with masked tokens, evaluates guesses, appends feedback to output, and returns either a "Correct!" message with a new prompt or a "Try again!" instruction. The function tracks guesses, gener... | def check_answer(guess:str):
global guesses
global answer
global return_guesses
global word1
global word2
global word3
model = get_model()
output = ""
protected_guess = guess
sentence = f"{word1} is to {word2} as [MASK] is to {guess}."
other_word = embeddings(model, ... |
def input_letter(row: int, column: int) -> dict:
"""
This function lets users input letters into a 4x4 square and checks whether in a determined manner.
:param row: int, the row of input letters
:param column: int, the column of input letters
:return letter_dict: dict, letters with coordination
"""
switch = Fals... | The main task of the code is to find all valid words in a 4x4 letter grid using a Boggle-like algorithm. It reads input letters, checks for validity, loads a dictionary, searches for words in the grid, counts them, and measures execution time. The result includes the total word count and the algorithm's speed in second... | def main():
"""
This program finds the words from the input letters in a 4x4 square with a "boggle" way.
"""
####################
letter_dict = input_letter(ROW, COLUMN)
if letter_dict is not None: # Determine whether there is any illegal input letter
start = time.time()
dict_dict = read_dictionary(FILE)
w... |
def request_token() -> str:
"""Request a token from the Open Trivia Database API."""
request = requests.get(API_REQUEST_TOKEN_URL)
request.raise_for_status()
return request.json()['token']
def request_questions(token: str,
category: str = None,
difficulty: st... | The main task of the code is to test parsing functions by fetching one question via an API token, then printing parsed data including categories, difficulty, question text, types, answers, and correct answers to validate extraction logic. | def main_test() -> None:
"""Test the main functions."""
token = request_token()
category = None
questions = request_questions(token, category=category, amount=1)
print(
'\n',
# questions,'\n',
parse_questions_categories(questions),'\n',
parse_questions_difficulty(ques... |
def generate_keys(key):
key_p10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
key_p8 = [6, 3, 7, 4, 8, 5, 10, 9]
# Apply P10 permutation
key_10 = permute_8bits(key, key_p10)
# Split into two 5-bit halves
left_half = key_10[:5]
right_half = key_10[5:]
# Perform circular left shifts
left_half =... | The code implements a Simplified Data Encryption Standard (S-DES) encryption algorithm. It encrypts plaintext using a key by generating two subkeys, applying initial permutation, performing two rounds of encryption with the subkeys, switching bit positions between rounds, and applying an inverse permutation to produce ... | def sdes_encrypt(plaintext, key):
key_1, key_2 = generate_keys(key)
# Initial permutation
initial_perm = initial_permutation(plaintext)
# Round 1
round_1 = fk(initial_perm, key_1)
# Switch
switch_output = switch(round_1)
# Round 2
round_2 = fk(switch_output, key_2)
# Inverse... |
def generate_keys(key):
key_p10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
key_p8 = [6, 3, 7, 4, 8, 5, 10, 9]
# Apply P10 permutation
key_10 = permute_8bits(key, key_p10)
# Split into two 5-bit halves
left_half = key_10[:5]
right_half = key_10[5:]
# Perform circular left shifts
left_half =... | The code decrypts ciphertext using the Simplified Data Encryption Standard (SDES) algorithm. It applies an initial permutation, performs two rounds of Feistel function operations with subkeys key_2 and key_1, swaps halves between rounds, and applies an inverse permutation to retrieve the plaintext. | def sdes_decrypt(ciphertext, key):
key_1, key_2 = generate_keys(key)
# Initial permutation
initial_perm = initial_permutation(ciphertext)
# Round 1
round_1 = fk(initial_perm, key_2)
# Switch
switch_output = switch(round_1)
# Round 2
round_2 = fk(switch_output, key_1)
# Inver... |
def on_session_started(session_started_request, session):
""" Called when the session starts.
One possible use of this function is to initialize specific
variables from a previous state stored in an external database
"""
# Add additional code here as needed
pass
def on_launch(launch_req... | The code defines an AWS Lambda handler for an Alexa skill, routing incoming requests (Launch, Intent, SessionEnded) to appropriate functions. It checks for a new session and validates the application ID (commented out), then processes requests by calling `on_launch`, `on_intent`, or `on_session_ended` based on the requ... | def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("Incoming request...")
"""
Uncomment this if statement and populate with your skill's application ID t... |
def detect_collisions(paths):
##############################
# Return a list of first collisions between all robot pairs.
# A collision can be represented as dictionary that contains the id of the two robots, the vertex or edge
# causing the collision, and the timestep at which the collision occurred.
... | The main task of the code is to find collision-free paths for multiple agents from their start to goal locations using a high-level search algorithm. It generates initial paths with A* planning, detects collisions, and iteratively resolves them by splitting collisions into constraints. For each constraint, it creates c... | def find_solution(self, disjoint=False):
""" Finds paths for all agents from their start locations to their goal locations
disjoint - use disjoint splitting or not
"""
self.start_time = timer.time()
planner = AStarPlanner(self.my_map)
# Generate the root node
... |
def while_input(text_input, err_msg='', *args):
while True:
user_input = input(f"{text_input} ").lower()
if proper_input(user_input, args):
return user_input
else:
print(f"{err_msg}")
continue
def proper_input(user_input, desired_input):
if user_input.... | The function `explore()` randomly selects a Chinpokomon, prompts the user to collect it, and if confirmed, passes the selected Chinpokomon to an inventory-checking function. | def explore():
wild_chinpokomon = random.choice([each.copy() for each in chinpokomon_list.values()])
user_input = while_input(f"You've stumbled across a {wild_chinpokomon['name']}! Would you like to collect it? (Y/N)", "ERR: Yes or No?", 'y', 'n')
if proper_input(user_input,"y"):
check_inv(wild_chi... |
def __applyForce(self): #add force vector to velocity
newVelocity = self.addVector(self.velocity, self.force)
self.velocity = newVelocity
self.force['mag'] = 0
def __rotate(self):
self.rotCenter = self.rect.center
self.imgAngle += self.rotAngle
self.imgAngle = self.imgAng... | The code updates an object's state by applying force, rotating, and translating it, likely simulating motion or transformation in a system like physics engines or animations. | def update(self):
self.__applyForce()
self.__rotate()
self.__translate() |
def get_all_moves(self, id, piece, current_board):
moves = []
start_id_and_moves = [] # A list of tuples, the id to move, the move itself and the source (src,id,move)
pos = self.find_index(id)
if 'pawn' in piece:
normal_moves = self.pawn_moves(pos, piece, id, current_boar... | The code identifies all valid moves for white pieces on a chessboard by simulating each move, checking if the resulting position leaves the white king in check. If not, the move is added to a list of possible moves for white. | def find_white_possible_moves(self, current_chess_board):
all_moves = []
for id, src in current_chess_board.items():
if 'white' in src:
moves, _ = self.get_all_moves(id, src, current_chess_board)
for move in moves:
current_board = self.fake... |
def get_all_moves(self, id, piece, current_board):
moves = []
start_id_and_moves = [] # A list of tuples, the id to move, the move itself and the source (src,id,move)
pos = self.find_index(id)
if 'pawn' in piece:
normal_moves = self.pawn_moves(pos, piece, id, current_boar... | This function identifies all legal moves for black pieces on a chessboard by iterating through each black piece, generating potential moves, simulating each move, and checking if the resulting position leaves the black king in check. Valid moves are those that do not result in check, and they are collected into a list ... | def find_black_possible_moves(self, current_chess_board):
all_moves = []
for id, src in current_chess_board.items():
if 'black' in src:
moves, _ = self.get_all_moves(id, src, current_chess_board)
for move in moves:
current_board = self.fake... |
def get_files(word):
return gfile.glob(SPEECH_DATA + '/'+word+'/*.wav')
def is_valid_file(file_name):
# load the audio file
audio_tensor = tfio.audio.AudioIOTensor(file_name)
# check the file is long enough
if not is_correct_length(audio_tensor, EXPECTED_SAMPLES):
return False
# convert ... | This function processes a given word's files into training, validation, and test datasets by splitting shuffled valid files according to predefined ratios, then generating samples via process_files() and appending them to global lists, with optional repetition of files. | def process_word(word, label, repeat=1):
# get a list of files names for the word
file_names = [file_name for file_name in tqdm(get_files(word), desc="Checking", leave=False) if is_valid_file(file_name)]
# randomly shuffle the filenames
np.random.shuffle(file_names)
# split the files into train, val... |
def from_user_input():
name = ask_input("Please enter the module name: ")
version = ask_input("Please enter the module version: ")
compatibility = ask_input(
"Please enter the compatibility level [default is 1]: ") or "1"
module = Module(name, version, compatibility)
url = ask_input("Please enter the U... | This code adds a Bazel module to a registry, either from user input or a JSON file. It initializes new modules with metadata, saves configurations, and validates the registry entry using a validation tool. | def main(argv=None):
if argv is None:
argv = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument("--registry", type=str, default=".",
help="Specify the root path of the registry (default: the current working directory).")
parser.add_argument(
"--input", type=str,... |
def error(msg):
eprint(f"{RED}ERROR: {RESET}{msg}")
def eprint(*args, **kwargs):
"""
Print to stderr and flush (just in case).
"""
print(*args, flush=True, file=sys.stderr, **kwargs)
def abort_migration():
info("Abort migration...")
exit(2) | This function checks if a command's exit code matches an expected value. If not, it logs an error with actual and expected codes, prints the stderr output, and aborts the migration process to halt further execution due to a critical failure. | def assertExitCode(exit_code, expected_exit_code, error_message, stderr):
if exit_code != expected_exit_code:
error(f"Command exited with {exit_code}, expected {expected_exit_code}:")
eprint(stderr)
abort_migration() |
def execute_command(args, cwd=None, env=None, shell=False, executable=None):
info("Executing command: " + " ".join(args))
with tempfile.TemporaryFile() as stdout:
with tempfile.TemporaryFile() as stderr:
proc = subprocess.Popen(
args,
executable=executable,
stdout=stdout,
... | The code prepares for a migration by checking the Bazel version (requiring at least 6.0.0), detecting the workspace name from the WORKSPACE file, creating/updating MODULE.bazel and WORKSPACE.bzlmod files with necessary configurations, and aborting if prerequisites are unmet. | def prepare_migration():
"""Preparation work before starting the migration."""
exit_code, stdout, _ = execute_command(["bazel", "--version"])
eprint(stdout.strip())
if exit_code != 0 or not stdout:
warning("Current bazel is not a release version, please make sure you are running at least bazel 6.0.0")
eli... |
def error(msg):
eprint(f"{RED}ERROR: {RESET}{msg}")
def eprint(*args, **kwargs):
"""
Print to stderr and flush (just in case).
"""
print(*args, flush=True, file=sys.stderr, **kwargs)
def abort_migration():
info("Abort migration...")
exit(2)
def print_repo_definition(dep):
"""Print the repository info to... | This function addresses errors when a Bazel module repository is unavailable by checking if it's the main repo, validating its definition, searching the registry for a matching module, and guiding users to add dependencies via `bazel_dep` in MODULE.bazel, module extensions, or WORKSPACE.bzlmod, with manual fallback if ... | def address_unavailable_repo_error(repo, resolved_deps, workspace_name):
error(f"@{repo} is not visible in the Bzlmod build.")
# Check if it's the original main repo name
if repo == workspace_name:
error(
f"Please remove the usages of referring your own repo via `@{repo}//`, targets should be referen... |
def warning(msg):
eprint(f"{YELLOW}WARNING: {RESET}{msg}")
def print_repo_definition(dep):
"""Print the repository info to stdout and return the repository definition."""
# Parse the repository rule class (rule name, and the label for the bzl file where the rule is defined.)
rule_class = dep["original_rule_clas... | The code addresses deprecated `bind` usage in Bazel by warning users to reference targets directly. It searches for existing `bind` definitions in resolved repositories, adds a TODO comment, and prompts the user to migrate the bind statement to `WORKSPACE.bzlmod` if desired. If the bind definition is missing, it warns ... | def address_bind_issue(bind_target, resolved_repos):
warning(
f"A bind target detected: {bind_target}! `bind` is already deprecated, you should reference the actual target directly instead of using //external:<target>.")
name = bind_target.split(":")[1]
bind_def = None
for dep in resolved_repos:
if d... |
def print_expanded_group(name):
print("\n\n+++ {0}\n\n".format(name))
def verify_module_existence(self, module_name, version):
"""Verify the directory exists and the version is recorded in metadata.json."""
if not self.registry.contains(module_name, version):
self.report(BcrValidationResult.FAILED, f"... | The code validates a module's metadata and dependencies by checking existence, source archive URLs, integrity, and configuration files like presubmit YML and .bazel, with optional skips for specific validations. | def validate_module(self, module_name, version, skipped_validations):
print_expanded_group(f"Validating {module_name}@{version}")
self.verify_module_existence(module_name, version)
if "source_repo" not in skipped_validations:
self.verify_source_archive_url_match_github_repo(module_name, version)
i... |
def prepare_migration():
"""Preparation work before starting the migration."""
exit_code, stdout, _ = execute_command(["bazel", "--version"])
eprint(stdout.strip())
if exit_code != 0 or not stdout:
warning("Current bazel is not a release version, please make sure you are running at least bazel 6.0.0")
eli... | The script automates migrating external dependencies from WORKSPACE to Bzlmod in Bazel. It generates required dependencies for specified targets, detects missing ones, and attempts to resolve issues like unavailable repositories or bind statements. Users can choose between `bazel build --nobuild` or `bazel sync`, force... | def main(argv=None):
if argv is None:
argv = sys.argv[1:]
parser = argparse.ArgumentParser(
prog="migrate_to_bzlmod",
description="A helper script for migrating your external dependencies from WORKSPACE to Bzlmod. "
+ "For given targets, it first tries to generate a list of external dependenc... |
def get_parser_args():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser_eval = subparsers.add_parser('eval', help='Evaluate')
parser_eval.add_argument('--dataset', type=str, default="cifar10", nargs="+", help="Dataset(s) to use for the benchmark. Can be the name of a d... | The code defines a main function that parses command-line arguments, checks the 'which' attribute of the base object, and executes either 'main_eval' or 'main_build' based on whether 'which' is set to 'eval' or 'build', respectively. | def main():
parser, base = get_parser_args()
if not hasattr(base, "which"):
parser.print_help()
return
if base.which == "eval":
main_eval(base)
elif base.which == "build":
main_build(base) |
def find_peak(wd_list, idxs, train_loader, val_loader, input_shape, output_shape, lr, epochs, autocast, device, verbose, seed):
best_wd_idx, max_acc = 0, 0
for idx in idxs:
weight_decay = wd_list[idx]
model = train(train_loader, input_shape, output_shape, weight_decay, lr, epochs, autocast, devi... | The function `evaluate` performs few-shot learning evaluation by extracting features from datasets using a model, saving them, and selecting subsets based on `fewshot_k`. It then trains a classifier with hyperparameter tuning (weight decay) on the selected features, evaluates on test data, and returns accuracy metrics ... | def evaluate(model, train_dataloader, dataloader, fewshot_k, batch_size, num_workers, lr, epochs,
model_id, seed, feature_root, device, val_dataloader=None, normalize=True, amp=True, verbose=False):
assert device == 'cuda' # need to use cuda for this else too slow
# first we need to featurize the ... |
def move(self, d, check_only=False):
"""Moves the tiles in the direction specified, or checks if a
move could be made in that direction.
Does not check the legitimacy of move for speed purposes.
Increments the score when two tiles are merged.
Parameters
----------
... | The main task of the code is to handle a player's turn in the game by executing a move in direction `d`, adding a random tile to the board, and checking if the game is over afterward. It assumes the game is not over initially and updates the `game_over` status based on the result of `check_game_over()` after performing... | def turn(self, d):
"""Taking a turn in the game consists of making a move followed by
adding a tile to the board.
Assumes game is not over to start and
checks if the game is over at the end."""
self.move(d)
self.add_random_tile()
self.game_over = self.check_game_... |
def PickBestModel(X_train, y_train,X_test, y_test,rootFolder=''):
MSE = []
Models = []
bestModel = None
linearRegression , linearRegressionMSE = LinearRegressionMultivariable(X_train, y_train,X_test, y_test,rootFolder)
MSE.append(linearRegressionMSE)
Models.append(linearRegression)
DTRegre... | The main task of the code is to preprocess and split movie/credit datasets for regression, scale features, train and select the best model, evaluate performance using MSE, and optionally plot results. It handles data loading, splitting, scaling, model selection, prediction, and visualization, with conditional logic for... | def Run(plotting = False,rootFolder='',train_val_split=True):
datasetpath = 'regression_train_data.csv'
regressiondatasetscaler = 'regressiondataset_scaler'
X_train, y_train = pre.ReadDataset('tmdb_5000_movies_train.csv', 'tmdb_5000_credits_train.csv','vote_average')
if train_val_split:
X_train,... |
def deactivate_this_collection(coll_name):
parent_coll = bpy.data.collections[coll_name]
for obj in collectionIterator(parent_coll):
deactivate_obj(obj)
def show_all_inside_obj(obj_name):
parent_obj = bpy.data.objects[obj_name]
for obj in objectIterator(parent_obj):
activate_obj(obj)
... | The code processes a JSON file to control 3D object configurations in a Blender scene, iterating through frames to render each setup. It loads a Blender file, manages object collections, applies attributes from the JSON to activate specific objects (e.g., blade colors, handle types), sets armature poses, adjusts lighti... | def main():
counter = start_frame
# open blend file
bpy.ops.wm.open_mainfile(filepath=os.path.abspath("./blend/scene.blend"))
# for name in obj_map.all:
# if str(name) in bpy.data.objects:
# pass
# else:
# print(" ########### not found", name)
# bpy.data.ob... |
def deactivate_this_collection(coll_name):
parent_coll = bpy.data.collections[coll_name]
for obj in collectionIterator(parent_coll):
deactivate_obj(obj)
def show_all_inside_obj(obj_name):
parent_obj = bpy.data.objects[obj_name]
for obj in objectIterator(parent_obj):
activate_obj(obj)
... | The script processes a Blender file by removing shape keys from mesh objects and renaming armature bones. It loads JSON data to control object visibility, exports GLB models for each frame, and runs an external script to combine outputs, iterating through specified frames to generate and manage 3D assets. | def main():
counter = 0
# open blend file
bpy.ops.wm.open_mainfile(filepath=os.path.abspath("./blend/scene.blend"))
# iterate through all objects and remove all shape keys
for obj in bpy.data.objects:
if obj.type == 'MESH':
if(obj.data.shape_keys != None and obj.data.shape_keys... |
def get_test_datas(test_data_dir):
test_data_list = []
test_label_list = []
sub_dirs = [x[0] for x in os.walk(test_data_dir)]
is_root_dir = True
for sub_dir in sub_dirs:
if is_root_dir:
is_root_dir = False
continue
dir_name = os.path.basename(sub_dir)
... | The code evaluates a trained neural network model on test data by loading the model checkpoint, running inference, calculating top-1 accuracy (precision) using in_top_k, and printing the precision along with the evaluation time. | def evaluate_test_datas(test_data_dir):
with tf.Graph().as_default():
test_data_list, test_label_list = get_test_datas(test_data_dir)
test_data_input_list, test_label_input_list = data_input(
test_data_list, test_label_list)
logs_train_dir = '/home/lg/tensorflow_project/ASR/datas... |
def createDirs(name):
if not os.path.exists(OUTPUT_PATH + name):
os.makedirs(OUTPUT_PATH + name)
def loadInSongs(name):
songs = []
with open(name) as f:
songs = f.readlines()
return [song.split("-")[0]
.replace(" ", "")
.replace("\t", "")
... | The code processes songs of a specified type by creating directories, loading song data from a text file, and checking each song with the `processSong` function. It counts how many songs meet the criteria and prints the result as "found: X / Y", where X is the count of valid songs and Y is the total number of songs pro... | def runDir(type_of_song):
createDirs(type_of_song)
createDirs("default")
found = 0
songs = loadInSongs(type_of_song + ".txt")
for song in songs:
if processSong(song, type_of_song):
found += 1
print("found: {0} / {1}".format(found, len(songs))) |
def miller_rabin_constants(n: int) -> tuple[int, int]:
"""Compute s and d such that n - 1 = d * 2^s, where d is odd."""
s, d = 0, n - 1
while d % 2 == 0:
s += 1
d //= 2
return s, d
def miller_rabin_test(n: int, s: int, d: int, a: int = 0) -> bool:
"""
Tests if `n` is composite wi... | The function `is_prime_baillie_psw` determines if an integer `n` is prime using the probabilistic Baillie-PSW primality test. It first handles small values (≤3) and even numbers, then applies the Miller-Rabin test with parameters derived from `n`, followed by a Lucas probable prime test. It repeats the Miller-Rabin tes... | def is_prime_baillie_psw(n: int) -> bool:
"""Tests if n is prime using the probabilistic Baillie-PSW primality test."""
# Ensure input requirements
if n <= 3:
return n == 2 or n == 3
if n % 2 == 0:
return False
k = 2
s, d = miller_rabin_constants(n)
return (
miller_... |
def _get_file_encoding_(self, file_path):
first_bytes = min(32, os.path.getsize(file_path))
with open(file_path, 'rb') as f:
raw = f.read(first_bytes)
if raw.startswith(codecs.BOM_UTF8):
return 'utf-8-sig'
else:
return 'utf-8'
def _parse_line_(self, li... | The code parses a WebVTT subtitle file into a list of scenes, each containing start/end timestamps and associated subtitles. It checks file existence, detects encoding, reads lines, processes them to build scenes, merges partial scenes, and handles errors by raising exceptions for missing files or invalid data. | def parse_file(self):
"""Parses WebVTT subtitle file into Scenes with start/end timestamps
and subtitle for that duration.
Args: None
Returns:
A list of scenes parsed from vttfile.
"""
if not os.path.exists(self.vttfile):
raise MissingFileError("... |
def print_board():
print(COLOUR_THEME['BOARD'])
print(' ============================= ')
print('| TIC-TAC-TOE |')
print(' ============================= ')
print('| | | |')
print('| {} | {} | {} |'.format(board[1]['display str'], board[2]['displ... | The main task of the code is to manage a single round of a turn-based game, handling player moves, checking win/tie conditions, updating scores, and resetting the board. It alternates between players, processes each move, and terminates the round upon a win, tie, or reset. | def play_round():
while True:
# clear_screen()
global current_player
print_board()
move = get_move(current_player)
mark_cell(current_player, move)
if check_win(current_player):
# clear_screen()
add_score(current_player)
print_b... |
def erase_text(driver):
webdriver.ActionChains(driver).key_down(Keys.CONTROL).send_keys('a').perform()
webdriver.ActionChains(driver).key_up(Keys.CONTROL).key_down(Keys.BACKSPACE).perform()
webdriver.ActionChains(driver).key_up(Keys.BACKSPACE).perform()
time.sleep(0.01)
def send_text(driver,content):
... | The code processes text using a spell-checking tool (GSpell) by splitting content into variable window sizes, applying corrections via a web driver, and evaluating results against ground truth. It computes metrics like semantic score, WER, and edit distance, then returns these metrics along with the corrected text. | def run_GSpell_aio_period(ground_truth, content, window_size, period_windows, driver, doc_ID):
all_aio_metrics = {}
content = content.replace(" ", " ").replace(" ", " ").replace(",.", ".").replace(".,", ".").replace(", ,", ",").replace("..", ".").replace(". .",".").replace(" .", ".").replace(" ,", ",").... |
def format_authors(authors, with_affiliation=False):
name_ls = []
for author in authors:
name = format_name(author)
if with_affiliation:
affiliation = format_affiliation(author['affiliation'])
if affiliation:
name_ls.append(f"{name} ({affiliation})")
... | The code processes a list of research files to extract and format key metadata, transforming raw data into a structured pandas DataFrame. It cleans fields like authors, affiliations, abstracts, and bibliographies, then compiles them into a DataFrame with defined columns for analysis. | def generate_clean_df(all_files):
cleaned_files = []
for file in tqdm(all_files):
features = [
file['paper_id'],
file['metadata']['title'],
format_authors(file['metadata']['authors']),
format_authors(file['metadata']['authors'],
... |
def sanitizeName(self, name):
names = re.split(r'[`!;:|.<>?~]', name)
for nm in names:
name = re.sub(' +', ' ', nm).strip()
if len(name) >= 5:
break
if len(name) > 25:
name = name[:25]
# print(f'Folder Name: {name}')
return name... | The main task of the code is to download YouTube content (videos) with a specified resolution, organize them into structured output directories based on metadata (title, number of videos), and save them to a user-defined or default path. It handles multiple videos by creating subfolders with sanitized titles or specifi... | def download(self, out_path = None, resolution = 'highest'):
if out_path is not None:
self.output_folder = str(out_path)
self.resolution = resolution
full_out_location = self.output_folder + "/"
if self.total_videos > 1:
full_out_location += self.sanitizeName(self... |
def connect_to_csw(self, url):
"""
Connect to a CSW using configuration options from config.py.
"""
if self.CSW_USER and self.CSW_PASSWORD:
self.csw_i = csw.CatalogueServiceWeb(
url,
username=self.CSW_USER,
password=self.CSW_PAS... | This method retrieves and processes metadata records from a GeoNetwork CSW endpoint specific to the provided institution by connecting to the virtual CSW, fetching records, transforming them, and handling the transformed data. | def records_by_institution(self, inst):
"""
Requests all records for a given institution. Expects a
GeoNetwork virtual CSW named csw-{inst}, where {inst} corresponds
to a key in self.institutions.
"""
url = self.CSW_URL.format(virtual_csw_name=inst)
self.inst = in... |
def connect_to_csw(self, url):
"""
Connect to a CSW using configuration options from config.py.
"""
if self.CSW_USER and self.CSW_PASSWORD:
self.csw_i = csw.CatalogueServiceWeb(
url,
username=self.CSW_USER,
password=self.CSW_PAS... | The method `records_by_csw` fetches and processes records from a Catalog Service for the Web (CSW) by constructing a URL with the provided `csw_name`, connecting to the CSW service, retrieving records, transforming them, and handling the transformed data for further use. | def records_by_csw(self, csw_name):
url = self.CSW_URL.format(virtual_csw_name=csw_name)
self.connect_to_csw(url)
self.get_records()
self.transform_records()
self.handle_transformed_records() |
def connect_to_csw(self, url):
"""
Connect to a CSW using configuration options from config.py.
"""
if self.CSW_USER and self.CSW_PASSWORD:
self.csw_i = csw.CatalogueServiceWeb(
url,
username=self.CSW_USER,
password=self.CSW_PAS... | The code updates a record using a UUID by fetching it from a CSW (Catalog Service for the Web) endpoint, parsing its XML metadata, transforming it with institution-specific data, and converting the result into JSON. It logs the output, handles decoding errors, and processes the transformed record for further use. | def update_one_record(self, uuid):
url = self.CSW_URL.format(virtual_csw_name="publication")
self.connect_to_csw(url)
self.csw_i.getrecordbyid(
id=[uuid],
outputschema="http://www.isotc211.org/2005/gmd"
)
self.records.update(self.csw_i.records)
rec... |
def create_geonetwork_session(self):
"""
Log into GeoNetwork. Used for non-CSW actions, like searching by
category or fetching the owner of a record.
"""
BASE_URL = self.GEONETWORK_BASE+"/srv/eng/"
LOGIN = self.GEONETWORK_BASE+"/j_spring_security_check"
self.gn_s... | This function retrieves metadata records from a GeoNetwork instance by category. It establishes a session, queries metadata using a CSW endpoint, maps owner IDs to institutions, processes results, and triggers further handling of transformed records. It handles Python version differences for URL encoding and logs warni... | def records_by_category(self, category):
if not self.gn_session:
self.create_geonetwork_session()
csw_url = self.CSW_URL.format(virtual_csw_name="publication")
self.connect_to_csw(csw_url)
if sys.version_info.major == 3:
url = self.GEONETWORK_BY_CAT.format(
... |
def connect_to_csw(self, url):
"""
Connect to a CSW using configuration options from config.py.
"""
if self.CSW_USER and self.CSW_PASSWORD:
self.csw_i = csw.CatalogueServiceWeb(
url,
username=self.CSW_USER,
password=self.CSW_PAS... | The code processes a CSV file to map UUIDs to institutions, either using provided 'inst' parameter, CSV fields like 'inst'/'owner', or a predefined map. It then retrieves, transforms, and handles records based on these mappings. | def records_by_csv(self, path_to_csv, inst=None):
with open(path_to_csv, "rU") as f:
reader = csv.DictReader(f)
fns = reader.fieldnames
uuids_and_insts = {}
url = self.CSW_URL.format(virtual_csw_name="publication")
self.connect_to_csw(url)
... |
def connect_to_csw(self, url):
"""
Connect to a CSW using configuration options from config.py.
"""
if self.CSW_USER and self.CSW_PASSWORD:
self.csw_i = csw.CatalogueServiceWeb(
url,
username=self.CSW_USER,
password=self.CSW_PAS... | This method retrieves records for a specified institution by connecting to a GeoNetwork virtual CSW, fetching data, transforming it, and processing the results. It constructs the CSW URL using the institution key, establishes a connection, extracts records, applies transformations, and handles the final transformed dat... | def records_by_institution(self, inst):
"""
Requests all records for a given institution. Expects a
GeoNetwork virtual CSW named csw-{inst}, where {inst} corresponds
to a key in self.institutions.
"""
url = self.CSW_URL.format(virtual_csw_name=inst)
self.inst = in... |
def connect_to_csw(self, url):
"""
Connect to a CSW using configuration options from config.py.
"""
if self.CSW_USER and self.CSW_PASSWORD:
self.csw_i = csw.CatalogueServiceWeb(
url,
username=self.CSW_USER,
password=self.CSW_PAS... | The function `records_by_csw` retrieves and processes records from a CSW (Catalog Service for the Web) by constructing a URL with the provided `csw_name`, connecting to the CSW service, fetching records, transforming them, and handling the transformed data for further use. | def records_by_csw(self, csw_name):
url = self.CSW_URL.format(virtual_csw_name=csw_name)
self.connect_to_csw(url)
self.get_records()
self.transform_records()
self.handle_transformed_records() |
def set_start_and_end(start_point, end_point):
if start_point is not None:
change_point = input("What would you like to change? You can enter 'o' for 'origin', 'd' for 'destination', "
"or 'b' for both: ")
if change_point == 'b':
start_point = get_start()
... | This function determines the shortest route between two points using set_start_and_end and get_route. It prints the route if found, or maintenance alerts if not. It then asks the user if they want to explore other routes, showing landmarks and recursively calling itself to continue the process. | def new_route(start_point=None, end_point=None):
start_point, end_point = set_start_and_end(start_point, end_point)
shortest_route = get_route(start_point, end_point)
if shortest_route:
shortest_route_string = '\n'.join(shortest_route)
print("The shortest route from {0} to {1} is:\n{2}".form... |
def greet():
print("Hi there and welcome to SkyRoute!")
print("We'll help you find the shortest route between the following Vancouver landmarks:\n" + landmark_string)
def new_route(start_point=None, end_point=None):
start_point, end_point = set_start_and_end(start_point, end_point)
shortest_route = get_... | The main task of the code is to execute a sequence of operations for a routing process: it starts by greeting the user, then creates or processes a new route, and finally concludes with a goodbye message. The function orchestrates these steps in order, likely managing user interaction and route configuration in a navig... | def skyroute():
greet()
new_route()
goodbye() |
def get_articles(src_dirs, entities):
# columns: week, text
week_to_text = {}
start_time = datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc)
start_time_week_day = start_time.weekday()
count = 0
for src_dir in src_dirs:
with open(src_dir, mode="r") as reader:
f = js... | The main task of the code is to process articles from specified data sources (NYT or COVID_news), generate a dynamic topic model (DTM) corpus, and save essential components for topic analysis. It filters articles by time ranges, constructs a bag-of-words representation, extracts topic distributions over time using LdaS... | def main(entities, data_source, source_dir, save_path, num_topics, year1, year2):
'''
:param entities: all forms of the same entity. e.g.: ['Bill Clinton', 'bill clinton', 'president clinton']
:param data_source: 'NYT' or 'COVID_news'
:param source_dir: e.g.: 'data/NYT' or 'data/covid_news'/
:para... |
def is_euler_graph(G):
V = vertices(G)
s=V[0]
s.predecessor = None
s.distance = 0
for v in V:
if v !=s:
v.distance = INFINITY
q = myqueue()
q.enqueue(s)
while q:
u = q.dequeue()
count = 0
for v in G[u]:
count = count+1
i... | The code finds an Eulerian circuit in a graph starting from a given node. It checks if the graph is Eulerian; if not, returns 0. It constructs the circuit by iteratively selecting non-bridge edges, removing them, and appending nodes to the path until returning to the start node. | def get_euler_circuit(G,start):
if not is_euler_graph(G):
return 0
path = list()
path.append(start)
sp = v[start]
temp=dict(G)
while True:
bridges=get_bridges(temp)
succes = False
next = None
for p in temp.get(sp):
if (sp,p) not in bridges:
... |
def startupMessage(self):
# create a copy to be able to delete inactive ones
all_users = list(self.storage.allUsers().keys())
for id in all_users:
self.sendTextMessage(id, "Hi! I'm online again!")
def load_unicode_data(self):
try:
csvfile = open('UnicodeData.txt',... | The code initializes a class with storage, message handling, configuration, and emoji data. It sets up a persistence layer, registers shutdown messages, configures retry timeouts, loads emoji data, and defines command keywords for greetings, search, and navigation. | def __init__(self):
self.storage = persistence.Persistence()
self.last_update_id = 0
self.startupMessage()
atexit.register(self.shutdownMessage)
self.server_retry = config.SERVER_RETRY_TIMEOUT
self.emojiChars = self.load_unicode_data()
self.emojiChars.update(se... |
def create_application(self, filepath,vrf=None,new_vrf=None):
app_mapping_path = os.path.join(filepath, os.getenv("APPLICATION_MAPPINGS"))
os.makedirs(app_mapping_path, exist_ok=True)
with open(os.path.join(filepath,os.getenv('BACKUP_APPLICATION_FILE') + '.json')) as app:
data = jso... | This code restores specified resources from a file, handling different resource types (e.g., application, inventory filter) by calling corresponding creation methods. If a VRF is provided, it uses it during restoration; otherwise, it processes resources without VRF. It logs each step and ensures only unprocessed resour... | def restore(self, filepath, modules,vrf,new_vrf):
resources = modules.split(',')
logger.debug('Found Resoureces: '+modules)
# IF VRF is provided
if vrf:
processed=[]
for resource in resources:
logger.info('Restoring Resource ' + resource)
... |
def normalizeData(rawData):
# normalize the raw dataset
dim = rawData.shape[1]
# the rawData has at least 2 raw, 1 for signal 1 for lable
minList = [np.amin(rawData[:,x]) for x in range(0, dim-1)] + [0]
maxList = [np.amax(rawData[:,x])+0.001 for x in range(0, dim-1)] + [1]
# add the [0] and [... | The function performs wavelet-based clustering on input data. It normalizes data, applies a non-decimated wavelet transform (ndWT) at specified scales, thresholds the transformed coefficients, and marks cluster regions. The process uses wavelet parameters (e.g., 'db1', 'bior1.3') and a threshold to identify significant... | def waveletCluster(data,scale,wavelet,threshold):
# the input data can only have one more row represent tags at the end
waveletlen = {'db1':0,'db2':1,'bior1.3':2}
dim = data.shape[1]-1
normData = normalizeData(data)
dataDic = map2ScaleDomain(normData,scale)
dwtResult = ndWT(dataDic,dim,scale,wav... |
def initialize():
problem.U = PriorityQueueLAS()
problem.g = {}
problem.rhs = {}
problem.k = {}
problem.k['m'] = 0
problem.s = {}
problem.s['start'] = problem.getStartState()
problem.s['goal'] = problem.getGoalState()
for state in problem.getStates... | The code implements a pathfinding algorithm (likely D*) to navigate from a start to a goal position in a grid, avoiding obstacles. It dynamically replans when encountering obstacles, updates the path, and prints the final route, path length, and layout details. The main task is to compute and output the shortest path w... | def main():
initialize()
problem.finalPath = []
problem.s['last'] = problem.s['start']
problem.dynamicAction = None
computeShortestPath()
print('The goal position is', problem.getGoalState())
print("The path is: ")
print(problem.s['start'],)
while ... |
def generate_dummy_function():
name = generate_name('func')
return_type = random.choice(['Int', 'String', 'Bool', 'Double', 'Float', 'Void'])
condition = random.choice([True, False])
loop = random.choice([True, False])
operator = random.choice(['+', '-', '*'])
if condition:
i = random... | The code generates Swift file content by creating a protocol, 100 protocol extensions, 10 conforming classes, and 100 enums. It constructs a template with dummy functions, protocols, and types for code generation, likely for testing or scaffolding. | def generate_file_content(class_name):
protocol_name = generate_name('protocol')
function = generate_dummy_function()
protocol = generate_dummy_protocol(protocol_name, function)
content = f'import Foundation\n\n{protocol}\n\n'
for i in range(100):
content += generate_dummy_extension(protoc... |
def error_message(self, msg: str, clean_screen: bool = True):
"""
Displays an error message.
Args:
msg (str): The error message to display.
clean_screen (bool): Whether to clear the screen after displaying the message.
"""
if len(msg.strip()):
... | The main task of the code is to validate and process user prompt requests from a list of dictionaries. It checks for required fields, handles different prompt types (menu, input, data, prompt), retrieves user input or menu selections, and saves the results. It returns True if all items are successfully processed, other... | def request_prompt(self, my_list: list) -> bool:
"""
Processes user prompt requests.
Args:
my_list (list): List containing prompt data.
Returns:
bool: True if prompt was successfully processed, False otherwise.
"""
for data in my_list:
... |
def optical_flow(capture):
# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 100,
qualityLevel = OPTICAL_FLOW_QUALITY,
minDistance = MIN_DISTANCE,
blockSize = BLOCK_SIZE )
# Parameters for lucas kanade optical flow
lk_params = dict( winSize = (15,15),
maxLevel = 2,
... | The main task of the code is to read or generate optical flow data from a video file, process it to extract speed, size, and direction metrics, and return these values. It caches processed data in a pickle file for reuse unless instructed to ignore the file, in which case it regenerates and visualizes the data. | def read_optical_flow_frames(path:str, camera:str, ignore_file=False):
# path is something like "data/scenario1/s1_p1"
# cam is something like "cam1"
vid_filename = path + camera + ".mov"
pickle_filename = path + camera + "_coords.pkl"
# get saved frame data
try:
if ignore_file:
raise FileNotFoundError
fr... |
def calc_frame_size(current_sample_index, frame_size, data_length):
if (current_sample_index + frame_size) > data_length:
frame_size = data_length - current_sample_index
return frame_size
def calc_elevation(aIndex):
if aIndex == 24:
return 48
return 8
def calc_increment(aIndex):
if a... | This code processes an audio file by applying Head-Related Transfer Functions (HRTFs) to simulate 3D spatial audio. It divides the audio into frames, convolves each with left/right HRIRs from a CIPIC dataset, adjusts for interaural time delays (ITD), and writes the transformed audio to a file. The process uses dynamic ... | def convert_audio(file):
# declare variables
convolved = []
result_left = []
result_right = []
increment = 1
current_sample_index = 0
aIndex = 0
eIndex = 8
azimuths = np.array([-80, -65, -55, *range(-45, 50, 5), 55, 65, 80])
elevations = -45
for x in range(0, 49): # elevatio... |
def create_spacial_affinity_kernel(spatial_sigma: float, size: int = 15):
kernel = np.zeros((size, size))
for i in range(size):
for j in range(size):
kernel[i, j] = np.exp(
-0.5 * (distance.euclidean((i, j), (size // 2, size // 2)) ** 2) / (spatial_sigma ** 2))
return k... | The function enhances image exposure by correcting underexposure using a spatial affinity kernel and gamma/lambda parameters. If 'dual' is True, it also corrects overexposure by inverting the image, then fuses under/over-corrected images. The result is clipped to 8-bit unsigned integers for output. | def enhance_image_exposure(im: np.ndarray, gamma: float, lambda_: float, dual: bool = True, sigma: int = 3,
bc: float = 1, bs: float = 1, be: float = 1, eps: float = 1e-3):
# create spacial affinity kernel
kernel = create_spacial_affinity_kernel(sigma)
# correct underexposudness
... |
def _read_pac(pac_path):
"""
Read a PAC file. We detect the compressed PAC format and
automatically decompress the data so we always return uncompressed PAC contents.
"""
with open(pac_path, "rb") as pac_fp:
pac_contents = pac_fp.read()
# Do we need to do anything with the uncompressed ... | The main task of the code is to extract and return a list of files contained within a PAC file by reading its contents, parsing the header to determine structural parameters, and enumerating file entries based on those parameters. | def enumerate_pac(pac_path):
"""
Return a list of files contained within a PAC file.
"""
pac_contents = _read_pac(pac_path)
_, string_size, file_count, entry_size, remaining = _parse_header(pac_contents)
file_list, _ = _enumerate_files(remaining, file_count, string_size, entry_size)
return... |
def _get_out_dir(pac_path):
"""
Get an output directory name based on the PAC file path we are given.
Used as the default output directory.
"""
parent_dir = os.path.dirname(pac_path)
out_dir, _ = os.path.splitext(os.path.basename(pac_path))
return os.path.join(parent_dir, out_dir)
def _read_... | The function `extract_pac` extracts contents from a PAC file into a specified directory, optionally filtering files using a callable `extract_filter`. It reads the PAC file, parses its header, enumerates files, and extracts them to the output directory, creating it if necessary. The `extract_filter` determines which fi... | def extract_pac(pac_path, out_dir=None, extract_filter=None):
"""
Extract the contents of a PAC file, outputting them to a directory.
We allow for extracing only certain files in the PAC via `extract_filter`
which is a callable object that is a suitable filter() function.
Reference: https://github.c... |
def sendString(self, fct, msg):
self.sock.send(msg.encode())
self.dispDebug(fct, 2, "Send '%s' to the server" % msg)
res = self.read_inbuf(fct)
if res != "OK":
self.dispError(fct, "Error: The server does not acknowledge, but answered:\n%s" % res)
self.dispDebug(fct, 3, "Receive acknowledgment from the se... | The function `waitForGame` sends a "WAIT_GAME" command (with optional training parameter), waits for a game name (until "NOT_READY" changes), reads the labyrinth size from the buffer, logs debug info, and returns the game name and buffer data. | def waitForGame(self, fct, training = ""):
if training != "":
self.sendString(fct,"WAIT_GAME %s" % training)
else:
self.sendString(fct, "WAIT_GAME ")
gameName = "NOT_READY"
while gameName == "NOT_READY":
gameName = self.read_inbuf(fct)
self.dispDebug(fct, 1, "Receive Game name=%s" % gameName)
... |
def sendString(self, fct, msg):
self.sock.send(msg.encode())
self.dispDebug(fct, 2, "Send '%s' to the server" % msg)
res = self.read_inbuf(fct)
if res != "OK":
self.dispError(fct, "Error: The server does not acknowledge, but answered:\n%s" % res)
self.dispDebug(fct, 3, "Receive acknowledgment from the se... | The code retrieves game data and determines the starting player. It sends a "GET_GAME_DATA" request, reads the game data, checks the starting player (0 for self, 1 for opponent), and returns both the data and the starting player indicator as a tuple. | def getGameData(self, fct):
self.sendString(fct, "GET_GAME_DATA")
# read game data
data = self.read_inbuf(fct)
self.dispDebug(fct, 2, "Receive game's data:%s" % data)
# read if we begin (0) or if the opponent begins (1)
buffer = self.read_inbuf(fct)
self.dispDebug(fct, 2, "Receive these player who beg... |
def sendString(self, fct, msg):
self.sock.send(msg.encode())
self.dispDebug(fct, 2, "Send '%s' to the server" % msg)
res = self.read_inbuf(fct)
if res != "OK":
self.dispError(fct, "Error: The server does not acknowledge, but answered:\n%s" % res)
self.dispDebug(fct, 3, "Receive acknowledgment from the se... | The main task of the code is to send a "GET_MOVE" command to a remote system, retrieve a move action and its corresponding result code, and return them as a tuple. It communicates via `sendString`, reads responses from the input buffer, logs debug information, converts the result to an integer, and finally returns `(mo... | def getCGSMove(self, fct):
self.sendString(fct, "GET_MOVE")
# read move
move = self.read_inbuf(fct)
self.dispDebug(fct, 1, "Receive that move:%s" % move)
# read the return code
buffer = self.read_inbuf(fct)
self.dispDebug(fct, 2, "Receive that return code:%s" % buffer)
# extract result
result = int... |
def sendString(self, fct, msg):
self.sock.send(msg.encode())
self.dispDebug(fct, 2, "Send '%s' to the server" % msg)
res = self.read_inbuf(fct)
if res != "OK":
self.dispError(fct, "Error: The server does not acknowledge, but answered:\n%s" % res)
self.dispDebug(fct, 3, "Receive acknowledgment from the se... | The code sends a move command to a function, receives and logs a return code and message, then returns the code. | def sendCGSMove(self, fct, move):
self.sendString(fct, "PLAY_MOVE %s" % move)
# read return code
buffer = self.read_inbuf(fct)
self.dispDebug(fct, 2, "Receive that return code:%s" % buffer)
result = int(buffer)
self.dispDebug(fct, 2,"results=%d" % result)
# read msg
buffer = self.read_inbuf(fct)
se... |
def dispDebug(self, fct, level, msg):
if self.debug >= level:
print("\033[35m\u26A0\033[0m [%s] (%s) %s" % (self.playerName, fct, msg), file = sys.stderr)
def sendString(self, fct, msg):
self.sock.send(msg.encode())
self.dispDebug(fct, 2, "Send '%s' to the server" % msg)
res = self.read_inbuf(fct)
if res... | The code's main task is to display game-related data by sending the "DISP_GAME" command to a function, reading the resulting buffer from input, and printing it. It includes debugging logging and handles communication with an external system through function calls. | def printGame(self, fct):
self.dispDebug(fct, 2, "Try to get string to display Game")
self.sendString(fct, "DISP_GAME")
buffer = self.read_inbuf(fct)
print(buffer) |
def dispDebug(self, fct, level, msg):
if self.debug >= level:
print("\033[35m\u26A0\033[0m [%s] (%s) %s" % (self.playerName, fct, msg), file = sys.stderr)
def dispError(self, fct, msg):
print("\033[5m\033[31m\u2327\033[2m [%s] (%s)\033[0m %s" % (self.playerName, fct, msg))
sys.exit(1)
def sendString(self, fct,... | The main task of the code is to validate a comment's length (max 100 characters) and send it if valid. It logs a debug message, checks the length, displays an error for exceeding limits, and uses `sendString` to transmit the formatted comment with "SEND_COMMENT" prefix if valid. | def sendCGSComment(self, fct, comment):
self.dispDebug(fct, 2, "Try to send a comment")
if len(comment) > 100:
self.dispError(fct, "The Comment is more than 100 characters.")
self.sendString(fct, "SEND_COMMENT %s" % comment) |
def get_notion_database(self, db_id: str, db_filter: dict):
endpoint = 'databases/' + db_id + '/query'
options = {
'data': json.dumps({'filter': db_filter})
}
return self.notion_request(endpoint=endpoint, request_type='post', options=options)
def create_properties(self, fie... | This function retrieves project data from Notion databases, structuring epics, stories, and tasks into a hierarchical dictionary. It skips specified databases, extracts metadata, and nests sub-projects with their associated stories and sub-tasks, including details like names, statuses, descriptions, and comments. | def get_projects(self):
projects = []
for database in self.databases:
if "skip" in database and database["skip"]:
continue
print(f"Getting notion database {database['name']}")
notion_database = self.get_notion_database(
db_id=database... |
def is_url(url):
try:
r = urlparse(url)
return all([r.scheme, r.netloc])
except BaseException:
return False
def format_bookmark_data(url, edit):
metadata = obtain_metadata(url)
bookmark_date = datetime.now().isoformat('T', 'seconds')
author = metadata.get('byline')
title ... | The main task of the code is to add a bookmark by validating a URL, formatting it with specified parameters, and writing it to an output. It returns an error code if the URL is invalid or if exceptions occur during processing. | def add(url, format, edit, output):
debug(f'add({url}, {edit}) called.')
if not is_url(url):
error(f'Invalid URL: {url}')
return 10
try:
bookmark_data = format_bookmark_data(url, edit)
bookmark = format_bookmark(bookmark_data, format)
write_bookmark(output, bookmark)... |
def configure_logging(verbose):
if verbose:
level = DEBUG
else:
level = INFO
basicConfig(
format='[%(asctime)s][%(levelname)s] %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
level=level,
)
def filename(type='html'):
return f'{datetime.now():%Y%m%dT%H%M%S}.{type}'... | The code defines a function `app_run` that processes command-line arguments for bookmarking a URL. It handles options for output format (HTML or Markdown), edit mode, and output location (defaulting to a journal directory). After parsing arguments, it configures logging, determines the output file/path, and calls an `a... | def app_run():
DEFAULT_JOURNAL_DIR = '~/Documents/notebook/bookmarks'
parser = ArgumentParser(prog=basename(argv[0]))
parser.add_argument('-v', '--verbose', default=False, action='store_true')
# parser.add_argument('-h', '--help', default=False, action='store_true')
parser.add_argument(
'-... |
def __merge_with_root_list(
self,
node: Node
) -> None:
"""
Merge a node with the doubly linked root list
------------------
Params:
node (Node): The node to merge with the root list
"""
node._parent = None
... | This method removes the maximum node from a max-heap in O(log(n)) time. It detaches the max node, merges its children into the root list, updates the root list, and consolidates the heap to maintain structure. If the heap becomes empty, it sets internal pointers to None. The method returns the removed max node or None ... | def pop(self) -> Union[Node, None]:
"""
Pop the max node from the heap in O(log(n))
------------------
Returns:
The max node in the heap OR None if heap is empty
"""
max_node = self._max_node
if max_node is None:
return
... |
def __chain_based_complete_one_component(self) -> Cluster:
"""
This function is used to compute the clusters
using chain based algorithm when the similarity matrix
has one component and is complete
------------------
Returns:
Cluster: The fi... | This function computes clusters using a chain-based algorithm. It returns a single Cluster if the similarity matrix has one component, or a list of Clusters if there are multiple components. The method selects between complete and uncomplete variants based on the 'complete' flag when handling one component cases. | def chain_based(self) -> Union[Cluster, List[Cluster]]:
"""
This function is used to compute the clusters
using chain based algorithm
------------------
Returns:
Cluster: if the similarity matrix has one component
List[Cluster]: if the similarity matrix... |
def lightKingIsChecked(self):
return self.darkAttackLayout[self.lightKing.getCoords()[0]][self.lightKing.getCoords()[1]] == 2
def darkKingIsChecked(self):
return self.lightAttackLayout[self.darkKing.getCoords()[0]][self.darkKing.getCoords()[1]] == 2
def piecesCanMove(self):
for i in range(0, 8):... | The code checks if either the light or dark king is in check and determines if checkmate occurs by evaluating whether any pieces can move to escape. It returns False if neither king is checked, otherwise returns the result of `piecesCanMove()` to assess if checkmate is achieved. | def isCheckmate(self):
if (not self.lightKingIsChecked()) and (not self.darkKingIsChecked()):
return False
return self.piecesCanMove() |
def lightKingIsChecked(self):
return self.darkAttackLayout[self.lightKing.getCoords()[0]][self.lightKing.getCoords()[1]] == 2
def darkKingIsChecked(self):
return self.lightAttackLayout[self.darkKing.getCoords()[0]][self.darkKing.getCoords()[1]] == 2
def piecesCanMove(self):
for i in range(0, 8):... | The main task of the code is to determine if a stalemate condition exists in a chess game. It checks if either king is in check (returning False if so) and otherwise evaluates whether any pieces can move, returning the result of `piecesCanMove()` to confirm stalemate status. | def isStalemate(self):
if self.lightKingIsChecked() is True or self.darkKingIsChecked() is True:
return False
return self.piecesCanMove() |
def read(self, vaddr=0):
# read dut addr
# return read data or None
#reg_data = random.randint(0, 2**32-1)
if not self.conn:
return None
reg_data = self.mcom.read(vaddr)
if reg_data is not None:
logger.info('read: {:08x} = {:08x}'.format(vaddr, reg... | This function handles the return/lose focus event of a register address input field. It reads the hexadecimal address from a QLineEdit, converts it to an integer, fetches the corresponding register value, and updates both the QLineEdit (for register data) and QTableWidget (for bit representation) with the retrieved val... | def slot_addr_retn(self):
# when reg_addr edit done: Return or Lose Focus
# do: [read] and update <QLineEdit>-reg and <QTableWidget>-bits
reg_addr = self.reg_addr.text()
logger.info('slot_addr_retn: addr = {}'.format(reg_addr))
reg_addr = glib.str2int(reg_addr, 16)
read_v... |
def update_reg(self, vsel=None, vval=None):
# search reg with @vsel, and set reg with @vval
# update <QTableWidget>-{regs, bits}
(mod_name, reg_name) = self.mxml.get_modreg(vsel)
if (mod_name is not None) and (reg_name is not None):
if mod_name != self.omod.name:
... | This function handles register address/data input, converts them to integers, formats as hex, and performs write/read operations. It updates UI elements and manages connection states, either updating the register or closing UART if write fails. | def slot_data_retn(self):
# when reg_addr edit done: Return or Lose Focus
# do: [write] [read] and update <QLineEdit>-reg and <QTableWidget>-bits
reg_addr = self.reg_addr.text()
reg_data = self.reg_data.text()
logger.info('slot_data_retn: addr = {}, data = {}'.format(reg_addr, re... |
def prepare_arms(self):
RIGHT_ARM = 0
LEFT_ARM = 1
EEF_LENGTH = 130 # [mm]
FOOD_SIZE = 70 # [mm]
CLOSE_SIZE = 60 # [mm]
GRASP_TORQUE = 3.0 # [N]
GRASP_THRESH = 2.0 # [N]
self.home_position()
# EndeffectorConfig
e... | This code initializes ROS action clients for motion control, waypoints, and end-effectors (both left and right), sets up publishers for camera, indicator, and cancel plan topics, and calls service proxies for end-effector configuration. It prepares robot arms, adjusts camera and indicator settings, waits for service av... | def __init__(self):
self.motion_client = actionlib.SimpleActionClient('/foodly/dev_api/move/motion', MotionAction)
self.motion_client.wait_for_server()
self.way_client = [ actionlib.SimpleActionClient('/foodly/dev_api/move/waypoints/right', WaypointsAction), \
ac... |
def mask_radial_MM(r=3.5):
mask = np.zeros((28, 28))
for i in range(28):
for j in range(28):
mask[i, j] = distance(i, j, r=r)
return mask
def addingPattern(r, mask):
fftshift_img = fftshift(r)
fftshift_result = fftshift_img * mask
result = ifftshift(fftshift_result)
retu... | The code generates three masked versions of input data X using different masks: high-frequency data with a radial mask inverted (1 - real part), low-frequency data with the radial mask's real part, and random data with a 50% random mask. Each version is created by applying the `addingPattern` function individually to X... | def generateData(X):
radioMask = mask_radial_MM(r=3.5)
highFreqData = np.zeros(X.shape, dtype=np.float32)
for i in range(X.shape[0]):
highFreqData[i] = addingPattern(X[i].numpy().astype(
np.float32), 1-np.real(radioMask))
lowFreqData = np.zeros(X.shape, dtype=np.float32)
for i i... |
def _is_legal_move(board, row, col, player):
'''
board (list): an object created by board_create()
row (int): the row coordinate of the proposed move.
col (int): the column coordinate of the proposed move.
player (int): HUMAN or COMPUTER
Return True if a given move is legal.
'''
if boar... | The main task of the code is to process a game turn by placing the human player's piece at specified coordinates, flipping opponent's pieces if the move is legal, then allowing the computer player to make a move and flip human pieces in turn. The function returns True if the human's initial move was legal, otherwise Fa... | def game_turn(board, row, col):
'''
board (list): an object returned by board_create()
row (int): The row coordinate where the piece should be placed.
col (int): The column coordinate where the piece should be placed.
Place the human player's piece on the board at the coordinates
row, col.
... |
def future_position(self, incoming_node: Node, course: list):
state = self.get_state(incoming_node, course)
inc_index = course.index(incoming_node)
i = inc_index
pre1 = [node for node in course if node.time< incoming_node.time]
pre = [node for node in pre1 if node.type != Type.in... | This function calculates the source and destination indices, travel time, and distance for a specific path scenario. It processes incoming vectors, determines direction changes, computes delays based on node positions, and aggregates time/distance using speed and stop constants. The result includes start/end indices, s... | def easy_case_inverse_direction(self, vec: Vector, course: list):
pos = self.future_position(vec.incoming, course)
inc_node, src_node, dst_node = vec.incoming, vec.src, vec.dst
inc_index = course.index(inc_node)
src, dst, i, src_delay, dst_delay = src_node.floor, dst_node.floor, inc_inde... |
def future_position(self, incoming_node: Node, course: list):
state = self.get_state(incoming_node, course)
inc_index = course.index(incoming_node)
i = inc_index
pre1 = [node for node in course if node.time< incoming_node.time]
pre = [node for node in pre1 if node.type != Type.in... | This function calculates the time and distance for an elevator's movement in a specific scenario, considering delays caused by direction changes and floor transitions. It determines source and destination indices, computes delays based on turning points in the course, and combines these with speed and stop constants to... | def hard_case_missed_floor(self, vec: Vector, course: list):
pos = self.future_position(vec.incoming, course)
inc_node, src_node, dst_node = vec.incoming, vec.src, vec.dst
inc_index = course.index(inc_node)
src, dst, i, src_delay, dst_delay = src_node.floor, dst_node.floor, inc_index, 0,... |
def case_check(self, vec: Vector, course: list):
elev_dir = self.get_state(vec.incoming, course)
call_dir = copysign(1.0, vec.src.floor - vec.dst.floor)
elev_pos = self.future_position(vec.incoming, course)
if len(course) ==1:
return 0
# Can we pickup the call? ... | This function determines the insertion index parameters for a vector in a course by evaluating different movement scenarios. It uses case checks to select between five cases, each calculating a tuple with time and distance values based on direction, floor differences, and stopping constants. The result is a tuple (0, 1... | def get_insertion_index(self, vec: Vector, course: list):
case = self.case_check(vec, course)
if case == 0:
dist = (abs(vec.dst.floor-vec.src.floor))*self.speed_const.get('tpf')+self.stop_const.get('full_break')
tup = (0, 1, vec.incoming.time, dist)
elif case == 1:
... |
def create_new_background(self):
if self._creating_background:
# discard calls triggered from within this function
return
self._creating_background = True
self.set_cross_hair_visible(False)
self.ax.figure.canvas.draw()
self.background = self.ax.figure.canv... | This code handles mouse click events to update a plot by managing crosshairs, rounding coordinates, tracking user clicks, and rendering Bezier curves. It checks if the click is inside the axes, processes coordinates, stores points, and redraws the figure with updated elements like scatter points, lines, and paths. The ... | def on_mouse_click(self, event):
if self.background is None:
self.create_new_background()
if not event.inaxes:
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.restore_region(self.background)
self.d... |
def prune_record(self, log):
print(log)
self.logger.write(log+"\n")
def weight_prune(
self,
prune_ratio,
random_prune=False,
):
model = self.model.cpu()
total_weight = 0
for name, module in model.named_modules():
if ( isin... | The main task of the code is to initialize pruning by setting a specified ratio, logging the pruning ratio, applying weight pruning based on the ratio, and subsequently checking the parameter count. This function prepares the model for pruning by configuring the pruning ratio, recording the action, executing the prunin... | def init_prune(self):
ratio = self.args.weight_init_prune_ratio
log = f"Init prune ratio {ratio:.2f}"
self.prune_record(log)
self.weight_prune(ratio)
self.check_param_num() |
def HamCycle(self):
### SINCE adjMat IS A COMPLETE GRAPH, THIS WILL SIMPLY GENERATE ALL
### POSSIBLE HAMILTONIAN PATHS
perms = []
self.allPossiblePaths(list(range(1, self.h+self.w, 1)), self.w + self.h - 1, perms)
return perms
def Search(self):
## BUILD THE AGENT-TASK G... | The code's main task is to find an optimal task allocation by evaluating Hamiltonian cycles (paths) to minimize the makespan. It iterates through all generated paths, calculates each path's makespan, identifies the minimum value, and constructs a schedule using the optimal path. The result is printed, showing the appro... | def Schedule(self):
id = 0
self.paths = self.HamCycle()
self.Search()
for i in range(len(self.paths)):
self.pattern = self.paths[i]
span = self.getMakespan(self.pattern)
if span < self.spanMin:
self.spanMin = span
id =... |
def forward_propagation(X, parameters, activation_func):
num_layers = int(len(parameters) / 2)
cache = dict()
cache['A0'] = X
for l in range(1, num_layers):
W = parameters['W' + str(l)]
b = parameters['b' + str(l)]
Z = linear_forward(cache['A' + str(l - 1)], W, b)
cache[... | This function trains a neural network using mini-batch gradient descent for a specified selection method. It shuffles data, processes batches, performs forward/backward propagation, updates parameters, and tracks accuracy/loss every 100 epochs. Regularization is applied, and results are logged for a given cross-validat... | def train_nn(X, Y, parameters, method, activation_func, fold_id):
logger.info('Training neural network for %s selection method...', method)
tqdm_iter = tqdm(range(hp.num_epochs))
costs = []
for i in tqdm_iter:
num_batches = X.shape[1] // hp.batch_size
idxs = np.arange(X.shape[1])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.