dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_next_state(state, action, current_color): """ Get the next state by opponent's discs args: state: the current state action: the location that the player want to put his disc for his turn current_color: the color code of the current player ...
The function updates Q-networks when the opponent wins by calculating error terms from the previous state and action, adjusting weights to reflect the outcome. It checks if the opponent's move leads to a win, computes hidden and output layer deltas, and updates network weights accordingly. If no win, it returns the act...
def op_selection(state, action, pre_state, pre_action): """ Update Q-networks if oppenent won args: state: the current state action: the action of the opponent pre_state: the previous state of this state pre_action: the action leading to th...
def init_state(): """ Create an initial state for the game """ state = np.zeros((64,), dtype=int) state[27] = MY_COLOR state[28] = OP_COLOR state[35] = OP_COLOR state[36] = MY_COLOR return state def my_selection(state, prob): """ Select an action to create a new state. The Q-networks...
The code simulates a single training episode using Q-learning, where the agent (MY_COLOR) selects actions with a probability `prob` for exploration, while the opponent (OP_COLOR) chooses random actions. The episode alternates turns, updates the game state, and returns the win status when the game ends. The agent's acti...
def training(who_first, prob): """ Training one episode. The program will take action based on Q learning algorithm. The opponent will take a random action args: who_first: the color code of the first player prob: the probability to get a random action. ...
def init_state(): """ Create an initial state for the game """ state = np.zeros((64,), dtype=int) state[27] = MY_COLOR state[28] = OP_COLOR state[35] = OP_COLOR state[36] = MY_COLOR return state def my_selection(state, prob): """ Select an action to create a new state. The Q-networks...
This code provides a graphical user interface (GUI) for a turn-based game on an 8x8 grid. It allows a human player and a program (AI) to alternate turns, with the program's moves determined by the `my_selection` function. The UI updates the board state, handles user input, checks for valid moves, and declares the winne...
def play_game(who_first): """ UI for playing the game args: who_first: the color code of the player who goes fisrt """ layout = [ ([sg.B(' ',size=(3,1), font='Arial 30', button_color=('Black','Green'), key=(j,i)) for i in range(8)] for j in range(8)), [sg.T('Playe...
def init_state(): """ Create an initial state for the game """ state = np.zeros((64,), dtype=int) state[27] = MY_COLOR state[28] = OP_COLOR state[35] = OP_COLOR state[36] = MY_COLOR return state def my_selection(state, prob): """ Select an action to create a new state. The Q-networks...
The function simulates a self-playing game between two neural networks, alternating turns between 'MY_COLOR' and 'OP_COLOR'. It uses forward propagation with given weights to evaluate opponent moves, selecting actions with maximum output values. The game proceeds until a terminal state is reached, returning the winner'...
def self_playing(weights, who_first): """ Self playing game based on the current and previous weights of the neuron networks args: weights: the weights matrix of NN who_first: the color code of the player who goes first return: color code of the winner """...
def initialize_board(output): ''' {Initial Configuration of the Othello Board} Input: True/False to print initial board returns: 8x8 Numpy Array Board Configuration 1 for Player1 2 for Player2 9 for empty board state ''' board = np.full((8,8), 9) board[3][4] = 1 board[4][3] = 1 board[3][3] = 2 ...
The function `play_othello` simulates a game of Othello between a player using a specified heuristic to evaluate moves and an opponent following a given strategy (optimal or random). It alternates turns, evaluates possible moves, selects the best move based on the heuristic, and updates the board state. The game contin...
def play_othello(heuristic, opponent_strategy, output, batch_size): ''' Input: string identifying heuristic to score players moves, string identifying type of opponent_strategy, output= True/False to print output marix, batch_size = integar how large result: 'W'= win or 'L'= loss for the game along with sc...
def print_start_screen(secret_word, warnings): """ Print welcome screen for a new game of Hangman. """ print("Welcome to the game Hangman!") # PRINT length of the secret word and how many warnings player starts with print("I am thinking of a word that is {} letters long.".format(len(secret_wo...
The main task of the code is to implement an interactive Hangman game where the user guesses letters of a secret word. The game tracks remaining guesses and warnings, displays available letters, checks valid inputs, provides immediate feedback on guesses, updates the partially guessed word, and handles hints (*) to sho...
def hangman_with_hints(secret_word): ''' secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should s...
def find_new_points(frame, hough_threshold, min_line_length, max_line_gap, **params) : gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) edges = run_best_edge_detector(gray, **params) simplified = simplify_edges(edges) lines = cv2.HoughLinesP(simplified, 1, np.pi/180, hough_threshold, minLineLength=min_li...
The main task of the code is to track moving points in a video using optical flow, filter valid points based on line detection, and visualize tracked points and vertical lines. It initializes points from the first frame, iteratively tracks them across subsequent frames, adds new points, removes invalid ones, and draws ...
def tracking(cap, **best_params) : """tracking initiation""" ret, old_frame = cap.read() old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY) p0, lines, edges = find_new_points(old_frame, HOUGH_LINE_THRESHOLD, MIN_LINE_LENGTH, MAX_LINE_GAP, **best_params) while True: ret, frame = cap.read...
def edge_detection(self, image, filter_type, kernel_size, thresholding_method): if len(image.shape) == 3 : gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else : gray = image.copy() if filter_type == 'gauss' : blur = cv2.GaussianBlur(gray, (kernel_siz...
The code evaluates various image processing parameters (filter type, kernel size, thresholding method) to find the optimal combination for edge detection. It tests each parameter set by generating 10 random images, computing weighted metrics between original and processed edges, and selecting the configuration with the...
def searching_best_params(self, first_frame) : filter_type = ['gauss', 'median', ] thresholding_method = ['median','otsu'] kernel_sizes=[5,7,9] best_score = 0 best_params = {} gray = cv2.cvtColor(first_frame, cv2.COLOR_BGR2GRAY) for f, ksize, m in prod...
def getUniqueValues(self): layer = getLayerFromId(self.LOCALITIES_LAYER) self.UNIQUE_VALUES = layer.dataProvider().uniqueValues(int(self.TAXON_FIELD_INDEX)) self.UNIQUE_COUNT = len(self.UNIQUE_VALUES) def getLayerFromId (uniqueId): return QgsProject.instance().mapLayer(uniqueId) def process(...
The main task of the code is to handle user confirmation for generating distribution maps by initializing input parameters from a GUI, validating data integrity, creating a spatial index for grid layers, and triggering map processing if the user confirms. It includes error handling and progress feedback through dialog ...
def confirm(self): # runs when OK button is pressed # initialise input parameters self.BASE_LAYER = self.dlg.ui.comboBase.currentItemData() self.SECONDARY_LAYER = self.dlg.ui.comboSecondary.currentItemData() self.SURFACE_LAYER = self.dlg.ui.comboSurface.currentItemData() ...
def check_win(self, player, last_move, board=None): # print(\f'{player==self.currentPlayer=}') self.logger.info('Checking for Win with {last_move:}') l = self.length h = self.height if not board: board = self.board board = self.board sequence = [] ...
This function handles the end of a player's turn by checking for a win, updating scores, logging game status, and managing game state. If a win is detected, it adjusts scores, logs the winner's details, draws the board, and ends the game. If no win, it updates the player's score and logs the turn's completion. Errors d...
def end_turn(self, player, choice): self.isWinner = self.check_win(player, choice, self.board) isWinner = self.isWinner if isWinner[0]: self.modPlayerPts(player=player, delta=10) self.modPlayerPts(player=player * -1, delta=-12) self.logger.info( ...
def possible_moves(self, board): open_spaces = [] rows = [(self.length * self.height) - self.length + i for i in range(self.length)] for i in rows: if board[i]['color'] == -1: # print(str(i) + " is a possible move") open_spaces.append(i...
The main task of the code is to handle a player's turn in a game by validating and processing their move. It updates turn states, checks if the chosen move is valid, prompts for input if invalid, and submits the move if accepted. The function returns the result of the move submission or False if no valid moves remain.
def start_turn(self, player, choice=None): self.logger.info("Starting Turn") self.turnKey = True msg = f"{self.lastTurn=}, {self.currentTurn=}, {self.nextTurn=}, {self.lastMove=}, {self.currentPlayer=}" # self.printLineBreak(text=msg, dbl_space=False) msg = f"current player: ...
def create_matrix(rows, cols, k, ss_1, ss_2, gap, extend): middle_matrix_direction = np.full((rows,cols),"m", dtype="object") X_matrix_direction = np.full((rows,cols), "x", dtype="object") Y_matrix_direction = np.full((rows,cols),"y", dtype="object") #middle_matrix = np.zeros((rows, cols)) #X_matri...
This function performs sequence alignment of two input sequences (ss_1, ss_2) using dynamic programming. It initializes matrices for alignment scoring, adjusts gap/extend penalties, traces optimal alignment paths, and returns aligned sequences, their distance, final score, and intermediate matrices. The parameter k con...
def score_alignment(ss_1, ss_2, k): rows = len(ss_1) + 1 cols = len(ss_2) + 1 if k > len(ss_1) or k > len(ss_2): k = min(len(ss_1), len(ss_2)) -1 middle_matrix, X_matrix, Y_matrix, middle_matrix_direction, X_matrix_direction, Y_matrix_direction, max_matrix, final_score = create_matrix(rows, col...
def get_snr_freq_range(self) -> list: """""" return self.__snr_freq_range def get_snr_resolution(self) -> int: """""" return self.__snr_res def calc_snr_at_cutoff(self, i, f, signal = (0, 0), noise = (0, 0), bins = False) -> float: """""" self.__data[i].apply("detrend", m...
This function calculates Signal-to-Noise Ratio (SNR) values across specified frequency ranges. It generates frequency bins, iterates through them, and computes SNR at each frequency using `calc_snr_at_cutoff`. If `j` is provided, it processes a single data index; otherwise, it processes all data points. The result is a...
def calc_snr_vs_freq(self, j = -1, freq = [0, 0], signal = (0, 0), noise = (0, 0), bins = False) -> np.typing.NDArray: """""" snr = np.array([]) if freq[0] == 0 and freq[1] == 0: freq = np.linspace(*self.get_snr_freq_range(), self.get_snr_resolution()) else: freq ...
def build_jmapping_dict(only_MCM_Js:bool = True, return_reverse=False): """Read in data to map TUV reactions to appropriate F0AM/MCM J-Value. By Default, returns TUV Rxn as key, and MCM_jname as value, unless in reverse. Called in check_joptions() within check_inputs() to make new TUV input files and ...
The function `write_TUV_input_file` modifies a TUV input template by updating specified variables with new values while preserving formatting, enabling J-value calculations for designated reactions, and saving the result as a new file with a standardized name. It ensures compatibility with TUV scripts by adhering to st...
def write_TUV_input_file(variable_changes, j_rxns,savepath:str, overwrite:bool=False, verbose:bool=True): """Function to read in the template file, change the vars in 'variable_changes', turn on the J-value calculations for rxns in 'j_rxns' and write a new TUV input file at savepath named something like '...
def get_and_set_lims(variable_changes): """Helper function called in check_inputs() that reads in an Excel File that defines the variables expected in TUV, their data types, their descriptions, units, default values, and valid ranges and updates those limits that depend on user input vars as apporpr...
This function validates user input variables against allowed ranges, data types, and constraints. It checks if variables are recognized TUV inputs, ensures they are not locked, converts boolean values, enforces numerical types, and verifies min/max bounds. It handles defaults for negative values, adjusts invalid inputs...
def check_inputs(variable_changes, j_options): """Function to check that user input changes are in allowed ranges. Returns dict "allowed_vars" and a modified version of input "variable_changes". Will error out if baddies found!""" # Get a list of all allowed Variables and their min/max values give...
def compute_node_entropy(self,label): # compute the entropy of a tree node (add 1e-15 inside the log2 when computing the entropy to prevent numerical issue) node_entropy = 0 # placeholder #(sum -p*log2(p+1e-15) N = len(label) n_idx,p = [],[] for i in range(10): ...
This function generates a decision tree recursively by splitting data based on selected features. It checks if a node becomes a leaf (when entropy is below a threshold) and assigns the majority class label. If not a leaf, it selects the optimal feature to split data into left and right subsets, then recursively builds ...
def generate_tree(self,data,label): # initialize the current tree node cur_node = Tree_node() # compute the node entropy node_entropy = self.compute_node_entropy(label) # determine if the current node is a leaf node if node_entropy < self.min_entropy: # dete...
def display_instructions(): util.clear_screen() print("You are attacking the last stronghold of the notorious wizard,") print("who is hidden behind an endless stone wall, each stone being") print("one of his former victims. Only you can attack and free them") print("from his magic.") print("You must destory the w...
The main task of the code is to initialize and manage a game called "The Wizard's Wall." It prompts the user for instructions, sets the difficulty level, constructs the game wall, executes the core game logic, and displays win/loss outcomes. The loop allows replaying the game based on user input, ensuring a complete ga...
def start_game(): util.clear_screen() print("The Wizard's Wall") correct = False #Offers to display the instructions and gets the difficulty while not correct: response = input("Do you want instructions? ") if response.lower()[:1] == "y": display_instructions() correct = True elif response.lower()[:...
def GenerateFlow(flie): sPath = "C:\\Users\\torres_fan\\Desktop\\captureData" flie = sPath + '\\' + flie flowList = [] # This will be used for storing flow. activeDict = {} # This is used to store currently active flow. with open(flie) as csv_file: csv_reader = csv.DictReader(csv_file, del...
The code processes multiple files to extract features based on the specified type, labels each file's features, concatenates all data, splits into training/test sets, and evaluates a classification model's performance.
def GetResult(fileList, sFeatureType): arrayList = [] for sFile in fileList: tempFlowList = GenerateFlow(sFile) tempFeatureList = [] for oFlow in tempFlowList: tempFeatureList.append(oFlow.get_features(sFeatureType)) featureArray = np.array(tempFeatureList) a...
def glob_all_src_files(target_dir='.'): """ Recurse through the target_dir and find all the .cc and .h files. """ files = glob_cc_src_files(target_dir) + glob_h_src_files(target_dir) return files def identify(header): """ String to identify submission's owner. """ ident = '(Malformed Header)' if...
The main task of the code is to verify a student's solution by checking headers, formatting, linting, and ensuring the code builds and runs correctly. It compares files against a base directory to detect changes, validates code structure, and executes the program using a provided run function to confirm functionality.
def solution_check_simple(run=None): """ Main function for checking student's solution. Provide a pointer to a run function. """ setup_logger() if len(sys.argv) < 3: logging.error('provide target directory, program name, and optionally a base directory') sys.exit(1) target_direct...
def glob_all_src_files(target_dir='.'): """ Recurse through the target_dir and find all the .cc and .h files. """ files = glob_cc_src_files(target_dir) + glob_h_src_files(target_dir) return files def identify(header): """ String to identify submission's owner. """ ident = '(Malformed Header)' if...
This script checks a student's code solution by verifying headers, formatting, linting, build, and runtime. It compares files against a base version if provided, ensures no unmodified files, and exits with a status based on checks.
def solution_check_make(run=None): """ Main function for checking student's solution. Provide a pointer to a run function. """ setup_logger() if len(sys.argv) < 3: logging.error('provide target directory, program name, and optionally a base directory') sys.exit(1) target_director...
def destructure_coord(i): return tuple([int(x) for x in i.split(',')]) def is_diagonal(i): return (i[0][1] != i[1][1]) and (i[0][0] != i[1][0]) def generate_points(i): if is_diagonal(i): xstep = -1 if i[0][0] > i[1][0] else 1 ystep = -1 if i[0][1] > i[1][1] else 1 return [(x, y) for x, y...
The code processes a list of line segments, filters out diagonal lines (if enabled), generates all coordinate points along each line, counts overlapping points, and returns the number of points overlapped by more than one line. It uses hashing to track occurrences and filters results based on overlaps. Your return
def day5_part1(input, filter_diagonal=True): input = input.split('\n') input = [tuple([destructure_coord(x[0]), destructure_coord(x[1])]) for x in [i.split(' -> ') for i in input]] # remove diagonal lines if filter_diagonal: input = [x for x in input if not is_di...
def check_student_id_input(input_prompt, first_part_error_message, second_part_error_message_1, second_part_error_message_2, third_part_error_message_2): """ Calls get list_of_lists_from_file function, wh...
The function `add_student` validates and sets a student's ID, first name, and last name on an empty student object using input-checking functions. It ensures the ID is numeric and 5 digits, names are alphabetic, then saves the student data to a file. The populated object is returned.
def add_student(a_student_instance): """ The function add_student takes in a_student_instance. It calls the set_student_id method on a_student_instance, whose parameter is an assignment to the value returned from calling check_student_id_input, which will be a valid student id. set_student_first_nam...
def check_category_id(category_id_input): """ Calls get_list_of_lists_from_file, passing in category.txt as an argument and returning a list containing lists of categories. The function goes through the list of category lists, getting the category id from each category list and appending each to a l...
The function adds a new category by validating the category ID, name (ensuring it contains only letters), and weight (converting to a percentage). It appends these details to 'category.txt' and returns the validated category ID, name, and formatted weight.
def add_category(cat_id_initialization, cat_weight_initialization): """ The function calls the check_category_id(), which returns the category_id, calls category_name(), which returns the category_name, and calls check_category_weight(), which returns the category weight. It opens the category.txt,...
def createGrid(): grid = [] for row in range(9): grid.append([]) for column in range(9): grid[row].append(0) return grid def placeInRow(grid, y, columns, num, grids, gridnumber): x = 'x' for column in range(len(columns)): if grid[y][columns[column]] == 0: ...
The code attempts to solve a 9x9 grid by placing numbers 1-9 in each row using a backtracking algorithm. It shuffles columns randomly for each row and tries to place numbers. If a placement fails, it recursively restarts the process. The main task is to generate a valid grid configuration through randomized backtrackin...
def main(): grid = createGrid() column = [0,1,2,3,4,5,6,7,8] for num in range(1,10): grids = [False] gridnumber = -1 for row in range(9): random.shuffle(column) x = placeInRow(grid, row, column, num, grids, gridnumber) if x == False: ...
def _init_game(self): """ Init games functions """ # set value to travel half the grid per second to quickly test the game self.loose = 0 self._init_time(self.grid_size[0] // 2) if self.with_rendering: self.render = RenderingManager(self.screen_size, ...
This method initiates an interactive game loop for human players, continuously taking input, checking game events, and rendering the game state if enabled. It resets the game when a loss condition is met and repeats the cycle until the game concludes.
def start_interactive_game(self): """ Start playing mode for a human with take_input routine """ assert self.with_rendering, "Can't play without render" while True: if self.loose != 0: self._init_game() if self._take_input(): ...
def loadImage(self, image): xs = image.width ys = image.height is_palette_image = image.mode == 'P' and (len(image.getcolors()) <= 16) # Try to find the image in the cache start_sector = self.vram_cache.getSectorOf(image) if start_sector is None: if is_palet...
The code draws an image at specified coordinates (xp, yp) by first validating its size (≤256x256) and checking if it's a palette-based image (≤16 colors). It loads the image data and uses either `drawPaletteImage` for palette-based images or `drawLoadedBitmap` for others to render the image at the given position.
def drawImage(self, xp, yp, image): xs = image.width ys = image.height is_palette_image = image.mode == 'P' and (len(image.getcolors()) <= 16) # We could use multiple draws to do large images later if xs > 255 or ys > 255: raise ValueError("Image must be within 256x2...
def init_game(self): self.board = Board() self.turn = Mark() self.turn.set_x() def render_game(self): Game.WIN.fill(Game.BLACK) pygame.draw.rect(Game.WIN, Game.WHITE, Game.LINE_1) pygame.draw.rect(Game.WIN, Game.WHITE, Game.LINE_2) pygame.draw.rect(Game.WIN, Game....
The code initializes a Tic-Tac-Toe game using Pygame by setting the window caption and icon, initializing game components, rendering the game state, configuring turn indicators, and starting the game loop. It prepares the game environment, displays the current player's turn, and manages the game's runtime with a clock....
def __init__(self): pygame.display.set_caption("Tic-tac-toe") pygame.display.set_icon(Game.X_IMG) self.init_game() self.render_game() self.turn_img = self.set_turn_img() self.turn_text = Game.FONT.render("{}'s turn".format(self.turn), True, Game.WHITE) self.clock ...
def eps_greedy(self): eps_prob = np.random.rand() if eps_prob < self.epsilon: state = self.get_state() action_ls = self.get_action() action = util.randomChoice(action_ls) action_val = self.convertAction(action) s_a_pair = state + [action_val] ...
This code implements a reinforcement learning agent's decision-making step. It selects an action using epsilon-greedy strategy, executes it by adjusting funds and investing, calculates reward, observes next state, and updates the Q-table using Bellman equation with learning rate (alpha) and discount factor (gamma) to i...
def my_turn(self): # compute action with maximum Qvalue action, currentQ, currentState = self.eps_greedy() # compute Reward R = self.computeReward(action) # take the action self.money -= action.get_cost() action.invest(self) if self.verbose: pr...
def encode(value, encoding='utf-8', encoding_errors='strict'): """ Return a bytestring representation of the value. """ if isinstance(value, bytes): return value if not isinstance(value, basestring): value = str(value) if isinstance(value, unicode): value = value.encode(e...
(The function generates `nshares` of a secret using a threshold scheme, requiring `threshold` shares for reconstruction. It validates inputs, hashes the secret if specified, and formats shares with a header containing the identifier, hash algorithm, threshold, and secret length. Returns a list of formatted shares or ra...
def share_secret(threshold, nshares, secret, identifier, hash_id=Hash.SHA256): """ Create nshares of the secret. threshold specifies the number of shares needed for reconstructing the secret value. A 0-16 bytes identifier must be provided. Optionally the secret is hashed with the algorithm specified ...
def encode(value, encoding='utf-8', encoding_errors='strict'): """ Return a bytestring representation of the value. """ if isinstance(value, bytes): return value if not isinstance(value, basestring): value = str(value) if isinstance(value, unicode): value = value.encode(e...
The function `reconstruct_secret` reconstructs a secret from multiple shares using threshold secret sharing. It validates share formats, checks for duplicates, and applies Lagrange interpolation to combine shares. If strict mode is enabled, it raises errors for invalid shares or hash mismatches; otherwise, it tries all...
def reconstruct_secret(shares, strict_mode=True): """ shares must be a container with a sufficient number of well-formatted shares used to reconstruct the secret value. If any share format is invalid a TSSError exception is raised. If strict_mode is False all combinations of shares are tried in orde...
def decomposCH(q0, q1): """ This function decomposes Controlled-H gate (CH) into Clifford+T gates Args: q0 (int): indicates to control qubit q1 (int): indicates to target qubit Returns a list of LowLevelComponent objects """ CH = [] CH += [MX.LowLevelC...
This function decomposes a multi-controlled-Hadamard (MCH) gate into Clifford+T gates using ancilla qubits. It applies a sequence involving decomposed multi-controlled-iX gates, a Hadamard gate, and inverse operations. The method follows arXiv:1212.0506's approach, rearranging qubit orders and utilizing ancilla qubits ...
def decomposMCH(nq): """ This function decomposes multi-controlled-H gate (CC...CH) into Clifford+T gates. (as in arXiv:1212.0506, section 5.2) Args: nq (int): number of qubits in circuit (nq >= 2) Returns a list of LowLevelComponent objects """ if nq <= 1: ...
def rearrangeQ(LLCs, cqp, nqp): # rearrange gates in a different order of qubits d = dict(zip(cqp, nqp)) RQ = lambda llc : MX.LowLevelComponent(llc.name, [d[i] for i in llc.idx]) return list(map(RQ, LLCs)) def decomposMCiX(nq): """ This function decomposes multi-controlled-iX gate (CC...CiX...
The function `decomposMCT` decomposes a multi-controlled T gate (CC...CT) with `k` T gates into a sequence of Clifford+T gates using an ancilla qubit. It first validates inputs, adjusts qubit counts, and applies a decomposition method from a specified paper. Depending on `k % 8`, it appends appropriate T, S, or their i...
def decomposMCT(nq, k=1): """ This function decomposes multi-controlled-T gate (CC...CT) into Clifford+T gates. (as in arXiv:1212.0506, section 5.2) Args: nq (int): number of qubits in circuit (nq >= 2) k (int): count of T gate (T ^ k) Returns a list of Low...
def decomposCCX(q0, q1, q2): """ This function decomposes toffoli gate (CCNOT) into Clifford+T gates Args: q0 (int): indicates to first control qubit (q0 >= 0) q1 (int): indicates to second control qubit (q1 >= 0) q2 (int): indicates to target qubit (q2 >= 0) ...
This function decomposes a multi-controlled X gate (CC...CX) into Clifford+T gates using a method from arXiv:1212.0506. It handles cases with 2+ qubits, adjusts for an ancilla qubit, and applies decomposition steps involving controlled operations, CX gates, and inverse operations. The result is a list of LowLevelCompon...
def decomposMCXp(nq): """ This function decomposes multi-controlled-X gate (CC...CX) into Clifford+T gates. (as in arXiv:1212.0506, section 5.2) Args: nq (int): number of qubits in circuit (nq >= 2) Returns a list of LowLevelComponent objects """ if nq <= 1: ...
def decompos(U): """ This function decomposes a unitary matrix of D-omega numbers into clifford+t gates. Args: U (numpy.matrix): 2^n * 2^n Unitary matrix of D-omega objects Returns: LLCs (list of LowLevelComponent objects) : containing Clifford+T gates that matrix ...
The function synthesizes a quantum circuit using Clifford+T gates from a given unitary matrix, following the algorithm in arXiv:1212.0506. It decomposes the input matrix into lower-level Clifford+T operations and constructs two circuits: one with basic Clifford+T gates and another with higher-level multi-controlled gat...
def syntCliffordTCircuit(U): """ This function runs the synthesis algorithm introduced in arXiv:1212.0506 Args: U (numpy.matrix): 2^n * 2^n Unitary matrix of D-omega objects Returns: **main result** cliffordTCircuit (Qiskit.QuantumCircuit) : the synthes...
def rearrangeQ(LLCs, cqp, nqp): # rearrange gates in a different order of qubits d = dict(zip(cqp, nqp)) RQ = lambda llc : MX.LowLevelComponent(llc.name, [d[i] for i in llc.idx]) return list(map(RQ, LLCs)) def decomposMCH(nq): """ This function decomposes multi-controlled-H gate (CC...CH) i...
This function decomposes a multi-controlled quantum gate (H, X, or T) into Clifford+T gates. It identifies negative controls, applies X gates for them, uses type-specific decomposition functions (decomposMCH, decomposMCT, decomposMCXp), rearranges qubits, and appends X gates again. The result is a list of LowLevelCompo...
def decomposMCGate(mlc): """ This function decomposes a (multi)controlled gate into clifford+t gates. Args: mlc (MidLevelComponent): a (multi)controlled gate of type H or X or T Returns a list of LowLevelComponent objects """ nq = mlc.q_array.size cqp = list(rang...
def initializeFromCaches(self): for network in self.networkTokens: for token in self.networkTokens[network]: cachedData = self.loadFromCache(network, token); if not cachedData is None: self.pricesByNetworkToken[network][token] = cachedData; def getSparseHistories(self): for network in self.networkTo...
The code initializes a price data structure for network tokens, loads cached data, and retrieves sparse/dense historical price data from CoinGecko. It sets parameters for time ranges, minimum price update intervals, and handles stablecoins separately. The verbose flag enables logging, and the endTime check triggers "cu...
def __init__(self, networkTokens, startTime=0, endTime=9999999999, minDurationBetweenPricesHours=2.5, minDurationBetweenPricesHoursStablecoin=25, cachePath="./cache", verbose=False): self.networkTokens = networkTokens; self.cachePath = cachePath; self.verbose = verbose; self.startTime = startTime; self.endTim...
def roll(self, roller=None): print(f"Rolling {self.num_dice} dice...") self.current_roll = roller or GameLogic.roll_dice(self.num_dice) self.dice_string = "*** {} ***".format(" ".join(str(num) for num in self.current_roll)) print(self.dice_string) def round_reset(self): self.tota...
The main task of the code is to manage a single round of a dice game, allowing the player to roll dice, select kept dice, accumulate scores, and decide to continue rolling, bank points, or quit. It handles scoring validation, updates the game state, and enforces rules like Zilch (zero score) resets, dice replenishment,...
def play_round(self): playing = True while playing: print(f"Starting Round {self.rounds}") same_round = True while same_round: self.roll() if GameLogic.calculate_score(tuple(self.current_roll)) == 0: print(dedent("""...
def pred(self,inputs): prop = self.forward_propagation(inputs) predictions = np.int8(prop) return predictions def forward_propagation(self,inputs): prop = np.dot(inputs, self.weight_matrix) return self.hard_limit(prop) def plot_model(points, labels, weights, classes,l_rate, legend_desc = "Desired label"): co...
The code trains a neural network using gradient descent by iteratively adjusting weights based on prediction errors. For each training example, it predicts an output, calculates the error compared to the desired label, updates the weight matrix using the learning rate, and plots the model's progress. This process repea...
def train(self, train_inputs, train_desired_labels, num_train_itr = 10): N = train_inputs.shape[0] for iteration in range(num_train_itr): for index in range(train_inputs.shape[0]): actual_prediction = self.pred(train_inputs[index,:]) if(actual_prediction != train_desired_labels[index]): output = se...
def reformat_url_to_be_uniform(url): return url.split('/season-')[0] def extract_reviews_for_critic_page(initial_url): reviews = [] print(f'Scraping critic review-page: {initial_url}') response = requests.get(initial_url, headers=headers) assert response.status_code == 200 soup = BeautifulSou...
The main task of the code is to fetch and return both critic and user reviews for a show by constructing standardized URLs from an input URL, extracting reviews from each endpoint, and returning them as a dictionary. It ensures uniform URL formatting, handles critic and user review pages separately, and includes a dela...
def get_reviews_for_show(url): uniform_url = reformat_url_to_be_uniform(url) critic_review_url = f'{uniform_url}/critic-reviews' extracted_critic_reviews = extract_reviews_for_critic_page( critic_review_url) user_review_url = f'{uniform_url}/user-reviews' extracted_user_reviews = extract_r...
def check_next_open(self, col): col = int(col) stand = self.stand result = 0 for row in range(ROWS): if stand.checkers[row][col] == 0: result = row else: if result == 0 and stand.checkers[0][col] != 0: return -1 ...
This function handles a player's move in a Connect Four-like game by determining the column and row for a checker drop, updating the game state, checking for a win or full board, and returning True if the game ends, otherwise switching turns and returning False.
def drop_checkers(self, pos): x, y = pos if SIDE_SPACE < x < WIDTH - SIDE_SPACE: col = ((x - SIDE_SPACE) // SECTION_WIDTH) row = self.check_next_open(col) if row != -1: self.stand.checkers[row][int(col)] = self.turn_col DROP.play() ...
def RSA_key_generator(bits): e = generate_e() p, q = generate_primes_RSA(bits//2,e) euler = (p-1)*(q-1) d = inverso_mult(e, euler) return p*q, e, d def string_bits_to_int(m): return int(''.join(format(ord(i), '08b') for i in m), 2) def sign_verify(M, c, e, n): h = hashlib.sha1(M.encode()).he...
The code generates RSA keys (n, e, d), creates a digital signature of a message using the private key, and verifies the signature with the public key. It repeatedly takes user input for messages, computes SHA-1 hashes, signs them, and checks validity. The main task is demonstrating RSA-based digital signature generatio...
def main(): print("\n\n\t\t*** RSA KEY GENERATOR AND DIGITAL SIGN ***\n\n") while True: M = input("Ingrese un mensaje: ") # Mensaje if M == "": break n,e,d = RSA_key_generator(400) print(f"\nModule:\t{n}\nPublic Key: {e}\nPrivate Key: {d}\n") h = hashlib.sha1(M.encode(...
def addLevel(self, path): lvlName = os.path.join(self.tempDir.name, 'game_lvl5.txt') if(path is ''): open(lvlName, 'w+').close() else: shutil.copyfile(path, lvlName) def startComm(self): self.io.initBuffers() #Reset currently sends initial commucations (wh...
This code initializes a game environment by setting up a temporary directory, configuring Java server parameters, validating the build version, launching a Java process for game interaction, and preparing communication channels. It handles game-specific settings, checks for correct build dependencies, and initializes c...
def __init__(self, game, version, lvl, pathStr): self.tempDir = tempfile.TemporaryDirectory() self.addLevel('') #Level template to be loaded into java self.TOKEN_SEP = '#' self.io = IOSocket(self.tempDir.name) self.sso = SerializableStateObservation() #self.agentName =...
def Initialize(): global root global row global col global FaultRatio row = 0 col = 1 FaultRatio = 0 def new_window(txt, capacity): global root root = Tk() Basic_design(capacity) root.title("Visualisation Of Algorithm: " + txt) root.geometry("1600x660") def anime(Frames, ...
This code implements the FIFO page replacement algorithm to simulate memory management, tracking page faults and hits. It processes a sequence of page references, maintaining a fixed-size frame set, and replaces the oldest page when a fault occurs. If animation is enabled, it visualizes the process dynamically. The fun...
def FIFO(pages, n, capacity, txt, animation): Initialize() global FaultRatio global col global root global row fault_record = [] hit_record = [] frames = [c for c in range(capacity + 3)] if animation is True: new_window(txt, capacity) for ii in frames: if ii == ...
def Initialize(): global root global row global col global FaultRatio row = 0 col = 1 FaultRatio = 0 def new_window(txt, capacity): global root root = Tk() Basic_design(capacity) root.title("Visualisation Of Algorithm: " + txt) root.geometry("1600x660") def anime(Frames, ...
This function simulates the LIFO (Last-In-First-Out) page replacement algorithm to calculate page faults and hits for different frame capacities. It iterates through page references, tracks page faults using a set, and replaces the most recently added page when a fault occurs. If animation is enabled, it visualizes the...
def LIFO(pages, n, capacity, txt, animation): Initialize() global col global FaultRatio global root global row fault_record = [] hit_record = [] frames = [c for c in range(capacity + 3)] if animation is True: new_window(txt, capacity) for ii in frames: if ii =...
def Initialize(): global root global row global col global FaultRatio row = 0 col = 1 FaultRatio = 0 def new_window(txt, capacity): global root root = Tk() Basic_design(capacity) root.title("Visualisation Of Algorithm: " + txt) root.geometry("1600x660") def anime(Frames, ...
The code implements the Least Recently Used (LRU) page replacement algorithm to simulate memory management. It tracks page faults and hits for a given process list, adjusts frame allocation dynamically, and optionally visualizes the process with animations. The function calculates the fault ratio, updates records, and ...
def LRU(processList, n, capacity, txt, animation): Initialize() global FaultRatio global col global root global row fault_record = [] hit_record = [] frames = [c for c in range(capacity + 3)] if animation is True: new_window(txt, capacity) for ii in frames: if...
def Initialize(): global root global row global col global FaultRatio row = 0 col = 1 FaultRatio = 0 def new_window(txt, capacity): global root root = Tk() Basic_design(capacity) root.title("Visualisation Of Algorithm: " + txt) root.geometry("1600x660") def anime(Frames, ...
The code simulates the Most Recently Used (MRU) page replacement algorithm, tracking page faults and hits for varying frame sizes. It processes a sequence of page requests, updating memory frames by replacing the most recently used page when a fault occurs. If animation is enabled, it visualizes the process. The functi...
def MRU(processList, n, capacity, txt, animation): Initialize() global FaultRatio global col global root global row fault_record = [] hit_record = [] frames = [c for c in range(capacity + 3)] if animation is True: new_window(txt, capacity) for ii in frames: if ...
def Initialize(): global root global row global col global FaultRatio row = 0 col = 1 FaultRatio = 0 def new_window(txt, capacity): global root root = Tk() Basic_design(capacity) root.title("Visualisation Of Algorithm: " + txt) root.geometry("1600x660") def anime(Frames, ...
This function simulates the Optimal Page Replacement Algorithm to calculate page faults and hits for a given process list. It iterates through varying frame capacities, tracks page replacements using future reference optimization, and optionally visualizes the process with animation. The algorithm determines which page...
def Optimal(processList, n, capacity, txt, animation): Initialize() global FaultRatio global col global root global row fault_record = [] hit_record = [] frames = [c for c in range(capacity + 3)] if animation is True: new_window(txt, capacity) for ii in frames: i...
def Initialize(): global root global row global col global FaultRatio row = 0 col = 1 FaultRatio = 0 def new_window(txt, capacity): global root root = Tk() Basic_design(capacity) root.title("Visualisation Of Algorithm: " + txt) root.geometry("1600x660") def anime(Frames, ...
This code simulates the Random page replacement algorithm, calculating page faults and hits for varying frame sizes (0 to capacity+2). It tracks fault/hit records, computes fault ratios, and optionally visualizes the process with animation. The core task is to model memory management efficiency under random replacement...
def Random(pages, n, capacity, txt, animation): Initialize() global FaultRatio global col global root global row fault_record = [] hit_record = [] frames = [c for c in range(capacity + 3)] if animation is True: new_window(txt, capacity) for ii in frames: if ii ...
def Initialize(): global root global row global col global FaultRatio row = 0 col = 1 FaultRatio = 0 def FIFO(pages, n, capacity, txt, animation): Initialize() global FaultRatio global col global root global row fault_record = [] hit_record = [] frames = [c f...
This code computes page fault ratios for various memory management algorithms (FIFO, LIFO, LRU, MRU, Optimal, Random) using a given reference string and number of frames. It then visualizes these fault ratios in a bar chart to compare algorithm performance. The function initializes each algorithm, runs simulations, col...
def graph(noF, refString): plot_list=[] algos=["FIFO","LIFO","LRU","MRU","Optimal","Random"] dummy=0 N = int(noF) pageR = list(refString.split(" ")) n = len(pageR) Initialize() FIFO(pageR, n, N, None, False) dummy=FaultRatio plot_list.append(dummy) Initialize() LIFO(pag...
def FIFO(pages, n, capacity, txt, animation): Initialize() global FaultRatio global col global root global row fault_record = [] hit_record = [] frames = [c for c in range(capacity + 3)] if animation is True: new_window(txt, capacity) for ii in frames: if ii == ...
The main task of the code is to visualize page replacement algorithms (FIFO, LIFO, LRU, etc.) based on the input reference string and number of frames. It maps the selected algorithm to its description and triggers the corresponding visualization function, enabling analysis of page fault behavior for different memory m...
def Visualise(option, noFrame, refString): noF = (int)(noFrame) pageR = list(map(int, refString.split(" "))) N = len(pageR) txt = "0" if option == "FIFO": txt = "First In First Out" FIFO(pageR, N, noF, txt, True) elif option == "LIFO": txt = "Last In First Out" ...
def get_int_list(personal_id_string): return [int(foo) for foo in personal_id_string] def check_personal_id(id_number, block_exceptions=False): month_code = get_int_from_int_list(id_number[3:5]) day_code = get_int_from_int_list(id_number[5:7]) # First digit can be from 1 to 6: is_first_digit_correct...
The code validates a personal ID code, determines the gender based on the first digit, extracts the birth date, and returns a formatted string like "Male born on YYYYMMDD" if valid. If invalid, it returns "Invalid code!".
def get_personal_description(id_code): id_code_as_int_list = get_int_list(id_code) if check_personal_id(id_code_as_int_list): gender = 'Male' if int(id_code[0]) % 2 == 1 else 'Female' return '{0} born on {1}'.format(gender, get_birthday(id_code_as_int_list)) else: return 'Invalid cod...
def get_digits_only(string): return ''.join(filter(lambda x: x.isdigit(), string)) def get_int_list(personal_id_string): return [int(foo) for foo in personal_id_string] def check_personal_id(id_number, block_exceptions=False): month_code = get_int_from_int_list(id_number[3:5]) day_code = get_int_from_in...
The code sanitizes text by extracting and validating numerical identifiers. It splits text into words, checks for 11-digit personal IDs (valid/invalid) and 7/9-digit company codes (valid/invalid), then returns unique entries of each category.
def text_sanitizer(text): words = text.replace('\n', ' ').split(' ') valid_ak = [] invalid_ak = [] valid_jak = [] invalid_jak = [] for word in words: temp = get_digits_only(word) if len(temp) == 11: id_code = get_int_list(temp) if check_personal_id(id_co...
def caesar(self, word:str, shift:int, encode:bool) -> str: ''' Method to apply caesar cipher :param word: word to convert :param shift: amount to shift each letter :param encode: whether to encrypt (true) or decrypt (false) :return: the encoded/decoded word ''' ...
This function determines the selected cipher (Caesar, Vigenere, Affine) and encryption/decryption mode, then executes the corresponding method with input text and parameters (shift, key, coefficients). It sets output to an in-app label or saves it to a file based on user selection.
def cipher(self) -> None: ''' Handles which method to call and what parameters to pass for the ciphers :return: None ''' output = "" if self.buttonGroup_1.checkedButton().text() == "Caesar": if self.buttonGroup_2.checkedButton().text() == "Encrypt": ...
def file_display(self, show:bool): ''' Toggles the file name box depending on the output selected :param show: Boolean on whether to toggle the box on or off :return: ''' if show: self.fileName.show() self.fileOut.show() else: s...
This code initializes a GUI component by setting up the UI, hiding specific input fields and labels, and connecting button clicks to methods that control file display options and cipher operations. It links 'outputOption1/2' to toggle file display, 'cipherOption1-3' to trigger shift-based cipher settings, and 'go_butto...
def __init__(self, *args, **kwargs): ''' Initializer method :param args: miscellaneous parameters :param kwargs: miscellaneous parameters ''' super().__init__(*args, **kwargs) self.setupUi(self) self.aInput.hide() self.bInput.hide() self.fi...
def parse_args(): parser = argparse.ArgumentParser(description="Analyze PDB files and save results to CSV.") parser.add_argument('--input_txt', type=str, help='Text file with paths to PDB files.') parser.add_argument('--hotspots', type=str, help='Hotspots to analyze.') parser.add_argument('--target', ty...
The code processes multiple PDB files by extracting hotspot and chain information, analyzing binder diffusion metrics (mean distance, max distance, radius of gyration), and appending results to a CSV file with file locking to prevent conflicts. It reads input paths from a text file, computes per-PDB statistics, and sto...
def main(): args = parse_args() input_txt = args.input_txt hotspots = args.hotspots target = args.target binder_chain = args.binder_chain target_chain = args.target_chain output_csv = args.output_csv # Read PDB file paths from the input text file with open(input_txt, 'r') as fil...
def model_to_dict(model): for col in model.__table__.columns: if isinstance(col.type, DateTime): value = convert_datetime(getattr(model, col.name)) elif isinstance(col.type, Numeric): value = float(getattr(model, col.name)) else: value = getattr(model, col...
The code converts a list or single object (Model instances or others) into a dictionary or list of dictionaries. It checks if `models` is a list, processes each element with `model_to_dict` if they are Model instances, or uses `result_to_dict` otherwise. For non-list inputs, it converts a Model to a dict or processes o...
def queryToDict(models): if isinstance(models, list): if models == []: return [] if isinstance(models[0], Model): lst = [] for model in models: gen = model_to_dict(model) dit = dict((g[0], g[1]) for g in gen) lst.app...
def _get_init_w_rf(self) -> np.ndarray: w_rf = self._complex_rand(self.size_w_rf) w_rf = w_rf / np.abs(w_rf) return w_rf def _get_init_v_bb(self) -> np.ndarray: return self._complex_rand(self.size_v_bb) def _calc_v_rf(self) -> np.ndarray: a = self.v_rf_a iter = self.v_rf_...
This code initializes a communication system's beamforming parameters, setting up analog/digital combiners (V_rf, W_rf), digital beamformers (V_bb, W_bb), and channel matrices. It configures dimensions for transmit/receive antennas, RF chains, and scattering clusters, preparing for MIMO signal processing and beamformin...
def __init__( self, P: float, var: float, beta: float, n_s: int, n_t: int, n_r: int, n_t_rf: int, n_r_rf: int, n_cl: int, n_ray: int, v_rf_a: float, v_rf_iteration: int, channel_matrix: np.ndarray, ) -> N...
def _reshape(self, real: np.ndarray, imag: np.ndarray, size: tuple) -> np.ndarray: return np.reshape(real + imag, size) def _half(self, arr: np.ndarray) -> list[np.ndarray]: n = len(arr) // 2 return arr[:n], arr[n:] def _calc_w_bb(self) -> np.ndarray: # Formula (8)s h = self.cha...
This code processes an action by splitting it into velocity and rotation components, reshaping them into specific dimensions, normalizing the rotation component, calculating a related variable, and returning the updated state along with a reward. The main task is to update the agent's internal state based on the input ...
def step(self, action: np.ndarray) -> list[np.ndarray, float]: n = np.prod(self.size_v_bb) * 2 v_bb = action[:n] w_rf = action[n:] self.v_bb = self._reshape(*self._half(v_bb), self.size_v_bb) self.w_rf = self._reshape(*self._half(w_rf), self.size_w_rf) self.w_rf = self.w_...
def update_transaction_ids_file(): # List of transaction IDs that we've published less than 14 days ago. transaction_ids_list = [] script_invocation_time = datetime.datetime.now() # Loop through each transaction listed in transaction_ids.txt to determine if we still need to keep track of it. with o...
The main task of the code is to process player transaction data by updating transaction IDs from a file, retrieving player page URLs, and passing both to a processing function that likely analyzes or stores transaction details. The code orchestrates data collection and processing for player-related transactions.
def main(): transaction_ids_list = update_transaction_ids_file() player_page_urls = get_player_page_links() process_feed(player_page_urls, transaction_ids_list)
def get_SZ_orient(self): """Get the S and Z matrices using the specified orientation averaging. """ tm_outdated = self._tm_signature != (self.radius, self.rat, self.wavelength, self.m, self.axis_ratio, self.np, self.ddelt, self.ndgs) scatter_outdated = self._sc...
This method computes or updates the S and Z matrices using either the `get_SZ_orient` method or the `psd_integrator`, depending on whether the parameters have changed. It checks for outdated signatures, recomputes matrices if needed, and returns the updated S and Z matrices.
def get_SZ(self): """Get the S and Z matrices using the current parameters. """ if self.psd_integrator is None: (self._S, self._Z) = self.get_SZ_orient() else: scatter_outdated = self._scatter_signature != (self.thet0, self.thet, self.phi0, self.p...
def layer_details(): n=len(model.layers) for i in range(n): c_count=0 d_count=0 layer_num_c=[] layer_num_d=[] for i in range(n): if ('convolutional') in str(model.layers[i]): c_count += 1 layer_num_c.append(i) elif (...
This function extracts weights and biases from convolutional and dense layers of a neural network model. It retrieves layer details, iterates through convolutional layers to dump their weights/bias, then does the same for dense layers, using specific dumping functions for each layer type.
def weight_bias_dump(): c_count, d_count, layer_num_c, layer_num_d = layer_details() for i in range(c_count): weights = model.layers[layer_num_c[i]].get_weights() conv_layer_weight_and_bias_dump(weights,layer_num_c[i]) for j in range(d_count): weights = model.layers[layer_num_d[j]].g...
def plot_data(x_train, y_train): """ Plot a graph 'Exam 2 score' vs 'Exam 1 score' with the x_train values """ # Create figure (will only create new window if needed) plt.figure() # Extract the positions of zeros and ones in y_train array pos_zeros = list(np.where(y_train == 0)) pos_one...
The main task of the code is to perform logistic regression with polynomial feature mapping and regularization. It reads data, processes features, trains a model using gradient descent with a regularization parameter, plots decision boundaries and cost functions, and evaluates accuracy. The code includes data preproces...
def main(): """ This is the main function """ # Read data from a .txt file that is separated by comma(,) data = pd.read_csv("ex2data2.txt", sep=",", header=None) # Number of training examples and features in the file num_ex = np.size(data.iloc[:, 1], 0) feature = np.size(data.iloc[1, :]...
def plot_data(x_train, y_train): """ Plot a graph 'Exam 2 score' vs 'Exam 1 score' with the x_train values """ # Create figure (will only create new window if needed) plt.figure(num="Data Visulization") # Extract the positions of zeros and ones in y_train array pos_zeros = list(np.where(y_t...
The code performs linear regression by loading data, preprocessing features, initializing parameters, running gradient descent to optimize theta, plotting the decision boundary and cost function, and calculating model accuracy. It reads a CSV file, separates features and labels, adds an intercept term, iteratively upda...
def main(): """ This is the main function """ # Read data from a .txt file that is separated by comma(,) data = pd.read_csv("ex2data1.txt", sep=",", header=None) # Number of training examples and features in the file num_ex = np.size(data.iloc[:, 1], 0) feature = np.size(data.iloc[1, :]...
def gradient_descent(x_train, y_train, theta, learning_rate, num_iter, lamda): """ Gradient descent algorithm Minimize(global/local minima) the cost function Return 2 values - optimized variable theta and variable J_history that contains value for every interations of cost function """ # Num...
The main task of the code is to train a multiclass logistic regression model using gradient descent on a digit dataset. It loads training data, preprocesses features and labels, initializes parameters, performs iterative gradient descent with regularization, computes accuracy, and visualizes cost functions for each cla...
def main(): """ This is the main function """ # Read data from .mat file. Return type is 'dict { }' data = loadmat("ex3data1.mat") # After separating made data type Array and reshaped variables x_train = data["X"] y_train = data["y"] # Set the zero digit to 0, because its mapped 10...
def mapto1(color): return (color[0]/255,color[1]/255,color[2]/255) def getGrayCluster(data,coord): x, y = coord x_max, y_max, _ = data.shape cluster = [] for i in range(x-1,x+2): for j in range(y-1,y+2): cluster.append(gray(tuple(data[i][j]))/255) return np.array(cluster)...
The function `predict_img` predicts image colors using a neural network defined by weights `w`, biases `b`, and layers, comparing reconstructed pixels to original data. It processes each pixel (excluding edges), maps values, clusters pixels, predicts colors, calculates errors, and computes accuracy. The result is an im...
def predict_img(w,b,layers,loss,data,centroids): print("Starting predictions") row, col, _ = data.shape newimg = [] diffs = [] pix_dict = {} z = 0 for i in range(1,row-1): imgrow = [] for j in range(1,col-1): if(j<int(col/2)): imgrow.append(mapto1(...
def initializeNN(size,layers,pix_in,centroids): w,b = [],[] g0_dim,gn_dim = pix_in,len(centroids) # Initializes list of weight and bias arrays (first layer is w[0]). The first # layer weight array w[0] has dimensions of (size,g0_dim), for example if the # height was 10 nodes and we have 9 initial ...
The code trains a neural network to classify input data patches into centroids using backpropagation. It initializes network weights/biases, iteratively performs forward/backward propagation on training data, updates parameters to minimize loss, and evaluates accuracy after each iteration. The main task is optimizing t...
def trainNN(size,layers,rate,pix_in,centroids,data,iter): w,b = initializeNN(size,layers,pix_in,centroids) centroiderr = [] train_data,output = get_datasets(centroids,data) print("Training with %i patches" % len(train_data)) for n in range(iter): for i in range(len(train_data)): ...
def __get_all_characters(self): print('\n\tRequesting all characters...\n') return self.__request_api_data('/v1/public/characters') def __simplify_characters_response_list(self, response_list): return [{ 'id':char.get('id'), 'name':char.get('name'), 'image':s...
This method retrieves either a list of characters or comics based on the input type, simplifies the retrieved data using specific helper methods, and returns the simplified list. It acts as a wrapper to fetch and process data uniformly for characters or comics.
def __get_simplified_list(self, type): ''' Input: list of dictionaries Output: same ''' if type=='characters': characters, _status = self.__get_all_characters() return self.__simplify_characters_response_list(characters) eli...
def __get_simplified_list(self, type): ''' Input: list of dictionaries Output: same ''' if type=='characters': characters, _status = self.__get_all_characters() return self.__simplify_characters_response_list(characters) eli...
The code's main task is to search and filter characters or comics based on a query and type filter. If a type (e.g., 'characters' or 'comics') is specified, it retrieves the simplified list for that type, applies the search query filter if provided, and returns the result. If no type is specified, it returns both chara...
def search(self, search_query='', type_filter=''): # If there's filtered by type if type_filter=='characters': characters = self.__get_simplified_list('characters') if not search_query: return {'characters':characters} # If there's a search ...
def lastUpdatedOn(self): today = date.today() print("Today's date:", today) collection = self.pump_and_dump("lastUpdate") collection.insert_one({'date': str(today)}) def updateCharts(self): db = self.get_database() posts = db.get_collection("forumPosts") finalDict...
The code initializes a Butler object, sequentially updating charts, symptoms, guidelines, Twitter, and Spotify with 10-second delays between each operation. It prints debug statements ("potato1", "potato2", etc.) to indicate progress. The `__init__` method orchestrates these updates in a predefined order, ensuring each...
def __init__(self): print("Butler is serving.") self.lastUpdatedOn() time.sleep(10) print("potato1") self.updateCharts() time.sleep(10) print("potato2") self.updateSymptomsAndGuidelines() time.sleep(10) print("potato3") self.updateT...
def holding_ids(self, symbols): symbols = [symbols] if hasattr(symbols, 'isalnum') else symbols # TODO: return 'N/A' if symbol doesn't exist objects = self.get_commodity_info(symbols) list = [(o['symbol'], o['holdings'][0]['id']) for o in objects] return [dict(list).get(s) for s in symbols] def parse(date): ...
This function retrieves the first price data for specified securities within a given date range, adjusting for dividends/splits if indicated. It returns the earliest or latest price (based on 'forward' flag) as a formatted dictionary with transaction details.
def get_first_price( self, symbols=None, date=None, extra=None, forward=True, limit=7): symbols = (symbols or self.securities) num = len(symbols) ids = self.holding_ids(symbols) date = parse(date) if date else d.today() - timedelta(days=limit) divs = True if (extra and extra.startswith('d')) else False ...
def parse(date): return date if hasattr(date, 'year') else parser.parse(date).date() def latest_price_dates(self, symbols, extra=None): #TODO: Check dividend and split dates objects = self.get_commodity_info(symbols) list = [] for o in objects: try: list.append(( o['symbol'], max(c['date'] fo...
The code retrieves and formats financial data (prices, dividends, or splits) for specified securities between start/end dates. It processes multiple symbols, adjusts dates, and structures results into a dictionary with entries for each symbol's events, handling different data types via the 'extra' parameter. If no data...
def get_price_list(self, symbols=None, start=None, end=None, extra=None): symbols = (symbols or self.securities) num = len(symbols) ids = self.commodity_ids(symbols) date = parse(end) if end else d.today() ends = list(it.repeat(date, num)) if num > 1 else [date] divs = True if (extra and extra.startswith('d...
def get_session(self): if not self.session: self.session = self.sessionmaker() return self.session def get_current(self) -> Block: """ Step 3 """ session = self.get_session() max = 0 cur = session.query(Block).all()[0] for block in sess...
The function retrieves the longest chain of blocks by traversing from the current block backward through parent pointers until reaching the genesis block, then reverses the collected blocks to return them in chronological order from earliest to latest.
def get_longest(self) -> List[Block]: """ Step 4 """ session = self.get_session() cur = self.get_current() longest = [] while(True): longest.append(cur) cur = self.search_block(cur.parent) if(cur == None): break ...
def log(self, msg, level=3): logtimefmt = "%Y-%m-%d %H:%M:%S" if self.loglevel >= level: timestamp = time.time() logstring = "["+time.strftime(logtimefmt)+"] ["+self.loglevelname(level)+"] "+msg print(logstring) def initRadio(self): self.setFrequency() ...
This code initializes a serial communication interface for a radio module, validates configuration parameters (frequency, power, etc.), opens a serial port, starts a read thread, and checks hardware readiness. It ensures correct setup for radio operations, logging errors for invalid configs and raising exceptions on se...
def __init__(self, callback, name, port, frequency = None, bandwidth = None, txpower = None, sf = None, cr = None, loglevel = LOG_NOTICE, flow_control = False, id_interval = None, id_callsign = None): self.serial = None self.loglevel = loglevel self.callback = callback self.na...
def processIncoming(self, data): self.callback(data, self) def log(self, msg, level=3): logtimefmt = "%Y-%m-%d %H:%M:%S" if self.loglevel >= level: timestamp = time.time() logstring = "["+time.strftime(logtimefmt)+"] ["+self.loglevelname(level)+"] "+msg prin...
The main task of the code is to read and process KISS protocol frames from a serial port, parsing command data, handling escape sequences, updating radio parameters (frequency, bandwidth, TX power, etc.), managing frame boundaries, and logging debug/error messages. It processes incoming bytes, detects frame start/end, ...
def readLoop(self): try: in_frame = False escape = False command = KISS.CMD_UNKNOWN data_buffer = b"" command_buffer = b"" last_read_ms = int(time.time()*1000) while self.serial.is_open: if self.serial.in_waitin...
def pseudo_king_moves(self, i, j): # only propose castles when possible moves = [] start = self.board._coordinate_to_location(i, j) for row_shift in [-1, 0, 1]: for col_shift in [-1, 0, 1]: erow, ecol = i + row_shift, j + col_shift if (row_shift != 0 o...
This method generates pseudo-legal moves for a piece at position (i,j) based on its type and the current player's turn. It checks if the square contains a piece of the current player's color, then collects potential moves using specialized methods for each piece type (king, queen, etc.), including en passant for pawns....
def pseudo_moves_from(self, i, j): moves = [] if not self.board.is_blank(i, j) and ((self.turn == 'w' and self.board.is_white(i, j)) or (self.turn == 'b' and self.board.is_black(i, j))): if self.board.is_king(i, j): moves.extend(self.pseudo_king_moves(i, j)) if s...
def parse(path): file = open(path) regex_str = r"(?P<dir>\d+)::(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})::(?P<name>[\w\s]+)::(?P<father>[" \ r"\w\s]+)::(?P<mother>[\w\s]+)::(?P<obs>[^:]*):: " res = [] regex = re.compile(regex_str) for line in file.readlines(): if match ...
The main task of the code is to parse data from "processos.txt", analyze name frequencies by century and overall, output the top 5 most frequent names, and save results to a JSON file. It focuses on processing historical process data to extract and rank name occurrences, with commented-out functions indicating addition...
def main(): filename = "processos.txt" # print(count_processes_by_year("processos.txt")) # first_names, last_surnames = count_names_by_century("processos.txt") # print(first_names) # print(last_surnames) # print(freq_names(filename)) # print(freq_relation(filename)) data = parse(filename...
def generate_map(self): map_size = settings.MAP_SIZE for i in range(map_size): tiles = [] for j in range(map_size): tiles.append(Tile(type=random.choice( [Tile.Types.empty, Tile.Types.ball, Tile.Types.radar, Tile.Types.enemy] ) ...
The main task of the code is to initialize default settings for an object by generating a map, loading movie data, creating a session, and returning the instance itself. The method `load_default_settings` orchestrates these setup steps, ensuring the object is properly configured with essential components like a map str...
def load_default_settings(self): self.generate_map() self.load_movies() self.create_session() return self
def lz77_packets(original_bytes, max_offset, max_length): written_bytes = [] bytes_to_compress = list(original_bytes) packets = [] # one iteration, haven't written the loop body yet while len(bytes_to_compress) > 0: candidate_bytes = bytes_to_compress[0:max_length] sliding_window = ...
The code compresses a byte array using the LZ77 algorithm with a 31-byte look-ahead buffer and 8-byte window, generates data packets, optimizes them by collapsing redundant entries, and converts the processed packets into compressed raw bytes.
def compress_lz77(byte_array): packets = lz77_packets(byte_array, 31, 8) collapsed_packets = collapse_data_packets(packets, 8) return raw_bytes_from_packets(collapsed_packets)
def _runjob(): print("starting ETL") run_etl(host="postgres") def _inspect(): print("inspecting image") cmd = f"tail -f /dev/null" _runcmd(cmd) def _runjob_and_inspect(): _runjob() _inspect()
The main task of the code is to execute different operations based on the input `action` parameter. It acts as a dispatcher: if `action` is "runjob", it calls `_runjob()`; if "inspect", it calls `_inspect()`; and if "runjob_and_inspect", it calls `_runjob_and_inspect()`. The function prints the action before executing ...
def _run(action: str): print("running action => ", action) if action == "runjob": _runjob() elif action == "inspect": _inspect() elif action == "runjob_and_inspect": _runjob_and_inspect()
def check_user(user_id: str = None, screen_name: str = None): # for x in screen_name"" try: i = api.get_user(user_id=user_id, screen_name=screen_name) if i: # #(i.id_str) # #(i.screen_name) # #(i.name) # #(i.followers_count) # #(i.profi...
The main task of the code is to check if the follower count in a database is outdated compared to a user's current followers. If so, it triggers a scraping process to update the data, using a fixed number of followers (20) when a specific screen name is provided, or a variable number (num) otherwise. The function logs ...
def confirm_scrape(num: int = 50, screen_name: str = None): """ (i.id_str, i.screen_name, i.name, i.followers_count, image)""" a = check_user(screen_name=screen_name) man = check_user(screen_name=main_man) if a or not isinstance(a, list): count = man[3] r = read_db_file() #(f"\n...
def overridePavData(pavDf, genoNames, chromNames): """ Modifies pav dataframe to replace the current value of 'index' with 'FeatureStart' """ # Initialize empty columns pavDf['index'] = 0 pavDf['presenceCounter'] = 0 for chrom in chromNames: pavDf[f"copyPptionInChr_{chrom}"] = 0 ...
This function converts a BED-like presence/absence matrix into a Panache-compatible JSON format by parsing, renaming columns, sorting data by genomic position, grouping by chromosomes, and returning structured data including chromosome names, genome names, and functional diversity.
def convertPav(pavFileToParse): """ Fonctions that write a parsed and transform json file compatible with Panache from a BED-like presence/absence matrix, also Panache-compatible """ pavData = pd.read_csv(pavFileToParse, sep='\t') pavData.rename(columns={"#Chromosome": "Chromosome"}, inplace=Tr...
def storeAnnotation(annotDict, annotArray, dictOfOverlaps): """ Checks if annot has overlaps, then stores annotation "object" into the annotation array """ # index is not based on the actual index from the gff file (since lines # != 'gene') are not stored nbOfAlreadyStoredAnnots = len(annotA...
The main task of the code is to parse GFF data for a chromosome, group genes and their associated exons into structured annotation objects, handle overlaps using a provided dictionary, and return an array of these annotations for Panache processing. It iterates through GFF rows, identifies genes and exons, aggregates e...
def createAnnotObjects(gffDataPerChrom, dictOfOverlaps): """ For a given chromosome, finds all annotations and turns them into usable objects for Panache """ # Array to fill with annotation data annotPerChrom = [] # At first, no annotation is being completed currentAnnotation = None ...
def readGff(gffFileToParse): """ Reads and format gff files into pandas dataframes """ gffHeaders = [ 'chrom', 'source', 'feature', 'start', 'end', # Doesn't need conversion since end pos is the same between 0-/1-based coordinates 'score', 'strand...
The function converts a GFF3 file into a structured JSON format compatible with Panache by parsing "gene," "intron," and "exon" features, extracting gene names via the "Name=" keyword, grouping data by chromosomes, and generating annotation data for downstream use.
def convertGff(gffFileToParse, chromNames): """ Fonctions that write a parsed and transform json file compatible with Panache from a gff3 file. Reads only the "gene" and "intron" or "exon" lines. Gene names should be written in the last column with the "Name=" keyword """ print('Parsing and...
def process_command_line(): parser = argparse.ArgumentParser() setup_parser(parser) return parser.parse_args() def find_clang_format_diff(): paths = ["clang-format-diff", "clang-format-diff.py"] if platform.system() == "Windows": paths.append("C:\\Program Files\\LLVM\\share\\clang\\clang-for...
The main task of the code is to execute the `clang-format-diff` tool on a specified source directory, using either user-provided or automatically detected paths. It processes command-line arguments, logs inputs, and handles errors gracefully by catching exceptions, logging fatal errors, and returning an appropriate exi...
def main(args=None): if not args: args = process_command_line() logger.debug("Arguments: %s", args) try: clang_format_diff_path = ( find_clang_format_diff() if not args.clang_format_diff else args.clang_format_diff ) test_clang_format(clan...
def __cal_position(self, others: list[StarData]) -> Vector: return self.position + (self.velocity + self.__cal_velocity(others)) / 2 * (DELTA_TIME / 1000) def __cal_velocity(self, others: list[StarData]) -> Vector: return self.velocity + self.__cal_acceleration(others) * (DELTA_TIME / 1000) def __cal_ac...
The code updates the object's position, velocity, and acceleration by calculating each using private methods (`__cal_position`, `__cal_velocity`, `__cal_acceleration`) based on a list of `StarData` instances, likely simulating celestial mechanics or motion dynamics.
def update(self, others: list[StarData]): self.position = self.__cal_position(others) self.velocity = self.__cal_velocity(others) self.acceleration = self.__cal_acceleration(others)
def new_belief(x_arr, y, vb, sd1, sd2): c_1 = [np.exp(-(x - vb) ** 2 / (2 * sd1 ** 2)) for x in x_arr] c_2 = np.exp(-(y - vb) ** 2 / (2 * sd2 ** 2)) # print(f'new belief: {ret}') return [(vb + c_1[i] * x_arr[i] + c_2 * y) / (1 + c_1[i] + c_2) for i in range(len(x_arr))] def loss_calc(x_arr, y, vb, sd1, ...
The code generates 1000 random x-values, computes loss and belief values for two scenarios (Big/Small) using predefined parameters, and visualizes them in a 2x2 subplot grid. It plots loss vs. x and new belief vs. x for each scenario, with customized x-axis ticks, to compare model performance and belief updates under d...
def plot_2(): pt = [(random.uniform(-30, 30), 0)[0] for _ in range(1000)] y_arr = [-11.25, 5.62] vb = 0.0 sd_arr = [5, 10] tars = [50.0, -50.0] nbs = [new_belief(pt, y_arr[i], vb, sd_arr[i], sd_arr[i]) for i in range(len(y_arr))] losses = [loss_calc(pt, y_arr[i], vb, sd_arr[i], sd_arr[i], ...
def separateImages(dirs, num_exp): i=0 in_list = [] final_list = [] for file in dirs: in_list.append(file) #print(in_list) i+=1 if (i%num_exp==0): final_list.append(in_list) i=0 in_list = [] return final_list def from_folders_single...
The code processes image groups from a directory to generate HDR files, using flags to handle rotation, single-image processing, and white balance. It organizes output into EXR files, alternating save paths based on parameters, and calls `create_hdr` with specified configurations.
def main(path, path_hdr_rotate, path_hdr, num_exp=9, isOnePlace = True, rotate = False, img_white = False, oneImg=False): dirs = sorted(os.listdir(path)) if isOnePlace: final_list = separateImages(dirs, num_exp) elif oneImg: final_list = from_folders_single_image(path, dirs, num_exp) ...
def squareUnderAttack(self, r, c): # To check if a given square is under attack by any piece self.whiteToMove = not self.whiteToMove # switch to opponents move oppMoves = self.getAllPossibleMoves() self.whiteToMove = not self.whiteToMove for move in oppMoves: if move...
This function generates valid castling moves for a king based on the current player's castling rights and whether the king is in check. It checks for both kingside and queenside castling possibilities, adding valid moves to the provided list if the conditions are met.
def getCastleMoves(self, r, c, moves): if self.squareUnderAttack(r, c, ): return # cannot castle when in check # King side Castling if (self.whiteToMove and self.currentCastlingRights.wks) or ( not self.whiteToMove and self.currentCastlingRights.bks): se...
def getAllPossibleMoves(self): # get all moves possible at a given time moves = [] for r in range(len(self.board)): for c in range(len(self.board[r])): turn = self.board[r][c][0] if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteT...
This function generates valid chess moves by first collecting all possible moves, then filtering out those that leave the king in check. It temporarily stores en passant and castling rights, applies castling moves, simulates each move to check for checkmate/stalemate, and restores original game state before returning t...
def getValidMoves(self): # To get the valid moves from the available possible moves # Temporary variable for enpassant and castle rights tempEnpassantPossible = self.enpassantPossible tempCastleRights = CastleRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks, ...
def resize_image(image): return cv2.resize(image, (1024, 576), interpolation=cv2.INTER_NEAREST) def findRelationShipsRegions(resized_image, direction="horizontal"): sobelxUint8 = performSobel(resized_image, direction) regions = select_roi_class(resized_image, sobelxUint8) # boje da bude recnik kasnije ...
The main task of the code is to process an input image by detecting horizontal regions, classifying them using a pre-trained VGG16 model and SVM classifier, extracting text via OCR, analyzing relationships between classified regions, and generating structured output with relationships and named entities. The code combi...
def generate_from_image(img, img_name): base_model = VGG16(weights='imagenet', include_top=False, input_tensor=Input(shape=(224, 224, 3)), input_shape=(224, 224, 3)) svm = load_svm() print(len(img), len(img[0])) resized_image = resize_image(img) regions_...
def get_words_and_containers(self, doc: Document, target_container: Union[TextLine, Paragraph, Field, str]): """ Inputs: document and the container to generate sequences for. Outputs: a dictionary containing the image, the The image/doc gets cropped to a smaller size. """ ...
This code processes a document by extracting words and their containers, preprocessing bounding boxes and pointers, optionally shuffling the sequence, and converting to midpoints if specified. It returns the processed data for further use in tasks like layout analysis or model input preparation.
def __call__(self, doc): words_and_containers = self.get_words_and_containers(doc, self.target_container) datum = self.preprocess_bboxes_pointers(words_and_containers, EOC_TOKEN) if self.random_shuffle: datum = self.random_shuffle_sequence(datum) if self.only_midpoi...
def update_games(): start_time = time.time() temp = tempfile.NamedTemporaryFile(prefix=current_time, suffix="_temp", mode="w") logger = config_struct_log(temp) yesterday = datetime.now() - timedelta(1) yesterday = datetime.strftime(yesterday, "%m/%d/%Y") try: sched = statsapi.schedul...
The code's main task is to execute two functions (`update_games()` and `prepare_games()`) while handling exceptions. If errors occur during either function, it logs them, sends error emails, and returns a 400 status. If no errors occur, it sends a confirmation email and returns a 200 status. The script ensures error tr...
def main(): error_occurred = False try: print("Trying to update games...") update_games() except Exception as e: print(f"Error occurred updating games: {e}") send_error_email("update_games()", e) error_occurred = True try: print("Trying to prepare games......
def _Newline(lines): in_string = False for line in lines: if line is None: continue line, in_string = _removeNewline(line, in_string) yield line def _process(opts, lines): if opts.database: yield '''\ drop database IF EXISTS {d}; create database {d} character set u...
This script processes input files by parsing command-line options (database, username, password), reads lines from input files, handles newline characters, stores processed data in a temporary file, reprocesses the data with a `_process` function, replaces newline characters again, and prints the final lines. The main ...
def main(): op = OptionParser() op.add_option('-d', '--database') op.add_option('-u', '--username') op.add_option('-p', '--password') opts, args = op.parse_args() lines = (l for l in fileinput.input(args)) lines = (l for l in _Newline(lines)) f = tempfile.TemporaryFile() for line in ...
def rotation_point(self): return self.bend_point(RATIO) def angle_point(self): return self.point_to_rotate().rotate(self.rotation_point(), ROTATION_ANGLE) def point_to_rotate(self): return self.bend_point(2 * RATIO)
The main task of the code is to generate a list of connected line segments by linking specific geometric points, including the original point, rotation pivot, angle reference, and target rotation point, forming a transformed path between `point_a` and `point_b` through rotational and angular adjustments.
def transform_line(self) -> list['Line']: return [ Line(self.point_a, self.rotation_point()), Line(self.rotation_point(), self.angle_point()), Line(self.angle_point(), self.point_to_rotate()), Line(self.point_to_rotate(), self.point_b) ]
def create_table(self): self.letters = [] row = [] for i in range(6): for j in range(5): txt = StringVar() txt.trace("w", lambda name, index, mode, sv=txt, r=i, c=j: self.next_entry(sv, r, c)) item = Entry(self.frm, width=5, fo...
The code initializes a Wordle game interface using Tkinter, loading a word list from "words.txt", setting up a GUI with input fields, buttons for checking guesses, CPU-assisted play, and reset functionality. It establishes game state variables, links to a CPU logic class for automated guesses, and configures the UI lay...
def __init__(self): self.word_list = [line[:-1] for line in open("words.txt", "r")] self.root = Tk() self.root.geometry('500x500') self.frm = ttk.Frame(self.root, padding=10) self.root.config(bg="#f0f0f0") self.frm.grid(sticky="nsew") self.correct_style =...
def inverseFilter(filterChar, wordList="none"): #returns a list of words that do NOT contain the filter character returnList = [] if wordList == "none": file = open("words.txt", "r") wordList = [line for line in file] file.close() for word in wordList: if filterChar not in wo...
The code evaluates a word's effectiveness in reducing a list of possible words through various letter state combinations (0: absent, 1: correct position, 2: wrong position). It iterates over all permutations of these states for each letter, applying filters to narrow the `reset_list` based on the word's letters and the...
def get_word_value2(word, reset_list): #goes through all the combinations of letter states for the word and returns a score based on the weighted average list reduction (lower is better) word_list = reset_list resulting_words_list_lengths = [] lettersInWord = [] for first_letter in range(3): f...
def game_data_avg(game_data): #returns average steps to complete a game try: return (game_data["1"] + 2 * game_data["2"] + 3 * game_data["3"] + 4 * game_data["4"] + 5 * game_data["5"] + 6 * game_data["6"]) / (game_data["1"] + game_data["2"] + game_data["3"] + game_data["4"] + game_data["5"] + game_data["6...
The code tests the effectiveness of a letter-frequency-based search algorithm in finding a target word ("salet") within a limited number of steps (1-6). It simulates multiple trials, tracks success rates, and updates statistics in a dictionary (`game_data`). If the word is found, it increments the corresponding step co...
def test_highestFrequency(n): #tests search using letter frequencies game_data = {"1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "DNF": 0} for i in range(n): available_words = [i[:-1] for i in open("words.txt", "r").readlines()] test_word = random.choice(available_words) # print(test_...
def game_data_avg(game_data): #returns average steps to complete a game try: return (game_data["1"] + 2 * game_data["2"] + 3 * game_data["3"] + 4 * game_data["4"] + 5 * game_data["5"] + 6 * game_data["6"]) / (game_data["1"] + game_data["2"] + game_data["3"] + game_data["4"] + game_data["5"] + game_data["6...
This function tests the efficiency of a multi-threaded algorithm (MT_HRBFR2) in solving a word game by simulating multiple attempts to guess a target word ("salet") within 6 steps. It tracks success rates, updates statistics in `game_data`, and uses strategies like `blimpSearch` and hardcoded guesses. If the word isn't...
def test_MultiThreadedHRBFR2(n): #tests deep search by highest weighted average list reduction game_data = {"1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "DNF": 0} for i in range(n): available_words = [i[:-1] for i in open("words.txt", "r").readlines()] test_word = random.choice(available_w...
def validState(wordState): #returns whether or not a word state is valid if len(wordState) != 5: return False else: try: for char in wordState: if int(char) < 0 or int(char) > 2: return False except: return False return Tru...
The code simulates a game where the user inputs a word and its state (validity), filters a word list based on these inputs, and runs a multithreaded algorithm to evaluate possible solutions. The loop allows up to six attempts, with the option to exit early. The main task is to iteratively narrow down potential words us...
def gameSim(wordList=available_words): #simulates a real game for i in range(6): word = input("Enter word: ") wordState = input("Enter word state: ") while not validState(wordState): word = input("Enter word: ") wordState = input("Enter word state: ") wordLis...
def set_initial_page_interface(self) -> None: """ Sets the initial page interface. """ st.set_page_config(page_title=self.title, page_icon=self.page_icon) def set_basic_properties_interface(self) -> str: """ Sets the basic properties interface. Returns: -...
The code runs a Streamlit application that validates a user ID input and dynamically displays different sections (Predictions, Results, GenAI) based on a radio selection. It initializes the interface, checks user credentials, and renders corresponding tabs for predictions, results, or AI features.
def run(self) -> None: """ Runs the Streamlit application. """ self.set_initial_page_interface() radio_option = self.set_basic_properties_interface() # Text input for user ID self.user_id = st.text_input("Enter User ID (e.g., john.doe):") if self.data_vali...