dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def address(data, position:int):
return data[position]
def returnTo(data:str, location:str = 'TER'):
if location == 'TER':
print(data)
elif location == 'CLIP':
pyperclip.copy(data)
else:
print("Invalid location")
def getIP(auth:str):
if len(auth.split('›')) > 2:
retur... | The main task of the code is to process user commands in a shell-like interface, executing actions like directory navigation, file operations, system info retrieval, and script execution. It categorizes commands into three groups (basic, argument-based, and two-argument commands), validates inputs, handles errors for i... | def mainLoop(key:int):
global selectedDir, shCommands
commands = ('sdir', 'ip', 'user', 'kernel', 'help', 'sd','clear','ldir','udir','crash')
commandsArg = ('cdir', 'echo', 'run', 'qkrun','open', 'touch')
commandsArg2 = ('return',)
enteredInput = input(">>>")
if len(enteredInput) < 2 :
r... |
def get_or_create_tag_template(values):
response = get_tag_template(values)
if response == None:
return create_tag_template(values)
else:
return response
def get_entries(values):
project_id = values.get("project_id")
entry_group_id = values.get("entry_group_id")
location = values... | The main task of the code is to process entries tagged as "table" by applying a predefined tag template. It retrieves entries, filters those with user-specified type "table," and generates corresponding tags using the template. The function does not return any value, focusing instead on modifying entries with table-spe... | def tag_entry_group_tables(values):
tag_template = get_or_create_tag_template(values)
entries = get_entries(values)
for entry in entries:
if entry.user_specified_type == "table":
process_table_tags(entry, values, tag_template.name)
return None |
def fit(self, X, Y, q=None):
if hasattr(self, "phi_X"):
tasklogger.log_info("Using precomputed diffusion coordinates.")
else:
tasklogger.log_start("diffusion coordinates")
if q is None:
with parallel.ParallelQueue(n_jobs=min(2, self.n_jobs)) as q:
... | The main task of the code is to perform harmonic alignment of two input datasets X and Y using spectral methods. It combines Laplacian eigenvectors/eigenvalues, constructs a wavelet transform in the spectral domain, merges eigensystems, and builds a joint diffusion map via a graph Laplacian to align the datasets in a s... | def align(self, X, Y, phi_X=None, phi_Y=None, lambda_X=None, lambda_Y=None):
"""Harmonic alignment
Parameters
----------
X : array-like, shape=[n_samples, n_features]
Input dataset
Y : array-like, shape=[m_samples, n_features]
Input dataset
phi_{X... |
def get_node(area, char):
dest = np.where(area == char)
return index_to_node(len(area[0]), int(dest[0]), int(dest[1]))
def get_neighbour_edges(x, y, area):
edges = []
current_node = index_to_node(len(area[0]), y, x)
current_value = char_to_index(area[y][x])
if x > 0 and char_to_index(area[y][x ... | The code reads a grid from a file, constructs a directed graph of adjacent cells, and computes the shortest path from a start node ('S') to an end node ('E'). Part 1 outputs the path length (minus one). Part 2 identifies all valid starting nodes, calculates their shortest paths to 'E', and prints the minimum path lengt... | def main():
area = np.genfromtxt("test.txt", delimiter=1, dtype=str)
start = get_node(area, "S")
dest = get_node(area, "E")
graph = nx.Graph().to_directed()
for index_y, line in enumerate(area):
for index_x, cell in enumerate(line):
edges = get_neighbour_edges(index_x, index_y, a... |
def clanInfo(clanTag):
url = f'https://api.clashofclans.com/v1/clans/%23{clanTag}'
response = requests.get(url, headers=headers)
data = response.json()
x = caseChange(data)
with open('1 Clan Information Data.txt', 'w', encoding='utf-8') as file:
file.write(f"{' ' * 30} Clan Information Data\... | The code allows users to retrieve specific clan information by selecting options: Clan details, members, war status, or capital details, using a provided clan tag. It loops until the user chooses to return. | def clanData():
clanTag = input('Enter clan tag: ').upper().strip()
while True:
x = int(input('\nEnter 1 for Clan Information\nEnter 2 for Clan Members Information\nEnter 2 for Current War Status\nEnter 4 for Clan Capital Details\nEnter 0 to return: '))
match x:
case 1:
... |
def playerData(player_data):
x = 0
pd = {}
for key in player_data:
pd[key] = player_data[key]
#print(f"{key}: {player_data[key]}")
x += 1
if x == 17:
break
newPlayerData = caseChange(pd)
with open('1 Player Data.txt', 'w') as file:
file.write(f"{' ... | The main task of the code is to retrieve Clash of Clans player data from an API using a player tag, then allow users to select and view specific data categories (player, troop, hero, spell, etc.) by entering numeric options. It handles API requests, validates inputs, and delegates data display to separate functions bas... | def playerdata():
playerTag = input("Enter player tag: ").upper().strip()
# Form the API endpoint URL
url = f"https://api.clashofclans.com/v1/players/%23{playerTag}"
# Make the API request
response = requests.get(url, headers=headers)
# Check if the request was successful (status code 200)
... |
def getConfig( self ):
"""Read the configuration and return it"""
cf = self.getConfigFile()
cp = configparser.ConfigParser()
# Set some defaults
cp['general'] = {
'geometry': "250x400",
'numbersize': 12,
'buttonsize': 10,
... | This code initializes a Tkinter GUI for a calculator application (PyRPN). It sets up the main window, configures layout and geometry, creates fonts, widgets, bindings, and initializes calculation functionality. It also handles window closure and sets a custom icon. | def __init__( self, calc, master=None):
tk.Frame.__init__( self, master, relief='sunken' )
self.config = self.getConfig()
self.master.title( 'PyRPN' )
self.shifted = False
self.shiftLock = False
self.layout = None
self.buttons = None
top = self.winfo_top... |
def move_has_disk_to_flip(self, move, player_number):
content_of_move_cell = self.board[move[0]][move[1]]
if move != () and self.coord_is_valid(move[0], move[1]) \
and content_of_move_cell == None:
for direction in POSSIBLE_MOVE_DIRECTIONS:
has_disk_to_flip = sel... | This function processes a player's move in a board game (e.g., Reversi/Othello). It validates the move, places the current player's disk on the board, increments their disk count, flips opponent's disks as required, and records the move. | def make_move(self, move):
if self.move_has_disk_to_flip(move, self.current_player):
# Put current player color on the current move cell
self.board[move[0]][move[1]] = self.current_player
# Adds 1 disk to the current players disk count
self.num_disks_dictionary[se... |
def copy_board_cell_states(self):
board_cell_states = [[None for _ in range(8)] for _ in range(8)]
rows_array = range(0, self.board.nrows, 1)
cols_array = range(0, self.board.ncols, 1)
for row in rows_array:
for col in cols_array:
board_cell_states[row][col] =... | The function evaluates the potential score of a given move in a board game (likely Othello/Reversi) by temporarily applying the move, calculating the resulting board state's score, then reverting the move to maintain the original game state. It returns the computed score for the move without altering the actual game pr... | def evaluate_move_greedy(self, move):
original_number_of_disks_AI_player = self.num_disks_dictionary[2]
original_board = self.copy_board_cell_states()
# Make the move in the board (including flips) temporarily to simulate the move
self.make_move(move)
after_move_board = self.c... |
def copy_board_cell_states(self):
board_cell_states = [[None for _ in range(8)] for _ in range(8)]
rows_array = range(0, self.board.nrows, 1)
cols_array = range(0, self.board.ncols, 1)
for row in rows_array:
for col in cols_array:
board_cell_states[row][col] =... | This function evaluates a move using the minimax algorithm with a specified depth limit. It simulates making a move, calculates its score based on the board state, and recursively explores subsequent moves by alternating between AI and opponent turns. The score is adjusted by recursively evaluating all potential future... | def evaluate_move_minimax(self, move, current_depth=0, max_depth=3):
original_number_of_disks_AI_player = self.num_disks_dictionary[2]
original_board = self.copy_board_cell_states()
# Make the move in the board (including flips) temporarily to simulate the move
self.make_move(move)
... |
def current_player_can_move(self):
return self.player_can_move(self.current_player)
def move_has_disk_to_flip(self, move, player_number):
content_of_move_cell = self.board[move[0]][move[1]]
if move != () and self.coord_is_valid(move[0], move[1]) \
and content_of_move_cell =... | This method handles a human player's move in a turn-based game. It validates the move, updates the board if legal, checks for game end, switches to the AI player, and triggers a timer for the AI's turn. | def play_as_human_player(self, btn, r, c):
'''
Arguments:
btn: Mouse button clicked
r, c are the row/column coordinates where the user clicked on the board.
'''
# Indicate that the game is processing the user's input
self.boar... |
def get_possible_moves_by_current_player(self):
rows_array = range(0, self.board.nrows, 1)
cols_array = range(0, self.board.ncols, 1)
allowed_moves_list = []
for row in rows_array:
for col in cols_array:
# Move to check and append if valid
... | The function determines the best move for the current player by evaluating all possible moves using either a greedy algorithm (for medium difficulty) or minimax (for hard difficulty), selecting the move with the highest score, and executing it if valid. | def make_best_move_by_current_player(self):
best_score = float('-inf')
best_move = None
# Get all possible moves for the AI player
possible_moves = self.get_possible_moves_by_current_player()
# Evaluate each move using the random, greedy or minimax function/... |
def current_player_can_move(self):
return self.player_can_move(self.current_player)
def make_random_move_by_current_player(self):
# Makes a random possible move on the board.
possible_moves = self.get_possible_moves_by_current_player()
if possible_moves:
self.current... | This function handles the AI computer player's turn by disabling the timer, updating the cursor, and selecting moves based on difficulty (random for easy, optimal for medium/hard). It repeatedly plays until the game ends or the human player can move again, ensuring continuous AI play when the human has no valid moves. | def play_as_ai_computer_player(self):
# Disable the Timer to prevent re-triggering
self.board.stop_timer()
# Set the cursor to indicate AI is processing
self.board.cursor = "wait"
# AI's turn to play
# if human player cannot move and is not game over the comput... |
def load_network():
print("Loading network...")
return np.load(FILE_PATH, allow_pickle=True)
def gradient_descent(X, Y, iterations, layers=None, Weights=None, Biases=None):
if iterations < 1:
return
# Train the network using gradient descent
if layers is None:
layers = [784, 6, 6, 6... | The main task of the code is to train a neural network by either loading pre-existing weights/biases or initializing them, performing gradient descent on training data for a specified number of iterations, and optionally saving the trained weights/biases to a file. The function returns the final trained weights and bia... | def train():
Weights, Biases = [None] * 2
if LOAD_FILE:
data = load_network()
Weights, Biases = data[0], data[1]
Weights, Biases = gradient_descent(TRAINING_DATA, TRAINING_LABELS, TRAINING_ITERATIONS, layers=LAYERS,
Weights=Weights, Biases=Biases)
... |
def get_map_size(initial):
map_size = 0
for i in range(len(initial["map"])):
for j in range(len(initial["map"][0])):
if initial["map"][i][j] != "I":
map_size += 1
return map_size
def guess_num_states(initial):
pass_dict_count = {}
taxis_num = len(initial["taxis"])
num = get_map_size(initial) ** taxis_num... | This code initializes an agent for a taxi problem by selecting an optimal policy. If the state space is small, it directly computes the optimal policy. For larger states, it heuristically evaluates subsets of taxis/passengers, runs simulations, and selects the configuration with the highest value. The agent then stores... | def __init__(self, initial):
t0 = time.time()
self.T = initial["turns to go"]
map_size = get_map_size(initial)
states_count_guess, pass_dict_count = guess_num_states(initial)
#print(states_count_guess)
if states_count_guess < 50000:
opt = OptimalTaxiAgent(initial)
self.map = initial["map"]
self.bes... |
def get_best_child(self, parent, check_legal=False):
most_tries = -1
best_action = best_node = None
for action, node in parent.childs.items():
# if it is used to take an action, we need to make sure it's legal.
if node is not None and node.tries > most_tries and \
(not check_legal or self.check_it(acti... | This code trains a decision tree using Monte Carlo Tree Search (MCTS) by iteratively performing selection, expansion, simulation, and backpropagation. It runs for a specified number of rounds, managing time limits and printing progress. Each iteration expands nodes, simulates outcomes with multiple rollouts, and update... | def train_tree(self, rounds, number_of_rollouts, turns=200, timelimit=58):
start = time.time()
fails = total_count = t = 0
while t < rounds / number_of_rollouts:
if (total_count + 1) % (50 // number_of_rollouts) == 0 and time.time() - start > timelimit:
break
if (total_count + 1) % (100 // number_of_rol... |
def delete_impossible_actions(self, node):
for action in list(node.childs.keys()):
if not check_if_legal(self.sim, action, self.player_number):
del node.childs[action]
node.unborn_childs -= 1
def train_tree(self, rounds, number_of_rollouts, turns=200, timelimit=58):
start = time.time()
fails = total_co... | This code initializes a game-playing AI agent using Monte Carlo Tree Search (MCTS). It sets up the game state, player number, and search tree with a root node. The agent trains the tree through multiple rounds of simulations, pruning invalid moves for player 1. It then selects the optimal action by traversing the tree,... | def __init__(self, initial_state, player_number):
self.ids = IDS
self.player_number = player_number
self.initial_state = copy.deepcopy(initial_state)
self.current_game_state = initial_state
self.root = Node(None, initial_state, player_number)
self.sim = Simulator(initial_state)
self.enemy = None
if self... |
def delete_impossible_actions(self, node):
for action in list(node.childs.keys()):
if not check_if_legal(self.sim, action, self.player_number):
del node.childs[action]
node.unborn_childs -= 1
def train_tree(self, rounds, number_of_rollouts, turns=200, timelimit=58):
start = time.time()
fails = total_co... | The code performs decision-making in a game using Monte Carlo Tree Search (MCTS). It updates the game state, prunes invalid actions, trains the MCTS tree with 250 rounds, 4 rollouts, and 40 turns, then selects the best child node as the next action. It measures execution time and returns the chosen action for gameplay. | def act(self, state):
start = time.time()
self.current_game_state = state
self.sim = Simulator(state)
# deleting actions that are not possible because of opponent's movements.
self.delete_impossible_actions(self.root)
rounds = 250
number_of_rollouts = 4
turns = 40
self.train_tree(rounds, number_of_ro... |
def _update_for_self_modifying_sku_offers(count_of_skus):
"""Calculate and update all self-modifying offers."""
for sku_dictionary in SKU_OFFER_TYPES["self_modifying"]:
number_of_sku = count_of_skus[sku_dictionary["sku"]]
sku_dictionary.update({"number_of_sku": number_of_sku, "count_of_skus": co... | The function calculates the total cost of given skus by applying various discount offers, validating input as a string with valid characters, and ensuring all characters are accounted for. It adjusts counts for offers like self-modifying, secondary, multiple, and mix-and-match discounts before computing the final total... | def checkout(skus):
"""
Function to calculate total value for skus provided.
"""
if not isinstance(skus, str):
return -1
# Check length of string, then do count for each candidate letter to get subtotals and total
# if total is different then an incorrect character is presen... |
def project_z(r, x, y):
"""Project an x,y pair onto a sphere of radius r OR a hyperbolic sheet
if we are away from the center of the sphere.
"""
d = math.sqrt(x*x + y*y)
if (d < r * 0.70710678118654752440): # Inside sphere
z = math.sqrt(r*r - d*d)
else: ... | This function simulates a deformed trackball by projecting normalized mouse coordinates onto a virtual sphere, computes the rotation axis via the cross product of previous and current points, calculates the rotation angle using their distance, and returns a quaternion representing the rotation. It handles edge cases fo... | def _rotate(self, norm_mouse_x, norm_mouse_y):
"""Pass the x and y coordinates of the last and current positions of
the mouse, scaled so they are in the range [-1.0,1.0].
Simulate a track-ball. Project the points onto the virtual
trackball, then figure out the axis of rotation... |
def _rotate(self, norm_mouse_x, norm_mouse_y):
"""Pass the x and y coordinates of the last and current positions of
the mouse, scaled so they are in the range [-1.0,1.0].
Simulate a track-ball. Project the points onto the virtual
trackball, then figure out the axis of rotation... | This function handles mouse input for trackball rotation. When dragging, it converts normalized mouse coordinates to a rotation quaternion, accumulates rotations, normalizes the quaternion periodically, updates the modelview matrix, and records the latest mouse position for subsequent movements. | def mouse_roll(self, norm_mouse_x, norm_mouse_y, dragging=True):
"""When you click or drag the primary mouse button, scale the mouse
x & y to the range [-1.0,1.0] and call this routine to roll the trackball
and update the modelview matrix.
The initial click should set dragging t... |
def _is_prime(capacity: int) -> bool:
"""
Determine if given integer is a prime number and return boolean
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
if capacity == 2 or capacity == 3:
return True
if capacity == 1 or capacity % 2 == 0:
return False
... | The main task of the code is to resize a hash table's capacity to a prime number, reinitialize the table structure, and rehash all existing key-value pairs into the new capacity. It ensures the new capacity is prime, preserves old data, rebuilds the table with new linked lists, and redistributes entries via rehashing t... | def resize_table(self, newCapacity: int) -> None:
"""
Updates the capacity of the table and rehashes all existing key value pairs.
:param new_capacity: The new capacity of the table.
"""
if newCapacity < 1:
return
# Set new capacity to next prime if not prime... |
def ratio_to_region(ratio, p, low_gamma):
high_gamma = higher_shock(p, low_gamma)
m_b = (2 * high_gamma / (2 * high_gamma - 1)) ** 2
m_c = (1 / p) * (2 * high_gamma / (2 * high_gamma - low_gamma)) ** 2
if (ratio >= 1) and (ratio < m_b):
region = 1
elif (ratio >= m_b) and (ratio < min(m_c, 4)... | This function computes and returns optimal utility values, expected outcomes, and ranges for donor and NPO interactions under varying gamma parameters. It evaluates both perfect rational framework (pfr) and transfer framework (tf) scenarios, calculating utility maximization across probability distributions, budget cons... | def plots_with_gamma_l(gamma=np.linspace(.01, .05, 3), prob_vector=prob, low_eta=eta_l, high_eta=eta_h,
donor_budget=budget,
npo_delta=delta, market_beta=beta, donor_alpha=alpha, npo_theta=theta, num=iter):
donor_pfr_optimal_dict = {}
donor_pfr_yt_dict = {}
y_pf... |
def ratio_to_region(ratio, p, low_gamma):
high_gamma = higher_shock(p, low_gamma)
m_b = (2 * high_gamma / (2 * high_gamma - 1)) ** 2
m_c = (1 / p) * (2 * high_gamma / (2 * high_gamma - low_gamma)) ** 2
if (ratio >= 1) and (ratio < m_b):
region = 1
elif (ratio >= m_b) and (ratio < min(m_c, 4)... | The function computes optimal donor and non-profit utilities under varying probabilities and theta values. It iterates over theta_vector and prob_vector, calculating utility maxima for donor and NPO outcomes using ratio-based region assignments and y-value optimization. Results include optimal utilities, expected outpu... | def plots_with_theta(theta_vector, prob_vector, low_eta, high_eta,
donor_budget,
npo_delta, market_beta, donor_alpha, low_gamma, num=iter):
donor_pfr_optimal_dict = {}
donor_pfr_yt_dict = {}
u_d_tf_optimal_dict = {}
y_pfr_optimal_dict = {}
y_tf_optimal_dict ... |
def ratio_to_region(ratio, p, low_gamma):
high_gamma = higher_shock(p, low_gamma)
m_b = (2 * high_gamma / (2 * high_gamma - 1)) ** 2
m_c = (1 / p) * (2 * high_gamma / (2 * high_gamma - low_gamma)) ** 2
if (ratio >= 1) and (ratio < m_b):
region = 1
elif (ratio >= m_b) and (ratio < min(m_c, 4)... | The code computes optimal donor and non-profit utilities, expected outcomes, and ranges for varying alpha and probability values, returning dictionaries of results for analysis or plotting. It iterates over alpha and probability vectors, calculating optimal values using utility functions and storing them for comparison... | def plots_with_alpha(alpha_vector, prob_vector=prob, low_eta=eta_l, high_eta=eta_h,
donor_budget=budget,
npo_delta=delta, market_beta=beta, npo_theta=theta, low_gamma=gamma_l, num=iter):
donor_pfr_optimal_dict = {}
donor_pfr_yt_dict = {}
u_d_tf_optimal_dict = {}
... |
def ratio_to_region(ratio, p, low_gamma):
high_gamma = higher_shock(p, low_gamma)
m_b = (2 * high_gamma / (2 * high_gamma - 1)) ** 2
m_c = (1 / p) * (2 * high_gamma / (2 * high_gamma - low_gamma)) ** 2
if (ratio >= 1) and (ratio < m_b):
region = 1
elif (ratio >= m_b) and (ratio < min(m_c, 4)... | The function computes and returns optimal donor and non-profit utility values, expected outputs, and ranges for different parameters (eta and p) under two models (PFR and TF). It iterates over eta_vector and prob_vector, calculating utilities, optimal outcomes, and regions for each combination, storing results in dicti... | def plots_with_eta(eta_vector, prob_vector=prob, high_eta=eta_h, donor_alpha=alpha,
donor_budget=budget,
npo_delta=delta, market_beta=beta, npo_theta=theta, low_gamma=gamma_l, num=iter):
donor_pfr_optimal_dict = {}
donor_pfr_yt_dict = {}
u_d_tf_optimal_dict = {}
y_p... |
def ratio_to_region(ratio, p, low_gamma):
high_gamma = higher_shock(p, low_gamma)
m_b = (2 * high_gamma / (2 * high_gamma - 1)) ** 2
m_c = (1 / p) * (2 * high_gamma / (2 * high_gamma - low_gamma)) ** 2
if (ratio >= 1) and (ratio < m_b):
region = 1
elif (ratio >= m_b) and (ratio < min(m_c, 4)... | The code computes optimal donor and non-profit utilities, expected outputs, and ranges under varying beta and probability scenarios. It iterates through beta values, calculates utility functions for different probabilities, determines optimal yt values, and stores results in dictionaries for analysis or plotting. | def plots_with_beta(beta_vector, prob_vector=prob, low_eta=eta_l, high_eta=eta_h,
donor_alpha=alpha,
donor_budget=budget,
npo_delta=delta, npo_theta=theta, low_gamma=gamma_l, num=iter):
donor_pfr_optimal_dict = {}
donor_pfr_yt_dict = {}
u_d_tf_opti... |
def eta_bar(npo_theta, low_eta, high_eta=eta_h):
return npo_theta * low_eta + (1 - npo_theta) * high_eta
def plots_with_gamma_l(gamma=np.linspace(.01, .05, 3), prob_vector=prob, low_eta=eta_l, high_eta=eta_h,
donor_budget=budget,
npo_delta=delta, market_beta=beta, donor... | The main task of the code is to generate and save plots analyzing donor and NPO utility functions, resource allocation ranges (y-values), and optimal strategies under varying gamma parameters. It validates input parameters, computes optimal solutions using helper functions, and iterates through gamma values to create v... | def plot_graphs_gamma():
if 2 * eta_bar(theta, eta_l, eta_h) < alpha or (delta * beta < eta_h) \
or alpha > delta / (math.sqrt(delta * beta / eta_h) - 1):
print('Error : Parameters out of domain values')
else:
donor_pfr_optimal_dict, u_d_tf_optimal_dict, y_pfr_optimal_dict, y_tf_opti... |
def eta_bar(npo_theta, low_eta, high_eta=eta_h):
return npo_theta * low_eta + (1 - npo_theta) * high_eta
def plots_with_theta(theta_vector, prob_vector, low_eta, high_eta,
donor_budget,
npo_delta, market_beta, donor_alpha, low_gamma, num=iter):
donor_pfr_optimal_dict = ... | The main task of the code is to generate and save plots analyzing donor and NPO utility functions and output ranges under varying theta values and alpha_local parameters. It first validates input parameters, computes optimal solutions for different theta scenarios, calculates y-axis limits, and then creates and exports... | def plot_graphs_theta(alpha_local):
if 2 * eta_bar(theta, eta_l, eta_h) < alpha_local or (delta * beta < eta_h) \
or alpha_local > delta / (math.sqrt(delta * beta / eta_h) - 1):
print('Error : Parameters out of domain values')
else:
donor_pfr_optimal_dict, u_d_tf_optimal_dict, y_pfr_... |
def eta_bar(npo_theta, low_eta, high_eta=eta_h):
return npo_theta * low_eta + (1 - npo_theta) * high_eta
def plots_with_alpha(alpha_vector, prob_vector=prob, low_eta=eta_l, high_eta=eta_h,
donor_budget=budget,
npo_delta=delta, market_beta=beta, npo_theta=theta, low_gamma=ga... | The function generates and saves multiple plots (donor utility, y-values, NPO utility) for varying alpha values, validating parameters first. It processes optimal solutions from `plots_with_alpha`, computes utility ranges, and exports figures as PDFs with labels like "figure7a.pdf" etc., distinguishing between low/high... | def plot_graphs_alpha(alpha_vector):
if 2 * eta_bar(theta, eta_l, eta_h) < alpha or (delta * beta < eta_h) \
or alpha > delta / (math.sqrt(delta * beta / eta_h) - 1):
print('Error : Parameters out of domain values')
else:
donor_pfr_optimal_dict, u_d_tf_optimal_dict, y_pfr_optimal_dic... |
def eta_bar(npo_theta, low_eta, high_eta=eta_h):
return npo_theta * low_eta + (1 - npo_theta) * high_eta
def plots_with_eta(eta_vector, prob_vector=prob, high_eta=eta_h, donor_alpha=alpha,
donor_budget=budget,
npo_delta=delta, market_beta=beta, npo_theta=theta, low_gamma=gamma_... | The main task of the code is to generate and save plots (donor utility, y-values, and NPO utility) for varying η values, after validating parameter domains. It computes optimal solutions using helper functions, determines plot limits, and exports figures as PDFs with specific naming conventions. | def plot_graphs_eta(eta_vector=np.linspace(.25, .75, 3)):
if 2 * eta_bar(theta, eta_vector[0], eta_h) < alpha or (delta * beta < eta_h) \
or alpha > delta / (math.sqrt(delta * beta / eta_h) - 1):
print('Error : Parameters out of domain values')
else:
donor_pfr_optimal_dict, u_d_tf_op... |
def eta_bar(npo_theta, low_eta, high_eta=eta_h):
return npo_theta * low_eta + (1 - npo_theta) * high_eta
def plots_with_beta(beta_vector, prob_vector=prob, low_eta=eta_l, high_eta=eta_h,
donor_alpha=alpha,
donor_budget=budget,
npo_delta=delta, npo_theta=th... | The main task of the code is to generate and save multiple plots (e.g., donor utility, y-values, and NPO utility) for different beta values in a specified range. It first validates input parameters to ensure they are within acceptable domains, computes optimal solutions using helper functions, determines plot limits, a... | def plot_graphs_beta(beta_vector=np.linspace(1.25, 1.75, 3)):
if 2 * eta_bar(theta, eta_l, eta_h) < alpha or (delta * beta_vector[0] < eta_h) \
or alpha > delta / (math.sqrt(delta * beta_vector[0] / eta_h) - 1):
print('Error : Parameters out of domain values')
else:
donor_pfr_optimal... |
def improved_k_key_generation(k,l):
"""Generates a key pair in k bit for Lamport one-time signature."""
byte_num = int(l / 8)
private_key = [[os.urandom(32) for _ in range(k)] for _ in range(l)] # Each element is a pair of l-length k-bit strings
public_key = [[hash_message(private_key[i][j]) for j in r... | The code demonstrates the improved k-Lamport one-time signature scheme by generating keys, signing a message, and verifying authenticity. It tests both valid and fake signatures to showcase verification outcomes. The task involves key generation, signing, and verification processes for cryptographic validation. | def run_k_lamport_signature(k=4):
# Example usage of the improved k-Lamport one-time signature scheme
l = 16
message = b'I am a byte string' # 16-k-bit message in hexadecimal
# Key generation
private_key, public_key = improved_k_key_generation(k,l)
# Signing
signature = improved_k_sig... |
def write4bits(self, data):
self.expanderWrite(data)
self.pulseEnable(data)
def command(self, value):
self.send(value, 0)
def display(self):
self._displaycontrol |= LCD_DISPLAYON
self.command(LCD_DISPLAYCONTROL | self._displaycontrol)
def clear(self):
self.command(LCD_CLE... | This code initializes an LCD display by configuring I2C settings, setting display parameters like size and font, transitioning from 8-bit to 4-bit mode, enabling the display, clearing it, and setting text direction. It prepares the LCD for operation by executing standard initialization commands from the HD44780 datashe... | def __init__(self, bus=None, addr=0x27, cols=16, rows=2, charsize=LCD_5x8DOTS):
if bus==None: # linux systems have multiple i2c buses user has to select one
raise SyntaxError("missing i2c bus number")
self._bus = SMBus(bus)
self._addr = addr
self._cols = cols
self._ro... |
def Msgs(self):
self.Msg1 = 'Error: the stoichiometry is incompatible with the wyckoff sites choice'
self.Msg2 = 'Error: failed in the cycle of generating structures'
self.Msg3 = 'Warning: failed in the cycle of adding species'
self.Msg4 = 'Warning: failed in the cycle of choosing wyckof... | This code initializes a crystal structure generator by processing input molecules, symmetrizing and orienting them, calculating bounding boxes and radii, estimating unit cell volume, and preparing Wyckoff positions and orientations for crystal generation with specified space group and stoichiometry. | def __init__(self, sg, molecules, numMols, volume_factor, allow_inversion=False, orientations=None, check_atomic_distances=True):
#Necessary input
self.Msgs()
"""A list of warning messages to use during generation."""
numMols = np.array(numMols) #must convert it to np.array
... |
def Msgs(self):
self.Msg1 = 'Error: the stoichiometry is incompatible with the wyckoff sites choice'
self.Msg2 = 'Error: failed in the cycle of generating structures'
self.Msg3 = 'Warning: failed in the cycle of adding species'
self.Msg4 = 'Warning: failed in the cycle of choosing wyckof... | This code initializes a molecular crystal structure by processing input parameters such as molecule orientations, layer group, and volume factors. It symmetrizes molecules, calculates geometric properties (bounding boxes, radii), estimates unit cell volume, and prepares Wyckoff positions for crystal generation. The cla... | def __init__(self, number, molecules, numMols, thickness, volume_factor, allow_inversion=False, orientations=None, check_atomic_distances=True):
#Necessary input
self.Msgs()
"""A list of warning messages to use during generation."""
numMols = np.array(numMols) #must convert it t... |
def expand_person_name(author):
given_name = author['given']
if 'non-dropping-particle' in author:
particle = author['non-dropping-particle']
family_name = f"{particle} {author['family']}"
else:
family_name = author['family']
names = name_variants(family_name, given_name)
fam... | This function processes a multivalued 'author' field from a Bibtext entry by searching each author's name in the provided reference text. It generates position-based labels for matching names and raises an exception in strict mode if any author is not found. | def generate_author_labels(field_value: list[dict], string_reference: str, tag: str) -> list[list]:
"""
Specific processing of multivalued structured 'author' field
:param field_value: value of the Bibtext field
:param string_reference: full text reference
:param tag: tag name
:return:
"""
... |
def generate_author_labels(field_value: list[dict], string_reference: str, tag: str) -> list[list]:
"""
Specific processing of multivalued structured 'author' field
:param field_value: value of the Bibtext field
:param string_reference: full text reference
:param tag: tag name
:return:
"""
... | The function generates bibliographic labels based on the reference type and fields, using specific helper functions for authors, issuance dates, and default fields. It filters valid fields, skips unsupported ones, and returns a sorted list of labels for structured citations. | def generate_labels(chosen_bibliography: CitationStylesBibliography, string_reference: str,
structured_reference: citeproc.source.Reference) -> list:
print(f"Label generation whith style <{chosen_bibliography.style.root.base}>")
labels = []
for tag, field in LABELS.items():
if fi... |
def validate_years(years) -> bool:
"""Validates the input of the year to be an integer and between 2 - 8"""
try:
assert years.isnumeric(), "Year value must be numeric"
assert int(years) in range(2, 9), "Year number must be between 2 - 8"
return True
except AssertionError as msg:
... | The main task of the code is to generate and analyze random sales time series data over a user-specified number of years (2–8). It calculates monthly and quarterly sales summaries, computes changes relative to a base period, derives seasonal indices, and generates PDF reports containing these analyses for both monthly ... | def main():
years = input("Enter the number of years between 2 - 8 for analysis: ")
if validate_years(years):
YEARS: int = int(years)
sales: list[Sales] = random_time_series(YEARS)
sales_m: dict = sales_by_month(sales)
sales_q: dict = sales_by_qrt(sales)
change_m: di... |
def use_ability_fast(source,target,ability,log_mode):
'Function for source creature to use selected ability in fight with target if it is a valid fast ability'
if ability == None:
return
elif ability.speed == 'fast':
use_ability(source,target,ability,log_mode)
def log_hit(source,target,locat... | This function simulates a turn-based battle between two fighters, calculating hit probabilities based on their ratings, applying damage, and handling abilities. It iterates through rounds until one fighter is incapacitated, logging actions if enabled. The result is 0 for a draw, 1 for fighter_a's victory, or 2 for figh... | def run_solo_encounter(fighter_a,fighter_b,log_mode):
'Run a solo encounter between fighter_a and fighter_b and return 0 for a draw, 1 for a fighter_a win and 2 for a fighter_b win'
# Initialize round counter
round_count = 0
# Round Loops
while 1:
# Increment and Print Round tracker
... |
def _filter_by_ratio(input_masks):
masks = []
for m in input_masks:
ratio = m["bbox"][2] / m["bbox"][3]
if ratio > 1 and ratio < 3:
masks.append(m)
return masks
def _filter_by_shape(input_masks):
masks = []
for m in input_masks:
if m["bbox"][2] > m["bbox"][3]: # ... | The code filters input masks by applying ratio, shape, and area constraints, extracts features, removes masks outside defined boundaries, eliminates masks with dissimilar areas to reference masks, and removes duplicates, returning refined masks. | def filter_data(input_masks, image):
masks = input_masks
# Intial filters
masks = _filter_by_ratio(masks) # 1 < ratio < 3
masks = _filter_by_shape(masks) # width > height
masks = _filter_by_area(masks, image) # area < 0.01
# Extract features (x, y, width, height, ratio, rgb)
_extract_fe... |
def generate_bigram(trainf):
counts = defaultdict(lambda:0)
bicounts = defaultdict(lambda:defaultdict(lambda:0))
# this loops through all the data and stores counts
for line in trainf:
line = "# " + line.strip() + " #"
phons = re.split(r'[\s]+', line)
# removes the word orth... | The main task of the code is to process a training file to generate either bigrams or trigrams based on the input parameter N (2 or 3), then compute the perplexity of a test file using the generated model. It reads command-line arguments for input files and model type, executes the corresponding generation function, an... | def main():
trainf = open(sys.argv[1])
N = sys.argv[2]
if N == '2': generate_bigram(trainf)
elif N == '3': generate_trigram(trainf)
else: print("This model can only do bigrams and trigrams :(")
trainf.close()
testf = open(sys.argv[3])
perplexity(testf)
testf.close() |
def create_meta_from_data(self):
self.meta_file = f'data/{self.name}_meta.xlsx'
self.create_columns_meta()
sql_index = list(self.data.index.names)
name_map = {v: k for k, v in self.columns['input_name'].to_dict().items()}
sql_index = [ name_map[ i ] for i in sql_index ]
... | The code creates an SQL table by checking if it already exists, initializing metadata from data or a file if needed, renaming columns, updating metadata files/tables, and overwriting the data table. | def create_table(self, meta_file=None):
"""Create an SQL table.
Args:
meta_file(str) location of file with meta data to intitiate table.
Initiation finds the file self.meta_file if meta_file is None.
Values from self.data are inserted if populated.
Otherwise, self.re... |
def get_rollout(self):
#TODO: implement multi-worker version of this
states = []
actions = []
rewards = []
next_states = []
dones = []
current_state = self.env.reset()
for step_counter in range(0, self.t_max):
action = self.get_action_from_a... | This code trains a reinforcement learning agent by collecting rollouts, computing advantages, updating policy/value networks, and logging metrics like total reward, episode length, and advantage mean. It also visualizes these metrics using a plotter. | def train(self):
rewards_buffer = []
sampled_total_rewards = []
sampled_episode_lengths = []
sampled_advantages = []
start_time = time.time()
for batch_index in range(0, self.number_of_batches):
self.entropy_term = 0
batch_states, batch_actions,... |
def evaluate(self) -> int:
score = 0
for i in range(64):
piece = self.board[i]
if piece == EMPTY:
continue
pieceColor = findPieceColor(piece)
pieceType = findPieceType(piece)
if pieceColor == BLACK:
score -= MA... | The code implements a quiescence search with alpha-beta pruning in a game-playing algorithm. It evaluates the current position, applies pruning based on alpha and beta bounds, and recursively explores only capturing moves to avoid unstable positions. The function updates alpha/beta values, returns the best score, and u... | def quiesce(self, alpha: int, beta: int, max_depth: int):
stand_pat = self.evaluate()
if max_depth == 0:
return stand_pat
if stand_pat >= beta:
return beta
if alpha < stand_pat:
alpha = stand_pat
moves = self.legalMoves()
for move in... |
def legalMoves(self) -> list[Move]:
plmoves = self.generateMoves()
lmoves = []
for move in plmoves:
self.make_move(move)
if self.kingCanBeCaptured():
self.unmake_move()
continue
lmoves.append(move)
self.unmake_move()... | The code iterates through all legal moves, recursively calculates the number of positions at the given depth using `perft`, and prints each move's result. It enforces a minimum depth of 1 and restores the board state after each move to maintain consistency. | def divide(self, depth: int) -> None:
if depth == 0:
raise "depth must be greater than 1 when calling divide"
moves = self.legalMoves()
for move in moves:
self.make_move(move)
print(f"{move}: {self.perft(depth - 1)}")
self.unmake_move() |
def quiesce(self, alpha: int, beta: int, max_depth: int):
stand_pat = self.evaluate()
if max_depth == 0:
return stand_pat
if stand_pat >= beta:
return beta
if alpha < stand_pat:
alpha = stand_pat
moves = self.legalMoves()
for move in... | This function performs alpha-beta pruning in a game tree search, evaluating legal moves recursively with depth control. It updates the best move when setBestMove is true, uses quiescence search at depth 0, and returns the evaluation score. The algorithm sorts moves by value, explores them, and prunes branches where eva... | def search(
self, depth: int, setBestMove: bool, alpha=float("-inf"), beta=float("inf")
) -> float:
if depth == 0:
self.evaluatedCount += 1
return self.quiesce(alpha, beta, 2)
if setBestMove:
self.evaluatedCount = 0
moves = self.legalMoves()
... |
def solveOmega(ql,qr,L,J0):
R = getR(ql,qr)
J = R.dot(J0).dot(R.T)
return linalg.solve_lyapunov(J,-L)
def getLRDecomp(Om):
#e-values converted to real by 1j, eigh has e-values in ascending order
lamb,v = linalg.eigh(1j*Om,eigvals=(2,3))
Q = np.sqrt(2)*np.vstack([v[:,0].real,v[:,0].imag,v[:,1].re... | This function integrates quaternions ql and qr representing orientations over a time step dt using decomposition of the Omega matrix derived from inputs. It updates each quaternion via multiplication with decomposed matrices, then normalizes results to maintain unit length, essential for accurate rotational dynamics si... | def step(ql,qr,L,J0,dt):
Omega = solveOmega(ql,qr,L,J0)
qMatL,qMatR = getLRDecomp(Omega)
ql = ql + quatMult(qMatL, ql)*dt
qr = qr + quatMult(qr, qMatR)*dt
return quatNormalize(ql), quatNormalize(qr) |
def unlist_selling(userid):
'''
unlists all of the items user is selling
'''
user_ref = DB.collection(u'Users').document(userid)
selling = user_ref.get().get('selling')
for items in selling:
unlist(items, userid)
def check_email(email):
'''
Checks if the email a user is signing ... | This function allows authenticated users to edit or delete their profile information, including validating passwords, updating personal details, checking email validity, handling profile picture uploads, and updating the database with changes while providing appropriate feedback through flash messages. | def edituser():
'''
Displays form for user to edit their information
'''
if "userid" in session:
userid = session['userid']
user_ref = DB.collection(u'Users').document(userid)
user_info = DB.collection(u'Users').document(userid).get().to_dict()
if request.method == 'POST'... |
def get_uploaded_images(images, folder):
'''
Gets all the images in a folder
Returns:
A list of image links
'''
uploaded_images = []
for image in images:
uploaded_images.append(upload_image(image, folder))
return uploaded_images
def get_categories():
'''
Gets al... | This function allows authenticated users to edit item details by handling form submissions, updating Firestore with new data (including images), and rendering the edit form with existing item info, categories, and images for modification. | def edititem(itemid):
'''
Displays form to edit item info
'''
if "userid" in session:
userid = session['userid']
if request.method=="POST":
item_ref = DB.collection(u'Items').document(itemid)
item = DB.collection(u'Items').document(itemid).get().to_dict()
... |
def help():
print("USAGE: python3", sys.argv[0], "SUBJECT FILE")
sys.exit()
def readfile(filename):
f = open(filename, 'r')
message = f.read()
f.close()
return message
def check_subject(subject):
if len(subject) > 80:
messages.error_max_length_subject()
tags, summary = parse_subj... | The main task of the code is to validate a subject and message from command-line inputs. It checks if exactly two arguments are provided, reads the message from the specified file, validates the subject and message content, and marks the message as successful if no errors are detected during validation. | def main():
if len(sys.argv) != 3:
help()
else:
subject = sys.argv[1]
filename = sys.argv[2]
message = readfile(filename)
check_subject(subject)
check_message(message)
if not messages.error:
messages.success() |
def read_file(self, input_path):
with open(input_path, 'r') as stream:
return stream.readlines()[self.lines_to_skip:]
def map_lines_to_atoms(self,lines):
atoms = []
for line in lines:
atom = self.map_line_to_atom(line)
if atom is not None:
atom... | The code reads a file from the given path, determines its type by extension, and processes its content into atoms or elements using specific mapping methods depending on whether the file is .xyz or .csv. | def read(self,input_path):
content = self.read_file(input_path)
if '.xyz' in input_path:
return self.map_lines_to_atoms(content)
elif '.csv' in input_path:
return self.map_lines_to_elements(content) |
def get_img_description(image):
return {"caption_1": generate_caption_blip(image),
"caption_2": generate_caption_git(image)}
def get_image_group(img, n_group):
pred = yolo_model.predict(img)
def find_n_max(n, data, pred):
proba = [nlargest(n, x)[n - 1] for x in data][0]
i = [x.i... | The code processes an uploaded image to generate a description (if enabled), groups similar images, identifies top 10 similar images from a candidate set, extracts metadata (names, descriptions, categories) for these matches, and returns structured JSON data containing image groups, similar image details, and optionall... | def predict(file: UploadFile = File(...), description: bool = True):
# Load the image file
content = file.file.read()
image = Image.open(io.BytesIO(content))
img_description = None
if description:
img_description = get_img_description(image)
print("Start image group...")
groups = g... |
def read_input_yaml() -> dict:
"""
Reads a YAML file using the "--config" flag with argpass
Reads YAML file into a dict
Returns:
- config (dict)
"""
# create an argpass parser, read config file,
parser = argpass.ArgumentParser()
parser.add_argument("--config")
args = parser.pars... | The main task of the code is to read and validate a configuration file. It loads a YAML config, checks if specified paths exist, validates CPU-related inputs, and ensures docking orders are correct. The function prints status updates and returns the validated config dictionary if all checks pass. | def read_and_validate_config() -> dict:
"""
Main script for config checker:
1. Accepts --config flag arg with argpass, reads yaml file into a dict
2. Checks paths in pathInfo to see if they are real
3. Checks inputs of cpuInfo to see if they are correct
4. Checks each dockingOrder in dockingOrde... |
def loadImage(img_path, device):
img = np.array(Image.open(img_path).convert('RGB'), dtype=np.uint8)
img = transforms.ToTensor()(img).to(device)
return img
def getModel(device, model_path, weights_path):
model = createModelFromCfg(device, model_path, weights_path)
model.eval()
return model
def g... | The code runs a YOLOv3 model for object detection on images, either a single image or a directory of images, using specified weights. It loads the model, processes input images, generates detection outputs, and visualizes or saves results. The script supports GPU acceleration if available, with fallback to CPU. | def run():
parser = argparse.ArgumentParser(description="Run model on image and visualize result.")
parser.add_argument("-w", "--weights", type=str, required=True, help="Path to weights or checkpoint file (.weights or .pth)")
parser.add_argument("-i", "--image", type=str, default="", help="Path to the image... |
def get_activity_data(self, dtime=None, src_file=None):
assert dtime or src_file, "Either dtime and/or src_file must be specified"
df = self.get_activities()
if dtime:
dtime = pd.Timestamp(dtime)
df = df[ df['dtime'].dt.date==dtime.date() ]
if len(df) > 1:
... | This code generates a multi-panel plot visualizing key metrics of a sports activity, including power/heart rate zones, power curves, and time-series data for metrics like speed, elevation, cadence, etc. It uses the specified x-axis (e.g., duration or distance) to plot these metrics, displaying averages, maxima, and zon... | def plot_activity(self, dtime=None, src_file=None, x='mov_duration', ftp=None, max_hr=182):
assert x in ['distance', 'mov_duration', 'duration', 'dtime']
df = self.get_activity_data(dtime=dtime, src_file=src_file)
df['mov_duration'] = pd.to_timedelta(df['mov_duration'], unit='s')
... |
def ensure_mydir(self):
if not os.path.exists(self.MYDIR):
print("Creating the ``{}'' directory".format(self.MYDIR))
os.mkdir(self.MYDIR)
def get_manifest(self,):
payload = self.web_request('manifest.json')
return json.loads(payload)
def refresh(self, m):
action =... | The main task of the code is to process command-line arguments by navigating a hierarchical command structure (self.COMMANDS), validating commands, and executing the corresponding callable function when a valid command is found. It ensures directory setup, loads data, and handles errors for unrecognized commands, termi... | def run(self):
self.ensure_mydir()
m = self.get_manifest()
self.refresh(m)
self.load()
if len(sys.argv) == 1:
self.usage()
args = sys.argv[1:]
node = self.COMMANDS
while True:
if len(args) == 0:
cmd = None
... |
def today():
base_url = env['today']
r = requests.get(base_url)
data = r.json()
datos = data['timestamps_int']
s = str(datos[0])
return s[0:8]
def arraypathTime(day):
base_url = env['rammb_url']
product = inputs['product']
url_array = f"{base_url}/data/json/goes-16/full_disk/{product... | The main task of the code is to process data based on the current day. It retrieves structured data using `arraypathTime`, flattens it into a list, prints the list, and passes it to `getOutputMap` for further processing. The function initializes an empty list, iterates through nested data, and consolidates values for o... | def mainProcess(inputs):
getDay = today()
# arraypathTime(getDay)
datos_array = arraypathTime(getDay)
array_instance = []
for item in datos_array:
for value in datos_array[item]:
array_instance.append(value)
print(array_instance)
getOutputMap(array_instance)
pass |
def load_training_data(self):
"""Load the training data for the current board size
"""
if os.path.isfile(f"training_data/replay_memory_{self.game.nrows}.pickle"):
with open(f"training_data/replay_memory_{self.game.nrows}.pickle", "rb") as pick:
self.replay_memory = p... | The code trains an agent using reinforcement learning by playing multiple episodes, saving experiences, periodically training a neural network with replay memory, comparing agents to determine the best performer, and updating the optimal agent. It optionally loads pre-existing training data and iteratively improves the... | def train(self, load_train = True):
"""Train the agent and check if there is a new best agent
Args:
load_train (bool, optional): Flag to ask if it is neccessary to load the stored training data. Defaults to True.
"""
if load_train:
self.load_training_data()
... |
def find_emptys(sudoku):
""" finds corrdinates of all empty, zero values
Input
sudoku : 9x9 numpy array
Output
two np arrays [row index,..],[col index,..]
"""
emptys = np.nonzero(sudoku==0)
if len(emptys[0]) == 0:
return None
else:
return empty... | The function recursively solves a Sudoku puzzle by finding empty cells, trying possible values, and backtracking if a value leads to a contradiction. It returns True if the Sudoku is solvable, otherwise False. | def is_solved(sudoku):
""" recursive function called to solve sudoku puzzle
Input
sudoku : 9x9 numpy array
Output
bool
"""
emptys = find_emptys(sudoku)
if emptys == None:
return True
next_empty, possibles = find_next_empty_with_possibles(su... |
def check_all_valid(sudoku):
""" checks if all spaces are valid based off rules of sudoku
Input
sudoku : 9x9 numpy array
Output
bool
"""
for r_i, r in enumerate(sudoku):
for c_i, c in enumerate(sudoku):
value = sudoku[r_i][c_i]
... | The code solves a Sudoku puzzle by checking if the input is valid and already solved. If valid and solved, it returns the solution; otherwise, it returns an array of -1s. The function relies on helper methods to validate cells, check completion, and handle failure cases. Your return | def sudoku_solver(sudoku):
"""
Solves a Sudoku puzzle
Input
sudoku : 9x9 numpy array
Empty cells are designated by 0.
Output
9x9 numpy array of integers
It contains the solution, if there is one. If there is no solution, all array entries should be -1.
"""
... |
def get_nextun(state):
ind = 0
while state[ind] != ".":
ind = ind + 1
return ind
def get_sorted(state,var):
remove = []
newoptions = options.copy()
for i in newoptions:
for j in rowColCons.get(var):
if state[j] != ".":
k = int(state[j])
... | This code solves a Constraint Satisfaction Problem (CSP) puzzle using backtracking. It recursively fills empty cells (denoted by ".") by selecting the next variable, trying ordered values, and returning the first valid solution. If no solution exists, it returns None. | def csp_backtracking(puzz):
if "." not in puzz:
return puzz
var = get_nextun(puzz)
for val in get_sorted(puzz,var):
newstring = puzz[0:var] + str(val) + puzz[(var+1):]
result = csp_backtracking(newstring)
if result is not None:
return result
return None |
def rebuild_P_S(S, dim=E):
row = S.shape[0] - dim + 1
n = S.shape[1]
P = np.zeros((n, row, dim))
for i in range(row):
P[:, i, :] = S[i:i+dim, :][::-1].transpose(1, 0)
return P
def get_P_Dis(P):
n, row, _ = P.shape
Dis = np.zeros((n, row, row))
for i in range(row):
for j ... | The code processes input data to compute prediction accuracy. It loads data, reconstructs a matrix `P`, calculates its distribution (`P_Dis`), identifies nearest indices, determines phase rates, computes nearest distances and weights, generates predictions, and evaluates accuracy. The primary task is to analyze data th... | def main(data_path="data.csv"):
data = np.loadtxt(data_path, delimiter=",")
P = rebuild_P_S(data)
P_Dis = get_P_Dis(P)
n_Index = get_nearest_Index(P_Dis)
Rate = get_Phase_rate(P)
nearest_Dis = get_nearest_Dis(P_Dis)
nearest_Dis_W = get_nearest_dis_W(nearest_Dis)
Predict = get_Predict(n_I... |
def parse_args():
parser = argparse.ArgumentParser(description='Generate requirements*.txt matching Pipfile*')
parser.add_argument('-o',
'--output',
help=('Generate only the main packages to a different file, '
'instead of requirement... | The main task of the code is to generate `requirements.txt` and `requirements-dev.txt` files from a `Pipfile` or `Pipfile.lock`, parsing default and development dependencies. It uses command-line arguments to control output paths and whether to include dev packages, writes formatted files with a header warning against ... | def main():
args = parse_args()
logger = get_logger(args.quiet)
if args.freeze:
pipfile = Project().lockfile_content
else:
# pylint: disable=protected-access
pipfile = Project()._lockfile
# pylint: enable=protected-access
def_req = parse_pip_file(pipfile, 'default... |
def config():
configname = 'RANSAC.config'
with open(configname, 'r') as conf:
conf.readline()
n = int(conf.readline().split()[0])
d = int(conf.readline().split()[0])
kmax = int(conf.readline().split()[0])
return n, d, kmax
def ransac(objp, imagep, n, d, kmax):
k=kmax
... | The code loads data points from two files, appends a bias column to the target points, uses RANSAC to fit a model to noisy data, computes model parameters, and calculates the error between predicted and clean reference points by summing squared differences. | def main():
fw="./data/ncc-worldPt.txt"
fi="./data/ncc-noise-1-imagePt.txt"
ip=np.loadtxt(fi,skiprows=1)
op=np.loadtxt(fw,skiprows=1)
new_col=np.ones((len(op),1),np.float32)
op = np.append(op, new_col, 1)
n, d, kmax = config()
M, inlier=ransac(op,ip,n,d,kmax)
# print(inlinerNum, best... |
def find_entity_location(agent_host,entityName):
world_state = agent_host.getWorldState()
while world_state.number_of_observations_since_last_state == 0:
time.sleep(0.1)
world_state = agent_host.getWorldState()
if world_state.is_mission_running == False:
return None
msg =... | The function `move_to` navigates an agent to a specified entity's location using pathfinding algorithms. It identifies the agent's and entity's positions, then applies A* search (mode 0), BFS (mode 1), or brute force (mode 2) to generate a path. If a path exists, it executes movements step-by-step; otherwise, it report... | def move_to(agent_host,entityName,mode=0):
entity_location = find_entity_location(agent_host,entityName)
agent_location = find_agent_location(agent_host)
if entity_location is None:
print("There is no " +entityName+ " nearby the agent")
return
if agent_location is None:
return
... |
def find_agent_location(agent_host):
world_state = agent_host.getWorldState()
while world_state.number_of_observations_since_last_state == 0:
time.sleep(0.1)
world_state = agent_host.getWorldState()
if world_state.is_mission_running == False:
return None
msg = world_state... | The function `move_to_location` navigates an agent from its current position to a specified 3D coordinate using pathfinding algorithms (A* or BFS) based on the `mode` parameter. It checks the agent's location, generates a path, and executes movements step-by-step. If no path is found, it returns early. A commented-out ... | def move_to_location (agent_host, location, mode = 0):
"""
Moves agent to location's coordinates location = (x, y, z)
"""
agent_location = find_agent_location(agent_host)
if agent_location is None:
return
#Use Astar
if(mode == 0):
visited_nodes = Astar_search(a... |
def get_similar_command (verb, commands_map, agent_host):
"""
Returns the closest matching malmo command defined in the commands map
within a certain threshold
"""
lemma_verb = verb.lemma_
# synonyms?
# left
if verb.pos != VERB:
return verb
# get synonym?
t = 0.5
... | This function parses a root verb (e.g., a MALMO command) by identifying its syntactic dependencies, mapping them to specific MALMO commands, and generating a list of executable commands. It checks the verb's rights (dependencies), processes adverbs, verbs, adpositions, nouns, etc., using helper functions like send_comm... | def parse_root_verb (verb, commands_map, agent_host):
"""
Parses root verb (malmo command)
"""
malmo_command = get_similar_command (verb, commands_map, agent_host)
if DEBUG:
print ("malmo command: ", malmo_command)
commands = []
if sum (1 for r in verb.rights) == 0:
c ... |
def find_nearest_trees (agent_host):
"""
Returns a dict of tree locations and distance pairs (x, z : distance)
sorted by increasing distance
"""
graph, center_layer, center_row, center_col = create_Graph (agent_host)
ind = np.argwhere (graph[center_layer:, :, :] == "log")
agent_location = ... | The code identifies the nearest tree, calculates its coordinates, moves the agent toward it, and adjusts the agent's rotation to face the tree. It uses helper functions to navigate and orient the agent, ensuring alignment with the target tree's position. | def find_nearest_tree (agent_host):
"""
Finds nearest trees and moves the agents towards it
"""
trees = find_nearest_trees (agent_host)
if len (trees) == 0:
return
coords, distance = trees[0]
(x, z) = coords
# steve height
y = 5
location = np.ceil ([x, y, z])
print (... |
def load_query(nf_folder_path):
"""
helper func that loads the test-set queries and yields the _id, _text as a tuple
"""
nf_folder_path = Path(nf_folder_path)
queries_path = nf_folder_path.joinpath('queries.jsonl')
with open(queries_path, 'r', encoding='utf-8') as f:
for line in f:
... | The main task of the code is to compute and save NDCG@10 scores for a cross-encoder model on a test dataset. It loads queries and gold standard data, processes each query to calculate scores using a fine-tuned search model, and writes the results to a CSV file for evaluation analysis. | def generate_cross_encoder_NDCG() -> list[float]:
"""
Generate and save to file a list of the NDCG@10 scores of the cross-encoder model
"""
queries = load_query(data_dir)
gold_standard = load_qrels(Path.joinpath(data_dir, 'test.tsv'))
inv_gold_standard = invert_gold_standard(gold_standard)
s... |
def thinking():
for i in range(5):
print(".", end="")
sleep(0.5)
print()
def displayHand(hand, cardCount):
print("Your Hand")
i = 0
while i < cardCount:
print(repr(hand[i]))
i += 1
def sortByTitle(hand):
title = "Title"
cardList = []
dictionary = {}
f... | This code implements a simple interactive card game where a user can select cards from a shuffled deck, view their hand, sort cards by title or gang, and search for specific cards, with options presented through a menu-driven interface. | def main():
print("Welcome to Gronky Cards\n")
print("Shuffling Cards", end="")
thinking()
deck = Deck()
playerHand = []
cardCount = int(input("How many cards would you like?: "))
for i in range(cardCount):
playerHand.append(deck.draw())
done = False
while not done:
... |
def iterate():
glViewport(0, 0, 500, 600)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, 500, 0.0, 600, 0.0, 1.0)
glMatrixMode (GL_MODELVIEW)
glLoadIdentity()
def three():
eight_way_symmetry(100, 400, 200, 400)
eight_way_symmetry(100, 300, 200, 300)
eight_way_symmetry(100,... | The main task of the code is to render a 3D scene using OpenGL by clearing buffers, resetting the camera, setting a white color, and drawing objects via `three()` and `seven()` functions, then swapping buffers to display the rendered frame. | def showScreen():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
iterate()
# (Red, Green, Blue)
glColor3f(1.0, 1.0, 1.0)
###============================###
### call_the_draw_methods_here ###
###============================###
three()
seven()
glutSwapB... |
def is_terminal_node(self, grid, rows, columns, in_row):
if list(grid[0, :]).count(0) == 0:
return True
for row in range(rows):
for col in range(columns - (in_row - 1)):
window = list(grid[row, col:col + in_row])
if self.is_terminal_window(window,... | This code implements the minimax algorithm for a turn-based game, recursively evaluating possible moves by alternating between maximizing and minimizing players. It checks valid moves, predicts board states, and returns heuristic scores for terminal nodes or depth limits. The algorithm selects optimal moves by maximizi... | def minimax(self, node, depth, maximizing_player, mark, rows, columns, in_row):
valid_moves = logic.get_valid_moves(node)
print('Valid moves: ' + str(valid_moves))
is_terminal = self.is_terminal_node(node, rows, columns, in_row)
if depth == 0 or is_terminal:
return self.get_h... |
def is_terminal_node(self, grid, rows, columns, in_row):
if list(grid[0, :]).count(0) == 0:
return True
for row in range(rows):
for col in range(columns - (in_row - 1)):
window = list(grid[row, col:col + in_row])
if self.is_terminal_window(window,... | This function implements the alpha-beta pruning algorithm for a game, recursively evaluating the best move by considering valid positions and heuristic values. It alternates between maximizing and minimizing players, pruning branches where the current path cannot yield a better result than previously found, using alpha... | def alphabetaminimax(self, node, depth, maximizing_player, mark, rows, columns, in_row, alpha=-np.inf, beta=np.inf):
valid_moves = logic.get_valid_moves(node)
print('Valid moves: ' + str(valid_moves))
is_terminal = self.is_terminal_node(node, rows, columns, in_row)
if depth == 0 or is_te... |
def get_data(file_path : str) -> str:
data = ''
if not file_path:
data = inputs("Enter the project structure :").splitlines()
else:
with open(file_path, 'r') as f:
data = [line[:-1] for line in f.readlines()]
return [path for path in data if path]
def struct_to_paths(root : str, data : str, tabsiz... | The code processes input data from a specified file, converts it into directory paths based on a given root structure, and creates those directories. It uses arguments to determine the file location, root path for structuring, and verbosity of the output. The main task is to generate and create directory paths from str... | def apply(args):
data = get_data(args.file)
paths = struct_to_paths(args.root ,data)
create_paths(paths, args.verbose) |
def get_data(file_path : str) -> str:
data = ''
if not file_path:
data = inputs("Enter the project structure :").splitlines()
else:
with open(file_path, 'r') as f:
data = [line[:-1] for line in f.readlines()]
return [path for path in data if path]
def struct_to_paths(root : str, data : str, tabsiz... | The code checks the validity of a file structure's architecture by categorizing files into statuses (e.g., exist, empty), applying user-defined filters (count, list, verbose), and displaying results with color-coded "VALID ARCHI" or "FAIL ARCHI" indicators. It processes input data, validates structure rules, and output... | def check(args):
data = get_data(args.file)
paths = struct_to_paths(args.root ,data)
categorizes = catorize_paths(paths)
#if args.all:
#args.list = True
if args.verbose:
args.count = True
args.list = True
args.all = True
if not args.empty and not args.all:
categorizes[FileStatus.EXIST... |
def menu_options():
print("\n-----------------------------------------------")
print("------ Welcome to FedUni Hotel Bookings -------")
print("-----------------------------------------------")
print("Main Menu - please select an option:")
print("1.) Add guest ")
print("2.) Add room ")
... | The code defines a menu function that displays options for managing guests, rooms, and bookings. It loops until the user selects '4' (view bookings) or '5' (quit), executing corresponding actions like adding entries or viewing data. Input validation ensures only valid choices (1-5) are processed, with '4' and '5' termi... | def menu():
global user_input
quit_switch = False
while (quit_switch == False):
menu_options()
user_input = input("Enter choice (1, 2, 3, 4 or 5): ")
if user_input == '1':
add_guest()
add_more_guest()
quit_switch = False
elif ... |
def getPrime(self, ):
while True:
n = 128
prime_candidate = self.getLowLevelPrime(n)
if not self.isMillerRabinPassed(prime_candidate):
continue
else:
# print(n, "bit prime is: \n", prime_candidate)
break
retu... | The main task of the code is to generate RSA public and private keys by selecting two primes (p, q), computing the modulus n = p*q, determining the public exponent e, and calculating the private exponent d. It stores the public key as (n, e) and the private key as (n, d) for cryptographic operations. | def __init__(self):
p = self.getPrime()
# print(p)
q = self.getPrime()
# print(q)
# p=7
# q=13
n = p*q
# print('n is :', n)
e = self.getE(p,q)
# print("this is e : ", e)
self.pub = (n,e)
d = self.getD(e, p , q)
# ... |
def mineBlock(self, block, difficulty = 5):
while block.Hash[:difficulty] != '0'*difficulty:
block.nonce+=1
block.Hash = block.calculateHash()
print(block.nonce, block.Hash)
finalHash = makDES(block.Hash.upper(), "133457799BBCDFF1")
block.Hash = finalHash
... | This function handles a client request by receiving a block of data through a socket. It first reads the block's size, then the block itself, deserializes it, validates it via `checkData`, and adds it to the blockchain if valid. It sends status updates to the client and returns True on success or False if validation fa... | def handle_request(self, sock):
data = b''
payload_size = struct.calcsize("L")
sock.sendall('Send Block'.encode())
print("Expecting Data")
while len(data) < payload_size:
data += sock.recv(4096)
packed_msg_size = data[:payload_size]
data = data[payload... |
def js_minify(js):
"""Minify a JavaScript string."""
js = remove_commented_lines(js)
js = js_minify_keep_comments(js)
return js.strip()
def prefixer_extensioner(file_path, old, new, file_content=None, prefix='', add_hash=False):
"""Take a file path and safely preppend a prefix and change extension.
... | This function processes a single JavaScript file by minifying its content, optionally adding a timestamp, and saving the result as a `.min.js` file (or specified output path) with optional gzip compression. It reads the input JS, minifies it, handles output paths, writes the minified code, and creates a compressed vers... | def process_single_js_file(js_file_path, timestamp=False,
overwrite=False, gzip=False, output_path=None):
"""Process a single JS file."""
log.info("Processing JS file: {0}.".format(js_file_path))
with open(js_file_path, **open_utf8sig_kw) as js_file:
original_js = js_file.read()
log.debu... |
def css_minify(css, wrap=False, comments=False, sort=False):
"""Minify CSS main function."""
log.info("Compressing CSS...")
css = remove_comments(css) if not comments else css
css = sort_properties(css) if sort else css
css = unquote_selectors(css)
css = condense_whitespace(css)
css = remove... | This function processes a CSS file by minifying its content, optionally adding timestamps, comments, or sorting rules. It writes the minified CSS to a specified output path, generating both standard and gzip-compressed versions if enabled. The function returns the file path of the processed CSS, handling filename prefi... | def process_single_css_file(css_file_path, wrap=False, timestamp=False,
comments=False, sort=False, overwrite=False, gzip=False,
prefix='', add_hash=False, output_path=None):
"""Process a single CSS file."""
log.info("Processing CSS file: {0}.".format(css_file_path))
with open(css_file_path,... |
def check_working_folder(folder_to_check=os.path.expanduser("~")):
"""Check working folder,passed argument,for everything that can go wrong.
>>> check_working_folder()
True
"""
folder_to_check = os.path.abspath(folder_to_check) # More Safe on WinOS
log.debug("Checking the Working Folder: '{0}'"... | The function processes multiple CSS, JS, and HTML files using multiprocessing, applying compression, formatting, or transformation options. If 'watch' is enabled, it continuously monitors the file for changes and reprocesses it upon modification. Otherwise, it processes the file once, invoking type-specific handlers fo... | def process_multiple_files(file_path, watch=False, wrap=False, timestamp=False,
comments=False, sort=False, overwrite=False, gzip=False, prefix='',
add_hash=False):
"""Process multiple CSS, JS, HTML files with multiprocessing."""
log.debug("Process {} is Compressing {}.".format(os.getpid(), file... |
def make_arguments_parser():
"""Build and return a command line agument parser."""
parser = ArgumentParser(description=__doc__, epilog="""CSS-HTML-JS-Minify:
Takes a file or folder full path string and process all CSS/HTML/JS found.
If argument is not file/folder will fail. Check Updates works on Python... | The main task of the code is to process CSS, HTML, or JS files (or folders) by applying transformations like minification, timestamping, compression, and hash addition based on command-line arguments. It uses multiprocessing for folder processing, handles logging, checks for updates, and supports testing. The script pr... | def main():
"""Main Loop."""
args = make_arguments_parser()
check_for_updates() if args.checkupdates else log.debug("No Check Updates")
if args.tests:
testmod(verbose=True, report=True, exclude_empty=True)
sys.exit(0)
log.disable(log.CRITICAL) if args.quiet else log.debug("Max Loggin... |
def ClearConsole():
os.system('cls')
def ValidateIPAndCIDR(ip, cidr):
try:
CalculateNetwork(ip, cidr)
except (ipaddress.AddressValueError, ipaddress.NetmaskValueError):
print("Invalid IP address or CIDR notation.\n")
return False
return True
def CalculateAddressSpace(ip, cidr):
... | This code calculates and displays subnet details based on user-provided IP addresses and CIDR notation. It validates inputs, determines host requirements per subnet, computes subnet masks, network addresses, broadcast ranges, and host ranges, then outputs structured subnet information for each calculated subnet. | def RunInConsole():
ClearConsole()
while True:
try: # Gets user input and tries to convert to int
ip = input("Enter the base IP address: ")
cidr = int(input("Enter the CIDR notation (e.g., 24): "))
except ValueError: # If input cannot be converted to int, ... |
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansio... | The code initializes a neural network with customizable blocks, attention modules (SE/CBAM), and feature fusion. It constructs convolutional layers, residual blocks, upsampling, and extra layers for tasks like image classification or segmentation, supporting dilation, normalization, and zero-initialized residuals for i... | def __init__(self, block=None, blocks=None, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None, extras=None, se=False, cbam=False, ff=False):
super().__init__()
if norm_layer is None:
norm_layer = nn.Ba... |
def makeText(text,color,bgcolor,top,left):
# create the surface and rect object for some text
textSurf=BASICFONT.render(text,True,color,bgcolor)
textRect=textSurf.get_rect()
textRect.topleft=(top,left)
return (textSurf,textRect)
def drawTile(tileX,tileY,number,adjx=0,adjy=0):
# draw a tile at tileX ad tileY
# pi... | The function `drawBoard` renders a game board by drawing tiles based on the input `board` grid, displaying a message if provided, and adding borders and overlays. It fills the background, blits tile graphics, and positions decorative elements like fences and move indicators. | def drawBoard(board,message,color1=BGCOLOR):
DISPLAYSURF.fill(color1)
if message:
textSurf,textRect=makeText(message,MESSAGECOLOR,color1,5,5)
DISPLAYSURF.blit(textSurf,textRect)
for tilex in range(len(board)):
for tiley in range(len(board[0])):
if board[tilex][tiley]:
drawTile(tilex,tiley,board[tilex]... |
def getPlayerPosition(board,number):
# return the x,y co=ordinates of the blank box
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
if board[x][y]==number:
return (x,y)
def drawBoard(board,message,color1=BGCOLOR):
DISPLAYSURF.fill(color1)
if message:
textSurf,textRect=makeText(message,MESSAGECO... | The code animates a player's movement on a grid-based board in a specified direction, handling jumps and rendering car images. It creates a temporary surface for movement, adjusts positions based on direction, and updates the display step-by-step for smooth animation, using different images for distinct player numbers ... | def moveAnimation(board,direction,number,message='',jx=0,jy=0):
playerx,playery=getPlayerPosition(board,number)
drawBoard(board,message)
baseSurf=DISPLAYSURF.copy()
# Drawing a base surface for temporary movement
if playerx==3 and playery==0:
textSurf=BASICFONT.render(str(number),True,TEXTCOLOR)
textRect=text... |
def raw_python_blocks(self, file_content):
# Assumes there's no blocks
yield from [match.span() for match in re.finditer(RAW_PATTERN_START + " .*? " + RAW_PATTERN_STOP, file_content)]
def python_without_statement_and_raw(self, file_content, tab_level):
start = 0
for block_start, block_st... | This function processes Python code by splitting it into blocks, handling each block by removing raw markers and formatting with indentation, then yielding processed content. It ensures leading/trailing code is processed, handles empty inputs, and maintains generator behavior while avoiding 'pass' statements. | def python_without_statement_blocks(self, file_content, tab_level):
start = 0
for block_start, block_stop in self.raw_python_blocks(file_content):
# yields before each blocks
if file_content[start:block_start]:
yield from self.python_without_statement_and_raw(file... |
def control_blocks(self, file_content):
statement_by_start_index = []
for occ in self.openners_matches(file_content):
statement_by_start_index.append(("OPEN", occ))
for occ in self.clauses_matches(file_content):
statement_by_start_index.append(("CLAUSES", occ))
fo... | This function generates Python code with proper indentation by processing control flow blocks recursively. It yields code before each block, the control flow statement itself, and then recursively processes indented sub-blocks with increased indentation levels. It handles content before the first block, after the last ... | def full_python_texts_generator(self, file_content, tab_level=0):
start = 0
for block in self.control_blocks(file_content):
# yields before each control flow blocks
if file_content[start:block[0][0]]:
yield from self.python_without_statement_blocks(file_content[st... |
def get_output_element(self, element, output_element):
"""
:param element: the element to fix in the fix-form
:param output_element: The element of the output which contain the
"""
_id = 0
target_id = int(element.get("id"))
# for i in range(len(output_ele... | The main task of the code is to process XML elements in `self.fix_root` by iterating through 'content' nodes, applying actions like 'update-blank', 'update', 'add', or 'remove' using corresponding methods, and finally writing the modified XML tree to "output.xml". It transforms the original XML structure based on speci... | def main(self):
for content in self.fix_root.iter('content'):
output_content = self.get_output_element(content, self.original_root)
if content.get("action") == "update-blank":
self.update_blank(content, output_content)
elif content.get("action") == "update":
... |
def add_new_asfeature(solution,seed):
"""
Randomly selects an as variable, which is not already in solution
Inputs: solution list contianing all features generated from harmony consideration
##TODO: Include alternative-specific coefficients
"""
new_asvar = [var for var in asvarnames if var not i... | The function performs pitch adjustment in a harmony search algorithm by either adding or removing features from a solution based on a probability (PAR_itr). It evaluates the modified solution's objective function and updates the harmony memory by replacing the worst solution if the new solution improves the BIC. The pr... | def pitch_adjustment(sol, har_mem, PAR_itr,seeds,itr):
seed = seeds[HMS*3+itr]
"""
(1) A random binary indicator is generated. If the number is 1, then a new feature is added to the solution
generated in the Harmony Memory consideration step. Else a feature is randomly excluded from the solution
(2... |
def best_features(har_mem):
"""
Generates lists of best features in harmony memory
Inputs:
Harmony memory
"""
best_asvars = har_mem[0][1].copy()
best_isvars = har_mem[0][2].copy()
best_randvars = har_mem[0][3].copy()
best_bcvars = har_mem[0][4].copy()
best_corvars = har_mem[0][5]... | The code performs a local search on the best solution in the harmony memory of an Artificial Bee Colony optimization algorithm. It iteratively tweaks the best solution's features (e.g., coefficient distributions, covariance matrices, variable transformations) to improve the Bayesian Information Criterion (BIC). Dependi... | def local_search(improved_harmony,seeds,itr):
seed = seeds[HMS*4+itr]
"""
Initiate Artificial Bee-colony optimization
##Check if tweeking the best solution in harmony improves solution's BIC
Inputs: improved memory after harmony consideration and pitch adjustment
"""
#For plots (BIC vs. ite... |
def harmony_consideration(har_mem,HMCR_itr,seeds,itr):
seed = seeds[HMS*2+itr]
"""
If a generated random number is less than or equal to the harmony memory consideration rate (HMCR)
then 90% of a solution already in memory will be randomly selected to build the new solution.
Else a completely new ra... | The function implements an adaptive Harmony Search algorithm to optimize solutions by dynamically adjusting HMCR and PAR parameters, iteratively generating and refining harmony memories through pitch adjustment, and incorporating local search to enhance convergence. It tracks BIC values for each iteration, maintains a ... | def improvise_harmony(HCR_max,HCR_min,PR_max,PR_min,har_mem,max_itr,threshold,itr_prop):
improve_harmony = code_name + 'improvise_harmony_' + current_date + '.txt'
sys.stdout = open(improve_harmony,'wt')
itr = 0
#for BIC vs. iteration plots
best_bic_points = []
current_bic_points = []
... |
def chk(grammerA, a, ai):
if ai not in grammerA:
return False
if a == ai:
return True
for i in grammerA[ai]:
if i[0] == ai:
return False
if i[0] in grammerA:
return chk(grammerA, a, i[0])
return False
def rep(grammerA, A):
temp = grammerA[A]
newTemp = []
for i in temp:
if chk(grammerA, A, i[0... | The code transforms a context-free grammar by renaming non-terminals to eliminate left recursion. It maps original symbols to new identifiers (A1, A2...), processes productions to replace symbols, checks for recursive rules, and applies left recursion removal. Finally, it reverses the symbol mapping to return the modif... | def rem(grammer):
c = 1
conv = {}
grammerA = {}
revconv = {}
for j in grammer:
conv[j] = "A"+str(c)
grammerA["A"+str(c)] = []
c+=1
for i in grammer:
for j in grammer[i]:
temp = []
for k in j:
if k in conv:
temp.append(conv[k])
else:
temp.append(k)
grammerA[conv[i]].append(temp)... |
def makeDoG(self):
self.dog = []
g1 = self.im.convert("L").filter(ImageFilter.GaussianBlur(self.sigma))
for i in range(1, self.scales+1):
g2 = self.im.convert("L").filter(ImageFilter.GaussianBlur(self.sigma*(self.k**(i))))
self.dog.append(np.array(g2) - np.array(g1))
... | The main task of the code is to process detected key points by filtering out edge points and invalid descriptors, then extracting valid features and descriptors for each key point. It iterates through key points, computes orientation and descriptors, removes points with zero weight/descriptor, and returns the refined k... | def apply(self):
self.makeDoG()
self.findKeyPoints()
self.feature = []
self.descriptor = []
i = 0
while i < len(self.keyPoints):
p = self.keyPoints[i]
# remove edge
if self.harrisEdge(p[0], p[1], p[2]):
del self.keyPoint... |
def create_dirs(self):
if not os.path.exists(self.args.normalizations_dir):
os.makedirs(self.args.normalizations_dir)
if not os.path.exists(f'{self.args.trained_models_dir}/{self.args.model_type}'):
os.makedirs(f'{self.args.trained_models_dir}/{self.args.model_type}')
def load_t... | This code initializes a training configuration for a machine learning model, setting up directories, loading TFRecord files, configuring normalization parameters, determining batch sizes, class balancing, and regional sample weighting. It prepares data loading and training settings for geospatial imagery analysis acros... | def __init__(self, args, dir_time, training_regions):
self.args = args
self.parent_dir = args.parent_dir
self.tfrecord_dir = args.tfrecord_dir
self.train_config = args.train_config
self.imagery_type = args.imagery_type
self.training_regions = training_regions
sel... |
def __should_refresh_access_token(self):
current_time = datetime.now()
time_to_refresh_access_token = self.access_token_valid_until - timedelta(seconds=600)
return current_time >= time_to_refresh_access_token
def refresh_access_token(self):
refresh_token_result = self.client.refresh_acc... | The main task of the code is to retrieve or refresh an access token for authentication. If an existing token exists and needs refreshing, it updates it; otherwise, it logs in using the provided email, sets authentication tokens from the login response, and returns the access token for API access. | def get_access_token(self, email: str):
if self.access_token is not None:
if (self.__should_refresh_access_token()):
self.refresh_access_token()
return self.access_token
login_result = self.__login(email)
self.__set_authentication... |
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("subcommand_plus_args", nargs="*")
return parser.parse_args()
def _get_completions_for_pcluster_subcommand(subcommand_argv: List[str]) -> List[str]:
"""
Get completions for the given pcl... | The main task of the code is to generate and print command completions for a CLI tool (likely AWS ParallelCluster). It configures logging, parses arguments, determines if a specific subcommand or general commands are needed, fetches the appropriate completions, and outputs them line-by-line for shell autocompletion fun... | def main() -> None:
config_logger(LOGGER, LOG_PATH)
LOGGER.debug("pcluster completion script starting")
args = parse_args()
if args.subcommand_plus_args:
completions = _get_completions_for_pcluster_subcommand(args.subcommand_plus_args)
else:
completions = _get_pcluster_commands()
... |
def getIndex(self, rn):
for ind, trip in enumerate(self.Heap):
if rn == trip[0]:
return ind
return -1
def upHeapify(self, i):
if i > 0 and (self.Heap[i][1] < self.Heap[(i - 1) // 2][1] or
(self.Heap[i][1] == self.Heap[(i - 1) // 2][1]
and self.Heap[i][2] < ... | This function updates a ride's time duration in a heap structure. It adjusts the heap by either updating the value and re-heapifying (up/down) or increasing the ride's count and time, then re-heapifying. If the new time exceeds twice the current value, it cancels the ride. The method ensures heap properties are maintai... | def updateTrip(self, rn, newtd):
ind = self.getIndex(rn)
if newtd <= self.Heap[ind][2]:
self.Heap[ind][2] = newtd
self.upHeapify(ind)
newind = self.getIndex(rn)
self.downHeapify(newind)
elif self.Heap[ind][2] < newtd <= 2 * self.Heap[ind][2]:
temprn, temprc, _ = self.Heap[ind]
... |
def search(self, rnval):
node = self.root
while node != self.NIL and rnval != node.rn:
if rnval < node.rn:
node = node.left
else:
node = node.right
return node
def delete(self, rn):
node = self.search(rn)
if node == self.NIL:
return
y = node
y_ogcolor = y.c... | This function updates a trip's data (td) based on the newtd value. If newtd is ≤ current td, it updates td directly. If newtd is between td and 2×td, it deletes the node and inserts a new one with adjusted rc and newtd. If newtd exceeds 2×td, it deletes the node entirely, effectively removing the trip from the structur... | def UpdateTrip(self, rn, newtd):
node = self.search(rn)
if newtd <= node.td:
node.td = newtd
elif node.td <= newtd <= 2 * node.td:
temprc = node.rc
self.delete(node.rn)
self.insert(node.rn, temprc + 10, newtd)
elif newtd > 2 * node.td:
self.delete(node.rn) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.