dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def set_move(x, y, player): # Set the move for the specified player if valid_move(x, y): board[x][y] = player return True return False def game_over(board): # Check if the game is over if wins(board, HUMAN) or wins(board, COMP): return True for row in board: for c...
This method handles a player's move in a game by checking if the selected cell is empty and the game is active. If the current player is human, it updates the cell with their symbol, switches to the AI's turn, and checks if the game is over. If the game ends, it triggers the end-game logic.
def make_move(self, x, y): if self.buttons[x][y]["text"] == "" and not self.is_game_over: if self.current_player == HUMAN: self.buttons[x][y]["text"] = self.h_choice set_move(x, y, HUMAN) self.current_player = COMP if not game_over(boar...
def get_eye_angle(eye_start_point, eye_end_point): """Calculates an eyes' gaze direction. It takes as input the first (eye_start_point) and last (eye_end_point) index of the dlib shape predictor referring to the an eye and returns the angle of gaze for that eye. The angle is in respect to the camera, hence,...
The main task of the code is to calculate the coordinates of where a person is looking by integrating head pose angles and eye gaze directions. It combines detected eye angles (with Kalman filtering for noise reduction) and head angles to compute refined gaze coordinates, adjusting for frame origin shifts. The function...
def get_gaze_coords(): """Determines the coordinates of where a person is looking by combining the head pose and gaze direction. It does not require any input parameters and returns the coordinates at which the person is looking as well as the X and Y angles of the eyes and head respectively.""" global...
def create_data(): data = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] factor_names = ['no surfacing', 'flippers'] return data, factor_names def create_tree(data, factor_names): # Get total labels in data label_list = [sam...
The main task of the code is to generate a dataset, construct a decision tree classifier using the data, and save the trained tree to a file for later use. It includes steps like creating data, calculating entropy (commented out), splitting data, selecting the best split factor (commented out), building the tree, and s...
def main(): my_data, my_factor_names = create_data() # print('My Data: ', my_data) # my_entropy = calc_entropy(my_data) # print('My Entropy: ', my_entropy) # split_1 = split_data(my_data, 0, 1) # print(split_1) # split_2 = split_data(my_data, 0, 0) # print(split_2) # best_factor =...
def get_class_priors(class_counts): """ :param class_counts: dict {class: num_instances} :return: dict {class: log(P(class))} """ num_instances = float(sum(class_counts.values())) return {klass: log(class_counts[klass] / num_instances) for klass in class_counts} def get_scores_given_...
The code updates class priors using `get_class_priors` and computes scores for input data `X` via `get_scores_given_class`, incorporating class counts, class labels, updated priors, and logarithmic theta values to refine model predictions.
def update_scores(self, X): """ Sets self.class_priors """ self.class_priors = get_class_priors(self.class_counts) self.scores = get_scores_given_class( X, self.classes, self.class_priors, self.get_lg_theta() )
def profile(Motifs): t = len(Motifs) k = len(Motifs[0]) profile = {} profile = count(Motifs) for symbol in 'ACGT': for j in range(k): profile[symbol][j] = profile[symbol][j]/float(t) return profile def profile_most_probable_pattern(Text, Profile): T = len(Text) K = le...
The code performs a greedy motif search to find the set of k-length motifs (one from each of t DNA sequences) with the lowest score. It initializes best motifs as the first k-mers from each sequence, then iterates over all possible starting positions in the first sequence. For each position, it constructs motifs using ...
def greedy_motif_search(Dna, k, t): BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for i in range(n-k+1): Motifs = [] Motifs.append(Dna[0][i:i+k]) for j in range(1, t): P = profile(Motifs[0:j]) Motifs.append(pr...
def _sarsa_target(self, reward, nxt, nxt_action): return reward + self._get_Q(nxt, nxt_action) def _expected_sarsa_target(self, reward, nxt): action_dist = self._get_action_dist(nxt) return reward + np.sum(action_dist * self._get_Q(nxt)) def _q_learning_target(self, reward, nxt): return reward + np.max(self._ge...
This function determines the target value calculation method based on the specified reinforcement learning algorithm. It returns different target values using Sarsa, Expected Sarsa, or Q-learning approaches by calling corresponding helper methods, with an error message for unsupported algorithms.
def _get_target(self, algo, reward, nxt, nxt_action): if algo == 'Sarsa': return self._sarsa_target(reward, nxt, nxt_action) elif algo == 'Expected Sarsa': return self._expected_sarsa_target(reward, nxt) elif algo == 'Q-learning': return self._q_learning_target(reward, nxt) else: print('Algorithm no...
def _choose_action(self, state): if np.random.rand() < self.epsilon: return np.random.randint(self.num_actions) else: return _random_argmax(self._get_Q(state)) def _get_target(self, algo, reward, nxt, nxt_action): if algo == 'Sarsa': return self._sarsa_target(reward, nxt, nxt_action) elif algo == 'Expe...
This code implements a reinforcement learning episode where an agent updates Q-values using a specified algorithm. It iteratively selects actions, interacts with the environment, calculates targets based on rewards and next states, and adjusts Q-values with a learning rate. The loop continues until reaching the goal st...
def run_episode(self, env, algo): steps = 0 cur = self.start action = self._choose_action(cur) while cur != self.goal: nxt, reward = env.step(cur, action) nxt_action = self._choose_action(nxt) target = self._get_target(algo, reward, nxt, nxt_action) old_val = self._get_Q(cur, action) self._set_Q...
def bestMove(board, depth, maxDepth, isMaximizing, alpha, beta, prevMoveX, prevMoveY, currentMove, nextMove): #increment the node counter by one, this is printed after every ai generated move for now for testing purposes global nodes nodes += 1 if isMaximizing: bestVal = -1000 bestM...
The code implements a Connect Four game where a human player (Red) competes against an AI (Yellow) using the minimax algorithm with alpha-beta pruning. The AI evaluates possible moves, tracks searched nodes and pruning efficiency, and places pieces on a 6x7 board. The game checks for wins (four-in-a-row) in all directi...
def main(): #prepare the board along with various variables board = [['']*7 for i in range(6)] currentMove = 'R' nextMove = 'Y' if random() > .5: randInt = trunc(random() * 7) board[5][randInt] = 'Y' run = True clock = pygame.time.Clock() while run: #limit the fps...
def get_body_count(self): return len(self._bodies) def get_main_body_index(self): return self._main_body_index def set_main_body(self, body_index): if body_index in range(self.get_body_count()): self._main_body_index = body_index else: self._main_body_index = None...
This method deletes a body at the specified index from a list, then adjusts the main body reference if the deleted body was the main one or preceded it. It ensures the main body index remains valid after removal.
def delete_body(self, body_index): if body_index in range(self.get_body_count()): self._bodies.pop(body_index) if self.get_main_body_index() is not None: if body_index < self.get_main_body_index(): self.set_main_body(self.get_main_body_index() - 1) ...
def get_max_r(self): return 10 ** self._max_r_log def delete_body(self, body_index): if body_index in range(self.get_body_count()): self._bodies.pop(body_index) if self.get_main_body_index() is not None: if body_index < self.get_main_body_index(): ...
This function merges two celestial bodies into a single composite body by calculating their combined mass, a new radius based on their individual radii, and the center of mass velocity. It then deletes the original two bodies and creates a new body with these computed properties, effectively simulating a collision and ...
def collide(self, body1_index, body2_index): body1 = self._bodies[body1_index] body2 = self._bodies[body2_index] mass = body1.get_mass() + body2.get_mass() radius = min(self.get_max_r(), np.sqrt(body1.get_radius() ** 2 + body2.get_radius() ** 2)) (x, y) = \ (body1.get...
def GetDecisions(self): for p in range(self.m_num_players): p_arm = self.m_players[p].ChooseBestArm() self.decisions[p] = p_arm return self.decisions def Pull(self): for p, p_arm in enumerate(self.decisions): p_sample = np.random.binomial(1, self.m_players[p]....
The code executes a time-based loop to repeatedly make decisions, perform actions (pulls), and receive feedback. After completing all time steps, it calculates the percentage of times each arm was pulled and the percentage of regret incurred during the process.
def Run(self): for t in range(self.m_time_horizon): self.GetDecisions() self.Pull() self.ReceiveFeedback() self.CountArmPullPercentages() self.CountRegretPercentages()
def check_keydown_events(event, ai_settings, screen, ship, bullets): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: # move right ship.moving_right = True if event.key == pygame.K_LEFT: # move left ship.moving_left = True elif ...
The function `check_events` processes user inputs and game events in a Pygame-based game. It detects keyboard presses/releases, mouse clicks, and quit commands. For keyboard actions, it triggers `check_keydown_events` and `check_keyup_events` to control the ship's movement. For mouse clicks, it checks if the play butto...
def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets): # find and respond to event such as movement or mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_ev...
def check_fleet_edges(ai_settings, aliens): # check edge and act accordingly for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets): # game acts accordingly w...
This function updates alien movement, checks for collisions between the ship and aliens, and triggers responses like ship damage or game-over conditions. It adjusts alien fleet direction at edges, updates alien positions, detects ship-alien collisions via pygame's sprite collision check, and calls ship_hit() if a colli...
def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets): check_fleet_edges(ai_settings, aliens) aliens.update() # check for alien and bullet collision if pygame.sprite.spritecollideany(ship, aliens): ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets) print(...
def find_all_includes(filename: str) -> List[str]: """Find all static includes in a file. A static include is an include that is being included with \"\" and not <>. This is obviously not mandatory for a project and <> can be also used for static includes but that is your problem. Make s...
This function builds a graph by recursively adding nodes for static includes and functions. It adds child nodes from static includes, avoids duplicates using 'found', and processes non-function children recursively. It also extracts functions from files, creates function nodes under the current tree, and attaches them ...
def find_children_and_add(self, tree: Node, found: List[Node], gca: Node): """This function is used to build the graph. find all children from the static includes and use them as children in the graph. Args: tree (Node): the subtree to add to found (List[Node]): list of ...
def find_children_and_add(self, tree: Node, found: List[Node], gca: Node): """This function is used to build the graph. find all children from the static includes and use them as children in the graph. Args: tree (Node): the subtree to add to found (List[Node]): list of ...
The main task of the code is to generate a directed graph representing include dependencies of C files starting from a specified main file. It constructs a graph by recursively adding dependencies, exports it as an image, converts it to a NetworkX DiGraph, and returns both the graph and the root node.
def generate_graph(self): """generate the graph of includes from a given start file (self.path_to_main). Returns: [Tuple[Node, nx.DiGraph]]: [a graph representation of the includes, same graph as nx graph] """ gca = Node("START") my_node = Node(self.path_to_main, gca...
def conv(self,shape,act=tf.nn.relu,pool=True,dropout=False,norm=True,name=None): # True why dropout bad in tensorflow?? with tf.name_scope('conv'): print("input shape ",self.last_shape) print("conv shape ",shape) width=shape[-1] filters=tf.Variable(tf.random_normal(shape), name="filters") # filters ...
The code constructs a dense convolutional neural network (DenseNet) with multiple dense blocks, each adding layers with specified growth rates. It validates input depth, initializes channels, applies convolutional layers, transitions, batch normalization, ReLU activation, max pooling, and reshaping to prepare for class...
def buildDenseConv(self): depth = 3 * 1 + 4 if (depth - 4) % 3 : raise Exception("Depth must be 3N + 4! (4,7,10,...) ") # # layers in each denseblock N = (depth - 4) / 3 dropRate = None # nil to disable dropout, non - zero number to enable dropout and set drop rate # # channels before entering the first de...
def handle401(self): self.send_response(401) #headers go here, if any self.send_header( "Content-Type", "text/plain" ) self.end_headers() #body goes here, if any self.wfile.write(bytes("Not Found :c ", "utf-8")) def end_headers(self): #send common headers ...
This code retrieves a car record by ID from a database if the user is logged in. It returns a 200 OK response with the car data in JSON format if found, otherwise handles 401 Unauthorized for missing user session or 404 Not Found for invalid car ID.
def handleRetrieveCar(self, id): if "userId" not in self.sessionData: print("User not logged in") self.handle401() return db = CarsDB2() car = db.getOneCar.getOneCar(id) if car != None: self.send_response(200) ...
def handle401(self): self.send_response(401) #headers go here, if any self.send_header( "Content-Type", "text/plain" ) self.end_headers() #body goes here, if any self.wfile.write(bytes("Not Found :c ", "utf-8")) def end_headers(self): #send common headers ...
The main task of the code is to delete a car from the database if the user is authenticated and the car exists. It first checks for user login status, retrieves the car by ID, deletes it if found, and returns a 200 response. If the car is not found or the user is not logged in, it handles errors with 401 or 404 respons...
def handleDeleteCar(self, car_id): if "userId" not in self.sessionData: print("User not logged in") self.handle401() return db = CarsDB2() car = db.getOneCar(car_id) if car != None: db.deleteCar(car_id) #maybe has to b...
def load_session(self): #upon client request self.load_cookie() if "sessionId" in self.cookie: sessionId = self.cookie["sessionId"].value self.sessionData = SESSION_STORE.getSessionData( sessionId ) if self.sessionData == None: sessionId = SES...
This code handles HTTP GET requests by retrieving car data based on the URL path. It splits the path to determine the collection ("cars") and optional member ID, then calls methods to fetch specific or all cars, or returns a not-found response if the collection is invalid.
def do_GET(self): self.load_session() #status code(required), headers (optional), body (optional) print("the request path is: ", self.path) parts = self.path.split( "/" ) collection = parts[1] if len(parts) > 2: member_id = parts[2] e...
def load_session(self): #upon client request self.load_cookie() if "sessionId" in self.cookie: sessionId = self.cookie["sessionId"].value self.sessionData = SESSION_STORE.getSessionData( sessionId ) if self.sessionData == None: sessionId = SES...
This code handles HTTP DELETE requests by parsing the request path to determine the target collection (e.g., "cars") and member ID. If the collection is "cars" and a valid member ID exists, it deletes the corresponding car entry; otherwise, it returns a "Not Found" response.
def do_DELETE(self): self.load_session() print("The request path for delete is: ", self.path) parts = self.path.split( "/" ) collection = parts[1] if len(parts) > 2: member_id = parts[2] else: member_id = None if collection == "cars": ...
def initialize_gui(): global cap, root, logo_photo, thresholds ctk.set_appearance_mode("dark") ctk.set_default_color_theme("blue") cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) cap.set(cv2.CAP_PROP_AUTOFOCUS, 0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 850) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 700) ...
The main task of the code is to initialize and run a graphical user interface (GUI) for a robot control system. It sets up frames, sliders, controls, a camera feed, and a dial, toggles slider visibility, configures robot controls, and handles window closure events. The `mainloop()` ensures the GUI remains active, enabl...
def main(): initialize_gui() create_main_frames() create_sliders_and_controls() toggle_sliders(ball_sliders_frame) setup_robot_control() update_camera_feed() update_dial() root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop()
def create_output_dir(new_model, config_data): print(f"Creating dreamfusion model folder: {new_model}") models_dir = os.path.dirname(cmd_dreamfusion_models_path) if cmd_dreamfusion_models_path else paths.models_path model_dir = os.path.join(models_dir, "dreamfusion", new_model) output_dir = os.path.join...
This code converts a Stable Diffusion model checkpoint into a Diffusers-compatible format by loading the checkpoint, configuring components (UNet, VAE, text encoder), applying a specified scheduler, and saving the converted model. It handles both local and HuggingFace-hosted models, manages device placement, and cleans...
def extract_checkpoint(new_model_name: str, checkpoint_path: str, scheduler_type="ddim", new_model_url="", new_model_token="", extract_ema=False): shared.state.job_count = 8 if shared.sd_model is not None: shared.sd_model.to('cpu') map_location = shared.device # Set up our...
def parser(myList): rec = "" check = 0 for i in range(len(myList)): if myList[i].isdigit() == True or (myList[i] == '.' and myList[i + 1].isdigit() == True and myList[i - 1].isdigit() == True) or (myList[i] == '-' and myList[i + 1].isdigit() == True): if check == 1 and len(rec) > 0: ...
The main task of the code is to read data from a file, parse its content using a parser function, check for errors with a validation function, and print the processed result. The function opens the specified file, reads its contents, processes them through parsing and error-checking, then outputs the final data structu...
def main(file): f = open(file, "r") myList = f.read() myList = parser(myList) checkError(myList) myPrint(myList)
def checkNumber(first, info): counter = 0 j = 0 for i in range(len(first)): rec = splitMyLine(first[i]) while j < len(rec): if (info == rec[j]): counter += 1 j += 1 j = 0 return counter def theHeartOfTheBeast(first, info): counter = ch...
The function processes elements in 'info' by iterating through them, using a reversed 'first' list. For each info element, it loops based on 'checkNumber' results, calling 'theHeartOfTheBeast' with modified splits of 'first' and the current info element. The task involves transforming data through nested loops, reversi...
def repertiture(mySplit, first, second, info): first.reverse() k = 0 print() while (k < len(info)): j = 0 while (j < checkNumber(first, info[k])): theHeartOfTheBeast(newSplit(first, info[k], j + 1), info[k]) j += 1 k += 1
def error_case(tab): for i in range(len(tab)): if (len(tab[i]) < 3): exit(84) check_first(tab) check_third(tab) check_four(tab) def transform_tab(tab): ret = [] for i in range(len(tab)): ret2 = [] ret2.append(tab[i][0]) ret2.append(tab[i][2]) r...
The code processes a file to calculate and display the total construction duration, adjusts data structure by adding placeholder values, determines task start times, and prints a formatted schedule showing activities with visual bars representing their durations.
def main(file): error_case(file) file = transform_tab(file) tot = get_total(file) print("Total duration of construction: " + str(tot) + " weeks") for i in range(len(file)): file[i].append(0) file[i].append(0) #print(file[i]) #print("-------") print() tab = get_beg...
def diviseTwo(first, second, mySplit): for i in range (len(mySplit)): if (i % 2 == 0): first.append(mySplit[i]) else: second.append(mySplit[i]) def parse(start): start_two_point = [] for i in range(len(start)): if (":" in start[i]): start_two_point...
The code processes a Makefile by reading and splitting its content into lines, cleaning up empty lines, dividing the content into sections, and using different functions to parse, generate a matrix, or handle key-based search operations based on the provided Key parameter.
def main(Makefile, Key): f = open(Makefile, "r") myList = f.read() mySplit = myList.split("\n") while (len(mySplit[len(mySplit) - 1]) == 0): del mySplit[-1] j = 0 first = [] second = [] for i in range (len(mySplit) - 1): if (mySplit[j] == ""): mySplit.pop(j) ...
def get_project_config(): """Create a folder for the project and store in name in config""" fc.project_name = input("What is the project name?") try: os.makedirs(fc.project_name) except OSError: print(f"Failed to create folder '{fc.project_name}'") def get_csv_file_config(filena...
The main task of the code is to process a CSV file by retrieving project and file configurations, printing the configuration details, and aggregating data based on the provided input file path and configuration. It initializes project settings, loads CSV-specific parameters, and executes an aggregation operation using ...
def main(argv): get_project_config() fc = get_csv_file_config(argv[0]) print(fc) aggregate(argv[0],fc)
def connect_to_db(config, db): """ Connects to the given database using the MySQL connector. """ db_config = getattr(config, db) connection = mysql.connector.connect( user=db_config.db_user, password=db_config.db_password, host=db_config.db_host, port=db_config.db_po...
The function `find_and_complete` queries an MLWH database using lane-specific parameters (batch ID and position) to retrieve run data. It then processes the results to determine QC status (PASS/FAIL) and sends this status to a system (SS) via the `send_npg_action` function, iterating over provided lane information.
def find_and_complete(config, lanes_info): """Find the run in MLWH and send PASS or FAIL to SS""" connection, cursor = connect_to_db(config, MLWH) with open("mlwh_script.sql") as f: mlwh_query_template = f.read() for lane in lanes_info: logger.info(f'{"-" * 80}') logger.info(f"...
def print_log(print_string, log): if log[1] == 0: print("{}".format(print_string)) log[0].write('{}\n'.format(print_string)) log[0].flush() def evaluate(test_loader, test_loader1, fake_loader, adv_loader, net, criterion, args, log, nums=100, nums2=None): if args.bayes: net.apply(freeze) ...
This code trains a neural network with distributed GPU support, Bayesian optimization, and evaluation. It initializes the model, configures distributed training, loads pre-trained weights, sets up optimizers (SGD for parameters, VarSGD for Bayesian variance), trains with learning rate scheduling, logs metrics, and save...
def main_worker(gpu, ngpus_per_node, args): global best_acc args.gpu = gpu assert args.gpu is not None print("Use GPU: {} for training".format(args.gpu)) log = open(os.path.join(args.save_path, 'log{}{}.txt'.format('_seed'+ str(args.manualSeed), '_eval' if args.evaluate else ''))...
def print_log(print_string, log, force=False): if log[1] == 0 or force: print("{}".format(print_string)) log[0].write('{}\n'.format(print_string)) log[0].flush() def evaluate(test_loaders, fake_loader, net, criterion, args, log, nums=100, nums2=None): if args.bayes: net.apply(freeze) ...
This code trains a neural network model for a classification task using distributed training. It initializes the model, loads a pre-trained checkpoint, sets up optimizers (SGD and VarSGD for Bayesian parameters), trains with learning rate adjustment, evaluates performance, and saves checkpoints. The model uses distribu...
def main_worker(gpu, ngpus_per_node, args): global best_acc args.gpu = gpu assert args.gpu is not None print("Use GPU: {} for training".format(args.gpu)) log = open(os.path.join(args.save_path, 'log{}{}.txt'.format('_seed'+ str(args.manualSeed), '_eval' if args.evaluate else ''))...
def _evaluate(self): if isinstance(self.dataloader, torch.utils.data.dataloader.DataLoader): predict = [] actual = [] compute_correct_predict = [] for X_batch, y_batch in self.dataloader: predicted = self.model(X_batch) predicted = ...
The main task of the code is to evaluate a model's performance by calculating accuracy, precision, recall, and F1-score, then displaying these metrics and generating a classification report. It combines aggregated metric visualization with detailed per-class analysis using predicted and actual labels for comprehensive ...
def _display_metrics_and_report(self): accuracy, precision, recall, f1, predict, actual = self._evaluate() self._display(metrics=zip([accuracy], [precision], [recall], [f1])) print("\nThe classification report is given below.\n") self._classification_report_show(predict=predict, actual=...
def randomColors(normalTokens, background = 0): # apply random colors of slightly darker gamma on white background == 0 # and bright colors on black background == 1 for token in normalTokens: if background == 0: token.color = getRandomColor() else: token.color = getRa...
The function `colorTokens` assigns random or predefined color schemes to a list of Tokens based on the specified background (white or black). It selects from four schemes: Random, Jet, Grayish, or a fixed list for white backgrounds, and a dark-adjusted Random scheme for black backgrounds, printing the chosen scheme bef...
def colorTokens(normalTokens, background = 0): """ given a list of Tokens (see the wordle for Token class) we add their color attributes @background == 0 means WHITE; == 1 means Black background, needs brighter colors by picking a random color scheme and applying on the Tokens """ if back...
def normalizeWordSize(tokens, freq, N_of_tokens_to_use, horizontalProbability = 1.0): """ (linearly) scale the font sizes of tokens to a new range depending on the ratio of the current min-max and take maximum @N_of_tokens_to_use of these tokens allow some words to have vertical orientation defined b...
The function generates a Wordle image from a text file by tokenizing, normalizing, and arranging words by frequency. It saves the image as a PNG and optionally allows interactive repainting with different color schemes, saving each version sequentially.
def createWordle_fromFile(fName, interActive = False, horizontalProbability=1.0): # the master function, creates the wordle from a given text file tokens = FR.tokenize_file_IntoWords(fName) tokens, freq = FR.tokenGroup(tokens) print('\n ===== Top', min(10, len(tokens) ), 'most frequent tokens =====\n...
def get_state(self, username): """ Returns the current state of the repo for the given user. The possible states are: - CLEAN: when we are in sync with the current tip of master and no changes have been made - IN_PROGRESS: when there are some changes in t...
The function `sync_state` checks a user's repository state. If the state is "PR_OPEN" and the associated pull request is resolved, it cleans up by removing the user's repository directory, pruning git worktrees, deleting the branch, and marking the state as "CLEAN". No action occurs for "CLEAN" or "IN_PROGRESS" states.
def sync_state(self, username): state = self.get_state(username) # If the state is CLEAN or IN_PROGRESS we don't have to do anything if state == "CLEAN": return if state == "IN_PROGRESS": return if state == "PR_OPEN": if self.is_pr_resolved(us...
def sync_state(self, username): state = self.get_state(username) # If the state is CLEAN or IN_PROGRESS we don't have to do anything if state == "CLEAN": return if state == "IN_PROGRESS": return if state == "PR_OPEN": if self.is_pr_resolved(us...
The main task of the code is to retrieve a list of tests from a CSV file based on the provided username and country_code. It validates the country_code format, synchronizes user state, pulls the master repository, locates the appropriate repository path, reads the specified CSV file, and returns its contents as a list ...
def get_test_list(self, username, country_code): if not len(country_code) == 2 and not country_code == "global": raise Exception("Bad country_code") self.sync_state(username) self.pull_master_repo() repo_path = self.get_user_repo_path(username) if not os.path.exists...
def sync_state(self, username): state = self.get_state(username) # If the state is CLEAN or IN_PROGRESS we don't have to do anything if state == "CLEAN": return if state == "IN_PROGRESS": return if state == "PR_OPEN": if self.is_pr_resolved(us...
The main task of the code is to add a new entry to a user's CSV file in their repository, ensuring no duplicate URLs exist and the repository is in a valid state. It synchronizes the state, checks for pending changes, locks the repository, appends the entry, commits the change, and updates the state to "IN_PROGRESS".
def add(self, username, cc, new_entry, comment): self.sync_state(username) self.pull_master_repo() logging.debug("adding new entry") state = self.get_state(username) if state in ("PR_OPEN"): raise Exception("You cannot edit files while changes are pending") ...
def sync_state(self, username): state = self.get_state(username) # If the state is CLEAN or IN_PROGRESS we don't have to do anything if state == "CLEAN": return if state == "IN_PROGRESS": return if state == "PR_OPEN": if self.is_pr_resolved(us...
This code edits an entry in a user's CSV file within a repository, ensuring no duplicate URLs are introduced. It checks the repository's state, locks the user's repo, modifies the CSV by replacing the old entry with the new one, and commits the change. It raises exceptions for invalid states or duplicates and updates t...
def edit(self, username, cc, old_entry, new_entry, comment): self.sync_state(username) self.pull_master_repo() logging.debug("editing existing entry") state = self.get_state(username) if state in ("PR_OPEN"): raise Exception("You cannot edit the files while changes ...
def save_label(self, flag): """ If flag == 0, save all rects(including unsaved rects); If flag == 1, update saved rects only(keep unsaved rects unsaved). """ try: self.keep_labeling = False if flag == 0: for item in self.unsaved_rects: ...
This code deletes selected rectangles from either saved or unsaved lists, updates the label file if necessary, and refreshes the display. It handles both saved (requiring label file revision) and unsaved (no label change) cases, resetting selection indices and clearing the selected rectangle after deletion. Error handl...
def delete_label(self): try: if self.selected_saved_rect_index != -1: # if delete a saved rect, revise label, too. del self.saved_rects[self.selected_saved_rect_index] self.save_label(1) if self.selected_unsaved_rect_index != -1: ...
def save_label(self, flag): """ If flag == 0, save all rects(including unsaved rects); If flag == 1, update saved rects only(keep unsaved rects unsaved). """ try: self.keep_labeling = False if flag == 0: for item in self.unsaved_rects: ...
The code clears labeled rectangles by resetting lists (saved_rects, unsaved_rects, selected_rect) to empty, invokes save_label(0) to record the clearance, and redraws the image. If an error occurs, it displays "Nothing to clear!" in red on the status bar.
def clear_label(self): try: self.saved_rects = [] self.unsaved_rects = [] self.selected_rect = [] self.save_label(0) self.draw_img() except: self.show_info(self.ui.textEdit_statusBar, "<span style=\" color:#ff0000;\"> Nothing to cle...
def show_info(self, target_widget, new_info): """ Print info on UI """ if isinstance(target_widget, QTextEdit): target_widget.append(new_info) elif isinstance(target_widget, QLabel): target_widget.setText(new_info) else: pass def save_l...
This code applies the currently selected category to either a saved or unsaved rectangle in an image labeling tool. It retrieves the category ID and name from a table, updates the corresponding rectangle's category data, saves changes, and triggers a redraw of the image. Error handling ensures valid selections and disp...
def apply_category(self): try: self.current_category_id = int(self.ui.tableWidget_categories.verticalHeaderItem(self.current_category_index).text()) except: print("no text") current_item = self.ui.tableWidget_categories.currentItem() try: self.current_c...
def open_dir(self): try: selected_dir = QFileDialog.getExistingDirectory() return selected_dir except: return None def load_category_name(self, path): categoty_list = [] if os.path.isfile(path): with open(path, 'r') as f: li...
This function selects a directory, identifies JPG/PNG images, generates corresponding label files (.txt), loads category names from a file, and initiates a loop to process images by reading them and updating the UI. It ensures label files exist, clears previous data, and maintains a processing loop with event handling ...
def choose_dir(self): _file_dir = self.open_dir() parent_dir = os.path.dirname(_file_dir) if _file_dir: self.file_dir = _file_dir self.file_names = [] for filename in os.listdir(_file_dir): if os.path.splitext(filename)[-1] == ".jpg" or os.pa...
def prev_frame(self): try: self.selected_rect = [] self.wait = False #self.keep_loading = False if self.frame_index == 0: return self.frame_index -= self.frame_step except: self.show_info(self.ui.textEdit_statusBar, ...
This method handles keyboard events in a GUI application, allowing users to input numeric labels for selected rectangles, navigate frames (B/N), save/delete labels (S/D), and update selected label IDs (E). It appends number keys to an ID string, triggers frame navigation, label management, and updates the UI with new I...
def keyPressEvent(self, event): keyboard_dic = {Qt.Key_0: "0", Qt.Key_1: "1", Qt.Key_2: "2", Qt.Key_3: "3", Qt.Key_4: "4", Qt.Key_5: "5", Qt.Key_6: "6", Qt.Key_7: "7", Qt.Key_8: "8", Qt.Key_9: "9" } if event.key() in keyboard_dic and self.selected_rect: self.id_str +...
def _findIndependences( self, G: LatentGroups, L: Cover, testSet: set[Cover], controlSet: set[Cover] ): if setLength(testSet | controlSet) < 2 * len(L) + 2: LOGGER.info(f"Not enough adjacent nodes at {L}..") Gp = deepcopy(G) I = Independences() for As in M.powers...
The function identifies conditional independences (CI) between adjacent nodes of locality L, using test set As and control set Bs. It constructs partitions of nodes based on these CI relationships, assuming full independence if none are found. The process involves graph orientation, set construction, and partitioning t...
def findIndependenceAcrossPartitions(self, L: Cover): """ Given a locality L, test for all CI relationships conditional on L amongst all of L's adjacent nodes (N). Args: L: The locality L that we are testing As: The adjacent nodes to L that form the test set ...
def generateLatentPowerset(self, G): """ Generate an iterator over powerset of active latents, Including the combination where all latents are included. """ Ls = set([V for V in G.activeSet if V.isLatent]) Lsubsets = reversed(list(M.powerset(Ls))) # if len(Ls) > 0...
This function iteratively identifies latent variable clusters by expanding active sets with latent children, adjusting granularity (k) to find valid clusters. It replaces latents with their children when they have multiple offspring, repeatedly searching for clusters until termination conditions (no more clusters, max ...
def _findClusters(self, G: LatentGroups): """ Called by findClusters and refineClusters. """ assert isinstance(G, LatentGroups), "G must be a LatentGroups object." prevCovers = set(G.latentDict.keys()) # Record current latent Covers k = 1 while True: ...
def findIndependenceForNonAtomic(self, L: Cover): """ Use CrossCoverTest to check for independence relationships amongst a non atomic Cover L and its children. Returns: I: independence relationships """ assert not L.isAtomic, f"{L} should be non atomic." ...
The main task of the code is to refine edges in a graph by identifying independencies from non-atomic and atomic latent variables, constructing edges based on these independences, pruning redundant edges, and applying collider tests to finalize the edge structure. It updates sets of independences (I), observed variable...
def refineEdges(self): I = Independences() E = Edges() O = set() # Find I from non-atomics first as they can affect all localities I_nonatomics = Independences() for L in self.G.latentDict: if L.isAtomic: continue I_nonatomics.upda...
def convert_int_to_list(u, n): return [int(x) for x in bin(u)[2:].zfill(n)] def is_lower_bounded(v, K): for k in K: if is_at_most(k, v): return True return False def reduce0(K): R = [] for k in K: if not is_lower_bounded(k, R): R.append(k) return...
The code identifies division trails in a vectorial Boolean function by analyzing its Algebraic Normal Form (ANF). It iterates over all possible input-output pairs (u, v) to check if the coefficient of x^v in F^u is 1. For each such pair, it determines if v meets specific constraints (lower bounded by K or equal to l), ...
def division_trails_over_vectorial_boolean_function(anf, n, m, K, l): #print("Entering division_trails_over_vectorial_boolean_function") K_new = [] L_new = [] for u in range(2 ** m): for v in range(2 ** n): # anf[u] is the ANF of F^u. # and[u][v] is the coefficient of x^...
def injection_permute(v): r = [0] * 128 for i in range(4): for j in range(32): r[32*i + j] = v[4*j + i] return r def reduce0(K): R = [] for k in K: if not is_lower_bounded(k, R): R.append(k) return R def reduce1(K, L): R = [] for l in L: ...
The function `bbdp_propagate_accurate_injection` processes cryptographic states by propagating them through non-linear operations, adding key material, and reducing state space. It handles two cases: when the group number is maximum, it permutes, expands, and generates key-related vectors (K) from states (L), then redu...
def bbdp_propagate_accurate_injection(core_operation_injection_dict, group_number, L): #print("Entering bbdp_propagate_accurate_injection") if group_number == NUMBER_OF_GROUPS: R = [] for l in L: # Permute and expand. R.append(injection_permute(l) + ([VALUE_FOR_EXPANDED_...
def exists_division_trail_over_construction(group_number, k, bit_number): #print("Entering exists_division_trail_over_construction") env = gp.Env(empty=True) env.setParam("OutputFlag", 0) env.start() model = gp.Model('kirby_injection_and_rounds', env=env) # Diversifier input of 64 bits to cons...
The function `bbdp` iteratively checks for "division trails" in cryptographic operations across groups and rounds. It processes sets `K` and `L`, pruning elements that meet trail conditions, and propagates results using helper functions. If a trail is detected in `K`, it returns `-1`; if `L` becomes empty after pruning...
def bbdp(core_operation_injection_dict, core_operation_round_dict, K, L, bit_number): #print("Entering bbdp") for group_number in range(NUMBER_OF_GROUPS + 1): print("Injection. Iteration number {}. Size of K is {} and L is {}.".format(group_number, len(K), len(L))) for k in K: if e...
def compute_anf(a): n = int(math.log2(len(a))) # Input is the value vector `a' of a Boolean function f. # Apply Moebius transform to value vector. for i in range(n): sz = (2 ** i) pos = 0 while pos < len(a): for j in range(sz): a[pos + sz + j] = (a[po...
The main task of the code is to precompute the Algebraic Normal Forms (ANFs) and division trails for the core operations of an injection function (mapping 4 bits to 4 bits) and a round function (mapping 9 bits to 9 bits). It then uses these precomputed structures to analyze the propagation of a specific monomial across...
def main(): # Write F for the core operation of the injection function, i.e., the layer of AND gates and inverters, which maps two bits to four bits. # The entry anf_injection[u] represents the ANF of F^u. anf_injection = [[]] * (2 ** 4) for u in range(2 ** 4): value_vector = list(map(bit_produc...
def get_rsi_timeseries(prices, n=1): # RSI = 100 - (100 / (1 + RS)) # where RS = (Wilder-smoothed n-period average of gains / Wilder-smoothed n-period average of -losses) # Note that losses above should be positive values # Wilder-smoothing = ((previous smoothed avg * (n-1)) + current value to average) ...
The main task of the code is to load and preprocess financial data from Yahoo Finance, generate technical indicators (e.g., moving averages, RSI, MACD), scale features, create time-series sequences for prediction, and split data into training/test sets for machine learning models. It returns scaled data, sequences, and...
def load_data(TICKER, n_steps=50, scale=True, shuffle=True, lookup_step=1, split_by_date=True, test_size=0.2, feature_columns=['adjclose', 'volume'], ma_periods=[5, 20], endDate="12/31/2070"): """ Loads data from Yahoo Finance source, as well as scaling, shuffling, normalizing and splitting. ...
def get_team_name(self, team_id): team_name = teams.find_team_name_by_id(team_id)["full_name"]#players.find_player_by_id(player_id)["full_name"] return team_name def check_team_in_cache(self, team_id): logging.info(f"Running {sys._getframe().f_code.co_name}") if str(team_id) not in self....
The main task of the code is to generate a normalized datapoint for a sports team by aggregating and padding game data from a database over a specified number of recent or randomly selected games, ensuring uniformity for machine learning analysis.
def get_team_datapoint(self, team_id, num_games, most_recent=False): logging.info(f"{sys._getframe().f_code.co_name} - Getting datapoint for last {num_games} games of: {self.get_team_name(team_id)} ({team_id})") print(f"Getting datapoint for last {num_games} games of: {self.get_team_name(team_id)} ({tea...
def check_player_in_cache(self, player_id): logging.info(f"Running {sys._getframe().f_code.co_name}") if str(player_id) not in self.player_games.keys(): self.player_games[str(player_id)] = self.get_player_history(player_id) self.update_player_db(player_id) def points_to_label(sel...
This function generates a sequence of game data for a player, either the most recent or a random subset, by querying a database. It pads game data to uniform size, stacks sequences, and returns the structured datapoint along with opposing team and label info if not using most recent games.
def get_player_datapoint(self, player_id, num_games, most_recent=False): logging.info(f"Running {sys._getframe().f_code.co_name}") #Getting player list of all the games self.check_player_in_cache(player_id) game_list = self.player_games[str(player_id)] game_list = list(map(int, ...
def createSynMessage(clientPort, severPort): src_port = addZero(bin(clientPort), 16) # 16 bits dest_port = addZero(bin(severPort), 16) # 16 bits seq_num = '00000000000000000000000000000000' # 32 bits ack_num = '00000000000000000000000000000000' # 32 bits data_offset = '0011' # 4 bits ack = '0' #...
The function establishes a TCP connection using UDP for the 3-way handshake. It creates a UDP socket, binds it to a local port, sends a SYN message to the server's welcoming socket, receives a SYN/ACK response, verifies the handshake, extracts the server's connection port, and initiates a data socket connection using t...
def connectWelcoming(serverIP, serverPort, tcpType): # create a udp socket with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp_socket: # bind the socket to a OS port udp_socket.bind(("localhost",0 )) socket_port = udp_socket.getsockname()[1] print("client socket bind to ...
def addZero(str, num_bits): binary_num = str[2:] pad = num_bits - len(binary_num) zeros = '' for _ in range(pad): zeros += '0' return zeros + binary_num def addLog(Source,Destination,SYN,ACK,FIN,Message_Length,ts): if SYN == "1" and ACK == "1": Message_Type = "SYN/ACK" elif S...
This code establishes a UDP-based connection using a custom protocol. It constructs a SYN packet with source/destination ports, sequence numbers, and flags, sends it to a server, waits for a SYN-ACK response, validates the acknowledgment, and initiates further connection setup if successful. The process involves UDP so...
def connectWelcoming(serverIP,serverPort): # create a udp socket with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp_socket: # bind the socket to a OS port udp_socket.bind(("localhost",0 )) socket_port = udp_socket.getsockname()[1] print("client socket bind to port",soc...
def createSynMessage(clientPort, severPort): src_port = addZero(bin(clientPort), 16) # 16 bits dest_port = addZero(bin(severPort), 16) # 16 bits seq_num = '00000000000000000000000000000000' # 32 bits ack_num = '00000000000000000000000000000000' # 32 bits data_offset = '0011' # 4 bits ack = '0' #...
The code implements a UDP-based three-way handshake to establish a connection with a server. It creates a UDP socket, binds it to a random port, sends a SYN message to the server's welcoming port, waits for a SYN/ACK response, verifies the packet, logs connection details, and initiates a new connection using the server...
def connectWelcoming(serverIP,serverPort): # create a udp socket with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp_socket: # bind the socket to a OS port udp_socket.bind(("localhost",0 )) socket_port = udp_socket.getsockname()[1] print("client socket bind to port",sock...
def getHostname(message): message =getList(binascii.hexlify(message).decode("utf-8")) qname = [] lenQNameInt = int(message[12], base=16) lenTldInt= int(message[12+lenQNameInt+1], base=16) for i in range(lenQNameInt): qname.append(bytearray.fromhex(message[13+i]).decode()) qname.appe...
This code sets up a UDP server to handle DNS queries by receiving UDP packets, checking a cache for hostname records, resolving hostnames if not cached, and sending IP responses back to clients. It measures resolution time and stores results in a cache with TTL.
def start_udp_server(host, port): # create a server socket with the following specifications # AF_INET -> IPv4 socket # SOCK_DGRAM -> UDP protocol with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket: # bind the socket to a OS port server_socket.bind((host, port)) ...
def connectionServerTable(): port = 10000 servicename = "connectionServerTable" serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((hostname, port)) print("<{}>:Port: {}".format(servicename, port)) serversocket.listen(5) print("<{}>:Listenning".format(servicename)) while 1: ...
The code defines a `run` method that executes different functions based on the instance's `name` attribute. It prints a start message, calls specific functions like `connectionServerTable()`, `connectionServerClient()`, or `receiveConfirmationOfPayment()` depending on the name, then prints an exit message. The method a...
def run(self): print("Starting " + self.name) if(self.name=="connectionServerTable"): connectionServerTable() if(self.name=="connectionServerClient"): connectionServerClient() if(self.name=="receivedConfirmation"): receiveConfirmationOfPayment() print("Exiting " + self.name)
def check_keydown_event(ai_settings, screen, ship, bullets, event): if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: fire_bullet(ai_settings, screen, ship, bullets) def check_keyup_eve...
This function handles user inputs in a Pygame game. It processes events like quitting, key presses (movement/shooting), key releases, and mouse clicks on the play button. It delegates actions to other functions for ship control, bullet firing, and game initialization, using provided game settings, objects, and status v...
def check_events(ai_settings, screen, status, ship, aliens, bullets, play_button, sb): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_event(ai_settings, screen, ship, bullets, event) elif even...
def check_fleet_edges(ai_settings, aliens): for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, screen, status, ship, aliens, bullets, sb): if status.ships_left > 0: status.ships_left -= 1 ...
The function updates alien movement, checks for collisions between the ship and aliens, and verifies if any aliens have reached the screen's bottom. It triggers responses like ship damage or game status changes when collisions occur or aliens reach the bottom, ensuring game mechanics like enemy behavior and collision h...
def update_aliens(ai_settings, screen, status, ship, aliens, bullets, sb): check_fleet_edges(ai_settings, aliens) aliens.update() if pygame.sprite.spritecollideany(ship, aliens): ship_hit(ai_settings, screen, status, ship, aliens, bullets, sb) check_alien_bottom(ai_settings, screen, status, s...
def top(posts, user, userSession): for post in posts: if "reply" not in posts[post]: displayPost(posts[post], posts, user, userSession) printDivider() def getPostSignatureFromPostPrefix(posts, prefix): for post in posts: if post.startswith(prefix): return post...
The function `ls` lists a specific post and its replies. If no position is provided, it displays top posts. It retrieves the root post from the given position, displays it, prints a divider, and iterates through its replies to show each one.
def ls(pos, posts, user, userSession): if len(pos) == 0: top(posts, user, userSession) return rootPost = getPostSignatureFromPostPrefix(posts, pos[-1]) displayPost(posts[rootPost], posts, user, userSession) printDivider() for post in getReplies(posts, rootPost): displayPost(p...
def help(): print("Valid commands : ") print("pubkey : print public key of current user") print("alias <name>: print alias or change alias if specified") print("post : create post:") print("next : view next thread alphabetically") print("prev : view previous thread") print("search <text>: fi...
This code implements a text-based user interface (TUI) for a system, authenticating users via password, then allowing interaction with posts and nodes. It handles commands like viewing aliases, public keys, nodes, posting content, navigating posts, and displaying top posts. The TUI maintains a session, processes user i...
def tui(user, posts, nodes, config): print("Welcome " + user['alias'] + "!") userSession = "" while True: password = input("Enter password : ") userSession = createUserSession(user, password, 1000000000000000000000000000000000) if userSession != None: print("Password Acce...
def poly_matrix(mx): mx_poly = mx # tricky: old matrix cols num doesn't change cols = np.shape(mx)[1] for i in range(cols): for j in range(i+1, cols): res1 = mx_poly[:,i].reshape(-1,1) res2 = mx_poly[:,j].reshape(-1,1) # element-wise multiplication ...
The code performs polynomial regression on the Iris dataset, converting species labels to numerical values. It iteratively splits data into training/test sets, constructs polynomial features, handles matrix inversion issues, calculates regression weights, and evaluates prediction errors for both training and testing su...
def main(): df = pd.read_excel("./Classification iris.xlsx", header=None) df.dropna(axis=0, how='any', inplace=True) df[4].replace('Iris-setosa', 1, inplace=True) df[4].replace('Iris-versicolor', 2, inplace=True) df[4].replace('Iris-virginica', 3, inplace=True) # print(df) data = df.to_nu...
def setFood(): global foodpos for i in range(1,10): x = random.randrange(-245, 245, 5) y = random.randrange(-280, 205, 5) if (x,y) not in foodpos: foodpos[i] = (x,y) def drawfood(somedic): foodpen.clear() for i in somedic: foodpen.up() foodpen.goto(som...
The main task of the code is to initialize and run a snake game by setting up a game window, handling user input for snake movement and pausing, drawing food and title, and starting game loops for the snake and monster. It records the start time globally and exits on screen click.
def main(x,y): global startTime startTime = time.time() setFood() drawfood(foodpos) screen.onkey(goUp, "Up") screen.onkey(goDown, "Down") screen.onkey(goRight, "Right") screen.onkey(goLeft, "Left") screen.onkey(pause, 'space') screen.listen() drawTitle() runSnake() ru...
def _set_groups(self): """ Purpose: Set account groups locally Inputs: None Runtime Errors if the api call fails """ if self._groups is None: URL = f"https://api.dynatrace.com/iam/v1/accounts/{self._account_num}/groups" bearer_token = self._beare...
The main task of the code is to retrieve and return the permission sets for both the Power User and Base User groups associated with a given application team name. It constructs group names using the input `group_name`, checks their existence, fetches their permissions, and returns them as a list of two dictionaries. I...
def get_permissions(self, group_name): """ Purpose: Get permissions set for both the Power User and Base User groups of a given group Inputs: The name of a given group, also defined as an application team Return: array of two dictionaries, first is the permission set of the power user...
def _set_groups(self): """ Purpose: Set account groups locally Inputs: None Runtime Errors if the api call fails """ if self._groups is None: URL = f"https://api.dynatrace.com/iam/v1/accounts/{self._account_num}/groups" bearer_token = self._beare...
The code sets default permissions for "Power Users" and "Base Users" groups of a specified group across all tenants. It constructs group names, retrieves permissions from defaults, checks group existence, and applies permissions. Returns True if all permissions are set successfully; False otherwise, with logging for su...
def set_default_permissions(self, group_name): """ Purpose: Set default permissions for both the Power User and Base User groups of a given group Inputs: Group Name Return: True/False based on if a group's permissions were set successfully """ self._set_groups() ...
def _set_groups(self): """ Purpose: Set account groups locally Inputs: None Runtime Errors if the api call fails """ if self._groups is None: URL = f"https://api.dynatrace.com/iam/v1/accounts/{self._account_num}/groups" bearer_token = self._beare...
The function `clear_permissions` removes all permissions assigned to a specified group by validating the user type, constructing the group name, checking its existence, retrieving permissions, and deleting them individually. It logs success/failure for each permission removal and returns `True` if all deletions succeed...
def clear_permissions(self, group_name, user_type): """ Purpose: Set clear all permissions assigned to a given group Inputs: Group Name Return: True/False based on if a group's permissions were removed successfully """ self._set_groups() self._load_defaults() ...
def consume(self, token_type = None, data = None): if self.found(token_type, data): token = self.current_token self.current_token = None return token else: raise Exception('Expected \'{}\' but found \'{}\' [{}] (at line {} position {})'.format(...
This function parses LaTeX display math enclosed in $$ by reading tokens until $$, then outputs either a span with the math or an SVG image if the content contains TikZ commands, handling compilation errors if SVG generation fails.
def parse_display_math(self): self.consume(Token.T_SEPARATOR, '\\[') s = '' while not self.found(Token.T_SEPARATOR, '\\]'): s += self.consume().data self.consume() if 'tikzcd' not in s and 'tikzpicture' not in s: self.output.write('<span class="ma...
def create_grid(): """Create a new grid with random alive/dead cells, and optionally some zombies.""" # Initialize an empty grid grid = [[0 for _ in range(COLS)] for _ in range(ROWS)] if START_PATTERN == "square": # Set all cells inside a square to 1 side_length = min(ROWS, COLS) // 2 ...
The code runs a cellular automaton game (likely Conway's Game of Life) with interactive features. It initializes a grid, handles user inputs (keyboard/mouse) for zooming, resetting, drawing, and adding patterns. The game updates the grid state, applies visual scaling effects, and renders the display in a loop. It suppo...
def main(): """Run the game.""" grid = create_grid() last_grid = [[0 for _ in range(COLS)] for _ in range(ROWS)] running = True scale_factor = 1 scale_direction = 1 zoom_factor = 0.0 drawing = False paused = False paused_before_draw = False while running: for event in...
def sparse_rademacher(matrix, sketch_size, nnz=None): n, d = matrix.shape if nnz is None: nnz = d/n d_tilde = int(nnz*n) indices = np.vstack([np.repeat(np.arange(sketch_size), d_tilde).reshape((1,-1)), np.random.choice(n,size=sketch_size*d_tilde).reshape((1,-1))]) ...
The function `less` generates a matrix sketch by either applying a sparse Rademacher-Hadamard transform (when `lev_scores=False`) or using leverage scores to sample important features (when `lev_scores=True`). It returns a sketched matrix, reducing computational complexity while preserving key structural properties. Th...
def less(matrix, sketch_size, lev_scores=False, nnz=None): if not lev_scores: return sparse_rademacher(hadamard(matrix), sketch_size, nnz) else: n, d = matrix.shape lev_scores = lev_approx(matrix, alpha=5) prob = lev_scores / lev_scores.sum() samples = torch.tensor(np.ran...
def loss(self, x): return 1./2 * ((self.H_opt @ (x - self.x_opt))**2).sum() def ihs_unweighted_(self, x, sketch_size, sketch, nnz, hs_old, iter): start = time() g = self.grad(x) if self.stop_averaging == 0 or iter < self.stop_averaging: hsqrt = self.sqrt_hess(x, 1) ...
This function performs iterative sketching (IHS) optimization using specified schemes (unweighted, poly, log) to minimize a loss function. It initializes random variables, iteratively updates them via scheme-specific methods, tracks losses and computation times, and returns optimized parameters along with normalized lo...
def ihs(self, sketch_size, sketch='gaussian', nnz=1., n_iter=10, scheme='unweighted',stop_averaging=0): self.stop_averaging = stop_averaging x = 1./np.sqrt(self.d) * torch.randn(self.d, self.c).to(self.device) hs = torch.zeros(self.d,self.d).to(self.device) print("IHS "+scheme ...
def newline(pdfpath): tree = due(pdfpath) root = tree.getroot() for new_line_block in tree.xpath('//new_line'): # Find all "text" element in the new_line block list_text_elts = new_line_block.findall('text') # Iterate over all of them with the current and previous ones for p...
The main task of the code is to parse a PDF document, extract structured phases and textual patterns using regular expressions, categorize them into labeled dataframes, and save the results to CSV files for analysis. It processes XML-like data from the PDF, identifies specific phase sequences, correlations, and keyword...
def main(pdfpath): newtree= newline(pdfpath) dict_fasi = {} data = get_xml_by_tag_names(newtree, 'new_line', 'text') search_delete_append(data, dict_fasi) testoo = [] clean(data, testoo) #testo = ''.join(testo) find_prima = re.compile(r"\]\s*prima(?!\S)") FIND_FASE12T = re.compile(r...
def scaled_k_marginal_score(self): # get the matrix of scores for each place/time (row) and k-col permutation (col) score_df = self.k_marginal_scores() # take the row-wise mean to get the score per place/time self._scores = score_df.mean(axis=1) # get the mean of the scores per p...
The code computes three scores—k-marginal, pickup-dropoff, and higher-order conjunction—by calling respective methods, logs each result, and calculates an overall score as the mean of these values scaled by 1000. It stores all scores in a report and returns the final overall score.
def overall_score(self): logger.info("computing k-marginals...") k_marginal_score = self.scaled_k_marginal_score() self.report["k_marginal_score"] = k_marginal_score logger.success(f"RESULT [KMARGINAL]: {k_marginal_score}") logger.info("computing pickup-dropoff marginal...") ...
def get_subs(self, i): """Builds a map from x to x@i and from x' to x@(i+1), for all x in system.""" subs_i = {} for v in self.system.variables: subs_i[v] = at_time(v, i) subs_i[next_var(v)] = at_time(v, i+1) return subs_i def get_unrolling(self, k): """Un...
This function generates a K-Induction encoding formula for a given property and step K by combining unrolling constraints, induction hypotheses, path conditions, and the negation of the property substituted with K-specific variables, aiming to verify the property's validity through formal induction.
def get_k_induction(self, prop, k): """Returns the K-Induction encoding at step K""" subs_k = self.get_subs(k) prop_k = prop.substitute(subs_k) return And(self.get_unrolling(k), self.get_k_hypothesis(prop, k), self.get_simple_path(k), ...
def _literal_generator(self, pieces: dict, steps: int, slv_type: str = 'Bool'): # generate all literals for the solver and generator # some solver types: Int(), Real(), Bool(), # Example: s-step-0 for i in range(steps): i_format = self._nformat(i) for p in pieces....
The code generates a problem structure by collecting initial state, goal states, and step states with constraints. It initializes variables, appends the initial state, goal state, and iteratively adds step states and maximum curvature constraints for each movement step, forming a sequence of problem definitions for pla...
def generate_problem(self): self.problem = [] # generate all variables we need self._literal_generator(self.pieces, self.length) # add init_state self.problem.append(self._init_state()) # add goal states self.problem.append(self._goal_state()) # add step s...
def prune(self, perms: list[str]): deduped = self.dedupe(perms) cleaned = self.clean(deduped) return cleaned def unpackFilters(self, filters: dict): offsuit = filters.get('offsuit') suited = filters.get('suited') suit = filters.get('suit') return [offsuit, suited,...
This function generates all possible poker hand combinations from a given two-card raw hand by inserting suits, then filters them based on specified criteria (offsuit, suited) and returns the resulting list of valid combinations.
def combinations(self, raw_hand: str, filters={}) -> list[str]: [top, bottom] = list(raw_hand) result = self.prune([top + x + bottom + y for x in SUIT_LIST for y in SUIT_LIST]) [offsuit, suited, suit] = self.unpackFilters(filters) if offsuit: return self.offsuit(result) ...
def vscale_from_zero(self): self.to_zero_flag = False logger.info(self.separator) logger.info("Vertical scale FROM zero") #TODO: Pass default SLA as a dict #verticalScale(cpu_req = cpu_req, cpu_lim = cpu_lim, mem_req = mem_req, mem_lim = mem_lim) verticalScale(cp...
The code handles incoming data by logging it, tracking HTTP request/responses, updating connection address details, managing a request queue, and controlling timers. It increments/decrements counters for pending requests, checks for HTTP methods, and sends data through the channel while handling exceptions.
def on_recv(self): if self.to_zero_flag: self.vscale_from_zero() data = self.data logger.info(data) # Connection destination remote address. If req, then app's addr. If resp, then client addr conn_dst_remote = self.channel[self.conn_orig].getpeername() # Co...
def create_and_start_timer(self,time): self.t = self.create_timer(time) self.t.daemon = True # TODO: Possible way to handle ctrl+C interruption and close proxy w/o sending other request. self.t.start() def vscale_from_zero(self): self.to_zero_flag = False logger.info(self.separat...
The main task of the code is to manage the proxy server's connection handling logic. It uses `select.select` to monitor input connections, accepts new client connections via `on_accept()`, processes incoming data with `on_recv()`, scales vertically from zero if needed, and closes idle connections when no data is receiv...
def main_loop(self): """ Flow logic of the proxy server. Args: Self Returns: Nothing """ # TODO: Introduce logic that makes use of metrics-server API for the TO zero self.input_list.append(self.server) self.create_and_start_timer(TIME_SHORT) while...
def play_round(self, DOPRINT=False): """play_round: plays a single round of the game, storing actions in the history""" actions_played = np.zeros((self.n,), dtype="int") for i in range(self.n): action_index = self.players[i].play(self.state) if not self.check_action(actio...
The code simulates a game twice: once with original player roles and once with roles flipped. It accumulates total payoffs for both scenarios, sums them, and compares the totals to determine the winner (or declare a draw). The main task is to evaluate and declare the winner based on aggregated payoffs from repeated gam...
def declare_winner(self, T=10): """This might not make sense in a matrix game""" # reset any history self.history = [] # play game T times with default coniguration for t in range(T): self.play_round() winnings1 = self.compute_total_payoff_from_history(beta=...
def InitializeWeights(nodes): """Initialize weights with random values in [-1, 1] (including bias)""" layers, weights = len(nodes), [] for i in range(1, layers): w = [[np.random.uniform(-1, 1) for k in range(nodes[i-1] + 1)] for j in range(nodes[i])] weights.append(np.matrix(w)...
The main task of the code is to train a neural network with specified hidden layers (defined by 'nodes') using given training data (X_train, Y_train) over a number of epochs. It updates weights via the Train function, tracks training and testing accuracy every 10 epochs, records the cost function values, and plots the ...
def NeuralNetwork(X_train, Y_train, epochs=10, nodes=[], lr=0.15): hidden_layers = len(nodes) - 1 weights = InitializeWeights(nodes) cost_list = list() epoch_list = list() for epoch in range(1, epochs+1): weights = Train(X_train, Y_train, lr, weights) if(epoch % 10 == 0): ...
def sendData(self): self.broadcastData( { # "pos": (self.rect.x, self.rect.y), "pos": (self.global_coordinates[0], self.global_coordinates[1]), "screen coord": (self.global_coordinates[0]-self.rect.x, self.global_coordinates[1]-self.rect.y), ...
This code updates the player's position and actions based on keyboard input. It moves the player left, right, up, or down, adjusts global coordinates relative to the screen, triggers animations, sends movement data, and handles attacks (spacebar) or bag toggling (key 'b'). The direction vector and sprite are updated ac...
def update(self, keys, screen_pos): """Update the player's position based on user input.""" if keys[pygame.K_LEFT]: self.current_sprite_y = 1 self.direc = Vector2(-1,0) self.rect.x -= self.speed self.global_coordinates[0] = -screen_pos[0] + self.rect.x ...
def getSnapShot(self) -> np.ndarray: small_img = pygame.surfarray.array3d(self.screen).copy() small_img = cv2.resize(small_img, (0, 0), fx=.5, fy=.5) small_img = np.swapaxes(small_img, 0, 1) return small_img def getAction(self, state) -> int: action = self.smart_player.smartMove(...
The code runs a game loop handling input events, updating game state, and rendering visuals. In 'auto' mode, it uses a neural network to determine actions, updates the network with rewards and states, and enforces a time limit. Manual mode uses a driver for control. It tracks FPS and exits on quit events or time expira...
def startGame(self): start_time = time.time() t = time.time() self.old_snap_shot = self.getSnapShot() self.new_snap_shot = self.getSnapShot() self.thread = threading.Thread() while self.gameIsRunning: event = pygame.event.poll() if event.type == py...
def repo_dir(repo, *path, mkdir=False): """Same as repo_path, but mkdir *path if absent """ path = repo_path(repo, *path) if os.path.exists(path): if (os.path.isdir(path)): return path else: raise GitException(f"Not a directory {path}") if mkdir: os.make...
This function creates a new Git repository at the specified path by initializing directory structure, checking for empty directory, creating essential Git files (description, HEAD, config), and setting up refs/heads/master as the default branch. It ensures the path is valid and empty before creating .git directories an...
def repo_create(path): """Create a new repo at path""" repo = GitRepo(path, force=True) # First make sure the path either doesn't exist or is empty. if os.path.exists(repo.worktree): if not os.path.isdir(repo.worktree): raise GitException(f"{path} is not a directory") if os....
def process_batch(self, batch, is_train: bool, metrics: MetricTracker, log=False, gen_step=True): real_A, real_B = batch real_A = self.move_batch_to_device(real_A, self.device) real_B = self.move_batch_to_device(real_B, self.device) fake_B = self.gen_B(real_A) fake_A = self.gen...
This function trains a model for one epoch by iterating over paired data loaders, updating generator and discriminator networks, computing losses, logging metrics, and handling validation. It manages training modes, gradient norms, learning rate scheduling, and distributed training settings, returning aggregated traini...
def _train_epoch(self, epoch): self.gen_B.train() self.gen_A.train() if self.disc_A is not None: self.disc_A.train() self.disc_B.train() self.train_metrics.reset() if self.local_rank == 0: self.writer.add_scalar("epoch", epoch) if sel...
def hierprob_from_flat_non_greedy( probability_matrix, classes, predictions, ytrue, balanced=False ): """_summary_ _extended_summary_ Parameters ---------- probability_matrix : matrix flat probability matrix outputted by the classifier classes : list unique classes seen by ...
The function `Accuracy_Rejection_flat` evaluates the accuracy of a classifier's predictions when applying rejection strategies based on probability thresholds. It iterates over steps (thresholds), computes accuracy scores for rejected and intermediate cases, checks data consistency, and returns metrics like accuracy, r...
def Accuracy_Rejection_flat(clf, X, ytrue, predictions, probabilities, balanced=False, scores_=False, step=0.01): steps = np.arange(0, 1 + step, step) acc_del = np.zeros(len(steps)) acc_int = np.zeros(len(steps)) lp = [] lt = [] p = [] classes = clf.classes_ # Loop over steps for ...
def mainMenu_loadAnimatedGif(path): # load first sprite outside of try/except to raise file-related exceptions spritePhotoImages = [ PhotoImage(file=path, format='gif -index 0') ] i = 1 while True: try: spritePhotoImages.append(PhotoImage(file=path, ...
The code initializes a game application by setting up the main menu, UI buttons, game modes, and Sixshot game mechanics. It configures catchphrases, animated GIFs, target cubes, scoring systems, and 3D-to-2D rendering for gameplay. The function prepares game states, timing, and interactive elements to enable user inter...
def appStarted(app): #Main menu app.mode = 'mainMenu' app.oldMode = app.mode app.paused = False app.catchphraseList = ['We have the meats!', 'You will love this!', 'Did you watch the dev hour for this?', 'Haha dev hour deez nuts', 'you would not believe your eyes', 'I heckin love TenZ', ...
def flatten_modules_handlers( handlers: list, ): """Flatten a list of previously calculated modules handlers boundaries (extract all "start" and "end")""" return list( sum( [(h[1], h[2]) for h in set(handlers)], (), ) ) def calculate_closest_modules_from_address( ...
(The function scans kernel memory for hidden modules not listed in sysfs by analyzing memory ranges around a leaked address or between known modules. It identifies potential hidden rootkits by searching for module structs in these regions, avoiding overlaps with existing handlers, and returns newly discovered modules.)
def lookup_sysfs_hidden_modules( cls, context: interfaces.context.ContextInterface, vmlinux_name: str, modules_handlers: list, leaked_address: int = 0, ): """ Some rootkits unlink themselves from list_head AND module_kobject. However, due to the use of a callb...
def set_compiled_kernel_space_boundaries(self): """Set compiler kernel address spaces. Preferred to linux.LinuxUtilities.generate_kernel_handler_info()[0] for convenience""" self.kernel_space_start = self.vmlinux.get_absolute_symbol_address("_stext") self.kernel_space_end = self.vmlinux.get_abso...
The code processes kernel symbols to extract and parse tracepoints, handling both absolute and relative pointers based on kernel configuration. It checks for required symbols, determines pointer type, converts relative offsets to absolute addresses, and collects parsed tracepoint data with progress updates.
def _generator(self): self.vmlinux = self.context.modules[self.config["kernel"]] if not self.vmlinux.has_symbol("__start___tracepoints_ptrs"): raise exceptions.SymbolError( "__start___tracepoints_ptrs", self.vmlinux.symbol_table_name, 'The prov...
def set_compiled_kernel_space_boundaries(self): """Set compiler kernel address spaces. Preferred to linux.LinuxUtilities.generate_kernel_handler_info()[0] for convenience""" self.kernel_space_start = self.vmlinux.get_absolute_symbol_address("_stext") self.kernel_space_end = self.vmlinux.get_abso...
(The code scans the `ftrace_ops_list` structure in a kernel module, iterating through its linked list entries. It parses each `ftrace_ops` element, tracks progress, and collects results. If parsing fails, exceptions are logged. Finally, it returns a list of parsed results.)
def _generator(self): """Iterate over ftrace_ops_list struct""" self.vmlinux = self.context.modules[self.config["kernel"]] if not self.vmlinux.has_symbol("ftrace_ops_list"): raise exceptions.SymbolError( "ftrace_ops_list", self.vmlinux.symbol_table_na...
def calc_dist_matrix(atoms, dist_thresh=None, mask_thresh=None, asymmetric=False): """ Ben Orr: Adapted this from pconpy.py Calculate the distance matrix for a list of residues. This function is currently called by plot_dist_mat (7.1.21) Args: # residues: A list of ``Bio.PDB.Residu...
The main task of the code is to generate and visualize a distance matrix from backbone atom coordinates. It processes command-line options for masking thresholds, plot formatting, and output type (plaintext or graphical). If plaintext is selected, it saves the matrix numerically; otherwise, it creates a matplotlib plot...
def plot_dist_mat(opts, bb_atoms): """ This is just the 'if name=main' block from pconpy.py """ ### Commenting this out, since I don't require <dist> arg in usage # Distance threshold for contact maps. # if opts["<dist>"]: # opts["<dist>"] = float(opts["<dist>"]) if opts["--mask-thr...
def get_bb_atoms(path): """ Params: path: Path to the pdb file Returns: bb_atoms: A list of prody Atom() objects that represent the N, CA, C, and CB's in the coordinating and neighboring residues. """ pdb_prody = pr.parsePDB(path) #os.path.join didn't add /'s where it was supposed to...? ## parsePDB opt...
The code processes PDB files to generate and save distance matrices for backbone atoms (N, CA, C, CB) across permutations of atom types. It extracts backbone atoms, handles edge cases with insufficient residues, creates permutations, computes distance matrices for each permutation, and writes them to output folders alo...
def run_make_bb_dist_mats(workdir, pdb_path, out_path, opts): # Eventually, I'll want to look at _Seq_cores_reps instead of _Seq_cores, since reps is nonredundant two_coord_res_pdbs = [] k = 0 for pdb in os.listdir(workdir + pdb_path): # pdb = '1a0b_ZN_1.pdb' # If -p option is used, set pdb to that file i...
def get_bb_atoms(path): """ Params: path: Path to the pdb file Returns: bb_atoms: A list of prody Atom() objects that represent the N, CA, C, and CB's in the coordinating and neighboring residues. """ pdb_prody = pr.parsePDB(path) #os.path.join didn't add /'s where it was supposed to...? ## parsePDB opt...
The main task of the code is to process PDB files in a directory, extract backbone atoms and metal cores, generate contact maps via distance matrices, and save residue information. It iterates through up to 5 PDB files, dynamically constructs output paths, and uses options to control processing, including overriding th...
def run_get_contact_res(workdir, pdb_path, output_path, opts): #opts = docopt(__doc__) i = 0 for pdb in os.listdir(workdir + pdb_path): print(pdb) # pdb = '1a0b_ZN_1.pdb' if opts["--pdb"]: pdb = str(opts["--pdb"]) output_path = 'core_contact_maps/' op...
def SetRoutedFlagToFalseForAllCustomers(self): for i in range(0, len(self.customers)): self.customers[i].isRouted = False def NearestNeighbor(self): model_is_feasible = True self.sol = Solution() insertions = 0 trucks = 4 while insertions < len(self.customers...
The main task of the code is to solve a routing problem by first resetting customer routing flags, applying a nearest-neighbor heuristic for initial solution generation, refining it via Variable Neighborhood Descent (VND) for optimization, and finally reporting the resulting solution. The method systematically combines...
def solve(self): self.SetRoutedFlagToFalseForAllCustomers() self.NearestNeighbor() self.VND() self.ReportSolution(self.sol) return self.sol
def get_args(): parser = ArgumentParser() parser.add_argument('-d', '--dataset', type=str, required=True, help='input dataset') parser.add_argument('-t', '--task', type=str, choices=['regression', 'classification'], default='regression', help='What training problem to run.') return parser.parse_...
The main task of the code is to find the best regression model for a given dataset. It parses command-line arguments, loads the dataset, removes missing values, and applies the `find_best_regressor` function to identify the optimal regressor. The process involves data preprocessing and automated model selection for reg...
def main(): args = get_args() ds = get_dataset(args.dataset, args.task) ds.dropna(inplace=True) find_best_regressor(ds)
def get_args(): parser = ArgumentParser() parser.add_argument('-d', '--dataset', type=str, required=True, help='input dataset') parser.add_argument('-t', '--task', type=str, choices=['regression', 'classification'], default='regression', help='What training problem to run.') parser.add_argument(...
(The code trains a regression neural network on a dataset, preprocessing features and targets, creating data loaders, and executing training for specified epochs with given hyperparameters.)
def main(): args = get_args() df = pd.read_csv(args.dataset) df = get_regression_dataset(df, relative_to='min', include_app=False, run_size='core', round_targets=False, include_runtime='both') df.dropna(inplace=True) TARGETS = ['quartz Relative Time', 'ruby Relative Time'] FEATURES = l...
def draw_linedefs(self): for line in self.linedefs: p1 = self.vertexes[line.start_vertex_id] p2 = self.vertexes[line.end_vertex_id] pg.draw.line(self.engine.screen, (70, 70, 70), p1, p2, 3) def draw_player_pos(self): pos = self.engine.player.pos x = self.remap...
The code's main task is to render a map's structural elements by drawing line definitions (walls/edges), the player's position, and the root node of a Binary Space Partitioning (BSP) tree, likely for a 3D game or map visualization. The vertex drawing is commented out, suggesting it's optional or disabled.
def draw(self): self.draw_linedefs() # self.draw_vertexes() self.draw_player_pos() self.draw_node(node_id=self.engine.bsp.root_node_id)
def searchIn(corpusDir, query, limit=MyQuery.DEFAULT_LIMIT, sort=None): '''Perform query search in the corpus given in input''' ix = open_dir(corpusDir) searcher = ix.searcher() parser = MultifieldParser(["title", "plot"], schema=ix.schema) setQueryParser(parser) query = parser.parse(query) ...
The code performs a multi-source movie search by querying IMDb, Rotten Tomatoes, and Wikipedia indexes, merging results into a unified list. It sorts movies by user-specified fields (e.g., release year, scores) or relevance, applying thresholds and merging scores. The final output is a sorted list of movies, limited by...
def search(rQuery): '''Performs the query search and return results found''' query = MyQuery(rQuery) # Search in each index and merge the results resultsImdb = searchIn(IMDB_INDEX, query.getImdbQuery(), query.limit, None) moviesImdb = toDictionary(resultsImdb, Movie.fromImdb) resultsRotte...
def readwords(): """read in all 5 letter words""" inf = open("/usr/share/dict/words", "r") words = [] for line in inf: word = line.strip() if len(word) == 5 and word.islower() and word.isalpha(): words.append(word) inf.close() return words def menu(): """present m...
The code processes a list of words by repeatedly applying user-selected filtering rules (e.g., ending with, starting with, containing, or excluding specific substrings). It maintains a dictionary of applied rules and reduces the word list accordingly. The loop continues until the user exits, after which the remaining w...
def main(): words = readwords() done = False rules = {} print(instructions) while not done: print("-"*30) print("words remaining: %d" % (len(words))) opt = menu() if len(opt) == 0: done = True elif opt == "e": endswith(words, rules) ...
def get_tract(zipcode): zipcode = int(zipcode) return zip2tract()[zipcode] def predict(tracts, itvn): df = load_data(itvn) df_x = df.iloc[:, :-2] idxs = df_x['census_tract_number'].isin(tracts.values) tracts = df_x[idxs].iloc[:, 0] df_x = df_x[idxs].iloc[:, 1:] x = transformer.transform(...
The main task of the code is to generate a map overlaying predicted scores on geospatial data for specific census tracts. It retrieves census tracts for a zipcode, predicts scores, filters geospatial data and scores to their common tracts, and renders an interactive map plot in Streamlit using the intersected data.
def main(): tracts = get_tract(zipcode) scores = predict(tracts, itvn) gdf = get_geodata(DATA_shp) gdf_tract_set = set(gdf['census_tract']) scores_tract_set = set(scores['census_tract_number']) tract_set = gdf_tract_set.intersection( scores_tract_set, set(tracts.values) )...
def get_model(self): models = {'lgr': self.lgr(), 'rgr': self.rgr(), 'lasso': self.lasso(), 'rft': self.rft()} return models[self.model] def lgr(self, max_iter=10000, penalty='l1', solver='saga'): model = LogisticRegression( rando...
The main task of the code is to initialize a machine learning model with input data (x, y) and a specified model. It sets up regression techniques (linear, ridge, lasso, random forest), performs cross-validation, and generates prediction results. The code prepares the model for analysis by calling methods to configure ...
def __init__(self, x, y, model): self.x = x self.y = y self.model = model self.get_model() self.lgr() self.rgr() self.lasso() self.rft() self.cross_validate_results() self.predict_results()
def _set_board_to(stockfish, moves): stockfish.set_position([move for move in moves.split(" ") if move != ""]) def draw_claim_victory(draw_text, moves, stockfish): return utils.respond( draw_text + f"final board:\n{get_board_backquoted(stockfish, moves)}" + f"\nmoves: {moves}", 2...
The function determines the game-over reason from a chess board state using Stockfish, then generates appropriate victory/draw messages based on scenarios like stalemate, checkmate, or rule-based draws, returning None if no condition matches.
def get_gameover_text(stockfish, moves, is_ai, mover, opponent=None, last_move=None): logger.debug(f"Getting Game Over Text For: {moves} {is_ai}") _set_board_to(stockfish, moves) fen = stockfish.get_fen_position() board = chess.Board(fen) logger.debug(f"{board.outcome()}") # check for different ...