dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_uncert_rank(data_old, data_GT, last_prop, coff):
res = []
for idx, sample in enumerate(data_old):
vid, duration, _, _, old_ap = sample
assert vid == last_prop[idx]["vid"]
assert vid == data_GT[idx][0]
vlen = last_prop[idx]['v_len']
pos_idx =old_ap['pos_idx']
... | The main task of the code is to refine annotations in a dataset by updating proposal intervals (APs) based on uncertainty scores. It loads existing data, calculates uncertainty ranks, iteratively appends new APs using uncertainty frames, updates annotations, computes IOU metrics for evaluation, and saves the refined da... | def main(old_path, new_path, prop_path, coff):
data_old = load_json(old_path)
data_GT = load_json(GT_PATH)
last_prop = load_pickle(prop_path)
if len(data_old[0]) == 4:
for i in range(len(data_old)):
data_old[i].append({'pos_idx':[], 'neg_idx': []})
IOU = [[], []]
uncert_ran... |
def get_classes(pattern_path, results_dir):
"""
Reads the classes of a pattern file and initiates the analysis of it.
:param pattern_path: the path of the pattern
:param results_dir: the result directory to store results
:return:
"""
file = open(pattern_path, 'r')
pattern = pattern_path.... | The main task of the code is to process a list of pattern files by extracting classes from each, storing results in a specified directory. It processes 10,000 files at a time, logging progress and periodically dumping results to disk using helper functions. Final results and skipped items are dumped after processing al... | def do_work(file_list, results_dir):
"""
Initiates the processing of all patterns in the provided file_list.
:param file_list: A list of pattern files to process
:param results_dir: he directory to store the results
:return:
"""
file_counter = 0
for file in file_list:
get_classes... |
def handle_delete(event_unique_id, message_json, message_dict):
insert_delete(event_unique_id, message_json, message_dict)
def insert_raw_event(event_unique_id, message_json, message_dict):
data_to_insert = {
'insert_id': event_unique_id,
'fxa_id': transform('uid', message_dict),
... | The code processes incoming Pub/Sub messages by parsing JSON payloads, tracking statistics (e.g., message counts, errors), generating unique event IDs, and routing events to specific handlers based on their type (e.g., 'delete', 'login', 'device:create'). It logs details, handles parsing errors, updates metrics, and ac... | def pubsub_callback(message):
global STATS, LAST_STATS
STATS['total_messages'] = 1 + STATS.get('total_messages', 0)
logging.debug('Received message: {}'.format(message))
message_payload = message.data.decode('utf-8')
# generate a unique id for this event
event_unique_id = str(uuid.uuid4())
... |
def scroll_to(driver, element):
driver.execute_script(
'arguments[0].scrollIntoView({block: "center"})', element)
def fill_out_form(driver, timeout, customer):
logging.info('Filling out checkout form...')
driver.find_element(By.ID, 'billingName1').send_keys(
customer['billing']['first-name']... | The code automates a guest checkout process by locating and clicking a checkout button, filling out a form with customer data, handling potential timeouts, scrolling to submit, checking for errors, skipping address validation if needed, and selecting shipping speed. It ensures seamless guest checkout flow with error ha... | def checkout_guest(driver, timeout, customer, auto_submit=False):
proceeded_to_form = False
logging.info('Checking out as guest...')
while not proceeded_to_form:
try:
WebDriverWait(driver, timeout).until(
EC.element_to_be_clickable((By.ID, const.CHECKOUT_AS_GUEST_ID)))
... |
def get_playback_status( self ):
return self.session_bus_property_interface.Get( self.session_bus_name , "PlaybackStatus" )
def get_volume( self ):
return self.session_bus_property_interface.Get( self.session_bus_name , "Volume" )
def get_position( self ):
return self.session_bus_property_interface.Get( self.sess... | The main task of the code is to aggregate and return common playback status details as a dictionary, including playback status, volume level, current playback position, and metadata, by calling respective methods on the object. | def get_common_status( self ):
return {
"status": self.get_playback_status().lower() ,
"volume": self.get_volume() ,
"current_time": self.get_position() ,
"metadata": self.get_metadata()
} |
def search_reddit(query: str, sort="relevance", syntax="lucene", time_filter="all", limit: int | None = None):
"""https://praw.readthedocs.io/en/latest/code_overview/models/subreddit.html#praw.models.Subreddit.search"""
rs = list(praw.Reddit().subreddit("all").search(query=query, sort=sort, syntax=syntax, time_... | The function aggregates and processes data from Reddit, HackerNews, and HuggingFace based on a query, combines results, sorts them by relevance, retrieves arXiv paper metadata and content, and returns structured dataframes for analysis. | def summarize(query, time_filter="month", days=30, limit=300):
print("search_reddit...")
reddit_document_df = search_reddit(f"selftext:{query}", sort="top", time_filter=time_filter, limit=limit)
print("search_reddit...done: ", len(reddit_document_df))
print("search_hackernews...")
hackernews_documen... |
def summarize(query, time_filter="month", days=30, limit=300):
print("search_reddit...")
reddit_document_df = search_reddit(f"selftext:{query}", sort="top", time_filter=time_filter, limit=limit)
print("search_reddit...done: ", len(reddit_document_df))
print("search_hackernews...")
hackernews_documen... | The code's main task is to fetch recent arXiv.org papers, filter them by popularity and date, translate summaries using DeepL with caching, and post results to Slack, Twitter (via v1/v2 APIs), and Bluesky, leveraging environment variables for API credentials and configuration. | def main():
# settings
query = "arxiv.org"
summarize_time_filter = "month" # or "week"
summarize_days = 30 # should be 30 if "month"
summarize_limit = 500
filter_days = 30
deepl_target_lang = "JA"
deepl_expire_days = 90
notify_top_n = int(os.getenv("NOTIFY_TOP_N", 10))
# prepa... |
def gap():
print(f"-"*47)
def inputFromFile(file):
try:
with open(file) as f:
if(not getDim(f.readline)):
errorPrint("File corrupted. Dimension must be integer from 1 to 20")
return [matrix,epsilon,Fa... | The function `inputInfo()` prompts the user to choose between reading input from a file or the command line. It validates the input (yes/no) and repeatedly asks until a valid choice is made. If "yes", it requests a filename and reads data from it; if "no", it reads from the command line. It checks if the input retrieva... | def inputInfo():
gap()
while(True):
print("Do you want to read input data from file? yes/no")
answ=input()
if(answ=="yes"):
print("Please enter your file name")
answ = inputFromFile(input())
... |
def create_masks(input_tokens, target_tokens):
padding_mask = create_padding_mask(input_tokens)
look_ahead_mask = create_look_ahead_mask(tf.shape(target_tokens)[1])
target_padding_mask = create_padding_mask(target_tokens)
look_ahead_mask = tf.minimum(target_padding_mask, look_ahead_mask)
return padding_ma... | This function constructs a transformer model for sequence-to-sequence tasks, using encoder-decoder architecture with multi-head attention, feed-forward networks, and mask handling. It takes input/target token sequences, processes them through encoder/decoder layers, and outputs predicted target sequences along with att... | def create_transformer(num_layers, num_heads, embedding_dim, ff_dim,
input_vocab_size, target_vocab_size,
dropout_rate=0.1, max_tokens=128):
input_tokens = keras.Input(shape=(None,), dtype=tf.int64, name='input_tokens')
target_tokens = keras.Input(shape=(None,), dtype=t... |
def train_step(transformer, optimizer, inputs, targets):
with tf.GradientTape() as tape:
preds, _, targets_real = make_predictions(transformer, inputs, targets, training=True)
loss = transformer_loss(targets_real, preds)
gradients = tape.gradient(loss, transformer.trainable_variables)
optimizer.apply_gra... | The code trains a transformer model for sequence-to-sequence tasks, using both training and test datasets during each batch. It initializes an Adam optimizer, tracks metrics (loss, accuracy, BLEU), and performs training/test steps per batch. The model's epochs are dynamically calculated based on dataset size. After eac... | def train(transformer_args, model_name, train_dataset, test_dataset, input_vectorizer, target_vectorizer, target_token_from_index, input_vocab_size, target_vocab_size):
epochs = max(5, int(np.log(len(train_dataset)) / np.log(0.85)) + 61)
optimizer = optimizers.Adam(learning_rate=0.0001, beta_1=0.9, beta_2=0.98, e... |
def score_holes(board, board_highest):
empty = []
holes = []
depth_score = 0
overhangs = []
for x in range(10):
for y in range(19, board_highest[x]-1, -1):
if board[y][x] == 0:
empty.append([x,y])
for cell in empty:
depth_score += cell[1] - board_highest[cell[0]]
if closed_hole(board, board_highest... | The code computes a heuristic score for a Tetris-like board state using weighted evaluation of features: holes, overhangs, jaggedness, slope, wells, and line clears. It combines these factors with specified weights to assess board stability and efficiency, prioritizing metrics like hole depth, placement height, and lin... | def score(board, board_highest, lines_cleared, placement_height, weights = [0.745, 0.523, 0.183, 0.252, 0.200, 0.200, 0.114, 0.204, 0.035, 0.438, 0.377, 0.061, 1]):
if len(weights) == 1:
return 0
holes, overhangs, hole_depth = score_holes(board, board_highest)
jagged, slope = score_bumps(board_highest)
if lines... |
def reachable(pos, piece, board, speed):
if not valid_position([5,0], piece['rel'], board) or not valid_position([5,0], piece_data[piece['default']]['rel'], board):
return False
delta_x = pos[0] - 5
delta_y = pos[1]
if delta_x != 0:
direction = delta_x / abs(delta_x)
else:
return True
curr_x = 5
curr_y = 0... | The function `find_path` recursively determines a valid movement or rotation path for a Tetris-like piece on a board, considering speed constraints, spin/tuck flags, and board boundaries. It checks downward, lateral, and rotational moves, returning a path with positions and actions if valid, otherwise `False.` | def find_path(pos, piece, board, board_highest, speed, spin = False, tuck = False):
if pos[1] <= 0:
return False
breakout_height = min(list(dict.fromkeys([board_highest[el[0] + pos[0]] for i, el in enumerate(piece['rel'])])))
if pos[1] < breakout_height:
if reachable(pos, piece, board, speed):
return [[pos, T... |
def get_column_heights(board):
heights = [20,20,20,20,20,20,20,20,20,20]
for x in range(10):
for y in range(19, -1, -1):
if board[y][x] == 1:
heights[x] = y
return heights
def placeable(pos, rel, board):
if valid_position(pos, rel, board) and not valid_position([pos[0], pos[1]+1], rel, board):
return Tru... | The function generates valid placements for a Tetris-like piece on a board, evaluating possible positions, rotations, and paths. It calculates scores using specified weights, checks placeability, and returns a list of placements with board states, positions, paths, and scores. If no valid placements exist, it defaults ... | def generate_placements(piece_name, board, speed, weights = [0.745, 0.523, 0.183, 0.252, 0.200, 0.200, 0.114, 0.204, 0.035, 0.438, 0.377, 0.061, 1]):
piece_ids = [el for el in piece_data.keys() if el[0] == piece_name[0]]
placements = []
board_highest = get_column_heights(board)
for piece_id in piece_ids:
piece =... |
def custom_bucket(input_tensor, bucket_size):
b_h, t, d_h = input_tensor.shape # (batch_size * heads, seq_length, dim)
num_samples = len(bucket_size) # number of samples in the batch
num_heads = b_h // num_samples # number of heads
all_buckets = [] # This will have a length of batch_size * num_head... | This code processes input tensors q and k by bucketing them, summing values within each bucket, concatenating the results, applying a linear transformation, and returning top-k selected outputs via differentiable_topk or gumbel_sinkhorn. The main task is to compute attention-like outputs with bucketed summation and sel... | def forward(self, q, k, bucket_size, topk=1):
bh, = q.size(0)
b = bh // self.heads
# Using custom bucket function
b_q_buckets = custom_bucket(q, bucket_size)
b_k_buckets = custom_bucket(k, bucket_size)
# Initialize lists to store the summed tensors for each sample in th... |
def custom_bucket(input_tensor, bucket_size):
b_h, t, d_h = input_tensor.shape # (batch_size * heads, seq_length, dim)
num_samples = len(bucket_size) # number of samples in the batch
num_heads = b_h // num_samples # number of heads
all_buckets = [] # This will have a length of batch_size * num_head... | The code computes attention scores between query and key tensors by grouping them into buckets, summing values within each bucket, and calculating pairwise interactions via einsum. It stores these interactions in a tensor `all_R`, then returns either a top-k selection of attention matrices or applies Gumbel-Sinkhorn op... | def forward(self, q, k, bucket_size, topk=1):
dim = self.dim
b_h, t, d_h = q.shape # b_h = batch_size * heads
bucket_len = len(bucket_size[0])
# Initialize a tensor to store all the R matrices for each combined head and batch
all_R = torch.zeros(b_h, bucket_len, bucket_len, dev... |
def get_cell(self, cell_x, cell_y):
return self.cells[cell_y - 1][cell_x - 1]
def set_cell(self, cell_x, cell_y, player):
self.cells[cell_y - 1][cell_x - 1] = player
def check_win(self):
for four in FOURS:
cell_dx = four[3][0]
cell_dy = max(four[0][1], four[3][1])
for cell_x in range(1, CE... | This function attempts to place a player's symbol in a specified column of a grid game (like Connect Four). It validates the move's coordinates and checks if the column is not full. If valid, it places the symbol in the lowest available row of that column, updates win/game-over status, and marks the board as changed. I... | def play_cell(self, cell_x, cell_y, player):
if (cell_x < 1 or CELL_X < cell_x or
cell_y < 1 or CELL_Y < cell_y or
self.get_cell(cell_x, CELL_Y) != '-'):
return False
for test_y in range(1, CELL_Y + 1):
if self.get_cell(cell_x, test_y) == '-':
self.set_cell(cell_x, test_y, player... |
def draw_lines(self, display):
for cell_x in range(0, CELL_X + 1):
pygame.draw.line(display, L_COLOR,
to_disp(cell_x + 0.5, 1 - 0.5),
to_disp(cell_x + 0.5, CELL_Y + 0.5), L_WIDTH)
for cell_y in range(0, CELL_Y + 1):
pygame.draw.line(display, L_COLOR,
to_disp(1 - 0.5, ... | The code renders the game's visual elements on the display by drawing grid lines, individual cells, highlights, and conditional game state messages (initialization or game over). It updates the `is_dirty` flag to False, indicating the display is now up-to-date and no further rendering is needed. | def draw(self, display):
self.draw_lines(display)
for cell_x in range(1, CELL_X + 1):
for cell_y in range(1, CELL_Y + 1):
self.draw_cell(display, cell_x, cell_y)
self.draw_highlight(display)
if self.game_init:
self.draw_init(display)
if self.game_over:
self.draw_over(displa... |
def printBoard(board, x, number):
print("-----------------" + 4 * x * "-")
print(f"| {spaces(board, x, 0)} | {spaces(board, x, 1)} | {spaces(board, x, 2)} | {spaces(board, x, 3)} |")
print("-----------------" + 4 * x * "-")
print(f"| {spaces(board, x, 4)} | {spaces(board, x, 5)} | {spaces(board, x, 6)} ... | The code initializes a 16-cell game board with two random "2" tiles, prints the board and its alternate representation, then starts a game loop. The main task is to set up a game state for a tile-matching puzzle, likely similar to 2048, by placing initial tiles and initiating gameplay. | def main():
number = 0
board = ["-"]*16
board[randint(0, 8)] = "2"
board[randint(8, 15)] = "2"
printBoard(board, alternateBoard(board), number)
gameLoop(board, number) |
def get_cell(self, cell_x, cell_y):
return self.cells[cell_y - 1][cell_x - 1]
def set_cell(self, cell_x, cell_y, player):
self.cells[cell_y - 1][cell_x - 1] = player
def check_win(self):
for triple in TRIPLES:
(cell1, cell2, cell3) = self.get_cells(triple)
if cell1 == cell2 == cell3 != '-':
... | The main task of the code is to handle a player's move in a game by validating the cell coordinates, placing the player's symbol if valid, checking for a win or game over condition, updating game state variables, and marking the board as dirty for rendering. It returns True on successful move, False otherwise. | def play_cell(self, cell_x, cell_y, player):
if (cell_x < 1 or CELL_X < cell_x or
cell_y < 1 or CELL_Y < cell_y or
self.get_cell(cell_x, cell_y) != '-'):
return False
self.set_cell(cell_x, cell_y, player)
self.win_data = self.check_win()
self.game_over = True if self.win_data else ... |
def printBoard(board, x, number):
print("-----------------" + 4 * x * "-")
print(f"| {spaces(board, x, 0)} | {spaces(board, x, 1)} | {spaces(board, x, 2)} | {spaces(board, x, 3)} |")
print("-----------------" + 4 * x * "-")
print(f"| {spaces(board, x, 4)} | {spaces(board, x, 5)} | {spaces(board, x, 6)} ... | The code initializes a 16-cell game board with two randomly placed "2"s, prints the board and its alternate version, then starts a game loop to handle gameplay mechanics like tile movement and merging, likely for a number-sliding puzzle game like 2048. | def main():
number = 0
board = ["-"]*16
board[randint(0, 8)] = "2"
board[randint(8, 15)] = "2"
printBoard(board, alternateBoard(board), number)
gameLoop(board, number) |
def to_cell(disp_x, disp_y):
cell_x = to_cell_x(disp_x)
cell_y = to_cell_y(disp_y)
return (cell_x, cell_y)
def play_cell(self, cell_x, cell_y, player):
if (cell_x < 1 or CELL_X < cell_x or
cell_y < 1 or CELL_Y < cell_y or
self.get_cell(cell_x, CELL_Y) != '-'):
return False
for test_y in ... | The main task of the code is to handle a player's click on a game cell by converting mouse coordinates to grid cell coordinates, validating the move, switching players if successful, and returning whether the move was valid. It updates game state flags for turn progression and game initialization. | def click_cell(self, mouse_x, mouse_y):
(cell_x, cell_y) = to_cell(mouse_x, mouse_y)
if self.play_cell(cell_x, cell_y, self.player):
self.player = opponent(self.player)
self.computers_turn = True
self.game_init = False
return True
return False |
def get_four_cells(self, cell_x, cell_y, four):
return [self.get_cell(cell_x + x, cell_y + y) for (x, y) in four]
def is_availible(self, cell_x, cell_y):
return cell_y == 1 or self.get_cell(cell_x, cell_y - 1) != "-"
def play_cell(self, cell_x, cell_y, player):
if (cell_x < 1 or CELL_X < cell_x or
cel... | This function checks all possible four-cell configurations on a board to identify a winning move. If three of the four cells are occupied by the same player and the fourth is empty, it places the player's piece in the empty cell to block an imminent win, returning True if successful. If no such move exists, it returns ... | def play_win_block(self, player):
for four in FOURS:
cell_dx = four[3][0]
cell_dy = max(four[0][1], four[3][1])
for cell_x in range(0, CELL_X + 1 - cell_dx):
for cell_y in range(0, CELL_Y + 1 - cell_dy):
cells = self.get_four_cells(cell_x, cell_y, four)
if (cells.count(... |
def to_cell(disp_x, disp_y):
(grid_x, grid_y) = to_grid(disp_x, disp_y)
(cell_x, cell_y) = (int(round(grid_x)), int(round(grid_y)))
if abs(grid_x - cell_x) > 0.4 or abs(grid_y - cell_y) > 0.4:
return (0, 0)
return (cell_x, cell_y)
def play_cell(self, cell_x, cell_y, player):
if (cell_x < 1 or CELL_X < c... | The main task of the code is to handle a player's click on a game cell by converting mouse coordinates to cell coordinates, attempting to play the cell for the current player, switching to the opponent's turn if successful, and returning whether the move was valid. | def click_cell(self, mouse_x, mouse_y):
(cell_x, cell_y) = to_cell(mouse_x, mouse_y)
if self.play_cell(cell_x, cell_y, self.player):
self.player = opponent(self.player)
self.computers_turn = True
self.game_init = False
return True
return False |
def opponent(player):
return 'O' if player == 'X' else 'X'
def get_cells(self, triple):
return [self.get_cell(cell_x, cell_y) for (cell_x, cell_y) in triple]
def play_cell(self, cell_x, cell_y, player):
if (cell_x < 1 or CELL_X < cell_x or
cell_y < 1 or CELL_Y < cell_y or
self.get_cell(cell_x,... | This function checks if the current player can win or block the opponent by completing a line of three. It iterates through all possible triples (rows, columns, diagonals), identifies if two cells belong to the player/opponent and one is empty, then places the player's mark in the empty cell to win/block, returning Tru... | def play_win_block(self, player):
for check in (player, opponent(player)):
for triple in TRIPLES:
cells = self.get_cells(triple)
if cells.count(check) == 2 and cells.count('-') == 1:
(cell_x, cell_y) = triple[cells.index('-')]
self.play_cell(cell_x, cell_y, player)
... |
def play_win_block(self, player):
for four in FOURS:
cell_dx = four[3][0]
cell_dy = max(four[0][1], four[3][1])
for cell_x in range(0, CELL_X + 1 - cell_dx):
for cell_y in range(0, CELL_Y + 1 - cell_dy):
cells = self.get_four_cells(cell_x, cell_y, four)
if (cells.count(... | The code handles the computer's turn in a game by attempting to play a winning or blocking move, then switching to the player's turn if no such move is found. | def update(self):
if self.game_over:
return
if self.computers_turn:
if not self.play_win_block(self.player):
self.play_random(self.player)
self.player = opponent(self.player)
self.computers_turn = False |
def play_win_block(self, player):
for check in (player, opponent(player)):
for triple in TRIPLES:
cells = self.get_cells(triple)
if cells.count(check) == 2 and cells.count('-') == 1:
(cell_x, cell_y) = triple[cells.index('-')]
self.play_cell(cell_x, cell_y, player)
... | The code handles a computer player's turn in a game. It checks if the game is over, then attempts to block the player's win using `play_win_block`. If unsuccessful, it makes a random move. Afterward, it switches to the opponent's turn by updating the player and setting `computers_turn` to False. | def update(self):
if self.game_over:
return
if self.computers_turn:
if not self.play_win_block(self.player):
self.play_random(self.player)
self.player = opponent(self.player)
self.computers_turn = False |
def banner() -> None:
"""
Print an AOC Banner.
:return:
"""
# Create the letter forms
font = choice(["ticksslant", "tarty7", "tarty1", "swampland"])
letters = [
text2art("A", font=font),
text2art("O", font=font),
text2art("C", font=font),
text2art("2", font=... | The main task of the code is to execute a function determined by command-line options on a specified file. It displays a banner, retrieves user-provided options, prints a header, resolves the appropriate function based on these options, and then invokes that function with the filename provided in the options. | def main() -> None:
banner()
opts = options()
print_header(opts)
# what are we loading?
fun = resolve_function(opts)
# let's call it
fun(opts.filename) |
def errorText(msg):
"""
Print messages with color
"""
sys.stdout.flush()
sys.stderr.flush()
sys.stderr.write(f"{colors.red}{msg}{colors.ENDC}")
def base64urldecode(data):
"""
Base64 URL Decode
Convert - to + and _ to /
Append padding
"""
data = data.replace('-', '+')
data = data.replace('_', '/')
data +=... | The code processes a JWKS RSA key by decoding its 'e' and 'n' components, constructing an RSA public key, and saving it as a PEM file. It skips non-RSA keys, prints debug info if enabled, and stores the key with a filename derived from its 'kid' identifier. | def processKey(key):
"""
Process each JWKS key
"""
if debugControl['debugFlag']:
print("Processing Key ID:", key['kid'])
if key['kty'] != 'RSA':
errorText(f"Skipping unsupported cryptographic algorithm {key['kty']}\n")
return
# An RSA public key consists of two numbers 'e' and 'n'
# e: RSA public key exp... |
def get_state(self, base_path):
self.state = self.STATE_NONE
if os.path.exists(self.out_path(base_path)):
self.state = self.STATE_RUNNING
with open(self.out_path(base_path)) as f:
for line in f:
if "ABORT at pc" in line or \
... | The code logs simulation performance metrics for a benchmark run. It retrieves state data, formats instruction count, cycle count, IPC, and simulation speed into a string, then logs these metrics with benchmark ID and worker IP context for tracking and analysis. | def show(self, base_path, benchId, worker_ip):
self.get_state(base_path)
attributes = {
"instrCnt": self.num_instrs,
"cycleCnt": self.num_cycles,
"totalIPC": f"{self.get_ipc():.3f}",
"simSpeed": self.get_simulation_cps()
}
attributes_str = ... |
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register... | The code measures a quantum bit (qubit) into a classical bit (cbit), handling both individual qubits and registers. If inputs are registers of matching length, it generates multiple measurement instructions for each qubit-classical pair. Otherwise, it validates the inputs and attaches a single measurement operation. Th... | def measure(self, qubit, cbit):
"""Measure quantum bit into classical bit (tuples)."""
if isinstance(qubit, QuantumRegister) and \
isinstance(cbit, ClassicalRegister) and len(qubit) == len(cbit):
instructions = InstructionSet()
for i in range(qubit.size):
... |
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _attach(self, gate):
"""Attach a gate."""
self.data.append(gate)
return gate | This function resets qubits in a quantum register by generating reset instructions. If given a QuantumRegister, it applies resets to all its qubits. Otherwise, it directly resets the specified qubit, returning the instruction set for execution. | def reset(self, quantum_register):
"""Reset q."""
if isinstance(quantum_register, QuantumRegister):
instructions = InstructionSet()
for sizes in range(quantum_register.size):
instructions.add(self.reset((quantum_register, sizes)))
return instructions
... |
def get_query_sum(self, episode) -> Dict[int, int]:
''' Get a dict showing how many occurance of all words in query
are there per episode
Returns
-------
Dict[int, int]
a dict like that
>>> query = 'covid vaccine usa'
>>> queries_sum = {790: ... | The code updates context data for an HTML template by paginating and combining query results, episode data, highlighted text snippets, and timestamps. It handles empty queries or no results by setting appropriate messages, while populating paginated data for rendering search results with dynamic highlighting and pagina... | def get_context_data(
self,
**kwargs: Any) -> Dict[str, Any]:
''' Update context_data to be used in html template
Returns
-------
Dict[str, Any]
updated context_data
'''
context = super(SearchResultsView, self).get_context_data(**kwar... |
def unpack_data():
s = []
desk_list = []
index = 1
for target in ['11','12','8','9','10']:
if isdir(join('fetched',target)) == True:
files = list(reversed(os.listdir(join('fetched', target))))
s = s + [join('fetched', target, f) for f in files]
if... | The code processes 3D data by reading files, extracting room dimensions, unpacking object data, and using a function to place objects in a virtual room. It combines and downsamples point clouds, then saves the result as a PCD file for visualization and further analysis. | def rearrange():
files = os.listdir(join('fetched'))
empty = [f for f in files if isfile(join('fetched', f)) == True and 'empty' in f][0]
width, height = int(empty.split('_')[1]), int(empty.split('_')[2])
desk_list, pcd_addrs = unpack_data()
print(desk_list)
room = np.zeros([width, height])... |
def getSentences(self, text):
self.nlp.add_pipe(self.nlp.create_pipe('sentencizer'))
document = self.nlp(text)
return [sent.string.strip() for sent in document.sents]
def processSentence(self, sentence):
tokens = self.nlp(sentence)
return self.processSubjectObjectPairs(tokens)
de... | This code extracts triples (subject-predicate-object relationships) from input text by splitting it into sentences, processing each sentence to identify relationships, and then printing the resulting knowledge graph structure. The main task is to transform textual information into structured graph data for representati... | def knowledge_graph(self, text):
sentences = self.getSentences(text)
triples = []
print (text)
for sentence in sentences:
triples.append(self.processSentence(sentence))
self.printGraph(triples) |
def estimate_b(y,x):
reg = sm.Logit(y,x).fit()
b_hat = reg.params
return b_hat
def log_likelihood(b_hat,x,y):
ll_value = 0
for i,row in enumerate(x):
odds = np.matmul(b_hat.T, x[i,:])
p = np.exp(odds)
ll_value += y[i]*odds - np.log(1+p)
return ll_value
def calc_estimator_... | The code performs logistic regression on a dataset with variables BMI, alcohol, and age to predict 'chd'. It calculates beta estimates, log-likelihood, variance, and forecasts for a new observation, presenting results in a structured DataFrame for six sub-questions (6a-6f). | def Q6():
y = data['chd'].to_numpy()
x_mat = data.loc[:,['BMI','alcohol','age']].to_numpy()
x = np.c_[np.ones(x_mat.shape[0]), x_mat]
observation = np.array([1,27,8,50])
pd.set_option('display.max_colwidth',None)
title = ['Logistic Regression Model Equation', 'Beta Estimator','Log Likelihood Val... |
def readJson(path):
if os.path.isfile(path):
with open (path , 'r') as f:
return json.load(f)
def addDocument(collectionName, collections):
document = db.collection(collectionName).add(collections)
print(document[1].id)
return document[1].id
def loadFairDetail(fairInfo):
print("... | The main task of the code is to load JSON files from the current directory, extract 'events' data, and process each event by adding it to a document collection and retrieving fair details. It iterates through files, filters JSONs, reads events, and triggers processing for each event with separators for clarity. | def loadEvents():
with os.scandir(currPath) as it:
for entry in it:
if entry.name.endswith(".json") and entry.is_file():
#print(entry.name, entry.path)
events = readJson(entry.path)['events']
for event in events:
print("********... |
def get_guilds_config():
result = {}
for discord in config["discords"]:
result[discord["guild_id"]] = discord
return result
def discordapiuser_get_current_authenticated_user():
req = discordapiuser_request("/users/@me")
if req.status_code != 200:
abort(req.status_code)
user = req... | The main task of the code is to handle the third step of a process involving Discord guild validation. It checks if the specified guild exists, verifies user authentication via a Discord token, confirms the user's membership in the guild, and renders a template with guild details, user info, and an error flag if member... | def step3(guild_id):
guilds_config = get_guilds_config()
if guild_id not in guilds_config:
abort(404)
if "discord_token" not in session:
return redirect(url_for("login", redirect=request.url))
user = discordapiuser_get_current_authenticated_user()
guild = discordapi_get_guild(guild_i... |
def get_guilds_config():
result = {}
for discord in config["discords"]:
result[discord["guild_id"]] = discord
return result
def discordapiuser_get_current_authenticated_user():
req = discordapiuser_request("/users/@me")
if req.status_code != 200:
abort(req.status_code)
user = req... | This function handles user authentication for a Discord server by verifying the guild configuration, checking user login status, retrieving user and guild data, modifying user roles based on predefined configurations, logging the authentication event in a specified channel, and redirecting the user with a success messa... | def step3_post(guild_id):
guilds_config = get_guilds_config()
if guild_id not in guilds_config:
abort(404)
guild_config = guilds_config[guild_id]
if "discord_token" not in session:
return redirect(url_for("login", redirect=request.url))
user = discordapiuser_get_current_authenticated... |
def gen_round_keys(round_keys):
rc = BitVector(hexstring="01")
multiplier = BitVector(hexstring="02")
for i in range(10):
round_constant = BitVector(hexstring=rc.get_bitvector_in_hex())
round_constant += BitVector(hexstring="000000")
w_0 = round_keys[i][0: 32] ^ g(round_keys[i][96: ... | This code implements AES encryption and decryption with key scheduling. It takes plaintext input, pads it to 16 bytes, converts it to a BitVector, and prompts for a 16-character key. It generates round keys, encrypts the input, measures execution times for key scheduling, encryption, and decryption, then outputs cipher... | def AES():
# key_scheduling_time = 0
# encryption_time = 0
# decryption_time = 0
round_keys = []
decipher_output = BitVector(size=0)
text = input("Plain Text:\n")
print("{} [in ASCII]".format(text))
if len(text) > 16:
text = text[0:16]
if len(text) < 16:
padding = 16 ... |
def _check_submodule(path, use_git=True, offline=False):
"""
Check if the given path is a git submodule.
See the docstrings for ``_check_submodule_using_git`` and
``_check_submodule_no_git`` for futher details.
"""
if use_git:
return _check_submodule_using_git(path, offline)
else:
... | The function ensures the `astropy_helpers` module is available for import by checking a specified path (e.g., a git submodule or local directory), downloading it from PyPI if needed, or using a provided archive. It handles offline mode, git submodule initialization, and automatic upgrades to the latest patch release. I... | def use_astropy_helpers(path=None, download_if_needed=None, index_url=None,
use_git=None, auto_upgrade=None):
"""
Ensure that the `astropy_helpers` module is available and is importable.
This supports automatic submodule initialization if astropy_helpers is
included in a project ... |
def create_navigation_option_widgets(self):
# Create Frame to hold menu options
self.options_frame = ctk.CTkFrame(self, fg_color='transparent',width = 15, height = 40)
self.page_buttons = []
self.main_page_button = ctk.CTkButton(self.options_frame,
... | This code initializes a customizable navigation bar component with menu icons, animation variables, and layout setup for a GUI application, integrating with a controller and supporting dark/light themes. It prepares toggle functionality and positions the bar within a parent frame. | def __init__(self, parent, controller, hidden):
super().__init__(master=parent, fg_color='transparent', width = 150)
self.controller = controller
self.parent = parent
# Import icons
self.open_menu_img = ctk.CTkImage(
light_image= Image.open('app_assets/menu.png'),
... |
def _divide_library(self, matrix, need_log):
"""
introduction: Separate 'good' and 'bad' data from total data, and splice index and data as a list.
:param matrix: Generated binary two-dimensional matrix
The data of this matrix contains only 0 or 1 (non-char).
... | The code encodes binary data from a 2D matrix into DNA sequences. It processes the matrix by dividing data into "good" and "bad" sets, pairs them, and synthesizes them into DNA sequences. The file size parameter optimizes redundancy during conversion. If logging is enabled, it tracks steps like data division, pairing, ... | def encode(self, matrix, size, need_log=False):
"""
introduction: Encode DNA sequences from the data of binary file.
:param matrix: Generated binary two-dimensional matrix.
The data of this matrix contains only 0 or 1 (non-char).
Type: int or bit.... |
def generate_latent(ahe_radiograph_np, mask_np):
model = VGG16FE().to(DEVICE)
ahe_image_numpy = cv2. GaussianBlur(
ahe_radiograph_np, (11, 11), cv2.BORDER_DEFAULT)
ahe_image_three_channels = cv2.cvtColor(
ahe_image_numpy, cv2.COLOR_GRAY2RGB).astype(np.float32)
ahe_image_three_channels ... | The function generates a marked image by combining an enhanced radiograph with a segmentation mask. It creates a latent representation, derives a spectrum from it, and overlays predicted curves onto the original image, returning both the spectrum data and the modified image. | def generate_marked_img(ahe_radiograph_np, ahe_radiograph_rgb_pil, segmentation_result_np):
mask_np = segmentation_result_np
ahe_np = ahe_radiograph_np
ahe_rgb_pil = ahe_radiograph_rgb_pil
latent = generate_latent(ahe_np, mask_np)
spectrum_np = generate_spectrum(latent)
new_img = generate_predic... |
def generate_segmentation(radiograph_pil):
model = UNET(in_channels=1, out_channels=1,
features=[4, 8, 16, 32]).to(DEVICE)
checkpoint = torch.load(UNET_MODEL_PATH, map_location="cpu")
model.load_state_dict(checkpoint["state_dict"])
model.eval()
image_pil = radiograph_pil
width,... | This code processes a radiograph image by converting it to grayscale, preprocessing, generating a segmentation mask, creating a marked image with spectral analysis, saving the result as PNG, and returning calculated angles from the spectrum. | def pipline(AHE_RADIOGRAPH_PATH):
radiograph = Image.open(AHE_RADIOGRAPH_PATH).convert("L")
radiograph_pil = preprocess_radiograph(radiograph)
radiograph_rgb_pil = radiograph_pil.convert("RGB")
segmentation_np = generate_segmentation(radiograph_pil)
radiograph_np = np.array(radiograph_pil)
spect... |
def __isW1(self, W: float):
if self.name == "K+L":
return W <= 1.975 and W >= 1.65
elif self.name == "K+S0":
return W <= 2.05 and W >= 1.725
return False
def __isW2(self, W: float):
if self.name == "K+L":
return W >= 1.65 and W <= 2.35
elif se... | This function processes a data table to compute interpolated values of physics parameters (St, Sl, Slt, Stt) and their uncertainties for different W and Q² combinations. It categorizes data based on W ranges, applies sigma-specific calculations, interpolates values using quadratic/linear methods, and merges results fro... | def __lower_Q2_int(self, data_table):
result = pd.DataFrame()
vol1, vol2, vol3, vol4 = pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
vol_for_ratio = pd.DataFrame()
get_ratios = False
Q2_list = []
W_Q2_Sigma, W_Q2_None, W_Q2_ratio = {}, {}, {}
f... |
def __isData1(self, W: float, Q2: float):
if self.name == "K+L":
return Q2 <= 1.0 and Q2 >= 0.65 and W <= 1.975 and W >= 1.65
elif self.name == "K+S0":
return Q2 <= 1.0 and Q2 >= 0.65 and W <= 2.05 and W >= 1.725
return False
def __isData2(self, W: float, Q2: float):
... | The main task of the code is to process a data table by categorizing rows into five volumes (vol1–vol5) based on conditions involving 'W' and 'Q2' values, applying specific transformations to each volume, cleaning negative values in 'St' and 'Sl' columns, and aggregating results by 'W', 'Q2', and 'cos_th' to return a g... | def __Str_func(self, data_table):
vol1, vol2, vol3, vol4, vol5 = [], [], [], [], []
vol1_df, vol2_df, vol3_df = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
vol4_df, vol5_df = pd.DataFrame(), pd.DataFrame()
for index, row in data_table.iterrows():
W = row['W']
... |
def __isWforQ2inter(self, W: float, Q2: float):
if Q2 < 1.8:
if self.name == "K+L":
return W <= 2.575 and W >= 1.65
else:
if Q2 > 1.0:
return W <= 2.575 and W >= 1.75
else:
return W <= 2.575 and W >= ... | This function generates a DataFrame containing structure function data by processing different W, Q2, and cos_th combinations. It applies specific functions to valid ranges, extrapolates outside ranges, and combines results while ensuring non-negative values. | def Str_func_all(self):
print(' Stand by for structure functions ...')
vol, vol1, vol2 = [], [], []
vol_inter, vol_extra, vol_zero = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
for W in self.W:
if (self.name == "K+L" and W <= 1.61) or (self.name == "K+S0" and W <= 1.686... |
def init_maze(height, width):
#generating a random maze n x n with adaptable n
maze = []
count = 1
#adding the rows to the bigger list and so to the matrix
for i in range(height):
row = []
for j in range(width):
row.append(count)
count += 1
maze.appen... | The code generates a maze with specified height and width, ensuring odd dimensions. It initializes the maze, iteratively modifies it to form paths, normalizes cell values (walls as 0, paths as 1), adds a start (2) and exit (3) point, and surrounds the maze with walls. The final maze includes expanded borders for bounda... | def generate_maze(height, width):
assert (N % 2 == 1 and M % 2 == 1)
maze = init_maze(height, width)
cnt = 0
while cnt < (height // 2) * (2 + (width // 2)):
cnt += iterate(maze, height, width)
if DEBUG_FLAG:
printmaze(maze)
# normalise (walls = 0)
for i in range(len(maze)):
... |
def getClassicLeagueStandings(self):
if 1 not in self.pathInfo:
return None
leagueId = self.pathInfo[1]
basicInfo = self.fplApi.getClassicLeagueStandings(leagueId=leagueId)
standings = []
currentGW = None
interestedFields = ['event_total', 'player_name', 'ra... | The function calculates live league standings by integrating current gameweek data, bonus points, and live player performance. It retrieves event status, classic league standings, and updates standings with live action data and differential adjustments. The result is formatted for dashboard display, returning updated s... | def calculateLiveStandingsForLeague(self):
if 1 not in self.pathInfo:
return None
eventStatus = self.fplApi.getEventStatus()
currentStandings = self.getClassicLeagueStandings()
currentGW = currentStandings['gameweekNumber']
# response = currentStandings
# if... |
def create_socket():
try:
global host
global port
global s
host = "127.0.0.1"
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
def bind_socket():
try:
global host
global port
... | The main task of the code is to set up a server socket by creating a socket, binding it to a specific address and port, and then accepting incoming connection requests. This establishes a listening endpoint for client connections in a network communication context. | def main():
create_socket()
bind_socket()
socket_accept() |
def _dealer_cf():
global dealer_label, dealer_card_value,dealer_score,dealer_ace,dealer_card_frame
dealer_label = tkinter.Label(card_frame,text='Dealer',background='green',fg='white').grid(row=0,column=0,sticky ='n')
dealer_card_value = tkinter.IntVar()
dealer_score = 0
dealer_ace = False
dealer_card_value.set(0)... | The function resets the game by clearing player and dealer cards, updating the result message to "BlackJack Time!!", destroying existing card frames, recreating them, shuffling the deck, and restarting the game. | def _reset_game():
global deck,result_string
result_string.set('BlackJack Time!!')
dealer_cards.clear()
player_cards.clear()
player_card_frame.destroy()
dealer_card_frame.destroy()
_dealer_cf()
_player_cf()
_shuffle_card()
_start_game() |
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0, num_layers - 1):
W = self.xavier_init(size=[layers[l], layers[l + 1]])
b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32)
... | This code initializes a physics-informed neural network (PINN) for solving partial differential equations (PDEs) with specified boundary/initial conditions. It sets up collocation points, training data, neural network layers, loss components (PDE residuals, data consistency, wall/outlet constraints), and optimizers (Ad... | def __init__(self, Collo, OUTLET, WALL, DATA, uv_layers, lb, ub, ExistModel=0, uvDir='', loss_type='square'):
# Count for callback function
self.count = 0
# Bounds
self.lb = lb
self.ub = ub
# Mat. properties
self.rho = 1.0
self.mu = 0.02
# Coll... |
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0, num_layers - 1):
W = self.xavier_init(size=[layers[l], layers[l + 1]])
b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32)
... | This code initializes a physics-informed neural network (PINN) for solving partial differential equations (PDEs). It sets up placeholders for input data, defines neural network layers, computes predictions for the solution and PDE residuals, and combines data loss (matching input-output pairs) with PDE loss (enforcing ... | def __init__(self, X, X_f, u, layers, ExistModel=0, uvDir='', loss_type='square'):
self.count = 0
self.lb = -np.pi
self.ub = np.pi
self.xd = X
self.ud = u
self.x_f = X_f[:, 0:1]
# Initialize NNs
self.layers = layers
self.loss_rec = []
s... |
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0, num_layers - 1):
W = self.xavier_init(size=[layers[l], layers[l + 1]])
b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32)
... | This code initializes a physics-informed neural network (PINN) for solving partial differential equations (PDEs). It sets up input placeholders, neural network layers, loss functions (data and PDE losses), and optimizers (Adam and L-BFGS-B). The model combines supervised learning (matching data points) with physical co... | def __init__(self, X, Xf, u, layers, lb, ub, ExistModel=0, uvDir='', loss_type='square'):
self.count = 0
self.lb = lb
self.ub = ub
self.x = X[:, 0:1]
self.t = X[:, 1:2]
self.xf = Xf[:, 0:1]
self.tf = Xf[:, 1:2]
self.u = u
self.uv_layers = layer... |
def optimize_alpha_MISE(Spikes, Time, nIter=100, alpha_start=0.01, alpha_end=4, alpha_step=0.01):
"""
optimize_alpha is used to optimize alpha for BAKS from a 1D array of real spiking data.
it uses the real data to generate a simulated spike array with known rate,
then uses that to generate a BAKS-estim... | This function optimizes the BAKS (Bandwidth-Adjusted Kernel Smoothing) method for spike rate estimation by minimizing the Mean Integrated Squared Error (MISE). It first computes the optimal smoothing parameter (alpha) using `optimize_alpha_MISE`, extracts spike times from input data, and then applies the BAKS algorithm... | def get_optimized_BAKSrates_MISE(Spikes, Time, nIter=10):
df, best_alpha = optimize_alpha_MISE(Spikes, Time, nIter)
SpikeTimes = extract_spike_times(Spikes, Time)
BAKSrate, h = BAKS(SpikeTimes, Time, a=best_alpha)
return BAKSrate, h, best_alpha |
def profile_menu():
print("-------------------------------------------------------------------------------")
print("Refugee's Emergency Profile Menu")
print("[1] Create new emergency profile")
print("[2] Edit emergency profile")
print("[3] Delete emergency profile")
print("[4] Search emergency p... | This function provides a menu-driven interface for managing volunteer profiles, allowing users to create, modify, delete, search, view all profiles, or return to the volunteer home screen. It continuously prompts for input until a valid option (1-6) is selected, executing corresponding actions like create_profile(), mo... | def emergency_profile(user):
while True:
profile_menu()
volunteer_option = str(input("Option: "))
if volunteer_option in ["1", "2", "3", "4", "5", "6"]:
if volunteer_option == "1":
create_profile()
elif volunteer_option == "2":
modify_... |
def check_date():
# a = 0
while True:
try:
start_date = input("Enter the date on which this occurred in the format yyyy-mm-dd: ")
datetime.datetime.strptime(start_date, '%Y-%m-%d') #checks whether it is in the correct format, and if it is a valid date
... | This function provides an admin interface to manage emergency plans, including creating new plans with validated inputs, saving them to a CSV file, and accessing other administrative features like viewing plans, camps, volunteers, and reports. The core task is creating and storing emergency plans with input validation ... | def adminFeatures():
b = 0
while b == 0:
print("-------------------------------------------------------------------------------")
print("[1] Create an Emergency Plan\n[2] View Emergency Plans\n[3] Edit an Emergency Plan\n[4] View camp details")
print("[5] Overview of voluntee... |
def print_legend(self) -> None:
"""Print a line containing the color legend"""
print(
f"[ Legend: "
f"{TERM_COLOURS.RED.value}Modified register{TERM_COLOURS.ENDC.value} | "
f"{TERM_COLOURS.RED.value}Code{TERM_COLOURS.ENDC.value} | "
f"{TERM_COLOURS.GREEN.... | The main task of the code is to display the current debugging context by updating and rendering key program states—such as registers, stack, memory regions, threads, and execution trace—when a debug session stops. It refreshes internal objects from the execution context, clears the screen, and prints structured informa... | def display_context(
self,
exe_ctx: SBExecutionContext,
) -> None:
"""For up to date documentation on args provided to this function run: `help target stop-hook add`"""
# Refresh frame, process, target, and thread objects at each stop.
self.frame = exe_ctx.GetFrame()
... |
def __next_level(self):
# Advance to next level and adjust speed modifier
self._level += 1
self._speed_modifier = 1 + self._level / 10
# Reset the aliens and the mothership timer and value
self.__alien_setup(ALIEN_NUMBER_ROWS, ALIEN_NUMBER_COLUMNS, ALIEN_START_POS, ALIEN_X_SPACI... | The code checks for collisions between player lasers, alien lasers, aliens, motherships, and obstacles. It updates scores, destroys entities, adjusts game speed, handles player lives, and triggers game over or next-level transitions. Collision responses include sound effects, reward adjustments, and entity removals, en... | def __check_collisions(self):
# Player lasers
if self._player.sprite.lasers:
for laser in self._player.sprite.lasers:
# Collision with aliens
alien_collisions = pg.sprite.spritecollide(laser, self._aliens, dokill=False)
if alien_collisions:
... |
def __check_collisions(self):
# Player lasers
if self._player.sprite.lasers:
for laser in self._player.sprite.lasers:
# Collision with aliens
alien_collisions = pg.sprite.spritecollide(laser, self._aliens, dokill=False)
if alien_collisions:
... | This code updates the game state by handling player and alien actions, collision checks, rendering, and AI interactions. It processes controller input, updates entities like the player, aliens, and mothership, manages shooting mechanics, adjusts rewards, and transitions to the final screen if the game ends. | def run(self, surface):
if self._game_status == Game_status.PLAYABLE_SCREEN:
self._controller.action()
self.__check_collisions()
self._player.update()
self._aliens.update(self._alien_direction)
self.__alien_border_constraint()
self.__alien... |
def cdr_aggregation(df: pd.DataFrame) -> pd.DataFrame:
df[COL_YEAR] = pd.DatetimeIndex(df[COL_DATE]).year
df[COL_MONTH] = pd.DatetimeIndex(df[COL_DATE]).month
df[COL_MONTH_NAME] = df[COL_MONTH].apply(lambda x: calendar.month_abbr[x])
cdr_record_cols = [col for col in df.columns if
... | The main task of the code is to process raw telco data by aggregating call detail records, reviews, and web interaction data, then merging these with census and training data to create a unified processed dataset, which is saved as a pickle file for analysis. | def main(args):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
cdr_df = pd.read_csv(os.path.join(args.raw_data_path, 'telco_cdr.tsv.gz'), compression='gzip', header=0, sep='\t',
quotechar='... |
def look_around(self):
return [self.look_into_direction(angle) for angle in self.EYES]
def correct_behavior(self, distances, t):
feed_data = np.array([distances + [self.v]]) / self.norm
predictions = self.engine.predict(feed_data)
self.a, self.s = predictions
self.v += self.a * t
self.angle +=... | The code defines a `move` method that checks if an object is stuck, then adjusts its movement behavior based on environmental distances and time `t`, finally advancing it by `t` units. The main task is to navigate or move the object while dynamically correcting its path using sensor data. | def move(self, t=T):
if self.stuck: return
distances = self.look_around()
self.correct_behavior(distances, t)
self.advance(t) |
def set_environ(client, lambda_client, controller_instanceobj, context,
eip=None):
""" Sets Environment variables """
if eip is None:
# From cloud formation. EIP is not known at this point. So get from controller inst
eip = controller_instanceobj[
'NetworkInterfaces']... | This function handles CloudFormation create/delete requests for Aviatrix controller HA setup. On 'Create', it validates IAM, S3 bucket, backup file, EIP, and AMI, then provisions HA infrastructure. On 'Delete', it attempts resource cleanup. Errors trigger failure responses with diagnostic messages, including manual cle... | def handle_cloud_formation_request(client, event, lambda_client, controller_instanceobj, context,
instance_name):
"""Handle Requests from cloud formation"""
response_status = 'SUCCESS'
err_reason = ''
if event['RequestType'] == 'Create':
try:
os.env... |
def update_env_dict(lambda_client, context, replace_dict):
""" Update particular variables in the Environment variables in lambda"""
env_dict = {
'EIP': os.environ.get('EIP'),
'AMI_ID': os.environ.get('AMI_ID'),
'VPC_ID': os.environ.get('VPC_ID'),
'INST_TYPE': os.environ.get('INS... | This Lambda function handles two types of requests: CloudFormation Template (CFT) setup for HA configuration and SNS events to attach Elastic IPs post-failover. It identifies event sources, processes CFT requests via `setup_ha`, manages SNS-triggered resource recreation on launch errors, and ensures proper security gro... | def _lambda_handler(event, context):
""" Entry point of the lambda script without exception hadling
This lambda function will serve 2 kinds of requests:
one time request from CFT - Request to setup HA (setup_ha method)
made by Cloud formation template.
sns_event - Request from sns t... |
def _trade_count_series(self, split=None, split_type=None):
trade_series = TimeSeriesSplit(self.data).split_selector(split, split_type)
trade_series['Trades'] = np.logical_and(trade_series['Position'] != trade_series['Position'].shift(1),
trade_series['Pos... | This function generates a DataFrame containing key trading metrics, including trade counts, entry prices, profit/loss (PL), cumulative PL, closed trade statistics, drawdowns, and average win/loss values. It processes time-series split data, computes cumulative sums, max drawdowns, and performance indicators, then retur... | def output_all_metrics_as_df(self, split=None, split_type=None):
output_df = TimeSeriesSplit(self.data.copy()).split_selector(split, split_type)
output_df['Trades'] = self._trade_count_series(split, split_type)
output_df['EntryPrice'] = self._entry_price_series(split, split_type)
output_... |
def date_range_split(self, split) -> pd.DataFrame:
"""
:param split: a tuple in datetime format that contains the start date and the end date of the range. Year-month-day
:return: dataframe that contains only the data within the date range
"""
date_range = self.data.copy()
... | This method routes the input 'split' parameter to the appropriate data splitting strategy based on the 'split_type' value, returning the result of the corresponding method (e.g., date range splitting, optimization window, rolling window, etc.), or a copy of the data if 'split' is None. It acts as a dispatcher for diffe... | def split_selector(self, split, split_type):
if split_type == 'DateRange':
return self.date_range_split(split)
elif split_type == 'FixedOptimizationWindow':
return self.optimization_window(split)
elif split_type == 'RollingOptimizationWindow':
return self.roll... |
def h(p1,p2):
x1,y1=p1;
x2,y2=p2;
return abs(x2-x1)+abs(y1-y2);
def reconstruct_path(parent,current,draw):
while current in parent:
current=parent[current];
current.Make_Path();
draw();
def draw(Window,grid,rows,width):
for row in grid:
for node in row:
nod... | This code implements the A* pathfinding algorithm on a grid. It uses a priority queue to explore nodes, calculating g-scores (path cost) and f-scores (estimated total cost). When the end node is reached, it reconstructs the path. The algorithm updates node states visually, handles user exit events, and returns True if ... | def algorithm(draw,grid,start,end):
count=0;
open_set=queue.PriorityQueue();
open_set.put((0,count,start));
parent={};
g_score={node:float("inf") for row in grid for node in row};
g_score[start]=0;
f_score = {node: float("inf") for row in grid for node in row};
f_score[start] = h(start.g... |
def make_grid(rows,width):
grid=[];
gap=width//rows;
for i in range(rows):
grid.append([]);
for j in range(rows):
node=Node(i,j,gap,rows);
grid[i].append(node);
return grid;
def draw(Window,grid,rows,width):
for row in grid:
for node in row:
... | This code creates a pathfinding visualization using Pygame. It initializes a grid, allows users to set start/end points and barriers via mouse clicks, and runs an algorithm (likely A* or Dijkstra's) when the spacebar is pressed. The algorithm uses a lambda function to continuously draw the grid during execution, updati... | def main(Window,width):
rows=50;
grid=make_grid(rows,width);
start=None;
end=None;
run=True;
started=False;
while run:
draw(Window,grid,rows,width);
for event in pygame.event.get():
if(event.type==pygame.QUIT):
run=False;
if started:
... |
def print_command(command_file, cmd):
"""
Writes the supplied command to the end of the generated script
:param cmd: The command to append
"""
with io.open(command_file, "a", encoding='utf-8') as myfile:
myfile.writelines(cmd + "\n")
def create_workfolders(runtype, analysis_settings, filena... | The function `run_batch` generates and executes batch commands for processing ground-up (GUL) and insured loss (IL) calculations using multiple parallel processes. It prepares input files, constructs command-line instructions for model execution, manages output directories, and invokes post-processing steps like `do_gu... | def run_batch(
max_process_id,
analysis_settings,
num_reinsurance_iterations,
fifo_tmp_dir,
mem_limit,
alloc_rule,
filename,
_get_getmodel_cmd,
custom_args={}
):
# remove the file if it already exists
if os.path.exists(filename):
os.remove(filename)
aux_file, _ =... |
def df_to_array(df):
X = df.copy()
X = X.drop(columns=['id', 'date'])
X = X.values.copy()
return(X)
def scale(array):
# Very important to scale!
sc = Normalizer(norm='l2')
array = sc.fit_transform(array)
return array
def cluster_kmeans_dtw(distance, k, X, df):
X1 = to_time_series_dat... | The main task of the code is to perform clustering on a dataset using specified algorithms (KMeans, KMedoids, SOM, Agglomerative) and distance metrics (e.g., DTW), with input validation, data preprocessing, and MLflow experiment tracking. It reads CSV data, scales features, selects the clustering model, applies the cho... | def main(in_csv, model, distance_metric, number_of_clusters):
in_csv = none_checker(in_csv)
in_csv = abspath(in_csv)
distance_metric = none_checker(distance_metric)
number_of_clusters = none_checker(number_of_clusters)
number_of_clusters = int(number_of_clusters)
all_data = pd.read_csv(in_csv, ... |
def batches(self, X_train, y_train):
# size
n_samples, _ = np.shape(X_train)
batch_size = self.batch_size
# batchs
batches = []
random_mask = list(np.random.permutation(n_samples))
random_X = X_train[random_mask, :]
random_Y = y_train[random_mask, :]
... | The main task of the code is to train a neural network classifier using TensorFlow. It handles class weighting, one-hot encoding, batch training, and model saving. The function fits the model to input data, computes loss with optional class weights, applies specified optimizers, and saves the trained model. It also opt... | def fit(self, X, y, sample_weight=None):
print("------------------------------------")
print("NeuralNetClassifier fit")
# size
n_samples, n_features = np.shape(X)
# class weight
if self.weighted_class:
class_weight = compute_class_weight('balanced', np.uniq... |
def get_device_data(token):
myDevice = Device({ "token": token})
result = myDevice.getData({
"query": "last_item",
"variable": "water_level",
})
print(result)
def get_device_location(token):
myDevice = Device({ "token": token})
result = myDevice.getData({
"query": "last_i... | The main task of the code is to retrieve and visualize elevation data around a device's location using a sensor token. It fetches device info, generates OpenStreetMap URLs, measures elevation query performance, constructs a 2D elevation map, creates an overlay based on a threshold, and plots the results with matplotlib... | def main():
token = "ba8d3764-1dc8-46ca-80ca-54aa3aec3297" # He_003 sensor on Bill's tago.io dashboard
print("--- output device info ---")
out = get_device_data(token)
print(out)
print("--------------------------")
device_location = get_device_location(token)
orig_url = get_osm_url(dev... |
def train_score(self, X, fixed = None):
if fixed is not None:
self.epochs = fixed
best_model_state_epoch = 300
self.model.train()
n_samples = X.shape[0]
self.batch_size = min(n_samples, self.batch_size)
val_ratio = 0.2
val_size = int(n_samples * val_ra... | The main task of the code is to normalize input data, convert it to a PyTorch tensor, compute a training score, determine a topological order, perform pruning on the data based on this order, and return the pruned DAG along with the topological order. | def fit(self, X):
X = (X - X.mean(0, keepdims = True)) / X.std(0, keepdims = True)
X = torch.FloatTensor(X).to(self.device)
self.train_score(X)
order = self.topological_ordering(X)
out_dag = self.pruning(order, X.detach().cpu().numpy())
return out_dag, order |
def clean_file_name(path):
"""
Removes the initial directory added by get_files()
"""
path = path.lstrip("./")
return path
def strip_styling(path):
"""
Remove styling from a relative path
"""
path = path.split(" ")[0]
return path
def check_private_paths(files):
"""
Return... | The main task of the code is to organize images in a markdown project by identifying image usages, detecting broken links, separating private/public images, moving images to appropriate directories, and updating markdown links accordingly. It ensures consistency by relocating images, fixing broken references, and notif... | def organize_images():
core.info("Finding markdown files and images...")
all_files = get_files(".", [".md"] + IMAGE_EXTS)
md_files = [clean_file_name(f) for f in all_files[".md"]]
img2files = {
clean_file_name(img): []
for ext in IMAGE_EXTS for img in all_files[ext]
}
# Check wh... |
def requestrestore():
try:
if not checkcopy():
copyfile()
waitforprocess("copyfile")
createbase()
waitforprocess("createbase")
globals.requests_list[0].setoid(getbaseoid(globals.conn, globals.requests_list[0].dbname)[0][0])
setusersbase(globals.conn, g... | This code processes a queue of database requests in a thread. It handles each request (RESTORE, DROP, DUMP) by calling corresponding functions, removes processed requests from the list using thread-safe locks, and manages thread state by acquiring/releasing locks and updating the ongoingthread status. | def databasethread():
globals.runningthread.acquire()
while len(globals.requests_list) > 0:
if globals.requests_list[0].type == 'RESTORE':
requestrestore()
elif globals.requests_list[0].type == 'DROP':
requestdrop()
elif globals.requests_list[0].type == 'DUMP':
... |
def look_for_spacers (record):
dr = run_vmatch2 (record)
extract_spacers (record, dr['positions'])
return dr
def look_for_cas (record):
run_prodigal ()
run_hmmsearch ()
genes = find_best_cas ()
return genes
def extract_protein (gene_id, temp_dir):
translation = temp_dir + '/translation.f... | The code processes a biological record by identifying spacers (via look_for_spacers) and Cas genes (via look_for_cas). It extracts protein sequences for effector genes, determines the gene's strand, and returns the record ID, spacer data, gene details, and strand information. Temporary files are cleaned up if specified... | def search_everything (record):
this_temp_dir = temp_dir + '/' + record.id
dr = look_for_spacers(record)
genes = look_for_cas(record)
strand = 0
for g in genes:
if genes[g]['effector']:
strand = genes[g]['strand']
genes[g]['sequence'] = extract_protein (genes[g]['id']... |
def title(self, n = None):
return self.textOfNode('title', n).strip()
def link(self, n = None):
if n is None: n = self.node[self._index]
l = self.textOfNode('link', n).strip()
return l if l else self.attrOf(n, 'link', 'href').strip()
def description(self, n = None):
htmldata = HT... | The code defines a method `record` that takes an input `n` and returns a dictionary containing four key-value pairs. Each key corresponds to a method call on `self` (e.g., `title(n)`, `link(n)`, `description(n)`) and an index retrieved from `self.node.index(n)`. The primary task is to aggregate and return structured da... | def record(self, n):
return {
'title': self.title(n),
'link': self.link(n),
'description': self.description(n),
'index': self.node.index(n)
} |
def readSlices( f ):
lines = f.readlines()
numSlices = int(lines[0])
slices = []
lineNum = 1
for i in range(numSlices):
numPoints = int(lines[lineNum])
lineNum += 1
slice = Slice( [ Vertex( [ float(n) for n in line.split() ] )
for line in lines[l... | The main task of the code is to create a 3D mesh viewer application. It reads triangle data from a file, initializes a GLFW window for rendering, sets up event callbacks for user interactions (keyboard, mouse, resizing), and enters a loop to continuously render the 3D mesh while handling real-time input. The program te... | def main():
global window, allSlices, mousePositionChanged
# Check command-line args
if len(sys.argv) < 2:
print( 'Usage: %s filename' % sys.argv[0] )
sys.exit(1)
args = sys.argv[1:]
while len(args) > 1:
# if args[0] == '-x':
# pass
args = args[1:]... |
def getCombinations(r):
global total
total = 9*len(arry)
return (recursiveCombinations(arry, [None for i in range(r)], 0, len(arry)-1, 0, r))
def joinList(l):
s = [str(i) for i in l]
return int("".join(s)) | The code attempts to find the largest number by recursively removing elements from a list based on combinations, checking divisibility by 3, and reversing lists to form the maximum value. It uses undefined functions like getCombinations and joinList, suggesting it's an incomplete or placeholder implementation for a com... | def getLargestNumb(temp, pickOut, original):
if(pickOut == len(arry)):
return 0
if(pickOut > 0 and pickOut <= (len(arry)-1)):
if(getCombinations(pickOut) != None):
remove = getCombinations(pickOut)
for i in remove:
original.remove(i)
original.r... |
def get_partition_queue_job_info(partition_name: str,
conn_manager: RemoteConnectionManager,
attribute: str,
job_state: str = "RUNNING"):
output = conn_manager.run_command(f'squeue --noheader -p {partition_name} -t {j... | The main task of the code is to aggregate and calculate the total CPU, RAM, and GPU resources (both allocated and locked) for each user running jobs on GPU partitions across the cluster. It collects data from all partitions, sums the resources per user, rounds RAM values to one decimal place, and returns a dictionary m... | def aggregate_user_info(conn_manager: RemoteConnectionManager) -> dict:
"""gets the ram, cpu and gpu usage for each user that has a running job on the gpu partitions
"""
info = defaultdict(lambda: {'cpu_allocated': 0, 'ram_allocated': 0, 'gpu_allocated': 0, 'gpu_locked': 0})
user_running_set = set()
... |
def _encode_native(self, text: str, allowed_special: Set[str]) -> Tuple[List[int], int]:
# Encodes a string into a sequence of token indices, handling special tokens.
#
# Args:
# - text (str): The text to encode.
# - allowed_special (set): A set of allowed special tokens.
... | This function encodes text into tokens, adjusts the last token's length if needed, decodes unstable bytes from the modified tokens, and generates possible completions based on those bytes. It handles edge cases where unstable bytes are absent, returning tokens and an empty set when no completions are possible. The core... | def _encode_unstable_native(self, text, allowed_special):
tokens, last_piece_token_len = self._encode_native(text, allowed_special)
if last_piece_token_len == 0:
return tokens, set()
tokens, last_piece_token_len = self._increase_last_piece_token_len(tokens, last_piece_token_len)
... |
def _encode_ordinary_native(self, text):
# print("_encode_ordinary_native", text)
# Encodes a string into a sequence of token indices.
#
# Args:
# - text (str): The text to encode.
#
# Returns:
# - list of int: The sequence of token indices.
rege... | This function encodes a byte sequence into a list of token indices by first attempting UTF-8 decoding. If successful, it uses _encode_ordinary_native. On decoding errors, it splits the bytes into valid and unstable parts, encodes the valid portion, and appends the unstable bytes as a single token. This ensures robust h... | def _encode_bytes(self, bytes_data: bytes) -> List[int]:
"""Encodes a byte sequence into a list of token indices.
Args:
bytes_data: The byte sequence to encode.
Returns:
A list of token indices representing the encoded byte sequence.
"""
try:
... |
def sum_prompts(a=None, b=None):
if a is None:
return b
if b is None:
return a
if (
(is_chat_prompt(a) and is_chat_prompt(b))
or (is_chat_prompt(a) and prompt_get_text(b) == "")
or (is_chat_prompt(b) and prompt_get_text(a) == "")
):
functions = (a.get("fun... | This function recursively renders a prompt structure based on element type and hierarchy level, accumulating prompts and token counts while enforcing a token limit. It handles nested lists, conditional rendering (e.g., "first", "scope"), special elements (e.g., "empty", "breaktoken"), function definitions, and chat mes... | def render_with_level_and_early_exit_with_token_estimation(
elem: PromptElement, level: int, tokenizer: str, token_limit: int
) -> RenderedPrompt:
if elem is None or elem is False:
return {"prompt": None, "empty_token_count": 0}
if isinstance(elem, list):
accumulated_result = {
... |
def sum_prompts(a=None, b=None):
if a is None:
return b
if b is None:
return a
if (
(is_chat_prompt(a) and is_chat_prompt(b))
or (is_chat_prompt(a) and prompt_get_text(b) == "")
or (is_chat_prompt(b) and prompt_get_text(a) == "")
):
functions = (a.get("fun... | This function recursively renders elements into structured prompts based on their type and priority level, handling nested structures, token counts, and callbacks. It processes lists, strings, integers, and various element types (e.g., 'first', 'chat', 'scope') to generate prompts with associated handlers, functions, a... | def render_with_level(elem, level, tokenizer, call_ejected_callback=False):
if elem is None or elem is False:
return {"prompt": None, "empty_token_count": 0, "output_handlers": [], "stream_handlers": []}
if isinstance(elem, list):
accumulated_result = {
"prompt": None,
"... |
def dispatch_govt():
while(1):
input("Enter any key to CONTINUE>")
print(" 1.Crop based farmer search 2.Farmers in alocation 3.Farmers using a water source")
print(" 4.Crops order by water usage 5.Crops order by cost 6.Farmers with land greater than:")
print(" 7.Overused w... | (dispatch) The function `dispatch(ch)` maps user input (`ch`) to specific helper functions. It checks the value of `ch` and calls corresponding functions (`dispatch_govt()`, `dispatch_far()`, etc.) for valid options (1-4). If `ch` is invalid, it prints an error message. Its main task is to route control to appropriate ... | def dispatch(ch):
"""
Function that maps helper functions to option entered
"""
if(ch == 1):
dispatch_govt()
elif(ch == 2):
dispatch_far()
elif(ch == 3):
dispatch_sup()
elif(ch == 4):
dispatch_lab()
else:
print("Error: Invalid Option") |
def __prepare_df(self, policy: InvalidParameterCombinationRenderPolicy) -> pd.DataFrame:
match policy:
case InvalidParameterCombinationRenderPolicy.omit:
# Filter values corresponding to ErrInvalidParameterCombination params
return self.__df[self.__df.invalid_paramete... | The main task of the code is to render multiple heatmaps using specified interpolation methods. It prepares a dataframe, iterates through interpolation techniques (currently only 'hamming'), and generates pairwise heatmaps and matrix heatmaps for each method, printing progress updates. The function leverages configurat... | def heatmaps(self):
"""
Renders multiple heatmaps.
:return:
"""
df = self.__prepare_df(policy=self.__config.plot.heatmap_render_policy)
# NOTE: one can pass a particular set of interpolation methods,
# but honestly I can't see any significant difference between ... |
def navigation(intent_request):
webpage = try_ex(lambda: intent_request['currentIntent']['slots']['webpage'])
NAVIGATION_URL = get_navigation_link(webpage.lower())
if NAVIGATION_URL:
fulfillmentState = 'Fulfilled'
message = f'Copy paste the link below in your browser to navigate to... | The code routes user intents based on login status. If unauthenticated, it handles `Navigation` and `RoomAvailability` intents or prompts login. If authenticated, it directs requests to specific functions like `book_tour`, `order_meal`, or `book_room`. Unsupported intents trigger exceptions. Your return | def dispatch(intent_request):
user_id = intent_request['sessionAttributes']['userID']
print("User: ", user_id)
intent_name = intent_request['currentIntent']['name']
if not user_id:
if intent_name == 'Navigation':
return navigation(intent_request)
elif intent_name ==... |
def call(self, x, iter=2, training=False):
bs = tf.shape(x)[0]
m_output = self.mobile_net(x)
reg_output = self.reg_module(m_output, training)
if training:
reg_output = reg_output[iter]
beta = tf.slice(reg_output, tf.constant([ 0, 0 ]), tf.stack([ bs, 10 ]))
pose = tf.slice(reg_output, tf.c... | The code performs a training step for a neural network model, iterating over T steps to optimize parameters by computing gradients of a loss function (LOSS or LOSS2) against ground truth data. It updates model variables using an optimizer, applies regularization, and tracks the loss metric for monitoring training progr... | def train_step(self, data):
input, gt = data
for t in range(self.T):
with tf.GradientTape() as tape:
beta, pose, mesh, keypoints, scale = self.call(input, iter=t, training=True)
# This is the thing that takes our MANO template to the same shape as gt.
gt_scale = tf.sqrt(tf.reduc... |
def blend_shape(beta, S):
# we note that l is the number of beta parameters.
# v is the number of vertices in the MANO hand (778)
# t is the dimensionality of each vertex (3).
# b is the batch_size.
return tf.einsum('bl,vtl->bvt', beta, S)
def blend_pose(pose, P):
batch_size = tf.shape(pose)[0]
I = tf... | The code generates a 3D mesh and joint positions from shape (beta) and pose parameters. It blends shape and pose deformations, applies linear blend skinning (lbs) to compute posed joints and mesh, adds fingertips via index gathering, remaps joints to RHD convention, and returns the final mesh and joint positions. | def call(self, beta, pose, training=False):
T_shaped = self.T_bar + blend_shape(beta, self.S)
B_p = blend_pose(pose, self.P)
posed_joints, posed_mesh = lbs(pose, self.J, self.K, self.W, T_shaped, B_p)
# Add fingertips and remap to RHD convention.
indices = [745, 333, 444, 555, 672]
fingertips ... |
def random_move(self, grid: np.ndarray) -> Tuple[int, int]:
"""Chose a random move from the available options."""
avail: List[Tuple[int, int]] = self.empty(grid)
return avail[random.randint(0, len(avail) - 1)]
def win(self, grid: np.ndarray, val: Optional[int] = None) -> List[Tuple[int, int]]:
... | The code implements a decision-making strategy for selecting the optimal move in a game (likely Tic-Tac-Toe) by prioritizing actions in a hierarchical order: first attempting to win, then blocking the opponent's win, creating forks, blocking forks, and defaulting to center, corner, or side moves. With probability `1-se... | def act(self, grid: np.ndarray) -> Tuple[int, int]:
"""Goes through a hierarchy of moves, making the best move that is currently available each
time (with probability 1-self.epsilon).
A tuple is returned that represents (row, col).
"""
# whether move in random or not
if ... |
def safeRotate(self, direction, rotations):
if rotations <= 0:
return 0
# First check if the rotations are expected to make the robot turn more than 180 degrees:
rotations = rotations % (2 * self.one80Rotations) # strip full turns
if rotations > self.one80Rotations:
... | The `randomStep` function performs a random rotation (between -0.6 and 0.6) and checks for collisions via `safeRotate`. If no collision occurs, it moves forward by a random distance (0.5–2.0 units); otherwise, it retreats backward by 0.20 units to avoid obstacles. The task combines random directional adjustments with c... | def randomStep(self):
# random rotation in direction
rot = random.randint(-6, 6) / 10
#print(rot)
result = self.safeRotate(rot, abs(rot))
#print("saferotate result: " + str(result))
if result == 1:
# random forward unless collision
dr = ra... |
def update_vertical_lines(self):
start_index = -int(self.V_NB_LINES/2)+1
for i in range(start_index, start_index+self.V_NB_LINES):
line_x = self.get_line_x_from_index(i)
x1, y1 = self.transform(line_x, 0)
x2, y2 = self.transform(line_x, self.height)
self... | This code updates a game's state by adjusting vertical and horizontal lines, tiles, and ship positions. It calculates movement based on time, manages scoring, and checks for collisions. If the game isn't over, it updates offsets, increases speed, and triggers game-over logic when collisions occur, displaying a restart ... | def update(self, dt):
time_factor = dt*60
self.update_vertical_lines()
self.update_horizontal_lines()
self.update_tile()
self.update_ship()
if not self.state_gameover and self.state_game_started:
#To get a consistant game on every machine with different game ... |
def length(self):
size = 0
pointer = self._head
while pointer != None:
pointer = pointer._next
size += 1
return size
def get_current(self):
if self.length() == 0: #If list empty, reset current to None.
self._current = None
return s... | This method removes the current track from a doubly linked playlist. It handles edge cases by updating head/tail pointers when deleting the first/last node, otherwise adjusts adjacent nodes' pointers. It also nullifies the deleted node's links and prints an error if the playlist is already empty. | def remove_current(self):
if self.length() != 0:
del_track = self.get_current()
#del_track.timesplayed = 0 Wasn't sure if you wanted to reset timesplayed to 0 if deleted from playlist
self.next_track()
if del_track == self._head:
if del_tr... |
def _board_is_full(board):
"""
Returns True if all positions in given board are occupied.
:param board: Game board.
"""
return all(['-' not in row for row in board])
def _position_is_valid(position):
"""
Checks if given position is a valid. To consider a position as valid, it
must be a ... | This function handles a player's move in a game by validating the move's legality, updating the game board, checking for a win or tie, and switching the player's turn if the game continues. | def move(game, player, position):
"""
Performs a player movement in the game. Must ensure all the pre requisites
checks before the actual movement is done.
After registering the movement it must check if the game is over.
"""
# check if game is already over
if game['winner'] or _board_is_ful... |
def initialize_with_zeros(dimension):
"""
his function initializes the weights and bias for a given dimension of the model with zeros.
:param dimension: An integer which is the dimension of the model.
:return: A dictionary containing the keys 'w' and 'b' with values of the weights and bias respectively... | The code trains a logistic regression model using gradient descent on provided training data, evaluates its performance on both training and test datasets, and returns the learned parameters (weights and bias), prediction results, cost history, and hyperparameters. It calculates and prints accuracy metrics for both dat... | def model(X_train, Y_train, X_test, Y_test, iterations_number=2000, learning_rate=0.5, print_cost=False):
"""
Trains a logistic regression model on given data and returns the final results.
:param X_train: An np.array which is the input training data
:param Y_train: An np.array which is the output trai... |
def init_model(resume_from_checkpoint=None, backbone='resnet'):
# load transforms
normalize = transforms.Normalize(
mean=[0.5], std=[0.5]
)
input_transform = transforms.Compose([
transforms.Resize(224),
transforms.ToTensor(),
normalize,
])
if backbone == 'resnet5... | This code initializes a model for embedding-based retrieval, setting up a neural network (e.g., MobileNet) with specified weights, configuring device placement (GPU/CPU), and generating or loading embeddings from a directory. It ensures embedding files exist by creating them if necessary, then reads precomputed embeddi... | def __init__(self, backbone='mobilenet', weights='', embeddings_dir='', library_dir='', today_menu_idx=None,
dist='l2'):
self.model, self.transforms = init_model(backbone=backbone, resume_from_checkpoint=weights)
self.device = torch.device('cuda:0') if torch.cuda.is_available() else tor... |
def _spectrum(self, a):
return np.power(np.abs(np.fft.rfft(a, norm=self.norm)), 2.0)
def gain(self, reference):
assert (
reference.size == self.frame_size
), f"input frame size different the specified upon construction"
assert len(reference.shape) == 1, f"only support for one... | This function computes a detectability metric between reference and test signals by calculating their spectral differences, applying gain normalization if enabled, and using masker power arrays to determine the detectability. It validates input size and dimensionality, then returns a squared norm or detectability value... | def frame(self, reference, test):
assert (
reference.size == self.frame_size and test.size == self.frame_size
), f"input frame size different the specified upon construction"
assert (
len(reference.shape) == 1 and len(test.shape) == 1
), f"only support for one-dim... |
def _input_fn(file_pattern: List[Text],
tf_transform_output: tft.TFTransformOutput,
batch_size: int = 200) -> tf.data.Dataset:
"""Generates features and label for tuning/training.
Args:
file_pattern: List of paths or patterns of input tfrecord files.
tf_transform_output: A TFTra... | The main task of the code is to train a machine learning model using TensorFlow, leveraging hyperparameters from `fn_args` or defaults. It processes training/evaluation data with TF Transform, configures distributed training via MirroredStrategy, builds a Keras model, trains it with TensorBoard logging, and saves the m... | def run_fn(fn_args: TrainerFnArgs):
"""Train the model based on given args.
Args:
fn_args: Holds args used to train the model as name/value pairs.
"""
tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)
train_dataset = _input_fn(fn_args.train_files, tf_transform_output, 40)
eval_data... |
def dVdt(V, t, kk):
if V > 0:
return kk * sqrt(V)
else:
return 0
def k(D):
a = 0.98
b = 0.63
g = 9.81
pp = 1
return -a*b*D*sqrt((2*g)/pp)
def Fin(VA, VB, TB, t, c):
return abs(fVA(VA, VB, TB, t, c)) + c.FRate | The function `fVB` computes the total rate of change of a variable `VB` by summing two components: (1) the derivative `dVdt` of `VB` with respect to time `t`, modulated by a parameter `k(c.DB)`, and (2) an inflow term `Fin` dependent on `VA`, `VB`, `TB`, `t`, and parameters `c`. It models dynamic interactions between v... | def fVB(VA, VB, TB, t, c):
return dVdt(VB, t, k(c.DB)) + Fin(VA, VB, TB, t, c) |
def normalize(np_instances, number_of_instances, number_of_features):
# find mean of all columns, then delete first column because that is the class label
# axis=0 means collapse data by column, so if taking mean, it means go to your data and squish it to make it one row
arr = np.mean(np_instances, axis=0)
... | The main task of the code is to perform feature selection using either forward selection or backward elimination on a dataset. It reads and normalizes input data, evaluates accuracy with leave-one-out cross-validation, and applies the chosen algorithm to identify optimal feature subsets for classification. | def main():
print("Welcome to Phillip Nguyen's Feature Selection Algorithm.")
file_name = input("Type in the name of the file to test: ")
# used to make sure user enters in a valid data file
# source: python docs
try:
file = open(file_name, "r")
except IOError:
raise IOError("In... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.