dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def initialize_pop(interval, n_dim, m, n_sub_pop, th_h=0.2):
pop = []
# size of each population
m_itr = m
# number of sub population
n_sub_pop_itr = n_sub_pop
for _ in range(n_sub_pop):
sub_pop = np.empty(shape=(m, n_dim))
sub_pop[:] = np.nan
for i in range(m):
... | This function performs a genetic algorithm on multiple subpopulations to optimize a fitness function. It initializes populations, iterates through generations, applies roulette wheel selection, crossover, and mutation, and tracks the best chromosome across all subpopulations. The goal is to find the optimal solution by... | def gentic_subpop_step2(interval, n_dim, m, n_sub_pop, MaxGen1, fitness_func, p_c):
low, high = interval[0], interval[1]
population = initialize_pop(
interval=interval, n_dim=n_dim, m=m, n_sub_pop=n_sub_pop)
best_fit = -float('inf')
best_choromosom = population[0][0]
for l in range(n_sub_pop... |
def gentic_subpop_step2(interval, n_dim, m, n_sub_pop, MaxGen1, fitness_func, p_c):
low, high = interval[0], interval[1]
population = initialize_pop(
interval=interval, n_dim=n_dim, m=m, n_sub_pop=n_sub_pop)
best_fit = -float('inf')
best_choromosom = population[0][0]
for l in range(n_sub_pop... | This code performs a genetic algorithm optimization step (step 3) on a subpopulation. It refines the best chromosome from step 2 through iterative generations (MaxGen2), applying crossover, mutation, and velocity-adjusted neighborhood changes. The process selects parents via roulette wheel, generates offspring, and upd... | def gentic_subpop_step3(interval, n_dim, m, n_sub_pop, MaxGen1, fitness_func, p_c, MaxGen2, v0, n_pop):
best_choromosom = gentic_subpop_step2(
interval, n_dim, m, n_sub_pop, MaxGen1, fitness_func, p_c)
vk = v0
# NbPr ~ 2 times of n_dim
best_fitness = -float('inf')
new_population = np.empty(... |
def get_threads(self):
"""
Returns a list of threads.
Args:
None
Returns:
list: A list of threads.
"""
if self.threads is not None:
return self.threads
else:
#attempt to read the thread_ids.json file
t... | The main task of the code is to switch the current thread by either name or ID, retrieve or create a new thread if necessary, and update the current thread state. It checks existing threads in a JSON file, prepares thread history, and returns the thread ID upon success. If both inputs are absent, it creates a blank thr... | def change_thread(self, thread_name: str or None = None, thread_id: str or None = None) -> int:
"""
Changes the current thread.
Args:
thread_name (str): The name of the thread to change to.
thread_id (str): The ID of the thread to change to.
Returns:
... |
def get_multiple_choice_input(self, choices):
"""Overwrite this function to change how the user is messaged"""
# Display the options with corresponding numbers
options = [f"{i+1}. {choice}" for i, choice in enumerate(choices)]
self.message_user(f"Please select one of the following option... | The function allows users to switch threads by selecting a thread name, ID, or choosing from a list of saved threads. It retrieves the selected thread's ID, loads its message history, and displays messages in reverse order, enabling seamless thread navigation and interaction. | def swap_Thread(self):
#Ask the user for the thread name or ID
options = ["Name", "ID", "Multiple Choice (Save Locally)"]
selected = self.get_multiple_choice_input(options)
# If the user selected name, ask for the name
if selected == "Name":
self.message_user("Please ... |
def ai_move_decision(self):
"""Returns the col, row coords for the best legal moves on the
board for ai"""
# Creates dictionary with column, row values of tiles that are legal
# moves as keys and their # of tiles to be flipped to their color as
# values
moves_dict = {}
... | The code handles a player's move in a board game by checking if a clicked square is empty (green). If legal, it changes the tile color to black (player's turn) and switches to AI's turn. It ensures legal moves exist, updates the board, and ends the game if no moves remain. | def player_make_move(self, mouseX, mouseY):
"""Checks if square clicked is "empty" aka has a green
tile. If so, changes the color to black for the player_turn and changes
color to white if AI turn.
Int, Int --> None
"""
# Make sure there are legal moves left
if se... |
def ai_move_decision(self):
"""Returns the col, row coords for the best legal moves on the
board for ai"""
# Creates dictionary with column, row values of tiles that are legal
# moves as keys and their # of tiles to be flipped to their color as
# values
moves_dict = {}
... | The main task of the code is to execute an AI's move in a board game by determining a valid move, flipping tiles to update the board, changing tile colors, and managing turn transitions. It checks if the AI can make a move, updates the game state, and ends the game if the AI has no valid moves. | def ai_make_move(self):
"""Calls the AI to make their move
"""
tup = self.ai_move_decision()
if tup:
col = tup[0]
r = tup[1]
self.flip_tiles(self.is_legal_move(col, r), self.white)
self.board.tile.change_color(col, r, self.white)
... |
def define_clfs_params():
'''
Initializes dictionaries of classifiers and parameters
'''
clfs = {'RF': RandomForestClassifier(n_estimators=50, n_jobs=-1),
'ET': ExtraTreesClassifier(n_estimators=10, n_jobs=-1, criterion='entropy'),
'AB': AdaBoostClassifier(DecisionTreeClassifier(max_dept... | The code's main task is to execute a machine learning pipeline for a specified model (Extra Trees) on data loaded from a file, evaluate its performance, and record the results in a text file. It defines classifiers, processes input data, runs the model, and stores metrics like accuracy and classification reports. | def main(filename):
'''
Executes functions sequentially, records main classifiers to output text file
'''
clfs, grid = define_clfs_params()
# models_to_run = ['LR','ET','AB','GB','NB','DT', 'KNN','RF']
models_to_run = ['ET']
X, y = get_x_and_y(filename)
top, table = magic_loop(models_to... |
def get_clip_txt_and_img(self, txt, img):
if self.image2text:
cue_clip_img_caption = self.get_clip_txt(img)
cue_clip_img_encoded = self.model.encode_text(cue_clip_img_caption)
cue_clip_img_encoded /= cue_clip_img_encoded.norm(dim=-1, keepdim=True)
else:
if... | This function generates model-specific predictions for candidate data based on the model type. It checks the model description to apply appropriate methods: CLIP calculates image-text scores, vision-language models use transformers, vision models process images, Word2Vec handles text embeddings, and text transformers c... | def get_predictions(self, candidates_data, cue_img, r):
if 'clip' in self.model_description.lower():
clip_cue_img, clip_cue_txt = self.get_clip_txt_and_img(r['cue'], cue_img)
model_predictions = self.calculate_clip_scores(candidates_data, clip_cue_img, clip_cue_txt)
elif self.mod... |
def isDone(self):
''' Checks if there are no empty cells in the sudoku '''
done = True
for row in self.board:
if not done:
break
for number in row:
if number == 0:
done = False
break
return do... | This function solves a puzzle (e.g., Sudoku) using backtracking. It recursively explores possible solutions by selecting the cell with the fewest options, updating the board, and backtracking when invalid. It yields valid solutions upon completion, tracks recursive calls, and handles dead-ends by resetting cells. | def find_solution_experimental(self):
self.calls += 1
''' Exit condition, only checks if there are non-empty cells '''
if self.isDone():
yield self.board
return
''' Re-compute all options and sort the entries by least options '''
... |
def _init(self, instance: Instance):
self.original = instance
self.copy = deepcopy(instance)
def clean(self):
question = self.copy.to_lower('question').split(', ')
self.copy.question = ''
for q in question:
if any(word in q for word in COMMA_REMOVE) and q[0] in COMMA_... | The main task of the code is to process an input instance by initializing, cleaning data, generating queries, preparing for point counting, and finally returning the computed points based on the crafted queries. | def solve(self, instance: Instance):
self._init(instance)
self.clean()
queries = self.craft_queries()
self.clean_for_points()
return self.count_points(queries) |
def find_row_in_my_data_list(guid_value):
global my_data_list
row = 0
for rec in my_data_list.keys():
if my_data_list[rec]["id"] == guid_value:
return row
row += 1
def save_json_to_file():
global my_data_list
with open("d:\\Python Project\\app to register househelp\\dada... | This function processes CRUD operations (insert, update, delete) on a data list using a GUID identifier, then saves the updated data to a file and refreshes the UI by reloading the data and clearing input fields. | def process_request(command_type, guid_value, first_name, last_name, cell_phone, custom_id):
global my_data_list
if command_type == "_UPDATE_":
row = find_row_in_my_data_list(guid_value)
if row >= 0:
dict = {"id": guid_value, "first_name": first_name,
"last_name"... |
def _prepare_dependencies(plugins: list):
"""Builds and if necessary downloads the given plugins and protoc.
Returns the paths to the executables of the plugins."""
clear_cache = os.getenv('PROTO_CLEAR_CACHE', False)
if clear_cache == 'true':
clear_cache = True
else:
clear_cache = Fa... | The main task of the code is to execute the `protoc` compiler for registered plugins, generating output files with specified arguments. It prepares dependencies, creates output directories, handles Python/GRPC outputs via `grpc_tools.protoc`, configures plugin-specific flags, and executes `protoc` commands. Special han... | def _run_protoc():
"""_run_protoc finds the required dependencies for registered plugins and calls
protoc for each of them with its arguments."""
check_cache = os.getenv('PROTO_CLEAR_CACHE')
if check_cache == 'true':
check_cache = True
else:
check_cache = False
# find required d... |
def qualifyCPcode(urlObject,cpcodeCondition,behavior):
cpcodeCondition["subject"] = "cpCode"
#Default Rule
if type(behavior["criteria"]) != list:
cpcodeCondition["is"] = behavior["behavior"]["options"]["value"]["id"]
else:#Not Default Rule
criteriaSatisfy = True
criteriaSatisfy ... | The code processes each request in requestObject by checking URL parameters against behaviors defined in a JSON file. It applies conditions like cpCode, caching, and tieredDistribution to each request, appending relevant rules. The main task is to qualify requests with behavior-specific conditions from a configuration ... | def requestQualifier(config,version,requestObject):
jsonfile = config+version+'.json'
fp = open(jsonfile,'r')
behaviorlist = json.load(fp)
for request in requestObject:
fullurl = request[0]["RequestUrl"]
urlObject = urlparse(fullurl)
#print(fullurl)
#print(urlObject.sche... |
def check_win(state):
flag = False
upper_tokens = []
lower_tokens = []
for tokens in state.upper_dict.values():
upper_tokens.append(tokens)
for tokens in state.lower_dict.values():
lower_tokens.append(tokens)
up_notoks = len(upper_tokens) == 0 and state.throws_left[1] == 0
l... | The function implements the double oracle algorithm to find Nash equilibria in a two-player game by iteratively refining strategies through alpha-beta pruning, best response calculations, and dynamic move set expansion until convergence, balancing exploration of actions with equilibrium conditions. | def double_oracle(state, alpha, beta, side, depth):
utility = 0
oppnent = 0
if not side:
oppnent = 1
if check_win(state) or depth == 0:
utility = evaluation(state, side)
print("cutoff test")
return utility, state
max_val = -100
min_val = 100
max_move = []
... |
def check_win(state):
flag = False
upper_tokens = []
lower_tokens = []
for tokens in state[1]:
upper_tokens.append(tokens)
for tokens in state[0]:
lower_tokens.append(tokens)
up_notoks = len(upper_tokens) == 0 and state[2][1] == 0
lo_notoks = len(lower_tokens) == 0 and state... | This function implements the Alpha-Beta Minimax algorithm with depth-limited search for a two-player game. It evaluates the best move by recursively exploring possible game states, using alpha-beta pruning to optimize performance. The function alternates between maximizing (for the current player) and minimizing (for t... | def alpha_beta_minimax(state, depth, max_player, side, alpha, beta, count=0):
if depth == 0 or check_win(state):
return evaluation(state, side), state
if max_player:
cur_max = float('-inf')
best_move = None
if depth >= 2:
move = simulation(state, side, [], 1)
... |
def read_orbs(self, types=[], mo_min=1, mo_max=0):
# Make sure atoms and norbs have been read
if not self.atoms_read:
self.read_atoms()
if not self.norbs_read:
self.read_norbs()
if self.configs_read or self.states_read:
self.file.seek(0)
if m... | This method reads and processes spin-adapted CI configurations from a file, extracting orbital occupation/virtual indices, energy values, and character contributions from molecular orbitals. It constructs Config objects with calculated attributes (char, achar, bchar, ochar, vchar) and energy, storing them in self.confi... | def read_configs(self,types=[]):
if self.states_read:
self.file.seek(0)
if not self.orbs_read:
self.read_orbs(types)
self.read_to('spin-adapted configurations')
self.read_for(4)
self.configs = []
line = self.line.split()
while len(self.li... |
def read_configs(self,types=[]):
if self.states_read:
self.file.seek(0)
if not self.orbs_read:
self.read_orbs(types)
self.read_to('spin-adapted configurations')
self.read_for(4)
self.configs = []
line = self.line.split()
while len(self.li... | The main task of the code is to read and process excited states from a file, including their energies, oscillator strengths, and CI coefficients. It parses input data to construct `State` objects with energy, transition dipole moments, and orbital character contributions from configurations. The function handles both e... | def read_states(self,types=[]):
# Make sure configs have been read
if not self.configs_read:
self.read_configs(types)
self.read_to('CI trans.')
self.read_for(3)
self.states = [State(0.0,0.0)]
# Read energies and oscillator strengths
line = self.line... |
def read_orbs(self, types=[], mo_min=1, mo_max=0):
# Make sure atoms and norbs have been read
if not self.atoms_read:
self.read_atoms()
if not self.norbs_read:
self.read_norbs()
if self.configs_read or self.states_read:
self.file.seek(0)
if m... | This function identifies superatomic orbitals and calculates their contribution to excited states. It checks if 'SUPER' type exists in input data, adds it if missing, then assigns 'super' status to orbitals exceeding a character threshold. For each excited state, it computes superatom and interband character contributi... | def find_superatom_char(self, types, cutoff=0.4):
# Check if type information has been calculated
t = False
for i in range(0,len(types)):
type = types[i]
if 'SUPER' in type:
t_ind = i
t = True
if t == False:
types.append... |
def read_configs(self,types=[]):
if self.states_read:
self.file.seek(0)
if not self.orbs_read:
self.read_orbs(types)
self.read_to('spin-adapted configurations')
self.read_for(4)
self.configs = []
line = self.line.split()
while len(self.li... | The code writes electronic transition properties (energy, oscillator strength, superatom character, collectivity, etc.) of quantum states to output files (.exc and .ex2). It reads configuration/state data if not already loaded, calculates energy shifts and collectivity, optionally adds dipole data from an input file, a... | def write_exc(self, outfilename, types=[]):
if not self.configs_read:
self.read_mos(types)
self.read_configs(types)
self.read_states(types)
if not self.states_read:
self.read_states(types)
for state in self.states:
state.find_energy_sh... |
def isFull(sudoku):
if not isValid(sudoku):
return False
for i in sudoku:
if ' ' in i:
return False
return True
def getPossibles(sudoku):
'''returns a sudoku with lists with the possible numbers
that can go in that position'''
possibles = createSkeleton(sudoku)
for i, line in enumerate(sudoku):
for j... | The code solves a Sudoku puzzle by identifying cells with only one possible value and filling them, then checking for numbers that appear exactly once in rows, columns, or 3x3 sub-squares to place them, returning the updated Sudoku after each placement. | def solveSudoku(sudoku):
if isFull(sudoku):
return sudoku
possibles = getPossibles(sudoku)
# checks for squares with only one possible number
for i, line in enumerate(possibles):
for j, item in enumerate(line):
if type(item) == list and len(item) == 1:
newSudoku = [list(line) for line in sudoku]
ne... |
def _get_positional_kwargs(self, dest, **kwargs):
# make sure required is not specified
if 'required' in kwargs:
raise TypeError("'required' is an invalid argument for positionals")
# mark positional arguments as required if at least one is
# always required
if kwarg... | This code adds a command-line argument to a parser, handling both positional and optional arguments. It processes default values, validates the argument type, and ensures metavar consistency. It creates an action object, checks for callable types, and returns the updated parser with the new argument. | def add_argument(self, *args, **kwargs):
"""
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
# if no positional args are supplied or only one is supplied and
# it doesn't look like an option string, parse a po... |
def convert_arg_line_to_args(self, arg_line):
return [arg_line]
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or... | This function processes argument strings to expand those referencing external files. It recursively reads file content, converts each line into arguments, and integrates them into the argument list, handling potential I/O errors. The process ensures arguments starting with specified prefixes are replaced by their file'... | def _read_args_from_files(self, arg_strings):
# expand arguments referencing files
new_arg_strings = []
for arg_string in arg_strings:
# for regular arguments, just add them back into the list
if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
... |
def evaluate(self):
self.total_expression += self.current_expression
self.update_total_label()
try:
self.current_expression = str(eval(self.total_expression))
self.total_expression = ""
except Exception as e:
self.current_expression = "Error"
... | This code binds keyboard keys to specific methods in a GUI application. It links the Enter key to evaluate expressions, digit keys to append numbers, operation keys to add operators, and Backspace to delete the last character, enabling interactive input handling in a calculator-like interface. | def bind_keys(self):
self.window.bind("<Return>", lambda event: self.evaluate())
for key in self.digits:
self.window.bind(str(key), lambda event,digit=key: self.add_to_expressions(digit))
for key in self.operations:
self.window.bind(key, lambda event, operator=key: self.... |
def create_display_frame(self):
frame = tk.Frame(self.window, height=221, bg=GRAY)
frame.pack(expand=True, fill="both")
return frame
def create_display_labels(self):
total_label = tk.Label(self.display_frame, text=self.total_expression, anchor=tk.E, bg=GRAY,
... | This code initializes a Tkinter-based calculator GUI, setting up the main window, display labels, digit/operator buttons, and their grid layout. It configures the interface with fixed dimensions, non-resizable settings, and binds keys for functionality. | def __init__(self):
self.window = tk.Tk()
self.window.geometry("375x667")
self.window.resizable(0,0)
self.window.title("Calculator")
self.total_expression = ""
self.current_expression = ""
self.display_frame = self.create_display_frame()
self.total_label... |
def loadNormalizedData():
test_labels, test_data = importCSVFile("dataset1.csv", 2000)
validation_labels, validation_data = importCSVFile("validation1.csv", 2001)
norm_max = max([np.amax(test_data), np.amax(validation_data)])
norm_min = min([np.amin(test_data), np.amin(validation_data)])
# Normali... | The main task of the code is to run a k-means clustering algorithm with adjustable parameters (iterations, clusters), load normalized data, optionally generate a scree plot, identify labeled centroids, and measure accuracy on validation data. It uses command-line arguments for configuration, including enabling debug ou... | def main():
random.seed(0)
global verbose
global num_iterations
parser = argparse.ArgumentParser(description='kNearestNeighbors')
parser.add_argument("-i", "--iterations", required=False, default=5, type=int,
help="amount of times find the best centroi... |
def line_is_correct(self, args, line_number):
if len(args) != 5:
self.errors.append({'case': self.cases_count, 'text': 'ARGS AMOUNT ERROR IN LINE %s' % line_number})
self.case_is_correct = False
return False
else:
# Check if country name is correct
... | This code parses a file containing country data, processing each case by reading country parameters, creating Country objects, updating grid dimensions, and handling multiple test cases. It skips empty lines, validates input, tracks errors, and triggers grid filling and day-counting processes once per case. | def parse(self, name):
file = open(name, 'r')
country_number = 0
line_number = 0
case_is_started = False
for line in file:
line_number += 1
# Skip whitespaces
if not line.strip():
continue
# If new case is started w... |
def initGameBoard(model):
drawBoxes(model)
drawLabels(model)
def drawShip(model, board, ship):
color = YELLOW
for sqr in ship.locations:
if board == 'user':
color = YELLOW
sqr_obj = model.user_locations[sqr]
else:
color = BLUE
sqr_obj = mod... | This code implements a Battleship game using Pygame. It initializes a game board, allows the user to place ships by clicking on the grid, and alternates turns between the player and CPU. The player fires at the CPU's board, while the CPU automatically makes attacks. The game checks for hits, misses, and win conditions,... | def main():
global DISPLAYSURF
model = GameBoardModel()
pygame.init()
DISPLAYSURF = pygame.display.set_mode((model.board_width * 2, model.board_height))
mousex = 0 # used to store x coordinate of mouse event
mousey = 0 # used to store y coordinate of mouse event
pygame.display.set_caption... |
def encode(i, frame_in, frame_out, quality, sharpen, noise):
img_in = pathIn(frame_in)
img_out = pathOut(frame_out)
# generating os command for conversion
# sharpen actuator
if sharpen != 0:
sharpenstring = ' -sharpen ' + str(sharpen) + ' '
else:
sharpenstring = ' '
# noise actuator
if noise != 0:
noisest... | The code processes video frames using a specified control algorithm (DCT, MPC, random, or bangbang) to encode each frame with adjustable quality and compression parameters. It logs metrics like quality, size, and SSIM for each frame, iteratively adjusting actuator values based on the chosen mode and setpoints. The goal... | def main(args):
# parsing arguments
mode = args[1] # identify, mpc
folder_frame_in = args[2]
folder_frame_out = args[3]
folder_results = args[4]
setpoint_quality = float(args[5])
setpoint_compression = float(args[6])
mode = 'dct'
# getting frames and opening result file
path, dirs, files = os.walk(folder_fra... |
def exposed(self, position):
x, y, z = position
for dx, dy, dz in FACES:
if (x + dx, y + dy, z + dz) not in self.world:
return True
return False
def show_block(self, position, immediate=True):
texture = self.world[position]
... | This method checks neighboring blocks around a given position. It iterates through all six face directions, verifies if each neighbor exists in the world, and updates their visibility: showing exposed blocks not already visible, and hiding non-exposed blocks that are currently shown. The task is to synchronize block vi... | def check_neighbors(self, position):
x, y, z = position
for dx, dy, dz in FACES:
key = (x + dx, y + dy, z + dz)
if key not in self.world:
continue
if self.exposed(key):
if key not in self.shown:
... |
def sectorize(position):
x, y, z = normalize(position)
x, y, z = x // RENDER_DISTANCE, y // RENDER_DISTANCE, z // RENDER_DISTANCE
return (x, 0, z)
def hide_block(self, position, immediate=True):
self.shown.pop(position)
if immediate:
self._hide_block(posit... | This function removes a block at the specified position from the world, updates the sector data structure, and optionally hides the block and checks neighboring blocks for immediate visual or structural updates if 'immediate' is True. | def remove_block(self, position, immediate=True):
del self.world[position]
self.sectors[sectorize(position)].remove(position)
if immediate:
if position in self.shown:
self.hide_block(position)
self.check_neighbors(position) |
def remove_block(self, position, immediate=True):
del self.world[position]
self.sectors[sectorize(position)].remove(position)
if immediate:
if position in self.shown:
self.hide_block(position)
self.check_neighbors(position)
def sect... | This method adds a block to the world at a specified position with a given texture. If a block already exists at that position, it is removed first. The block is then stored in the world dictionary, and its position is added to the corresponding sector list. If 'immediate' is True, the block is rendered if exposed, and... | def add_block(self, position, texture, immediate=True):
if position in self.world:
self.remove_block(position, immediate)
self.world[position] = texture
self.sectors.setdefault(sectorize(position), []).append(position)
if immediate:
if self... |
def convert_to_black_background(self):
kernel = np.ones((self.kernel_size, self.kernel_size), np.uint8)
(thresh, img) = cv2.threshold(self.read_to_black_white_img(), self.min_thresh, 255, cv2.THRESH_BINARY_INV)
img = cv2.dilate(img, kernel, iterations=1)
return img
def getx1x2(self):
... | The main task of the code is to pad an image with a black border of size `self.n` pixels on all sides using NumPy's `np.pad` function, after converting the image to a black background. The original cropping logic is commented out, so the function ultimately returns the padded image with zero-padding applied. | def crop(self):
img = self.convert_to_black_background()
x1, x2 = self.getx1x2()
y1, y2 = self.gety1y2()
# img = img[y1 - 1:y2 + 1, x1 - 1:x2 + 1]
img = np.pad(img, [(self.n, self.n), (self.n, self.n)], mode='constant', constant_values=0)
return img |
def build_rep_lst_agg(rep_lst):
'''
For example, if rep_lst = [2, 4, 5], the rep_lst_agg = [2, 6, 11]
'''
rep_lst_agg = [] # the aggregate list of replicates
for i in range(len(rep_lst)):
rep_lst_agg.... | The function generates interactive visualizations (bar, stacked bar, percentage-based stacked bar) to display saturation levels from input data `X`, conditioned on `cond_lst` and aggregated by `rep_lst`. Users select plot types via checkboxes, triggering corresponding plotting functions. | def saturation_level_plot(X, cond_lst, rep_lst):
temp = X.copy()
rep_lst_agg = build_rep_lst_agg(rep_lst)
show_typical_bar = st.checkbox("View Typical Bar Plots")
if show_typical_bar:
saturation_level_plot_bar(temp, rep... |
def open_file(formData,canvas,scaled_image_size):
"""
Desc:
This function is responsible for opening an image file either jpg, or png.
Inputs: N/A
Returns: N/A
"""
file_path = askopenfile(mode='r', filetypes=[('Image Files', 'jpg'),('Image Files', 'png')])
if file_path is not None:
... | The main task of the code is to initialize a GUI interface for uploading images and entering associated text. It creates labels, buttons, and text fields within a Tkinter frame, stores these elements in a dictionary for later access, and links buttons to functions for file upload, text submission, and processing. The i... | def initialise_image_and_text(dictionary):
image_and_image_text = dictionary.get('image_and_image_text_frame')
dictionary['active_frame'] = image_and_image_text
formData = dictionary.get('form_data')
home_page = dictionary.get('home_page_frame')
scaled_image_size = dictionary.get('scaled_image_size'... |
def reset_model(self):
logging.info('Model reset')
self.model = river.naive_bayes.GaussianNB()
def train(self, state: GameState) -> None:
"""Taking a state that represents a piece positioned just before it
locks, train the AI that the piece's current position represents the
user-... | The code processes training and test records from queues in a loop, resetting the model if needed, and handles exceptions by logging errors. It continuously retrieves and processes items from train_queue and test_queue, executing train() and test() methods respectively, while managing reset operations and error logging... | def run(self):
while not self.stopped:
# Reset the model if the main thread set the reset_flag
if self.reset_flag:
try:
self.reset_model()
self.reset_flag = False
except:
logging.exception('Reset ... |
def predict(model, data, permute=False):
if permute:
predictions = list()
for batch_index in range(data.shape[0]):
predictions.append(predict_with_permutations(model, data[batch_index]))
return np.asarray(predictions)
else:
return model.predict(data)
def patch_wise_pr... | This function processes a validation test case by generating predictions from a model and saving the results as NIfTI files. It loads test data and ground truth from a dataset, applies the model (with options for patch-wise prediction and overlap), converts predictions to images using specified activation/threshold set... | def run_validation_case(data_index, output_dir, model, data_file, training_modalities, activation='softmax',
output_label_map=False, threshold=0.5, labels=None, overlap=16, permute=False,
non_healthy=False):
"""
Runs a test case and writes predicted images to file... |
def _is_tensor_a_torch_image(x: Tensor) -> bool:
return x.ndim >= 2
def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor:
"""Crop the given Image Tensor.
Args:
img (Tensor): Image to be cropped in the form [..., H, W]. (0,0) denotes the top left corner of the image.
... | The function `five_crop` crops an input image tensor into four corner regions and a central region, returning them as a list of five tensors. It is deprecated, with a warning to use `F.five_crop` instead. The function validates input dimensions, ensures the crop size is feasible, and applies corner and center crops usi... | def five_crop(img: Tensor, size: BroadcastingList2[int]) -> List[Tensor]:
"""DEPRECATED. Crop the given Image Tensor into four corners and the central crop.
.. warning::
This method is deprecated and will be removed in future releases.
Please, use ``F.five_crop`` instead.
.. Note::
... |
def _is_tensor_a_torch_image(x: Tensor) -> bool:
return x.ndim >= 2
def five_crop(img: Tensor, size: BroadcastingList2[int]) -> List[Tensor]:
"""DEPRECATED. Crop the given Image Tensor into four corners and the central crop.
.. warning::
This method is deprecated and will be removed in future rele... | The code performs a deprecated ten-crop operation on an image tensor, generating four corner crops, one central crop, and their flipped counterparts (horizontal by default or vertical if specified). It returns a list of ten tensors: five from the original image (top-left, top-right, bottom-left, bottom-right, center) a... | def ten_crop(img: Tensor, size: BroadcastingList2[int], vertical_flip: bool = False) -> List[Tensor]:
"""DEPRECATED. Crop the given Image Tensor into four corners and the central crop plus the
flipped version of these (horizontal flipping is used by default).
.. warning::
This method is deprec... |
def get_legal_knight_moves(self, state: State, location: Location) -> List[Location]:
moves = self.getLocationsFromTranslations(location, KNIGHT_TRANSLATIONS)
moves = self.filter_capture_own_piece_moves(state, location, moves)
moves = self.filter_own_king_in_check(state, location, moves)
... | This function determines legal moves for a chess piece at a given location. It checks if the location is empty, validates the player's turn, and delegates to specific methods for each piece type (knight, king, bishop, etc.) to calculate valid moves, returning them as a list of locations. | def get_legal_moves(self, state: State, location: Location) -> List[Location]:
piece = state.get_piece(location)
# Handle empty location
if piece == " ": return []
# Handle invalid turn
if state.active == "w" and piece.islower(): return []
if state.active == "b" and piec... |
def _traverse(self, string) -> Union[Active, None]:
active = Active(self.root, "", 0)
active.node = self.root
active.length = 0
active.edge = ""
for c in string:
if active.edge:
if (
c
!= self.total_string[
... | This function traverses a trie structure to find all suffixes of the input string. It yields tuples containing each suffix string and its end position, calculated by summing edge lengths from the node's start up to the root. The traversal begins with _traverse, checks for active nodes, iterates through leaves, and comp... | def find_all(self, string: str) -> Generator[Tuple[StringId, int], None, None]:
active = self._traverse(string)
if not active:
return None
node = active.node
if active.edge:
node = node.nodes[active.edge]
for node in node.iter_leaves():
suffix_... |
def fillReplayMemory(self, trainingEnv):
"""
GOAL: Fill the experiences replay memory with random experiences before the
the training procedure begins.
INPUTS: - trainingEnv: Training RL environment.
OUTPUTS: /
"""
# Fill the repla... | The main task of the code is to train a reinforcement learning (RL) agent by interacting with a specified environment over multiple episodes. It utilizes experience replay, epsilon-greedy action selection, and periodic learning updates to improve the agent's policy. The code tracks performance metrics (main and risk sc... | def training(self, trainingEnv, numberOfEpisodes, verbose=True, rendering=False, plotTraining=True):
"""
GOAL: Train the RL agent by interacting with the RL environment.
INPUTS: - trainingEnv: Training RL environment.
- numberOfEpisodes: Number of episodes for the traini... |
def login(self, email, password):
email_input = self.driver.find_element_by_id('userSignInFormEmail')
password_input = self.driver.find_element_by_id('user_password')
btn = self.driver.find_element_by_class_name('gr-button')
email_input.send_keys(email)
password_input.send_keys(p... | The code's main task is to automate logging into a website, search for books using a specified term, extract information from the search results, and return the collected book data. It navigates to a base URL, performs login, waits for page loads, retrieves book links, gathers details from those links, and finally quit... | def run(self):
self.driver.get(self.base_url)
time.sleep(5)
self.login(self.email, self.password)
links = self.search_for(self.search_term)
new_books = self.get_books_info(links)
time.sleep(4)
self.driver.quit()
return new_books |
def set_picAtoms(self, image = None, font = 6, colormap="RdYlBu_r", title="With atoms"):
try:
self.fig_atoms.clf()
except Exception as e:
print("Probably there's no figure to clear (fig_atoms).")
print("ERROR: " + str(e))
try:
self... | The main task of the code is to update multiple picture-related attributes (atoms, non-atoms, original data, background) by triggering a series of `set_pic` methods when `self.update_pics_controll` is enabled. It resets the control flag to 0 after execution and returns `True` if the update occurs, or `False` otherwise. | def update_pics(self):
self.update_pics_controll = 1
if self.update_pics_controll:
self.set_picAtoms()
self.set_picNoAtoms()
self.set_picOriginal()
self.set_picBkg()
self.update_pics_controll = 0
return True
... |
def update_plot_window(self):
n_runs = 3
var = "Atom Number"
try:
n_runs = int(self.plotWin.entryN_Runs.get_text())
if n_runs > len(self.im.history[var]):
n_runs = len(self.im.history[var])
if not self.plotWin.ave... | The main task of the code is to update data buffers, visualizations, and status information when new data is detected. It checks if data needs refreshing, triggers updates to the data buffer, plot window, images, and status, and handles exceptions. The function returns True after processing. | def update_functions(self):
try:
import numpy as np
# if dc.glob == self.im.dc.glob:
# return True
read_data = dc.receiving_flag != 1 and dc.glob != self.im.dc.glob
print("READ DATA: " + str(read_data))
if read_data:
s... |
def forward(
self,
output=None,
return_loss = False,
ignore_padding_zeros=False,
mask_prob=0.,# if > 0: Apply BERT style LLM mask
mask_token_prob = 0.,
mask_token=100,#token to be used to change into
context_mask = None,
task_end_token= -1,
... | This code generates token sequences using a model, incrementally building output by sampling tokens. It supports Gumbel sampling with top-k filtering, early stopping at EOS tokens, and padding. The process iterates for a fixed number of tokens, handling batches, and returns the generated sequence with optional truncati... | def generate(
self,
*,
output=None, #should provide it with at least a start token
tokens_to_generate=32,
filter_thres = 0.9,
temperature = 1.,
use_gumbel_sample=True, #whether or not ot use gumbel sampling
eos_token = None,
pad_value=0, #for padd... |
def create_tokens(code: str) -> list:
"""
Transforms a string of Lisp code into a list of tokens.
:param code: A string of Lisp code.
:type code: str
:returns: A list of tokens.
:rtype: list
"""
return code.strip().replace(")", " ) ").replace("(", " ( ").split()
def parse(tokens: list) ... | The main task of the code is to interpret and evaluate Lisp-like code. It runs an interactive REPL if the --repl flag is provided, continuously prompting for input, tokenizing, parsing, and evaluating expressions. Otherwise, it directly evaluates the contents of the "code" variable. | def main():
"""
Accept a string of Lisp, interpret the code, then evaluate it.
"""
# create interactive repl if --repl argument provided, else evaluate value of "code"
if len(arguments) > 1 and arguments[1] == "--repl":
try:
while True:
prompt = input("* ")
... |
def create_QFT(circuit,up_reg,n,with_swaps):
i=n-1
""" Apply the H gates and Cphases"""
""" The Cphases with |angle| < threshold are not created because they do
nothing. The threshold is put as being 0 so all CPhases are created,
but the clause is there so if wanted just need to change the 0 of the... | This code implements a quantum circuit for modular exponentiation and order finding, a key component in Shor's algorithm. It applies controlled modular additions (ccphiADDmodN) with powers of 2 multiplied by 'a' mod N, followed by QFT and inverse QFT operations. The circuit includes controlled-swap gates and modular in... | def Ua_basic(circuit, ctl, q, aux, a, N, n):
create_QFT(circuit,aux,n+1,0)
for i in range(0, n):
ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1)
create_inverse_QFT(circuit, aux, n+1, 0)
for i in range(0, n):
circuit.cswap(ctl,q[i],aux[i])
a_inv = modinv(a, N)
... |
def register_cnot(circuit,x,t,type,n_ctrl):
if type=='0':
for i in range(0,n_ctrl):
circuit.x(x[i])
circuit.mcx(x,t)
for i in range(0,n_ctrl):
circuit.x(x[i])
else:
circuit.mcx(x,t)
def incremental_gate_controlled(circuit,x,g,n):
if(n==2):
circ... | This function implements a controlled quantum operation block within a quantum circuit, using ancilla qubits (f, k, l) to apply a conditional transformation. It toggles qubits with X gates, applies CNOTs for entanglement, and invokes a controlled block operation (via 'controlled_block') to execute a specific quantum al... | def round(circuit,u,v,ca,s,r,cb,cc,m,f,k,l,n):
register_cnot(circuit,k,f,'0',l) #the qubit is toggled if k is 0, so we add another x-gate
circuit.x(f)
register_cnot(circuit,v,f,'0',n)
circuit.x(f)
incremental_gate_controlled(circuit,f[0:1]+k[0:l],v[0:l],l+1)
circuit.x(f)
#creating sub_circui... |
def bitwise_complement(circuit,g,n):
for i in range(0,n):
circuit.x(g[i])
def doubly_controlled_carry_gate(circuit,ctrl1,ctrl2,a,g,m,c,n):
circuit.mcx(ctrl1[0:1]+ctrl2[0:1]+g[n-2:n-1],m)
for i in range(n-1,1,-1):
if(c[i]=='1'):
circuit.cx(a[i],g[i-1])
circuit.x(a[i])
... | This function implements a controlled modular addition operation (ccADDmodN) on a quantum circuit. It performs a sequence of bitwise complementations, controlled additions/subtractions, and XOR operations to conditionally add a value 'a' modulo 'N' to a quantum register. The process involves comparing N-a and a, applyi... | def ccADDmodN(circuit, ctrl1, ctrl2, q, aux, g, a, N, n):
s_a=bin(int(a))[2:].zfill(n)
s_N=bin(int(N))[2:].zfill(n)
N_a=bin(int(N)-int(a))[2:].zfill(n)
"""CMP(N-a)"""
bitwise_complement(circuit,q,n)
doubly_controlled_carry_gate(circuit,ctrl1,ctrl2,q,aux,g,N_a,n)
bitwise_complement(circuit,q,... |
def Ua_basic(circuit, ctl, q, aux, a, N, n):
create_QFT(circuit,aux,n+1,0)
for i in range(0, n):
ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1)
create_inverse_QFT(circuit, aux, n+1, 0)
for i in range(0, n):
circuit.cswap(ctl,q[i],aux[i])
a_inv = modinv(a, N)
... | The function `period_finder` constructs a quantum circuit to determine the period of a number `a` modulo `N` using quantum algorithms (e.g., Shor's algorithm). It configures qubit registers, applies modular exponentiation, inverse QFT, and conditional operations based on parameters like `method` (basic/inplace) and `se... | def period_finder(N,a,number_shots,sequential,simulator,ibm,quantum_machine,method):
n = math.ceil(math.log(N,2))
if sequential=='False':
if method=='Basic':
n_qubit=4*n+2
else:
n_qubit=4*n+1
else:
if method=='Basic':
n_qubit=2*n+3
else:
... |
def addition(circuit,x,y,c,N):
for i in range(1,N):
circuit.cx(x[i],y[i])
circuit.cx(x[N-1],c)
for i in range(N-2,0,-1):
circuit.cx(x[i],x[i+1])
for i in range(0,N-1):
circuit.ccx(y[i],x[i],x[i+1])
circuit.ccx(y[N-1],x[N-1],c)
for i in range(N-1,0,-1):
circuit.cx(... | This function performs modular addition of two numbers x and y modulo p in a quantum circuit. It adds x and y, subtracts p, applies controlled additions, compares results, and flips a qubit. The core task is quantum modular arithmetic, essential for algorithms like Shor's algorithm. | def addition_modp(circuit,x,y,c,g,p,n):
p1 = p+'0'
addition(circuit,x,y,c,n)
constant_subtraction(circuit,y[0:n]+c[0:1],g,p1,n+1)
controlled_constant_addition(circuit,c,y,g,p,n)
comparator(circuit,y,x,c,n)
circuit.x(c) |
def binary_doubling_cyclic(circuit,x,n):
for i in range(n-1,0,-1):
circuit.cx(x[i-1],x[i])
circuit.cx(x[i],x[i-1])
circuit.cx(x[i-1],x[i])
def constant_subtraction(circuit,x,g,c,n):
sub_x = QuantumRegister(n)
sub_g = QuantumRegister(1)
sub_circ = QuantumCircuit(sub_x,sub_g, name=... | This function implements a quantum circuit for modular doubling operation. It applies cyclic binary doubling, constant subtraction, and controlled addition to perform doubling modulo p, using quantum gates to handle arithmetic operations on qubits. The circuit manipulates qubit registers x and c, applying X and CX gate... | def doubling_modp(circuit,x,c,g,p,n):
p1 = p+'0'
binary_doubling_cyclic(circuit,x[0:n]+c[0:1],n+1)
constant_subtraction(circuit,x[0:n]+c[0:1],g,p1,n+1)
controlled_constant_addition(circuit,c,x,g,p,n)
circuit.x(x[0])
circuit.cx(x[0],c)
circuit.x(x[0]) |
def controlled_addition(circuit,ctrl,x,y,c,n):
sub_x = QuantumRegister(n)
sub_y = QuantumRegister(n)
sub_c = QuantumRegister(1)
sub_circ = QuantumCircuit(sub_x,sub_y,sub_c, name='adder')
addition(sub_circ,sub_x,sub_y,sub_c,n)
sub_inst = sub_circ.to_gate().control()
circuit.append(sub_inst,ct... | The main task of the code is to implement a controlled modular addition operation in a quantum circuit. It performs controlled addition, constant subtraction, controlled constant addition, and a comparator to conditionally apply operations based on qubit states, ultimately executing arithmetic modulo p with quantum gat... | def controlled_addition_modp(circuit,ctrl,x,y,c,g,p,n):
p1 = p+'0'
controlled_addition(circuit,ctrl,x,y,c,n)
constant_subtraction(circuit,y[0:n]+c[0:1],g,p1,n+1)
controlled_constant_addition(circuit,c,y,g,p,n)
controlled_comparator(circuit,ctrl,y,x,c,n)
circuit.x(c) |
def doubly_controlled_addition(circuit,ctrl1,ctrl2,x,y,c,n):
sub_x = QuantumRegister(n)
sub_y = QuantumRegister(n)
sub_c = QuantumRegister(1)
sub_circ = QuantumCircuit(sub_x,sub_y,sub_c, name='adder')
addition(sub_circ,sub_x,sub_y,sub_c,n)
sub_inst = sub_circ.to_gate().control().control()
ci... | This function performs a doubly-controlled modular addition operation on quantum registers, using two control qubits (ctrl1, ctrl2) to conditionally add values modulo p. It incorporates ancilla qubits (g, c) for intermediate computations, involving steps like controlled addition, subtraction, and comparison. The proces... | def doubly_controlled_addition_modp(circuit,ctrl1,ctrl2,x,y,c,g,p,n):
p1 = p+'0'
doubly_controlled_addition(circuit,ctrl,x,y,c,n)
constant_subtraction(circuit,y[0:n]+c[0:1],g,p1,n+1)
controlled_constant_addition(circuit,c,y,g,p,n)
doubly_controlled_comparator(circuit,ctrl1,ctrl2,y,x,c,n)
circuit... |
def controlled_binary_doubling_cyclic(circuit,ctrl,x,n):
for i in range(n-1,0,-1):
circuit.ccx(ctrl,x[i-1],x[i])
circuit.ccx(ctrl,x[i],x[i-1])
circuit.ccx(ctrl,x[i-1],x[i])
def constant_subtraction(circuit,x,g,c,n):
sub_x = QuantumRegister(n)
sub_g = QuantumRegister(1)
sub_circ =... | The main task of the code is to implement a controlled modular doubling operation on a quantum circuit. It applies controlled arithmetic operations (doubling, subtraction, addition) modulo $ p $, using a control qubit to conditionally execute these operations on target qubits. The circuit manipulates quantum registers ... | def controlled_doubling_modp(circuit,ctrl,x,c,g,p,n):
controlled_binary_doubling_cyclic(circuit,ctrl,x[0:n]+c[0:1],n+1)
constant_subtraction(circuit,x[0:n]+c[0:1],g,s_p1,n+1)
controlled_constant_addition(circuit,c,x,g,s_p,n)
circuit.x(x[0])
circuit.ccx(ctrl,x[0],c)
circuit.x(x[0])
circuit.x(... |
def controlled_addition(circuit,ctrl,x,y,c,n):
sub_x = QuantumRegister(n)
sub_y = QuantumRegister(n)
sub_c = QuantumRegister(1)
sub_circ = QuantumCircuit(sub_x,sub_y,sub_c, name='adder')
addition(sub_circ,sub_x,sub_y,sub_c,n)
sub_inst = sub_circ.to_gate().control()
circuit.append(sub_inst,ct... | This code implements a quantum circuit for Montgomery multiplication modulo p, a technique used in modular arithmetic for efficient encryption. It constructs a sub-circuit with controlled additions, binary halving, and modular adjustments, then appends it to the main circuit. The process involves quantum registers for ... | def montgomery_multiplication_modp(circuit,x,y,c,z,g,m,r,p,n):
p1 = p+'0'
sub_x = QuantumRegister(n)
sub_y = QuantumRegister(n)
sub_c = QuantumRegister(1)
sub_z = QuantumRegister(n)
sub_g = QuantumRegister(1)
sub_m = QuantumRegister(n)
sub_circuit = QuantumCircuit(sub_x,sub_y,sub_c,sub_z... |
def controlled_addition(circuit,ctrl,x,y,c,n):
sub_x = QuantumRegister(n)
sub_y = QuantumRegister(n)
sub_c = QuantumRegister(1)
sub_circ = QuantumCircuit(sub_x,sub_y,sub_c, name='adder')
addition(sub_circ,sub_x,sub_y,sub_c,n)
sub_inst = sub_circ.to_gate().control()
circuit.append(sub_inst,ct... | This function implements Montgomery squaring in a quantum circuit for modular arithmetic. It constructs a subcircuit performing Montgomery multiplication modulo p, applies controlled operations for modular addition and subtraction, and integrates it into the main circuit. The process involves quantum registers for oper... | def montgomery_squaring_modp(circuit,ca,x,c,z,g,m,r,p,n):
p1=p+'0'
sub_ca = QuantumRegister(1)
sub_x = QuantumRegister(n)
sub_c = QuantumRegister(1)
sub_z = QuantumRegister(n)
sub_g = QuantumRegister(1)
sub_m = QuantumRegister(n)
sub_circuit = QuantumCircuit(sub_ca,sub_x,sub_c,sub_z,sub_... |
def check_if_power(N):
""" Check if N is a perfect power in O(n^3) time, n=ceil(logN) """
b=2
while (2**b) <= N:
a = 1
c = N
while (c-a) >= 2:
m = int( (a+c)/2 )
if (m**b) < (N+1):
p = int( (m**b) )
else:
p = int(N+... | The code implements Shor's algorithm for integer factorization using quantum computing. It checks if $ N $ is even or a prime power, selects a coprime $ a $, and uses a quantum circuit (`period_finder`) to determine the period of $ a^x \mod N $. It processes measurement results to derive factors of $ N $, returning the... | def Shor(N,a=0,number_shots=0,sequential='True',simulator='True',ibm='True',quantum_machine='',method='Basic',runtime='False',prob='False'):
""" Check if N is even """
if (N%2)==0:
print('N is even, so does not make sense!')
exit()
""" Check if N can be put in N=p^q, p>1, q>=2 """
""... |
def mod_inv_function(circuit,u,v,ca,s,r,cb,cc,m,f,k,l,n):
circuit.x(s[0])
circuit.x(f)
for i in range(0,2*n):
round(circuit,u,v,ca,s,r,cb,cc,m[i:i+1],f,k,n,l)
def constant_subtraction(circuit,x,g,c,n):
sub_x = QuantumRegister(n)
sub_g = QuantumRegister(1)
sub_circ = QuantumCircuit(sub_x,... | This function performs modular inverse computation on a quantum circuit. It applies X gates conditionally, executes a modular inverse function, and uses controlled operations (CX, controlled doubling, addition) to manipulate qubits. It iteratively adjusts values with constant subtraction/addition and bitwise complement... | def mod_inv(circuit,u,v,ca,s,r,cb,cc,m,f,k,y_r,y_k,p,l,n):
for i in range(0,n):
if p[i] == '1':
circuit.x(u[i])
mod_inv_function(circuit,u,v,ca,s,r,cb,cc,m,f,k,n,l)
for i in range(0,n):
circuit.cx(r[i],y_r[i])
if(i<l):
circuit.cx(k[i],y_k[i])
for i in rang... |
def prevPrime(n):
if n%2==0: return prevPrime(n-1)
elif isPrime(n): return n
else: return prevPrime(n-2)
def buildModHashTable(L,p):
return buildHashTable (L, lambda w: modHash(w,p), p)
def hashCompress(L, m):
t = len(L)
positionedL = [(L[x], x) for x in range(t)]
sortedL = mergeSortHash(pos... | The code initializes a hash table with controlled load factors. It calculates the number of buckets (self.r) using a prime number derived from the input size and load (lam), then constructs a hash table (HT) with these parameters. The code compresses this hash table into a smaller size (self.m) based on the desired loa... | def __init__ (self,keys,lam,load):
# keys : list of keys to be hashed
# lam : load on outer table, i.e. average bucket size
# (broadly, higher lam means more compression,
# but perfect hash function will be harder to construct)
# load : desired load on resulting h... |
def _validate_integer(self, action_result, parameter, key):
if parameter:
try:
if not float(parameter).is_integer():
return action_result.set_status(phantom.APP_ERROR, VALID_INTEGER_MSG.format(key=key)), None
parameter = int(parameter)
... | The main task of the code is to handle the "list container" action by validating parameters, making a REST call to a Docker API endpoint to retrieve container data, processing the response, and updating the action result with container details like IDs and names, while handling errors and formatting the summary for the... | def _handle_list_container(self, param):
# Implement the handler here
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self
# (BaseConnector) to represent the action for this param
action_result = self.add_act... |
def _validate_integer(self, action_result, parameter, key):
if parameter:
try:
if not float(parameter).is_integer():
return action_result.set_status(phantom.APP_ERROR, VALID_INTEGER_MSG.format(key=key)), None
parameter = int(parameter)
... | This code handles the deletion of a builder cache by validating parameters like 'keep_storage' and 'filters', making a POST request to prune the cache, and returning the result. It ensures input validation, processes the API response, and updates the action summary with the cache data. | def _handle_delete_builder_cache(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
keep_storage = param.get('keep_storage', '')
# Validate 'keep_storage' action parameter
... |
def ensure(self, size=0):
if len(self.l) < size:
self._r()
def consume(self, size=0):
"""'eats' some chars of the buffer.
it handles reading ahead,
level, etc
"""
self.ensure(size)
size = min(size, len(self.l))
b = self.l[:size]
self.l = self.l[size:]
self.ensure(1)
###tries level guessing. wh... | This function scans and returns a substring of consecutive characters from `self.l` that are all in the provided `toks` list, stopping when a character not in `toks` is encountered. It either consumes the scanned characters (removing them from the input) or just peeks at them, based on the `consume` flag. The result is... | def getWhile(self, toks=[], consume=True):
"checks if a string of possible tokens until one is different"
p = 0
b = ""
while p<len(self.l) and (self.l[p] in toks):
p += 1
self.ensure(p+1)
if consume:
b = self.consume(p)
else:
b = self.peek(p)#we still have to inform what we scanned
print ("s... |
def _r(self):
print("reading")
if self.f.closed :
print("reading a closed file! wtf no")
self.level = -1
return
l = self.f.readline()
level = 0
#if (strip) and (l[-1]=="\n"): l = l[:-1]
if l == "":
self.f.close()
print ("no moar to read")
if self.l:
if self.l[-1] != "\n": self.l += "... | This method finds the earliest occurrence of any token in `toks` within the current string, handles end-of-file logic if the file is closed, and returns the substring up to that position. If `consume` is True, it consumes the characters; otherwise, it peeks. If no tokens are found and `or_end` is True, it returns the f... | def getTill(self, toks=[], consume=True, or_end=True):
p = 0
while p==0:
ps = []
for i in toks:
pp = self.l.find(i)+1#notice +1
if pp>0 : ps.append(pp)
if ps : p = min(ps)
if p==0:
if self.f.closed :
p = 0
if or_end :
p = len(self.l)
break
else:
self._r()
i... |
def _get_cram_banks(self) -> Banks:
cram = self._all_blank_cram_banks()
self._write_cram_banks(cram)
return cram
def _get_bram_banks(self) -> Banks:
bram = self._all_blank_bram_banks()
self._write_bram_banks(bram)
return bram
def get_nonzero_chunks(cls, data: np.ndarray, granularity: int, align: bool)... | The code writes a binary bitstream to a file, configuring CRAM and BRAM banks with options for optimization, chunking, and output settings. It writes comments, preamble, frequency ranges, CRC resets, warmboot/nosleep flags, and data from CRAM/BRAM banks, adjusting parameters like bank width, height, and offset based on... | def write_bin(self, bin_file: BinaryIO, opt: BinOpt=BinOpt()):
"""Writes binary bitstream"""
cram = self._get_cram_banks()
bram = self._get_bram_banks()
bin_out = BinOut(bin_file)
reuse = opt.optimize > 0
# comment
comment = self._comment
if opt.skip_comment:
comment = None
bin_out.write_c... |
def get_possible_val(board, i, j):
"""
Get the possible values of the cell [i,j] by removing those present in the row, column and 3x3 square it belongs to
:param board: sudoku
:param i: row of the current cell
:param j: column of the current cell
:return: list of the possible values
"""
... | The function recursively attempts all possible values for a Sudoku cell, assigns each value to the board, and proceeds to the next cell. It checks if the board becomes valid after each assignment. If valid, it returns; otherwise, it backtracks by resetting the cell. This backtracking approach systematically explores po... | def try_values(board, to_check, k):
"""
Given a cell, try every possible values.
After trying one value call the function on the next cell.
:param board:
:param to_check: list containing the coordinates of the empty/variable cells
:param k: index position of the coordinates of the current cell
... |
def get_3x3blocks():
"""
Get the coordinates of the nine 3x3 squares in a 9x9 sudoku
:return:
"""
blocks_list = []
for k in range(0, 9):
tmp_list = []
rows = [i + 3 * (k % 3) for i in range(0, 3)]
cols = [i + 3 * math.trunc(k / 3) for i in range(0, 3)]
for x in ro... | The code solves Sudoku using Simulated Annealing by iteratively generating random states, calculating their conflict cost, and adjusting temperature to explore solutions. It initializes parameters, tracks empty cells, and decreases temperature until a valid board (cost=0) is found, returning the solved Sudoku and itera... | def solves_sudoku(board):
"""
Solves the sudoku using Simulated Annealing.
Define a starting temperature and a temperature decrease rate for the Simulated Annealing.
:param board:
:return:
"""
# the starting board is used to track the empty/variable cells, those with 0
working_board = np... |
def get_empty_cells(board):
"""
Get the indexes of all the empty/variable cells sorted by the rows with less empty cells
:param board: sudoku's board
:return:
"""
empty_cells = []
for i in get_rows_ranked(board):
for j in range(9):
if board[i][j] == 0:
emp... | The code solves a Sudoku puzzle by filling empty cells using the `try_values` method. It checks if the resulting board is valid with `validate_sudoku`. If invalid, it raises an error stating no solution exists. The main task is to solve the Sudoku board and verify its correctness, ensuring all rows, columns, and 3x3 gr... | def solver(board):
"""
Solving function.
:param board:
:return:
"""
empty_cell = get_empty_cells(board)
# try_values_heuristic(board, empty_cell, 0)
try_values(board, empty_cell, 0)
if not validate_sudoku(board, 9):
errmsg = 'There is no solution to this sudoku.'
ra... |
def testAddMine():
#arrange
store = s.Store()
coord = (1, 2)
#act
store.addMine(coord)
#assert
result = store.isMine(coord)
print(store.mines)
assert(result)
def testSetUpMines():
store = s.Store()
mines = 1
size = 5
#act
minesList = setUpMines(mines, size)... | The main task of the code is to initialize a minesweeper game with a 5x5 grid and 5 mines, then execute test functions to validate mine placement logic, including adding mines, setting up mine coordinates, and creating coordinate lists for testing purposes. | def main():
#game variables
size = 5
mines = 5
testAddMine()
testSetUpMines()
testCreateMineCoords() |
def data_reshaper(self,data):
#data coming format: time, day, user_id, problem_id, {network_value}, correct_and_continued
#data going format: time, day, user_id, problem_id, network, value, correct_and_continued
h, w = data.shape
return_data = torch.zeros(h*self.networks, 7, dtype=torch.... | The code's main task is to process user interaction data through a neural network with memory cells, updating hidden states and context vectors using GRU-like operations. It integrates user-problem interactions, computes attention scores, and predicts outcomes (e.g., correctness) by combining memory states and input fe... | def forward(self,data):
self.tensor= torch.unique(torch.cat((self.tensor,data)),dim=0)
data = self.data_reshaper(data)
#data format: time, day, user_id, problem_id, network, value, correct_and_continued
users, counts = torch.unique(data[:,2], return_counts=True)
h_C_indices = sel... |
def send(sock, msg):
msg = struct.pack('>I', len(msg)) + msg
sock.sendall(msg)
def recieve(sock):
msg_len = receive_all(sock, 4)
if not msg_len:
raise RuntimeError("socket connection broken")
msg_len = struct.unpack('>I', msg_len)[0]
# Read the message data
return receive_all(sock, m... | The code establishes a client connection to a server at a specified HOST and PORT, sends a username input by the user, checks for a 'okay' response to confirm connection success, prompts the user for a destination to chat with, and initiates a chat session using the `chat` function. The main task is to facilitate clien... | def connect(client, HOST, PORT):
client.connect((HOST, PORT))
send(client, input('enter your username:').encode())
response = recieve(client)
if response != b'okay':
return
dest = input('connection made, who do you want to message?')
chat(client, dest) |
def load_raw_data_sliding_window(Directory):
raw_data = []
for activity in Directory:
if activity == "Transitions":
for transition in os.listdir('Data_Input/' + activity):
for orientation in os.listdir('Data_Input/' + "/" + activity + "/" + transition):
fo... | The main task of the code is to load and process 3D point cloud data by generating frame sequences, oversampling remaining frames, and saving them to a directory. It then loads these preprocessed arrays for training/testing, ensuring data consistency by tracking existing files in the target directory. | def load_mmData(Directory, TrainTest, Array_DIR):
point_cloud_scatter_samples = load_raw_data_sliding_window(Directory)
frame_sequences = generate_frame_sequences(point_cloud_scatter_samples)
saved_array_parts = len(os.listdir(Array_DIR))
oversample_and_save_remaining_frames(
frame_sequences, sa... |
def aspect_layer(ques, ans1, ans2, asp_num, dataset_name):
if args.limited:
user_prompt = task_funct[dataset_name][1](ques, ans1, ans2, asp_num)
else:
user_prompt = task_funct[dataset_name][0](ques, ans1, ans2, asp_num)
messages = [
{"role": "user", "content": user_prompt},
]... | The code evaluates two responses (ans1, ans2) to a question (ques) using a multi-layered neural network framework. It computes aspect-based scores across layers, aggregates results, and saves detailed evaluation data (scores, content, prompts) along with human scores (hm) to a file. The output includes aggregated score... | def BroadLLM_eval(input_):
ques, ans1, ans2, hm, dataset_name = input_
num_neuro = 2
num_layer = 2
cost = 0
layer = 0
hist_contents = {}
hist_scores = {}
hist_user_prompts = {}
aspects, asp_content, cst = aspect_layer(ques, ans1, ans2, num_neuro, dataset_name)
cost += cst
if ... |
def start_turn(self):
self.clear_board()
self.place_characters()
print(self.llm_friendly_world_state_string())
# get the first entity in the turn order and calculate its valid moves
entity = self.turn_order[0]
valid_moves = entity.calculate_valid_moves(self)
... | The main task of the code is to execute a game turn by selecting an action from possible options using a team-specific controller, applying the chosen action to update the game state, and concluding the turn. It involves initializing available actions, delegating decision-making to the appropriate controller, and progr... | def preform_turn(self):
possible_actions = self.start_turn()
# use the controller associated with the team to pick the action
controller = self.controllers[self.turn_order[0].team]
action_index = controller.choose_actions(self, possible_actions)
chosen_action = possible_... |
def find_s(rows):
for y, line in enumerate(rows):
x = line.find('S')
if x != -1:
return Coordinate(x, y)
def find_conns(start):
e = ''
for direction in ['N', 'S', 'E', 'W']:
new_pos, new_dir = go(start, direction)
if new_dir is not None:
e += direction... | The code reads a maze from a file, identifies the starting position 'S', determines connected paths, replaces 'S' with a pipe, and traces a loop through the maze. It counts steps taken until returning to the start, then outputs half the step count as the answer, asserting it equals 6903. | def part_1():
global maze
maze = [x.strip() for x in open('day10/input', 'r') if x != '\n']
start_pos = find_s(maze)
connections = find_conns(start_pos)
replace_s_to_pipe(start_pos, connections)
pos, direction, steps = start_pos, connections[0], 1
while True:
pos, direction = go(po... |
def find_s(rows):
for y, line in enumerate(rows):
x = line.find('S')
if x != -1:
return Coordinate(x, y)
def find_conns(start):
e = ''
for direction in ['N', 'S', 'E', 'W']:
new_pos, new_dir = go(start, direction)
if new_dir is not None:
e += direction... | The code processes a maze to determine the number of enclosed regions (dots) inside a loop formed by pipes starting from 'S'. It reconstructs the loop path, slices the maze to the loop's bounds, and uses a ray-casting algorithm to count interior dots, asserting the result as 265. | def part_2():
global maze
maze = [x.strip() for x in open('day10/input', 'r') if x != '\n']
start_pos = find_s(maze)
connections = find_conns(start_pos)
replace_s_to_pipe(start_pos, connections)
pos, direction, = start_pos, connections[0]
path = []
while True:
path.append(pos)
... |
def createNewNode(self):
connection = []
# noinspection PyUnresolvedReferences
if self.selected is None:
pos = [self.mapFromGlobal(QtGui.QCursor.pos()).x(), self.mapFromGlobal(QtGui.QCursor.pos()).y()]
elif type(self.selected) == nodeWidget.QNodeWidget:
pos = [sel... | This method handles user actions for node/edge operations in a GUI, executing create, edit, or delete actions based on the input 'action' parameter, but only when the object is not in edit mode and has focus. It raises an error for unsupported actions and triggers an update after processing. | def handleAction(self, action, origin=None):
if not self.inEditMode and self.hasFocus():
if action == "createNode":
self.createNewNode()
elif action == "editNode":
self.setEditNode(True)
elif action == "deleteNode":
self.deleteC... |
def deleteNode(self, node):
self.nodes.pop(node.id)
node.setParent(None)
node.deleteLater()
self.updateSelection(None)
def rebuildNode(self, data, edges=None):
position = [
data["position"][0] + self.offset.x(),
data["position"][1] + self.offset.y()
... | The code implements an undo functionality by reverting the last action (atom) from a state machine. It handles different atom types (e.g., editNode, addNode, deleteNode, editEdge, addEdge, deleteEdge) by applying corresponding reversals: restoring node/edge states, deleting added items, or rebuilding removed ones. Unim... | def undo(self):
atom = self.stateMachine.undo()
if atom is not None:
print(atom)
if atom["type"] == "editNode":
self.nodes[atom["id"]].applyChange(atom["old"])
elif atom["type"] == "addNode":
self.deleteNode(self.nodes[atom["data"]["id"... |
def deleteNode(self, node):
self.nodes.pop(node.id)
node.setParent(None)
node.deleteLater()
self.updateSelection(None)
def rebuildNode(self, data, edges=None):
position = [
data["position"][0] + self.offset.x(),
data["position"][1] + self.offset.y()
... | This function performs a 'redo' operation by retrieving the last undone action (atom) from the state machine. It applies the atom's changes to nodes or edges based on its type: editing, deleting, or adding elements. Specific methods like applyChange, deleteNode, and rebuildNode handle each atom type. If an unsupported ... | def redo(self):
atom = self.stateMachine.redo()
if atom is not None:
print(atom)
if atom["type"] == "editNode":
self.nodes[atom["id"]].applyChange(atom["new"])
elif atom["type"] == "deleteNode":
self.deleteNode(self.nodes[atom["data"]["... |
def inverse(a,b):
# returns: b^{-1} (mod a)
if b < 0:
return a - inverse(a,-b)
r = {-1:a,0:b}
s = {-1:1,0:0}
t = {-1:0,0:1}
q = {}
i = 0
while r[i] != 0:
i += 1
r[i] = r[i-2]%r[i-1]
q[i] = r[i-2]//r[i-1]
s[i] = s[i-2]-q[i]*s[i-1]
t[i] = t[... | The code retrieves messages from a server, checks if senders are contacts, decrypts messages using AES with shared keys, verifies digital signatures via elliptic curve operations, and deletes messages post-processing. It ensures message authenticity by validating signatures through hash truncation, modular arithmetic, ... | def checkMessages():
messages = server.checkMessages(name)
if messages == []:
print('There are no messages for you {}'.format(name))
else:
if len(messages) == 1:
print('You have {} message:'.format(len(messages)))
else:
print('You have {} messages:'.format(len... |
def inverse(a,b):
# returns: b^{-1} (mod a)
if b < 0:
return a - inverse(a,-b)
r = {-1:a,0:b}
s = {-1:1,0:0}
t = {-1:0,0:1}
q = {}
i = 0
while r[i] != 0:
i += 1
r[i] = r[i-2]%r[i-1]
q[i] = r[i-2]//r[i-1]
s[i] = s[i-2]-q[i]*s[i-1]
t[i] = t[... | The code verifies a digital signature using elliptic curve cryptography. It retrieves signatures from a server, selects a signature pair (r,s), truncates the message hash, computes modular inverses, and checks if the derived value v matches r. If valid, it accepts the signature; otherwise, it flags an error. | def checkSignature():
signatures = server.sendSignatures(name)
if signatures == {} or (len(signatures) == 1 and name in signatures):
print('There are no signatures to check')
else:
print('You can check the signature of:')
i = 1
people = []
for x in signatures:
... |
def inverse(a,b):
# returns: b^{-1} (mod a)
if b < 0:
return a - inverse(a,-b)
r = {-1:a,0:b}
s = {-1:1,0:0}
t = {-1:0,0:1}
q = {}
i = 0
while r[i] != 0:
i += 1
r[i] = r[i-2]%r[i-1]
q[i] = r[i-2]//r[i-1]
s[i] = s[i-2]-q[i]*s[i-1]
t[i] = t[... | The code decrypts received files using AES with shared keys and verifies their digital signatures. It checks if senders are contacts, decrypts filenames and content, validates signatures via SHA-512 and ECC operations, and confirms authenticity. If valid, it saves files and deletes them post-processing. Your return | def checkFiles():
files = server.sendFiles(name)
if files == []:
print('There are no files for you {}'.format(name))
else:
if len(files) == 1:
print('You have {} file:'.format(len(files)))
else:
print('You have {} files:'.format(len(files)))
for i in f... |
def xy2ColRow(x, y):
startX = -BOARD_WIDTH / 2
startY = -BOARD_WIDTH / 2
col = int((x - startX) / CELL_SIZE)
row = int((y - startY) / CELL_SIZE)
return col, row
def dropXPiece(col, row):
x = -BOARD_WIDTH / 2 + col * CELL_SIZE + CELL_SIZE / 2
y = -BOARD_WIDTH / 2 + row * CELL_SIZE + CELL_SIZE... | This function handles a player's click on a board by validating coordinates, placing a piece if the cell is empty, switching turns between 'x' and 'o', checking for a win, declaring the winner, and offering to restart the game. It ignores invalid clicks or occupied cells and manages game flow via turtle graphics. | def handleClick(x, y):
# if click is outside the board, ignore it
if x < -BOARD_WIDTH / 2 or x > BOARD_WIDTH / 2 or y < -BOARD_WIDTH / 2 or y > BOARD_WIDTH / 2:
return
global cur_player
# convert x, y to col, row
col, row = xy2ColRow(x, y)
# if piece already exists, ignore it
... |
def _writeFormHeader(self, headerDict: dict, sheet: Worksheet):
# Write check box
sheet.cell(row=3, column=14).value = '❑ \t Prototype'
sheet.cell(row=4, column=14).value = '❑ \t Pre-Launch'
sheet.cell(row=5, column=14).value = '❑ \t Production'
sheet.cell(row=7, c... | This code generates an Excel workbook by populating a template sheet with data from self.dataDict. It processes each item in 'processes', splits them into chunks, creates new sheets for each chunk, writes process-specific data, and saves the workbook as the specified file. | def generate(self, fileName: str):
headerDict = self.dataDict
processList = self.dataDict['processes']
templateSheet = self.workbook[self.templateSheetName]
self._writeFormHeader(headerDict, templateSheet)
totalProcess = len(processList)
pageCount = 1
for i, pro... |
def _make_new_candidates(self, c_min, c_max, dist_type, reelection):
n_candidates = np.random.randint(2, 11)
# n_candidates = 4
reelection = np.random.choice((0,1), n_candidates, p=(1-reelection, reelection))
candidate_dist = self._make_distribution(n_candidate... | The main task of the code is to execute a voting process by generating candidates, conducting primary elections to narrow down options, then holding general elections using primary results, and finally tallying vote counts with Counter to determine outcomes. | def _run_voting(self):
self._make_new_candidates(self.c_min, self.c_max, self.dist_type_c, self.reelection)
primary_results = self._run_primary_voting()
results = self._run_general_voting(primary_results)
return Counter(results) |
def handle_events(self):
# Handle each user event by changing the game state appropriately.
# - self is the Game whose events will be handled
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
self.close_clicked = True
if event.type == p... | The code runs the game loop, handling events, updating game state, and rendering frames at a set FPS until the player closes the window. It checks if the game should continue, updates game elements, and manages the frame rate using a clock. | def play(self):
# Play the game until the player presses the close box.
# - self is the Game that should be continued or not.
while not self.close_clicked: # until player clicks close box
# play frame
self.handle_events()
self.draw()
if self.continue_game:
... |
def mainMenu():
"""
This function will prompt the user to select an option from a menu of options, if the selection does not match
one of the options then the user will be notifyed and be prompted to select again
input: N/A
output: userInput [str]
"""
print(
"1. Print timetable",
... | The code defines a main function that runs a menu-driven application for managing a timetable. It displays a welcome message, loops to show a main menu, and executes actions like printing the timetable, enrolling in a class, dropping a class, or quitting. The loop continues until the user selects the quit option, which... | def main():
print("=" * 26, "Welcome to Mini-BearTracks", "=" * 26, sep="\n")
quit = False
while not quit:
action = mainMenu()
if action == "1":
printTimetable()
if action == "2":
enroll()
if action == "3":
dropClass()
if action ... |
def points_from_chords(file_name):
from madmom.audio.chroma import DeepChromaProcessor
from madmom.features.chords import (
DeepChromaChordRecognitionProcessor,
CRFChordRecognitionProcessor,
CNNChordFeatureProcessor
)
if (not args.mappings_from_chords_chroma and
not args.... | The function generates a timeline of mapping points based on user-specified audio analysis methods (chords, beats, notes) and parameters (output length, interval constraints). It combines points from selected sources, adjusts them according to constraints, and creates consecutive mappings between adjusted time points f... | def generate_mappings():
if (args.mappings_from_chords_chroma or
args.mappings_from_chords_cnn):
args.mappings_from_chords = True
if (args.mappings_from_beats_detection or
args.mappings_from_beats_detection_crf or
args.mappings_from_beats_tracking or
args.mappings_from_be... |
def parse_config_file(config_loc: str) -> dict:
""" Constructs an argument class from the configuration located at <config_loc>.
Args:
config_loc (str): Location of the configuration file.
Returns:
Argument: Argument class
"""
assert os.path.exists(config_loc), f" Given confi... | The function constructs a PyTorch model and transformation pipeline from a configuration file. It loads a base model and head module specified in the config, combines them into a sequential model, and applies transformations. The config dictates model architecture, weights, and preprocessing steps, returning the assemb... | def construct_full_model(config_loc: str) -> Tuple[torch.nn.Module, Compose]:
""" Construct a torch.nn.Module model and its transform from the config provided in config_loc.
Args:
config_loc (str): Location of the config file containing information about the model.
Returns:
Tuple[torch.nn.... |
def getNewGeneration(self, generationZise = 10):
nGenerationAnglesL1 = self.gs.generateNewGenGeneration(generationZise)
nGenerationAnglesL2 = self.gs.generateNewGenGeneration(generationZise)
nGenerationAnglesL3 = self.gs.generateNewGenGeneration(generationZise)
generationColl = {}
... | The main task of the code is to evolve solutions through a genetic algorithm by iteratively combining, mutating, and adding new individuals to two family populations over a specified number of generations. It checks for a valid solution in each generation, and if found, returns it. If not, it updates the populations wi... | def getGeneticResult(self, generations, familyPopulation = 10):
family1 = self.getNewGeneration(familyPopulation)
family2 = self.getNewGeneration(familyPopulation)
#New generation combined can have mutations in a grade of 10% of cases
for generation in range(generations):
pri... |
def eval():
# Retreive both best scores (straights)
my_score = best_in_score(ai_token)
your_score = best_in_score(player_token)
# Get the difference, this will give + if good for us
eval_score = my_score[0] - your_score[0]
# But if it is the player's turn, we want the opposite of that value
... | The code implements a minimax algorithm for a turn-based game, recursively evaluating all valid moves up to a given depth. It assesses board states to determine optimal moves, prioritizing winning positions and avoiding losses. When multiple moves yield equal scores, it randomly selects one to avoid bias. The algorithm... | def minimax(depth):
# Base condition, evaluate the final board state
if depth == 0:
return eval()
# Check for valid columns
valid = valid_cols()
if len(valid) == 0: # Full board
four_check = check_for_four()
# [-99, -99] is a tie, no winner
if four_check == [-99,... |
def _get_entity_table_name(entity_urn: str) -> str:
"""Gets the table which holds the data of an entity identified with a URN
Args:
entity_urn (:obj:`str`): URN of the entity.
Returns:
str or None: name of the table which holds the data of the specified entity,
... | The function retrieves historical PLC sensor data from a database by constructing and executing SQL queries, either fetching a specified number of rows or data within a given date range. It processes multiple PLC entities, translates table names to URNs, and compiles results into a DataFrame, returning None if no data ... | def get_data_from_plc(
self,
plc_sensors: dict,
n: int = 100,
from_date: str = None,
to_date: str = None,
):
"""Get historic data of PLCs.
Args:
plc_sensors (:obj:`dict`): in which the key is the URN of the PLC and the
value is a l... |
def preparePath(filepath):
if type(filepath) != str:
return filepath
if filepath.startswith("@"):
return None
if filepath.startswith("vehicles/"):
filepath = "/" + filepath
if filepath.endswith(".dds"):
filepath = filepath[:-4]
filepat... | This code generates a material by combining multiple layers using node-based shaders in a 3D software. It clears existing nodes, processes each layer to create BSDF shaders, mixes layers via opacity maps, handles transparency, and connects normal/geometry nodes to ensure correct rendering. The final output combines all... | def apply(self):
# Set up material
self.material.use_nodes = True
tree = self.material.node_tree
nodes = tree.nodes
# Clear Material
nodes.clear()
# Remove empty layers
self.layers = list(filter(None, self.laye... |
def ID3(self, attribute):
(unique_count, id3_S) = ([],[])
S = len(attribute)
for i in self.find_unique(attribute):
unique_count.append(attribute.count(i))
for item in unique_count:
id3_S.append(item/S)
return id3_S, self.find_unique(attribute)
def entropy(... | The code calculates the information gain of a specified attribute in a dataset using the ID3 algorithm. It computes the original entropy $E_S$ of the dataset and the conditional entropy $E_{Sa}$ after splitting by the attribute, then returns their difference $E_S - E_{Sa}$ as the attribute's information gain, aiding in... | def Gain(self, attribute, lable_Yes='Yes', lable_No='No'):
ID3 = self.ID3(self.y)[0]
E_S = self.entropy(ID3[0], ID3[1])
E_Sa = self.Multiple_entropy(attribute, lable_Yes, lable_No)
return E_S-E_Sa |
def _reset(self):
self.car_velocity = np.zeros(2)
self.car = Circle((0, 0), 20)
self.current_sim_steps = 0
self.car_direction = 0
self.travelled = 0
self.last_command = np.full(2, 0.5, dtype=np.float32)
self.sim_score = 0
self.terminate_simulation = False
... | The code simulates a car's movement in a environment by updating its velocity, direction, and position based on the given action. It calculates the observation, reward (based on forward velocity and magnitude), and checks for collisions. If a collision occurs, it terminates the simulation with a penalty; otherwise, it ... | def _step(self, action):
if self.terminate_simulation:
return self._reset()
self.last_command = action
commit_action = action
self.car_velocity -= self.car_velocity * 0.9 * (1.0/self.SIM_FPS)
self.car_direction += (2*commit_action[1]-1) * self.steering_amount * (1.... |
def define_axes(self):
s = 0.1
dx = 0.3
dy = 0.4
y0 = 1-s-dy
x0 = 0.15
xlabel = "$AGE$"
ylabel = "$GPA$"
self.ax = self.canvas.figure.add_axes([x0,y0,dx,dy])
self.zoom_ax = self.canvas.figure.add_axes([1-s-dx,y0,dx,dy])
self.ax.set_xlabe... | This method updates a graphical plot by clearing the current figure, redefining axes, updating data and parameters, adjusting plot elements, setting the title, redrawing the canvas, saving the figure, logging parameters, and emitting a completion signal. | def update_graph(self, **kwargs):
self.canvas.figure.clear()
self.define_axes()
self.update_data(**kwargs)
self.update_params(**kwargs)
self.update_axes(**kwargs)
#self.update_area_selector(**kwargs)
self.canvas.figure.suptitle(self.params.title)
self.canv... |
def define_axes(self):
s = 0.1
dx = 0.3
dy = 0.4
y0 = 1-s-dy
x0 = 0.15
xlabel = "$AGE$"
ylabel = "$GPA$"
self.ax = self.canvas.figure.add_axes([x0,y0,dx,dy])
self.zoom_ax = self.canvas.figure.add_axes([1-s-dx,y0,dx,dy])
self.ax.set_xlabe... | This code initializes a graphical view for displaying a graph, setting up a figure with specified dimensions, DPI, and colors. It creates a canvas, defines axes, initializes data/parameters, labels, layout, and connects canvas interactions. The graph is then rendered and displayed with test_show() for visualization. | def __init__(self, graph_title, parent = None):
super(MyGraphView, self).__init__(parent)
self.graph_title = graph_title
self.dpi = 100
self.fig = Figure((10.0, 5.0), dpi = self.dpi, facecolor = (1,1,1), edgecolor = (0,0,0))
self.canvas = FigureCanvas(self.fig)
self.def... |
def get_opcode(operation):
assert type(operation) == int, "opcode needs to be int"
s = str(operation)
opcode = int(s[-2:])
if opcode == 99:
np = 0
elif opcode == 3 or opcode == 4 or opcode ==9:
np = 1
elif opcode == 5 or opcode == 6:
np = 2
elif opcode == 1 or opcode ... | This code interprets a program represented as a tuple by executing opcodes for arithmetic operations, input/output, and control flow. It processes each instruction, modifies memory, adjusts the instruction pointer, and handles relative base offsets. The main task is to simulate the execution of a custom assembly-like l... | def compute(program):
# assert type(program) is tuple, "program must be a tuple"
ip = 0
rb = 0
while True:
# print(program)
instruction = program[ip]
opcode, np = get_opcode(instruction)
if opcode == 1:
operands = get_operands(program, ip, rb)
r... |
def visualize_one(cleaned_df):
"""
Filter the dataframe to get the data for plotting a histogram and density plot by borough and year.
"""
print('Question 1')
data = query_accidents_by_value_and_year(cleaned_df, 'borough', BOROUGH_COORDS)
plot_multiple_bar_by_metric(data, YEARS, title='Accidents... | The main task of the code is to execute all predefined visualization functions (visualize_one to visualize_nine) using the provided cleaned DataFrame, yearly data dictionary, and subplot configuration. It generates diverse plots to analyze data trends, patterns, and distributions across different timeframes and dimensi... | def run_visualizations(cleaned_df, year_df_dict, subplot=False):
"""
Run all possible visualizations.
"""
visualize_one(cleaned_df)
visualize_two(cleaned_df)
visualize_three()
visualize_four(cleaned_df)
visualize_five(cleaned_df, year_df_dict, subplot=subplot)
visualize_six(cleaned_d... |
def read_file_from_s3(bucket_name, file_key) -> None:
try:
s3_resource = boto3.resource('s3')
s3_client = s3_resource.meta.client
response = s3_client.get_object(Bucket=bucket_name, Key=file_key)
csv_data = io.BytesIO(response['Body'].read())
df = pd.read_csv(csv_data)
... | This Lambda function processes database schema changes from incoming events, generates corresponding SQL DDL statements, determines if changes require approval, logs these changes into a DDL_HISTORY table with status flags, and triggers deployment workflows via Lambda invocation. It handles four change types: data type... | def lambda_handler(event, context):
# Parse the event received from the previous Lambda function to get list of tables having changes
df = pd.json_normalize(event)
changed_tables = df.TableName.unique()
config_df = read_file_from_s3('wormholeltd-bucket', 'config/config-snowflake.csv')
config =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.