dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def check_keydown_events(event, ai_settings, screen, ship, bullets): # Respond to keypresses if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True # When the user press the sapcebar elif event.key == pygame.K_SPACE: ...
The function `check_events` processes user inputs by handling keyboard and mouse events. It exits the game on quit, triggers actions on key presses/releases (via `check_keydown_events` and `check_keyup_events`), and initiates gameplay when the play button is clicked (via `check_play_button`). It updates game state base...
def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets): # Respond to keypress and mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event, ai_setting...
def check_fleet_edges(ai_settings, aliens): # Respond appropriately if any aliens have reached an edge 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): ...
The function updates alien positions, checks for collisions between the ship and aliens, and detects if aliens reach the screen's bottom. It triggers responses like ship damage or game over events when collisions occur or aliens hit the bottom, using helper functions to manage game logic.
def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets): # Check if the fleet is at an edge and then update # the position of all aliens in the fleet check_fleet_edges(ai_settings, aliens) aliens.update() # Look for alien-ship collisions # The method spritecollideany() take...
def deprocess(image): with tf.name_scope("deprocess"): # [-1, 1] => [0, 1] return (image + 1) / 2 def preprocess(image): with tf.name_scope("preprocess"): # [0, 1] => [-1, 1] return image * 2 - 1 def load_examples(): if a.input_dir is None or not os.path.exists(a.input_dir): ...
The code's main task is to train or export a neural network model for image processing, handling different modes (train/test/export). It sets random seeds, loads data, initializes the model, and runs training loops with loss tracking, image conversion, and checkpoint saving. In export mode, it generates a meta graph fo...
def main(): if a.seed is None: a.seed = random.randint(0, 2**31 - 1) tf.set_random_seed(a.seed) np.random.seed(a.seed) random.seed(a.seed) if not os.path.exists(a.output_dir): os.makedirs(a.output_dir) if a.mode == "test" or a.mode == "export": if a.checkpoint is None:...
def show_progress(self): """ Displays image in progress """ mask_indx = np.argwhere(self.active_mask == 1) img = self.img_in_progress.copy() for i in range(mask_indx.shape[0]): x, y = mask_indx[i] img[x, y, :] = 255.0 plt.imshow(img) ...
The main task of the code is to perform iteration updates by displaying progress, adjusting the fill border, and updating priorities during a process. It manages UI feedback and priority adjustments in iterative operations.
def iteration_update(self): """ Iteration updates """ self.show_progress() self.set_fill_border() self.update_priorities()
def iteration_update(self): """ Iteration updates """ self.show_progress() self.set_fill_border() self.update_priorities() def get_highest_priority(self): """ Returns the index of the pixel wit highest priority """ return np.unravel...
The code performs image inpainting by iteratively selecting high-priority regions from a mask, finding corresponding source patches, and filling the masked areas. It initializes confidence and active mask states, updates the image in each iteration, and returns the completed inpainted image once all active regions are ...
def do(self): # initialize state self.data = np.zeros(self.orig_image.shape[:2]) self.confidence = (1 - self.orig_mask).astype(float) # cv.imshow('Confidence', self.confidence) self.active_mask = np.copy(self.orig_mask) self.img_in_progress = np.copy(self.orig_image) ...
def generate_data(lcg, n): data = [] for i in range(0, n): data.append(next(lcg)) return data def solve_unknown_all(data): differences = [former - latter for former, latter in zip(data, data[1:])] zeroes = [t2 * t0 - t1 * t1 for t0, t1, t2 in zip(differences, differences[1:], differences[2:]...
The code's main task is to test the recovery of parameters (modulo, multiplier, increment) of a Linear Congruential Generator (LCG) from a generated sequence of pseudorandom numbers. It initializes an LCG with known parameters, generates 32 data points, then attempts to reverse-engineer the LCG's parameters using the `...
def main(): seed = 123 a = 1103515245 c = 12345 m = 2**31 lcg = LCG(seed, a, c, m) data = generate_data(lcg, 32) # breakpoint() modulo, multiplier, increment = solve_unknown_all(data) perform_test(lcg, multiplier, increment, modulo, data)
def get_extra_move_ids_input(): _input = input("Extra Move Ids (name:id,name:id...)> "); if not (":" in _input) and (";" in _input): entry_splitter = ";"; else: entry_splitter = ":"; move_ids = {}; for entry in _input.split(","): parts = entry.split(entry_splitter); ...
The code's main task is to execute different processing modes (individual or multiple) based on user input. It reads a moves file, collects extra move IDs, and invokes either `main_individual` or `main_multiple` functions to handle data processing accordingly.
def main(): #Modes #0 - Individual #1 - Multiple mode = int(input("Mode> ")); filename = input("Moves File> "); extra_move_ids = get_extra_move_ids_input(); if mode == 0: main_individual(filename, extra_move_ids); elif mode == 1: main_multiple(filename, extra_move_id...
def only_nums(str): r = re.sub(r'[^\d]+', '', str) return r def get_str(str, sep, offset): str_list = re.split(sep, str) return str_list[offset] def get_vel_list(lst, sep, offset): r = [] for i in range(len(lst)): c = re.split(sep, lst[i]) r.append(only_nums(c[offset])) retur...
The code processes audio samples to generate SFZ region definitions, organizing samples by velocity and key ranges. It handles velocity modes (raw, dictionary, dynamic) to sort and map samples, assigns key centers, and constructs `<region>` tags with lokey/hikey and velocity opcodes. Metadata, panning, and sequence par...
def process_regions(__group, key_mode, key_offset, center, vel_mode, vel_offset, vel_curve, vel_crv_min, rr): None global vel_lines global rr_len global rr_idx global sfz_header global rr_step global p_in global metadata global byte_note global ign_root global key_verbose ...
def get_args(): """ Parse all arguments from the command line using ArgumentParser. Returns an args object with attributes representing all arguments. """ from argparse import ArgumentParser description = CONTACT + """ An argument -t or -p or -f is required. The -p argument accepts a hexidecimal pattern string...
The main task of the code is to search for specified content in files provided via command-line arguments or standard input. It verifies arguments, processes each file by opening it, performing the search, and closing it, then removes processed files from the list. If no files are specified, it searches using stdin. Th...
def main(): args = get_args() # Get commandline arguments. args = verify_args(args) # Check arguments for sanity, and edit them a bit. if args.fsearch: # If filenames were given on the commandline, process them. while args.fsearch: # List of files to search inside. try: # Open a filehandler for the filename. ...
def check_inbounds(self, agents, actions): cleaned_actions = [] for agent, action in zip(agents, actions): if action == NO_OP or action == SHOOT: cleaned_actions.append(action) continue target_location = self.get_target_location(agent, action) ...
This function processes agents' actions by freezing agents with active timers, updating orientations for movement actions, checking action validity, resolving collisions, and executing the actions while tracking game state changes.
def perform_agent_actions(self, agents, actions): for idx, agent in enumerate(agents): if agent.freeze_timer > 0: actions[idx] = NO_OP for agent, action in zip(agents, actions): if action in WALK_ACTIONS: agent.change_orientation(action) se...
def avail_moves(self, color): """Store available tile movements into valid_moves dictionary""" self.valid_moves = defaultdict(list) for row in range(self.size): for col in range(self.size): if (self.disks[row][col] and self.disks[row][col].colo...
This function handles a player's move by placing a colored tile on the board at specified coordinates. It checks if the move is valid, places the tile at the calculated grid position, flips opponent's tiles as needed, updates the game state, and returns True if the move is successfully executed.
def input_tile(self, x, y, color): """According to the players' moves, input tiles into the board""" row = y // self.SPACING col = x // self.SPACING self.avail_moves(color) if (row, col) in self.valid_moves: tile_x, tile_y = self.get_center(x, y) self.disk...
def _extract_text_from_pdfs(self): if not hasattr(self, 'text_by_title'): def _extract_text_from_pdf(pdf): text_from_pdf = '' text_by_page = {} pdf_reader = PdfReader(pdf) if isinstance(pdf, UploadedFile): filen...
The main task of the code is to process PDF documents by extracting text, splitting it into chunks, and building a knowledge base if it doesn't already exist, then returning the constructed knowledge base.
def process_pdf(self): if not hasattr(self, 'knowledge_base'): self._extract_text_from_pdfs() self._split_text_in_chunks() self._build_knowledge_base() return self.knowledge_base
def beginning(): global text_4 global switch print("good") text_4 = "Press P to play!" if cv2.waitKey(33) & 0xFF == ord('p'): text_4 = '' switch = False count_down() def finish(): global text_4 global text_3 text_4 = 'Press q to Quit' if user_count > ai_count:...
The code's main task is to manage game progression by checking the global 'switch' state and current 'rounds' value. If 'switch' is active, it triggers different actions: starting the game (round 1), ending it (round 6), or prompting continuation for intermediate rounds. It prints status updates and calls functions to ...
def checkpoint(): global switch if switch == True: if rounds == 1: beginning() elif rounds == 6: print("last round") finish() elif rounds >= 1: print("continue") print(f"rounds are {rounds}") press_continue()
def camera(): ret, frame = cap.read() resized_frame = cv2.resize(frame, (224, 224), interpolation=cv2.INTER_AREA) image_np = np.array(resized_frame) normalized_image = (image_np.astype(np.float32) / 127.0) - 1 # Normalize the image data[0] = normalized_image logo = cv2.imread(r'C:\Users\nilou\D...
The main task of the code is to repeatedly execute the camera(), checkpoint(), and count_down() functions in a loop while the global variable 'rounds' is less than 7, allowing the user to exit early by pressing the 'q' key.
def main(): global rounds while rounds < 7: camera() checkpoint() count_down() if cv2.waitKey(1) & 0xFF == ord('q'): break
def distance(self, pose1, pose2): d_x = pose1.x - pose2.x d_y = pose1.y - pose2.y return math.sqrt(pow(d_x, 2)+pow(d_y, 2)) def isObstacle(self, maplist, pose): x = int(pose.x) y = int(pose.y) if maplist[y][x] == 1: return True else: retur...
The code implements a rolling window path planning algorithm to generate a smooth trajectory from an initial pose to a goal pose. It iteratively selects subgoals within a circular window, avoiding obstacles by evaluating heuristic costs. When the current position is far from the goal, it samples points around the windo...
def rollingWindow(self, init_pose, goal_pose): del self.path[:] subgoal_list = [] cur_center = init_pose minHcost = 100000000000000000 subgoal = pose(0,0,0) print("init center:"), (cur_center.x, cur_center.y) while cur_center != goal_pose: if self.dist...
def generate_song_selection_criteria(highest_intervals, index): """ Using the list of highest intervals, this function recursively creates different combinations of audio feature values that a Spotify user may prefer Inputs: highest_intervals (list): a list of interval, average value pairs for...
This function generates song recommendations using Spotify's API by combining user-specified genres with new releases and seed tracks from a provided compilation. It leverages audio feature criteria derived from the compilation, prioritizes recent songs, and aggregates multiple recommendation batches to return a list o...
def find_recommended_songs(track_compilation, input_genre): """ Given a track compilation and user-inputted genre, this function recommends songs based on new releases and a seed of 5 tracks in the track compilation Inputs: track_compilation (dictionary): an album or playlist input_genr...
def _save_result_attributes(self): self.tool_type = self.db_tool[0]['type'] self.tool_brand = self.db_tool[0]['brand'] self.weekday_charge = self.db_tool[0]['weekday_charge'] self.weekend_charge = self.db_tool[0]['weekend_charge'] self.holiday_charge = self.db_tool[0]['holiday_ch...
The main task of the code is to compute rental charges and return structured data. It calculates due dates, charge days, discounts, and final charges, then compiles attributes like tool details, dates, and formatted monetary values into a dictionary for output.
def calculate(self): self._save_result_attributes() self._calculate_due_date() self._calculate_charge_days() self._calculate_final_charge() data = { "tool_code": self.tool_code, "tool_type": self.tool_type, "tool_brand": self.tool_brand, ...
def generation(self, i: int) -> int: """ Single pass in Genetic algorithm Args ---- i: generation number Returns ------- Total Fitness of the chromosomes of current generation """ # Stage 1 logger.info(f"\t\tGeneration {i}, Stage 1: Selecti...
The main task of the code is to execute a genetic algorithm simulation for a specified number of generations, tracking fitness scores for each generation. It terminates early if the fitness difference falls below a threshold (`eps`) for a minimum number of consecutive generations (`eps_count`). The function returns a l...
def start_simutation(self, n_gens: int, eps: float=0.1, eps_count: int=5) -> List[int]: """ Run simulation for n_gens Args ---- n_gens : Number of generations eps: tolerance for difference in score eps_count: minimum count of generations for which fitness diff is small ...
def get_pixel(): with Image.open("picture.jpg") as img: new_pixel_names: list[str] = adjust_pixels(img) final_list = [] for i in range(len(new_pixel_names)): final_list.append(sum(tuple_colours[new_pixel_names[i]])) return(final_list) def print_colour_from_pic(): with Imag...
The code processes an image's pixel data to analyze and visualize color frequencies. It extracts unique colors, sorts them by occurrence, and iterates through pixels to draw them in a grid pattern using `click_on_colour`, adjusting positions based on `m.size` and pixel size. The function aims to render or simulate an i...
def draw_pic(m): pic_pix = get_pixel() a_colour = print_colour_from_pic() a_unique_colour = list(dict.fromkeys(a_colour)) sorted_colors = sorted(a_unique_colour, key=lambda x: a_colour.count(x)) for col in sorted_colors: count = a_colour.count(col) print("col:", col, count) ...
def get_app_names(regex=None, all=False, bootstart=False): if all: apps = get_all_app_names() elif bootstart: apps = _get_bootstart_app_names() else: if regex is None: raise SafExecutionException('An app must be specified') apps = get_all_app_names() # htt...
The main task of the code is to restart applications matching a given regex pattern. It retrieves app names using `get_app_names`, checks for matches, and iteratively stops then starts each app, aggregating return codes. Parameters control match scope and behavior, with exceptions raised if no apps match. The function ...
def restart(app_regex, all=False, bootstart=False, iknow=False): app_names = get_app_names(app_regex, all, bootstart) rc = 0 if len(app_names) == 0: raise SafExecutionException('No app found matching %s' % app_regex) for app_name in app_names: rc += stop(app_name, iknow=iknow) ...
def getSensorReadings(): val = { S1: GPIO.input(SENSOR_1), S2: GPIO.input(SENSOR_2), S3: GPIO.input(SENSOR_3), S4: GPIO.input(SENSOR_4), } # printSensorReadings(val) return val def turn_45_left(): moveRightMotorForward() moveLeftMotorBackward() time.sleep(INIT...
The code determines a robot's movement based on sensor readings, adjusting direction (left/right) or proceeding straight, checking for dead ends by testing turns, and returning actions like "adjust_left", "adjust_right", "straight", or "dead_end" depending on sensor states and navigation logic.
def decideAction(): sensorVal = getSensorReadings() # map sensorVal to BOT_MOVEMENT if (sensorVal[S2] == 0 and sensorVal[S3] == 1) or (sensorVal[S1] == 0 and sensorVal[S2] == 0 and sensorVal[S3] == 0 and sensorVal[S4] == 1): return "adjust_right" elif (sensorVal[S2] == 1 and sensorVal[S3] == 0) ...
def decideAction(): sensorVal = getSensorReadings() # map sensorVal to BOT_MOVEMENT if (sensorVal[S2] == 0 and sensorVal[S3] == 1) or (sensorVal[S1] == 0 and sensorVal[S2] == 0 and sensorVal[S3] == 0 and sensorVal[S4] == 1): return "adjust_right" elif (sensorVal[S2] == 1 and sensorVal[S3] == 0) ...
The code's main task is to execute a decision-making process by determining an action, logging it, and performing the corresponding movement or adjustment. It handles various directional commands (e.g., straight, turn left/right, adjust), special cases like "dead_end" or "stay," and executes specific functions based on...
def act(): decision = decideAction() # print(decision) logDecisions(decision) if decision == "straight": straight() elif decision == "adjust_left": adjust_left() elif decision == "adjust_right": adjust_right() elif decision == "left": turn_left() elif deci...
def decideAction(): sensorVal = getSensorReadings() # map sensorVal to BOT_MOVEMENT if (sensorVal[S2] == 0 and sensorVal[S3] == 1) or (sensorVal[S1] == 0 and sensorVal[S2] == 0 and sensorVal[S3] == 0 and sensorVal[S4] == 1): return "adjust_right" elif (sensorVal[S2] == 1 and sensorVal[S3] == 0) ...
The function `act_optimised` executes navigation actions based on decisions from `decideAction()`. It logs decisions, performs directional movements (e.g., turn left/right, straight), adjusts paths, or handles dead ends. If the global `ans` list contains pre-stored actions, it prioritizes those; otherwise, it uses real...
def act_optimised(): global ans decision = decideAction() # print(decision) logDecisions(decision) if decision == "straight": straight() elif decision == "adjust_left": adjust_left() elif decision == "adjust_right": adjust_right() elif decision == "left" or decisi...
def import_stock_data(tickers, start): data = pd.DataFrame() if len([tickers]) ==1: data[tickers] = pdr.get_data_yahoo(tickers, data_source='yahoo', start=start)['Adj Close'] data = pd.DataFrame(data) else: for t in tickers: data[t] = pdr.get_data_yahoo(t, data_source='ya...
The code simulates stock price movements using Monte Carlo methods over a specified number of days. It processes input parameters, imports historical stock data, calculates daily returns, and generates future price scenarios. It then computes expected values, returns, and breakeven probabilities, visualizes the simulat...
def simulate_mc(params, graph): print("[INFO] Simulation Started.") # converting data in required data type # params is the dictionary which contains the data required for simulation ticker = str(params['ticker']) ticker = ticker.rstrip() ticker = ticker.upper() start = params['s_Date'] ...
def _build_accepted_media_types(media_types: Union[str, Sequence[str]]) -> str: """ Builds the Accept header of media types as required by the GetObject transaction request. The qvalue is used to specify the desirability of a given media type with 1 being the most desirable, 0 being the least, and a ran...
The `get_object` method retrieves structured information and multimedia files related to system entities by specifying a resource, object type, and entity keys. It accepts media type preferences and a location flag, sending an HTTP request with these parameters to fetch objects in the requested MIME format. The respons...
def get_object(self, resource: str, object_type: str, resource_keys: Union[str, Mapping[str, Any], Sequence[str]], media_types: Union[str, Sequence[str]] = '*/*', location: bool = False, ) -> Sequence[Objec...
def item_clicked(event, item_id, amount_label): if item_id in item_selections: item_selections[item_id] += 1 else: item_selections[item_id] = 1 update_amount_label(amount_label, item_id) def remove_item_clicked(event, item_id, amount_label): if item_id in item_selections: item_se...
The code creates a GUI for a menu selection interface using Tkinter. It displays scrollable menu items with images, names, prices, ratings, and quantity adjustment buttons. Users can click items or use "+"/"-" buttons to select quantities, which updates labels. A "Place Order" button triggers an order placement functio...
def orderSelectionScreen(): # Create the GUI window root = Tk() root.title("Menu") root.geometry("625x725") root.config(background="#FFFFFF") root.wm_attributes("-topmost", True) # Create a frame to hold the menu items menu_frame = Frame(root, background="#232F3E") menu_frame.pack(f...
def create_deck(num_decks): suits = ['\u2660', '\u2663', '\u2661', '\u2662'] ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] deck = [(rank + suit) for suit in suits for rank in ranks] * num_decks random.shuffle(deck) return deck def deal_cards(num_decks, retriver_cards): ...
This code simulates a Blackjack game where players bet quatloos, manage hands, and interact with a dealer. It allows custom deck counts, random seeds, and Retriever cards. The game handles player actions (hit/stay), dealer logic, busts, wins, and ties, updating the player's money accordingly. The loop continues until t...
def main(): print("Welcome to Blackjack!") num_decks = int(input("How many decks of cards would you like to use? ")) random_seed = input("What seed would you like to use? ") random.seed(random_seed) retriever_cards = int(input("How many Retriever cards would you like to add? ")) deck = create_de...
def add_markerh(cell,x,y,layer=1): rect = gdspy.Rectangle((0, 0), (15, 2), layer) rect.translate(x, y) cell.add(rect) rect = gdspy.Rectangle((0, 3), (15, 5), layer) rect.translate(x, y) cell.add(rect) rect = gdspy.Rectangle((0, 6), (15, 8), layer) rect.translate(x, y) cell.add(rect) ...
This function creates a GDSII cell with structured placements of shapes and markers. It iterates through provided functions to generate elements (like waveguides) at calculated positions, using a grid layout with defined spacing. Markers are added for alignment, and structures are arranged in rows/columns with dynamic ...
def make_cell2(name,functions): cell = gdspy.Cell(name) n = len(functions) space = 10+15 #dist = np.array([10,20,30,40,50])*1e-3 dist = np.arange(20,80,2)*1e-3 #dist = np.arange(40, 60, 1) * 1e-3 #dist = np.append(dist,np.arange(40, 100, 2) * 1e-3) r = (60/2)*1e-3 for i in range(n...
def get_map(self): return self.maps[self.current_map] def get_obect(self,name): return self.get_map().tmx_data.get_object_by_name(name) def teleport_player(self,name): point =self.get_obect(name) self.player.position[0] = point.x self.player.position[1] = point.y self.player.save_locatio...
The code checks for collisions with portals to teleport the player between maps and detects collisions with walls to move sprites back. It iterates through portals, checks if the player collides with a portal's origin area, and teleports them to the target map. Then, it checks each sprite's collision with walls, revers...
def check_collision(self): #Portals for portal in self.get_map().portals : if portal.from_world == self.current_map : point = self.get_obect(portal.origin_point) rect = pygame.Rect(point.x,point.y,point.width,point.height) if self.player.feet....
def get_all_shapes_by_vid(open_face_path, video_path): os.makedirs(open_face_path, exist_ok=False) os.system('./OpenFace/build/bin/FeatureExtraction -3Dfp -pose -tracked -multi_view 1 -f "{0}" -out_dir "{1}"'.format (video_path, open_face_path)) output_csv = '{0}/{1}.csv'.format(open_face_path...
This function processes a video file by normalizing its face size, extracting 3D facial landmarks and head pose data, transforming frames to align facial features, extracting mouth regions, and compiling processed frames into a video. It saves normalized video, frame data, and shapes for further use in facial animation...
def process_video_file(index, item, total, config, db_config, gen_db_path, target_video_fps): video_start_time = time.time() folder_name, file_name = item.split('/') gen_folder_path = '{}{}/'.format(gen_db_path, folder_name) num_of_frames_path = '{0}{1}_{2}'.format(gen_folder_path, file_name, db_config....
def Build_Dict(data,numOfBins): """ :param data: :return: attributes tree """ attributes = {} for i in data: attr = i.split()[1] x = i.split()[2] if i.split()[2] == 'NUMERIC': field = list(range(numOfBins)) else: field = x.replace('{', '')...
The code implements the ID3 algorithm to build a decision tree model using training data (`train`), saves the trained model to a file, and evaluates its performance on test data (`test`). It processes structural information from `structFile` to define attributes, constructs the decision tree, and compares predicted out...
def ID3_algorithm(test, train, structFile): """ main program :param train: :param test: :param structFile: """ numOfBins=len(train[numericCol(train,structFile)[0]].unique()) attributes = Build_Dict(open(structFile),numOfBins) attrList = list(attributes.keys()) attrList.remove('cl...
def check_all_prns(self): results = {prn: self.verify_l1ca_code_first_10_bits(prn) for prn in range(1, 33)} passes = sorted([prn for prn, res in results.items() if res]) failures = sorted([prn for prn, res in results.items() if not res]) if len(passes) == 32: print('All PRNs ...
The main task of the code is to generate and analyze L1CA navigation code samples for two PRNs (Pseudo-Random Noise codes) by creating code sequences, generating sampled signals with specified parameters (5 MHz sampling rate, 5 ms duration, 1.023 MHz carrier frequency), and plotting their correlation. The function vali...
def main_function(self, prn1, prn2): """A function that performs everything that needs to be done with two different PRNs""" self.check_all_prns() fs = 5e6 # 5 MHz sampling rate T = 5e-3 # 5 milliseconds sampling duration fc = 1.023e6 code_1 = self.generate_l1ca_codes(p...
def cov(x: Array, y: Array, w: Array) -> float: """ Covarianza. """ return mean(x * y, w) - mean(x, w) * mean(y, w) def var(x: Array, w: Array) -> float: """ Varianza. """ return cov(x, x, w) def mean(x: Array, w: Array) -> float: """ Media pesata. """ return np.sum(x * w) / np.sum(w)
This function performs a weighted linear regression using the least squares method, calculating the slope (m) and intercept (c) of the best-fit line along with their variances, standard deviations, covariance, and correlation. It also computes auxiliary statistics like weighted means, variances, and covariances of inpu...
def linear_fit( x: Array, y: Array, sigma_y: Array, digits: Optional[int] = None, verbosity: int = 1 ) -> Fit: """ Fit lineare con metodo dei minimi quadrati. """ # Pesi w = 1 / (sigma_y ** 2) # m m = cov(x, y, w) / var(x, w) var_m = 1 / (var(x, w) * np.sum(w)) sigma_m ...
def linear_fit( x: Array, y: Array, sigma_y: Array, digits: Optional[int] = None, verbosity: int = 1 ) -> Fit: """ Fit lineare con metodo dei minimi quadrati. """ # Pesi w = 1 / (sigma_y ** 2) # m m = cov(x, y, w) / var(x, w) var_m = 1 / (var(x, w) * np.sum(w)) sigma_m ...
This function plots a linear fit of data points with error bars, overlays the best-fit line, and visualizes uncertainty bands (±σ) around the line using shaded regions. It returns the computed fit parameters, including slope, intercept, and uncertainties.
def plot_linear_fit( x: Array, y: Array, sigma_y: Array, xlabel: str, ylabel: str, sigmas: list[float] = [1], digits: Optional[int] = None, verbosity: int = 1 ) -> Fit: """ Plot fit lineare. """ fit = linear_fit(x, y, sigma_y, digits, verbosity) # Punti con incertezza p...
def checkForPinsAndChecks(self): pins, checks = [], [] checked = False if self.whiteToMove: startRow, startCol = self.whiteKingLocation[0], self.whiteKingLocation[1] allyColor, enemyColor = 'w', 'b' else: startRow, startCol = self.blackKingLocation...
The main task of the code is to generate all valid moves for the current player, considering check conditions, pins, and special game states. It identifies the king's position, filters moves to avoid leaving the king in check, handles blocking checks or capturing checking pieces, enables king movement when under multip...
def getValidMoves(self): moves = [] self.checked, self.pins, self.checks = self.checkForPinsAndChecks() #get current turn's king's coordinates if self.whiteToMove: kingRow, kingCol = self.whiteKingLocation[0], self.whiteKingLocation[1] else: ki...
def add_character(): title = "Add Character" label = "Search and select a character:" callback = lambda name: handle_add_character(name) message_var = tk.StringVar() input_dialog(title, label, callback, message_var) def modify_character(): char_name = simpledialog.askstring("Input", "Enter the n...
This code defines a function `button_click` that processes user input choices to perform specific actions in a GUI application. Depending on the `choice` parameter (1-6), it triggers functions for adding, modifying, displaying, removing, or listing characters and maps. Choice 0 exits the application by closing the wind...
def button_click(choice): if choice == 1: add_character() elif choice == 2: modify_character() elif choice == 3: display_character_info() elif choice == 4: display_map() elif choice == 5: remove_character() elif ...
def add_character(): title = "Add Character" labels = ["Name:", "Date of Birth (YYYY/MM/DD):", "Date of Death (Leave blank if alive):"] callback = lambda name, birth_date, death_date: handle_add_character(name, birth_date, death_date) message_var = tk.StringVar() input_dialog(title, labels, callback...
This function handles user menu choices in a game interface. It routes input (1-6) to specific actions like adding/modifying characters, displaying info/map, or listing characters. Choice 0 exits the game. Invalid inputs trigger an error message. The core task is managing game interactions through a menu-driven GUI sys...
def button_click(choice): if choice == 1: add_character() elif choice == 2: modify_character() elif choice == 3: display_character_info() elif choice == 4: display_map() elif choice == 5: remove_character() elif ...
def get_distance(self, current_x, current_y, goal_x, goal_y): distance = math.sqrt((goal_x - current_x)**2 + (goal_y - current_y)**2) return distance def set_attitude(self, roll_angle = 0.0, pitch_angle = 0.0, yaw_angle = None, yaw_rate = 0.0, use_yaw_rate = False, ...
This code controls a drone to navigate toward a target position by continuously calculating the distance from its current coordinates to the goal. It adjusts the drone's attitude using `set_attitude()` and breaks the loop once the target is reached (distance ≤ 1). Afterward, it hovers for 5 seconds with reduced thrust ...
def ControllerFunction(self): # self.set_attitude() start = time.time() #distance = 100000000 while True: rospy.Subscriber('/qvio/pose', PoseStamped, self.pose_callback) print(f"current_x : {self.current_x},current_y : {self.current_y}") ...
def FF(x,lbd,para): """the second equation""" alpha,c,d,gamma=para G = x[0]+1j*x[1] lbd_dagger = np.conjugate(lbd) lbd_G = lbd*G lbd_G_dagger = np.conjugate(lbd_G) w = alpha*np.average(lbd/((lbd_G_dagger-1)*(lbd_G-1))) return np.array([w.real,w.imag]) def march_boundary(x0,lbd,para,lr=0....
The main task of the code is to simulate a path by iteratively updating a point $ x $ using boundary marching and gradient-based steps, tracking the trajectory and corresponding values $ w $. It dynamically adjusts the step size based on changes in $ w $, computes gradients, and moves along tangent directions to trace ...
def single_draw(x0,para,lr=0.1,step=0.05,num=200): step0=step lbd = tools.eigen(para=para,P=100000) all_x =[] all_w = [] w = FF(x0,lbd,para) all_x.append(x0) all_w.append(w) x = x0+np.array([0,0.01]) for i in range(num): try: x = march_boundary(x,lbd,para,lr = lr...
def kI(): return np.average((np.conjugate(lbd)*lbd)/(np.conjugate(lbd*GG-1)*(lbd*GG-1)+UV*np.conjugate(GG)*GG)) def kI1_(): """ d kI/d G^\prime """ return np.average(-1.0*kI_part()*(lbd*np.conjugate(lbd*GG-1)+UV*np.conjugate(GG))) def G1_(): #dG^\prime/dx ...
The main task of the code is to compute the derivative of F1 with respect to x (dF1/dx) using a mathematical expression involving parameters (alpha, CC) and functions (kI(), kI1_(), G1_(), G2_(), uv_()). The result is stored in variable 'g' and returned.
def GG1_(): """ dF1/dx """ g = alpha*(CC_*kI()+CC*kI1_()*G1_()+CC*kI2_()*G2_()+CC*kI11_()*uv_()) return g
def kIp(): return np.average((lbd)/(np.conjugate(lbd*GG-1)*(lbd*GG-1)+UV*np.conjugate(GG)*GG)) def kI5_(): """ d (kI^\prime)^\dagger /d G^\prime """ return np.conjugate(kI4_()) def G1_(): #dG^\prime/dx return BB_*t+delta(3)*BB+CC_*x[0]+delta(0)*CC def kI6_():...
The function `GG3_` computes the derivative $ \frac{dF3}{dx} $ by combining terms involving parameters ($ \alpha, BB $) and functions ($ kIp, kI5_, G1_, G2_, kI33_, uv_, \delta $). It calculates a complex expression with conjugates, products, and subtractions of $ BB_*t $ and $ BB*\delta(3) $, returning the result as $...
def GG3_(): """ dF3/dx """ g = alpha*(CC_*np.conjugate(kIp())+CC*kI5_()*G1_()+CC*kI6_()*G2_()+CC*kI33_()*uv_())-BB_*t-BB*delta(3) return g
def single_start_point(y0,var,phip,lbd,alpha,lr=0.1,ifprint=True): y = y0 for i in range(40): f,g = gradient_boundary(y0,var,phip,lbd,alpha,real=True) y0 = y0+lr*newton_step(f,g) if np.sum(np.abs(f))<8e-1: lr = 1.0 if np.isnan(f[0]): raise RuntimeError("Er...
The main task of the code is to scan initial points on a grid, identify unique roots using a solver, and generate trajectories for each distinct root via a marching method, returning a list of trajectory results. It first maps initial points to roots, filters unique roots, and then computes trajectories for each, optio...
def draw_all(var,phip,lbd,alpha,lr=0.1,num=50,auto=False,step_len = 0.15,onlyinitpoint=False,scannum=30): print("Scanning for the initial points") xxx = np.linspace(-1.5,1.5,num=scannum) yyy = 1*xxx xxx = xxx.reshape(-1) yyy= yyy.reshape(-1) N = len(xxx) record = 0*np.ones_like(xxx) root...
def change_attribute_points(self): which_stat = input("Which stat would you like to increase? Please select from strength, dexterity, " "constitution, intelligence, wisdom, and Charisma. ") if which_stat.lower() not in ["strength", "dexterity", "constitution", "intelligence", ...
The main task of the code is to gather and validate user inputs for a character's name, species (Human/Elf/Dwarf), and job (Fighter/Rogue), then display initial attributes, allow point allocation, and finalize character stats by setting species, job, and hit points.
def starting_character_information(self): character_name = input( "Please type what you would like your character name to be? ") self.name = character_name.title() character_species = input( "Please type what you would like your character species to be? Please choose from...
def setup_page_preview(): st.title("NBA salaries prediction demo") """This is a test model aims to predict NBA player salaries based on their statistic in 2017-2018 season. """ """Follow the instructions below to calculate a prediction. """ st.title("*1. Enter player name.*") """You may cho...
The main task of the code is to process player data by setting up a preview page, generating numerical features via a sidebar, creating a feature vector from these values, producing output using the player and features, and displaying league statistics. It orchestrates data initialization, feature extraction, output ge...
def main(): # setup pages and returns its fields player = setup_page_preview() num_features_dict = setup_sidebar(player) # create train features vector feature_values = [[v for _, v in num_features_dict.items()]] # create output create_output(player, feature_values) # display league stat...
def initialize(self,folder,language) : path=join(folder,"Cache",language+"_ssml") if exists(path): shutil.rmtree(path) os.mkdir(path) else: os.mkdir(path) path2=join(folder,"Cache",language) if exists(path2): shutil.rmtree(path2) ...
The main task of this code is to process caption text files in a specified directory, extract time-stamped text data, parse durations and offsets for each segment, and synchronize them with audio using a callback function. It identifies language codes, initializes translation processes, and generates structured output ...
def translation_from_caption(self,video_directory): for file in os.listdir(join(video_directory,"Cache")): if file.endswith(".txt"): self.sequence_number=1 self.audio_number=1 self.prev_offset=0 self.durations=[] self.of...
def send_motor_commands(self, send_data): # Clear any data in the serial input self.comms.flush_input() # Send frames to each motor self.comms.send_frame(motor_front_left, [send_data['leftdir'], send_data['speed'], send_data['leftcheck']]) sleep(0.001) self.comms...
This function controls a robot's movement by sending directional and speed commands to its motors. It validates input direction (forward/reverse) and speed (0-100), calculates motor-specific values, sends commands, checks responses, and handles errors. If successful, it updates the robot's state and direction; otherwis...
def move_robot(self, direction, speed): ''' Sends commands to each motor the move the robot forward or backward ''' if direction == self.FORWARD: left_direction = self.MOTOR_FORWARD right_direction = self.MOTOR_REVERSE elif direction == self.REVE...
def send_motor_commands(self, send_data): # Clear any data in the serial input self.comms.flush_input() # Send frames to each motor self.comms.send_frame(motor_front_left, [send_data['leftdir'], send_data['speed'], send_data['leftcheck']]) sleep(0.001) self.comms...
This function rotates a robot by sending motor commands to turn left or right based on the specified direction (clockwise/counter-clockwise) and speed. It validates input parameters, computes motor direction and check values, sends commands, verifies responses, stops the robot on errors, and updates its state if succes...
def rotate_robot(self, direction, speed): ''' Sends commands to each motor to rotate the robot left or right ''' if direction == self.CLOCKWISE: rotate_direction = self.MOTOR_FORWARD elif direction == self.COUNTERCLOCKWISE: rotate_direction = ...
def bubble_sort(self): n = len(self._arr) for i in range(n): swapped = False for j in range(0, n-i-1): if self._arr[j] > self._arr[j+1]: self._arr[j], self._arr[j+1] = self._arr[j+1], self._arr[j] swapped = True ...
This method selects and executes the specified sorting algorithm (bubble, selection, insertion, merge, or heap sort) on the array, then calculates and stores the elapsed processing time for the operation.
def select_sorting(self): if self._algorithm == 'bubble': self.bubble_sort() elif self._algorithm == 'selection': self.selection_sort() elif self._algorithm == 'insert': self.insertion_sort() elif self._algorithm == 'merge': self.me...
def process_ad(self, index: int, row): ''' find top phrases and add the ad to the cluster graph ''' doc_id = row[self.id] self.index_to_docid[index] = doc_id self.docid_to_index[doc_id] = index if 'title' in row: text = row['title'] if type(row['title']) == str else ...
The main task of the code is to process each advertisement individually in a loop, maintain mappings between document IDs and indexes, and incrementally save clustering results. It updates cluster information for each ad, tracks progress, generates cluster labels, writes the cluster graph, outputs CSV labels, and recor...
def clustering(self): ''' process each ad individually and incrementally save cluster graph. ''' t = time.time() index = 0 for _, row in self.data.iterrows(): if index and not index % 10000: time_elapsed = time.time() - t print(index, '/', sel...
def __tokenize(self, string): tokens = [] token = "" isString = False for char in string: # The tokenizing is done character by character, verifying certain cases at each step if not self.__isOperator(char) and not self.__isSeparator(char): # The splitting is d...
The code performs lexical analysis on a given file, tokenizing each line, validating tokens against a language's syntax (e.g., checking for required separators), and recording valid tokens into a Program Intermediate Form (PIF). It detects lexical errors like missing separators or invalid tokens, logs them to an output...
def scan(self, fileName): self.__st = Hashtable() # Start from scratch the scanning self.__pif = [] lineNumber = 1 # Keep track of the line number message = None # In this variable we will store any potential lexical error messages with open(fileName, "r") as file: # We read...
def chk(s, t): if len(s) != len(t): return False if len(s[0]) != len(t[0]): return False for i in range(len(s)): for j in range(len(s[0])): if s[i][j] != t[i][j]: return False return True def r90(s): hh = len(s) ww = len(s[0]) ss = [] for i in range(ww...
The code checks if string s is a rotation of string t by 0°, 90°, 180°, or 270°, using helper functions to rotate t and compare with s. It returns True if any rotation matches s.
def chkrt(s, t): return chk(s, t) or chk(s, r90(t)) or chk(s, r180(t)) or chk(s, r270(t))
def CreateNode(self, pos:Vector2d, isCenter = True): newNode = Node(self) if isCenter: newNode.MoveCenterTo(pos.x, pos.y) else: newNode.pos = pos if self.IsValidNodePosition(newNode): self.AddNode(newNode) return True return False ...
This code processes mouse events to handle node/link creation and object removal in a Qt application. It creates nodes on left-double-click, initiates link creation with right-click drag, removes objects via middle-click, and finalizes links on right-click release. It also delegates input processing to active links and...
def ProcessInput(self, event : QInputEvent): result = False mousePos = Vector2d(event.localPos().x(), event.localPos().y()) type = event.type() #processing all events that require knowledge about all objects if type == QEvent.MouseButtonDblClick: if event.button() == ...
def dictWords(words): newWords = set([]) for word in words: newWords.add(word.split('\n')[0]) return newWords def getPrefixes(validWords): prefixes = [] for w in validWords: soFar = '' for c in w: soFar += c prefixes.append(str(soFar)) return set(p...
The main task of the code is to traverse a graph structure (likely representing letter connections) to find valid words from a predefined dictionary. It loads word lists, generates valid words and their prefixes, then performs graph traversal to identify all possible words, measuring the time taken and outputting the c...
def main(): graph = LetterGetter.main() words = open(allWords, 'r').readlines() global validWords validWords = dictWords(words) print(len(validWords)) global prefixes prefixes = getPrefixes(validWords) print(len(prefixes)) start_time = time.time() traverseGraph(graph) ...
def ensure_topic_is_not_empty_on_startup(self): # Put some data in it, so jbi doesn't complain about an empty topic for i in range(10): self.generate_and_send_data(i) time.sleep(1) def create_basic_config(self): config = copy.deepcopy(CONFIG_CMD) config["histograms"]...
This test verifies that the 'just_bin_it' system correctly collects and sums all data events within a specified time interval. It configures an interval, sends synthetic data, waits for processing, and checks that the histogram data matches the expected total events during the interval, ensuring the system's state tran...
def test_counting_for_an_interval_gets_all_data_during_interval(self, just_bin_it): self.ensure_topic_is_not_empty_on_startup() # Config just-bin-it interval_length = 5 config = self.create_basic_config() config["interval"] = interval_length self.send_message(CMD_TOPIC, ...
def ensure_topic_is_not_empty_on_startup(self): # Put some data in it, so jbi doesn't complain about an empty topic for i in range(10): self.generate_and_send_data(i) time.sleep(1) def create_basic_config(self): config = copy.deepcopy(CONFIG_CMD) config["histograms"]...
This test verifies that when no data is received during a configured interval, the system correctly exits the interval with a 'FINISHED' state and zero accumulated data. It sets up a 5-second interval, waits for it to elapse without input, then checks that the histogram data sum is zero and the state is marked as finis...
def test_counting_for_an_interval_with_no_data_exits_interval(self, just_bin_it): self.ensure_topic_is_not_empty_on_startup() # Config just-bin-it interval_length = 5 config = self.create_basic_config() config["interval"] = interval_length self.send_message(CMD_TOPIC, by...
def ensure_topic_is_not_empty_on_startup(self): # Put some data in it, so jbi doesn't complain about an empty topic for i in range(10): self.generate_and_send_data(i) time.sleep(1) def create_basic_config(self): config = copy.deepcopy(CONFIG_CMD) config["histograms"]...
This test verifies that when a single event message is sent within a configured interval (5 seconds), the system correctly aggregates the data. It checks if the histogram data from Kafka matches the expected total events within the interval's time range and confirms the state transitions to "FINISHED" after the interva...
def test_counting_for_an_interval_with_only_one_event_message_gets_data( self, just_bin_it ): self.ensure_topic_is_not_empty_on_startup() # Config just-bin-it interval_length = 5 config = self.create_basic_config() config["interval"] = interval_length self.se...
def ensure_topic_is_not_empty_on_startup(self): # Put some data in it, so jbi doesn't complain about an empty topic for i in range(10): self.generate_and_send_data(i) time.sleep(1) def create_basic_config(self): config = copy.deepcopy(CONFIG_CMD) config["histograms"]...
This test verifies that the system correctly ignores empty intervals by ensuring no events are counted when no data is received during the specified interval. It checks if the histogram data sum is zero and the state transitions to "FINISHED" after an interval with no input, confirming proper handling of empty interval...
def test_counting_for_an_interval_data_after_empty_interval_is_ignored( self, just_bin_it ): self.ensure_topic_is_not_empty_on_startup() # Config just-bin-it interval_length = 5 config = self.create_basic_config() config["interval"] = interval_length self.sen...
def ensure_topic_is_not_empty_on_startup(self): # Put some data in it, so jbi doesn't complain about an empty topic for i in range(10): self.generate_and_send_data(i) time.sleep(1) def create_basic_config(self): config = copy.deepcopy(CONFIG_CMD) config["histograms"]...
This test verifies that legacy data schemas ("ev42" input, "hs00" output) are correctly processed by sending mock data, checking Kafka offset progression, and validating histogram totals against expected event counts. It ensures proper state transition to "FINISHED" after processing 12 messages with a 5-second interval...
def test_legacy_schemas(self, just_bin_it): self.ensure_topic_is_not_empty_on_startup() # Config just-bin-it interval_length = 5 config = self.create_basic_config() config["interval"] = interval_length config["input_schema"] = "ev42" config["output_schema"] = "hs...
def get_errors_file_path(errors_list_file): script_directory = os.path.dirname(__file__) #print(script_directory) if errors_list_file == "": file_path = os.path.join(script_directory, "bckgrep_backup_errors_6.csv") else: file_path = os.path.join(script_directory, errors_list_file) re...
The main task of the code is to parse a log file, identify errors within a specified timestamp range, and generate an HTML-formatted summary of the found errors. It reads error patterns from a predefined list, searches the log for matches, and compiles the results into a structured HTML report for easy review and analy...
def log_parser( log_file, beginning_timestamp="1970-01-01T00:00:00", end_timestamp="2190-01-01T23:59:59", errors_list_file ="" ): """ Parses a log file, searches for errors, and generates an HTML log summary. Args: log_file (str): The path to the log file. beginning_timestam...
def initialize(pointer_list, pre_pointer): #build min heap i = (len(pointer_list)//2) pointer = pointer_list[0] while (i > 0): BubbleDown(pointer_list, i) i = i-1 while(pointer != pointer_list[0]): pre_pointer.append(ExtractMin(pointer_list)) def get_value(A): #check root ...
The code processes a list of commands to simulate operations on a sorted data structure with a pointer. It initializes a max-heap, handles "move_pointer_left/right" and "insert" commands, and returns the value at the current pointer position after each operation. The output list captures these values for all commands. ...
def pretend_sorted_array(commands): ''' Pre: commands is a list of commands Post: return list of outputs ''' output = [] pointer_list = [] pre_pointer = [] ''' We know that 'initialize' will always be the first command. So we initalize by building a max-heap. ''' init = commands[0].split() #spli...
def calculate_J(self, template_feature): assert len(np.shape(template_feature)) == 4 Gradient_F = self.Gradient_F(template_feature) Gradient_F = tf.expand_dims(Gradient_F, axis=2) J = tf.matmul(Gradient_F, self.p_W_p_p) return J[:, :, 0, :] def calculate_r(self, template_feat...
The main task of the code is to compute the delta_p vector by solving a linear system involving the Jacobian matrix (J) and residual vector (r) through matrix operations. It calculates temp_1 as J^T@J, temp_2 as J^T@r, then solves (J^T@J + εI)⁻¹@J^T@r for delta_p, where ε is a small regularization term. The result is t...
def calculate_del_p(self, template_feature, input_feature, matrix): J = self.calculate_J(template_feature) r = self.calculate_r(template_feature, input_feature, matrix) temp_1 = tf.matmul(tf.transpose(J, [0, 2, 1]), J) r = tf.expand_dims(r, axis=-1) temp_2 = tf.matmul(tf.transpo...
def create_boards(self): self.lower_board = Board("game", "ships' board") self.upper_board = Board("game", "strikes' board") def create_ships(self): self.carrier = Ship("Carrier", 5) self.battleship = Ship("Battleship", 4) self.cruiser = Ship("Cruiser", 3) self.submarine ...
The code initializes a player's game setup by creating game boards, positioning ships, and preparing tracking lists. It sets the player's name, generates game boards, places ships, displays the lower board for positioning, and initializes a hits list to track attacks. The process includes user feedback messages to guid...
def __init__(self, name): self.name = name self.create_boards() self.create_ships() print_separator() print(f"Player {self.name} created!\nNow positionning the ships...") display_board(self, self.lower_board) self.position_ships() self.hits_list = []
def get_holiday(ibge_code, date): """ Gets a holiday Args: ibge_code (string): IBGE code date (string): Data that might have a holiday Return: (Message, code): Return the message result of the get method and the http code """ try: # Check if date is valid ...
This function handles holiday-related API operations (GET, PUT, DELETE) based on the request method. It retrieves holiday data, adds/updates holidays (with flexible date checks), or deletes holidays using IBGE codes and holiday info, returning operation results with HTTP status codes.
def holiday_methods(ibge_code=None, holiday_info=None): """ Setup of all holiday routes and methods of the api Args: ibge_code (string): IBGE code holiday_info (string): Data that might have a holiday date or holiday name Return: (Message, code):...
def setupDialog(self): self.form = settings_dialog.Ui_Dialog() self.form.setupUi(self) def loadConfigData(self): f = self.form # Checkboxes ------------- c = conf['loose_search'] if f.checkBox_search_mode.isChecked() != c: f.checkBox_search_mode.click() ...
This code initializes a dialog window by setting up its parent, loading configuration data, establishing connections, and displaying the dialog. It inherits from QDialog, configures the window type, assigns references to the main window and parent, and executes the dialog using self.exec().
def __init__(self, parent): QDialog.__init__(self, mw, Qt.WindowType.Window) mw.setupDialogGC(self) self.mw = mw self.parent = parent self.setupDialog() self.loadConfigData() self.setupConnections() self.exec()
def _filename_to_ixp(self, filename): """Extracts ixp from filename""" tokens = self._parse_filename(filename) return tokens[-3] def _filename_to_date(self, filename): tokens = self._parse_filename(filename) date = tokens[-2] # Create timezone aware datetime retu...
The code's main task is to import data from a specified file by extracting an IXP identifier and date from the filename, then processing each row of the file's data with the extracted date. It handles exceptions during filename parsing and iterates through the data to import it, logging progress and errors.
def handle(self, *args, **options): """Perform import of file""" filename = options['file'] try: ixp = self._filename_to_ixp(filename) date = self._filename_to_date(filename) except Exception as e: print("Could not load file: {}".format(filename)) ...
def populateBoard(board, row, col): """ Given a 9x9 grid of 0's, it recursively fills the grid. Makes a list of integers from 1-9, shuffles the list, and checks for the first integer in the list which can be inserted at the cell. If found it inserts it in the current cell and continues on. If no...
The code generates a specified number of Sudoku puzzles with user-selected difficulty and formatting, writes them to a file, and reports the generation time. It prompts for puzzle count, difficulty (Easy/Difficult), and formatting preference, then creates empty boards, populates them, reduces numbers based on difficult...
def main(): f = open("SudokuPuzzles.txt", "w") user_input = int(input("How many Sudoku puzzles would you like to generate?:\n")) difficulty = 'A' while difficulty != 'E' and difficulty != 'D': difficulty = input("Do you want Easy or Difficult puzzles?: (E or D)\n") to_format = 'A' while ...
def line_number(source: str) -> (int, str): _, tail = consume("N", source) number, tail = integer(tail) _, tail = maybe_space(tail) return number, tail def alpha(source: str) -> (str, str): head = source[0] tail = source[1:] if not head.isalpha(): raise ParseError(source, "Expected...
This function parses a line of source code into a list of AST instructions, extracting each instruction with its decimal argument while skipping spaces. It optionally handles line numbers and returns the parsed instructions along with the remaining unparsed string after the newline.
def line(source: str) -> ([ast.Instruction], str): # line numbers are optional try: _, tail = line_number(source) source = tail except ParseError: pass instructions = [] while source[0] != "\n": try: instruction, tail = alpha(source) # In ou...
def consume(needle: str, source: str) -> (str, str): """Checks that source starts with given needle Returns: A tuple with needle and tail (rest of the source) """ if not source.startswith(needle): raise ParseError(source, "Expected " + needle) return needle, source[len(needle):] de...
The code parses a source string into an abstract syntax tree (AST) Program. It reads a number after a '%' marker, then collects lines until the next '%', constructing the Program with that number and the collected lines.
def program(source: str) -> ast.Program: _, tail = consume("%", source) _, tail = newline(tail) number, tail = program_number(tail) _, tail = newline(tail) lines = [] while tail[0] != "%": l, tail = line(tail) if len(l) > 0: lines.append(l) return ast.Program(...
def update_volume(): volume_level = get_stored_volume() print(f"updating volume to {volume_level}") pygame.mixer.music.set_volume(volume_level) def fetch_events(service): now = datetime.datetime.utcnow().isoformat() + "Z" event_result = service.events().list( calendarId=calendar_id, ...
The code periodically fetches events from a service every 10 minutes, checks if any event's start time has passed, plays an alarm sound if so, and removes processed events. It maintains a queue for event data and runs in a loop with 15-second intervals to monitor and trigger alarms based on event timing.
def check_events(service, event_queue): last_fetch_time = datetime.datetime.min.replace(tzinfo=datetime.timezone.utc) fetch_inverval = datetime.timedelta(minutes=10) check_interval = 15 # 0.25 minute events = [] while True: now = datetime.datetime.now(datetime.timezone.utc) upd...
def fetch_and_update_events(self): try: events = self.fetch_events(self.service) if events: self.event_queue.put(events) self.log_message("Events fetched successfully on startup") else: ...
The code's main task is to initialize the parent class, fetch and update events, start a thread for event checking, handle exceptions during thread initiation, and log status messages. It ensures event monitoring by launching a dedicated thread, logs success or errors, and marks the on_start method as completed.
def on_start(self): super().on_start() self.fetch_and_update_events() # self.check_events(self.service, self.event_queue) try: self.start_event_check_thread() self.log_message("Event check thread called from on_sta...
def process_event(event: Union[GCalEvent, CancelledGCalEvent], property_doc_ref: Any): if event.status == 'cancelled': handle_cancelled_event(event) else: handle_validated_event(event, property_doc_ref) def clear_event_store(property_ref: str): # Get a reference to the 'trips' collection ...
The main task of the code is to synchronize Google Calendar events with a property document in a database. It validates events, processes them, manages pagination, and handles retries for sync token errors, updating the database with the latest sync token after each synchronization.
def sync_calendar_events(property_doc_ref: Any, retry_count: int = 0): if isinstance(property_doc_ref, str): try: property_doc_ref = db.document(property_doc_ref) except ValueError: app_logger.error('Invalid property document reference: %s', property_doc_ref) rai...
def renew_notification_channel(calendar_id, channel_id, channel_type, channel_address): service = build('calendar', 'v3', credentials=creds) # Create a new channel with a unique id new_channel_id = str(uuid.uuid4()) new_channel = ( service.events() .watch(calendarId=calendar_id, body={'...
This function initializes trips by linking a property to a Google Calendar. It updates the property's document with the calendar ID, sets up a webhook for real-time event updates, and synchronizes future events. It logs calendar details, creates a notification channel, and stores the channel ID/expiration in the proper...
def initalize_trips_from_cal(property_ref: str, calendar_id: str): app_logger.info('Initialising trips from calendar: %s , property: %s', calendar_id, property_ref) # get the property document collection_id, document_id = property_ref.split('/') property_doc_ref = db.collection(collection_id).document(...
def check(): """ Check environment to connect to database (PGDSN) and whether we can support another connection pool """ if not os.getenv('PGDSN'): raise ValueError("no database url specified") sql = 'SELECT numbackends FROM pg_stat_database WHERE datname = (SELECT current_database());'...
This code runs CRUD operations (initdb/rwops) with customizable read/write ratios, managing database connections and threads. It initializes schemas, executes parallel read/write tasks, adjusts thread counts based on ratios, handles interrupts, and logs performance metrics in iterations.
def run(options): """ Run various operations (commmands) with customizations Available commands: { initdb, rwops } initdb: initialize bench database with schema rwops: run CRUD operations """ db_conns = check() if db_conns > 16: sys.exit(0) import t...
def check_file(filename): if curr_dir != '/': path = curr_dir + "/" + filename else: path = curr_dir + filename return check_file_path(path) def make_query(query, is_return): conn = psycopg2.connect(dbname='postgres', user='postgres', password='postgres', host...
The code deletes a specified directory from a database, handling empty and non-empty cases. It checks if the folder is empty, sends deletion messages to clients, and executes SQL queries to remove entries from the 'files' table. If non-empty, it prompts user confirmation before deletion.
def delete_dir(folder): if check_file(folder): if curr_dir != "/": path1 = curr_dir + "/" + folder # /abc => /abc/1488 else: path1 = curr_dir + folder # / => /abc a = make_query("SELECT * FROM files WHERE dir='{}'".format(path1), True) path = var_stor + path...
def check_file(filename): if curr_dir != '/': path = curr_dir + "/" + filename else: path = curr_dir + filename return check_file_path(path) def make_query(query, is_return): conn = psycopg2.connect(dbname='postgres', user='postgres', password='postgres', host...
The function deletes a file by first checking its existence, constructing its full path, querying a database for its entry, and if found, removing the database record and sending deletion commands to two system components via sockets.
def delete_file(filename): if check_file(filename): if curr_dir != "/": path1 = curr_dir + "/" + filename else: path1 = curr_dir + filename a = make_query("SELECT * FROM files WHERE filename='{}'".format(path1), True) path = var_stor + path1 if len(a) ...
def check_exists(filename): if curr_dir != '/': path = curr_dir + "/" + filename else: path = curr_dir + filename return check_exists_path(path) def make_query(query, is_return): conn = psycopg2.connect(dbname='postgres', user='postgres', password='postgres', ...
This function creates a directory in a distributed file system by inserting a directory record into a database and notifying all data nodes. It constructs the full path from the current directory and new_path, marks it as a directory, and sends a "makedir" message to all data nodes via send_msg, using the formatted pat...
def mkdir(new_path): if check_exists(new_path): if curr_dir != "/": path = curr_dir + "/" + new_path else: path = curr_dir + new_path make_query("Insert into files(filename, datanode1, datanode, dir, is_dir, size) VALUES ('{0}','{1}','{2}','{3}', {4}, '-')" ...
def check_exists(filename): if curr_dir != '/': path = curr_dir + "/" + filename else: path = curr_dir + filename return check_exists_path(path) def get_ips(): count = random.sample(datanodes, 2) return count def send_msg(sock, msg): sock.send(bytes(msg, "utf-8")) def make_query(...
The code creates a new file in a distributed system by sending creation commands to two data nodes and recording metadata in a database. It checks if the file exists, retrieves IP addresses, and inserts a database entry with the filename, assigned data nodes, directory path, and initial size. If the current directory i...
def create(filename): if check_exists(filename): ips = get_ips() if curr_dir != "/": send_msg(s[ips[0]], "create " + var_stor+curr_dir + "/" + filename) send_msg(s[ips[1]], "create " + var_stor+curr_dir + "/" + filename) #TODO make_query( "Insert i...
def check_file(filename): if curr_dir != '/': path = curr_dir + "/" + filename else: path = curr_dir + filename return check_file_path(path) def send_msg(sock, msg): sock.send(bytes(msg, "utf-8")) def mkdir(new_path): if check_exists(new_path): if curr_dir != "/": ...
This function reads a file from a remote node via socket communication, saves it to a specified directory, and handles data transfer in chunks. It checks file existence, constructs the file path, sends a read command, creates necessary directories, and writes received data to a local file. If the server responds with '...
def read_from_node(filename, addr, save_dir): if check_file(filename): if curr_dir != "/": path = curr_dir + "/" + filename else: path = curr_dir + filename sock = s[addr] rec_con = conn[addr] send_msg(sock, "read " + var_stor + path) pathlib....
def make_query(query, is_return): conn = psycopg2.connect(dbname='postgres', user='postgres', password='postgres', host='localhost', port="5432") cursor = conn.cursor() cursor.execute(query) conn.commit() if is_return: res = cursor.fetchall() cursor.close() ...
The code performs a backup of files from a specified datanode by querying a database for non-directory files associated with the node, reading them into a backup directory, and updating the system state. It handles two query conditions for datanode1 and datanode, adjusts source paths accordingly, writes backup data, an...
def backup(addr): a = make_query("SELECT * FROM files Where datanode1='{}' AND is_dir=FALSE;".format(addr), True) a += make_query("SELECT * FROM files Where datanode='{}' AND is_dir=FALSE;".format(addr), True) back_dir = '/backup_{}'.format(addr) for i in a: if i[1] != addr: read_for...
def check_file(filename): if curr_dir != '/': path = curr_dir + "/" + filename else: path = curr_dir + filename return check_file_path(path) def get_ips_for_file(path): a = make_query("SELECT * FROM files WHERE filename='{}'".format(path), True) return a[0][1], a[0][2] def read_from_...
The code reads a file by first validating its existence, retrieving associated IP addresses based on the current directory path, and then using the first IP to read the file from a node at the '/received_files' location.
def read(filename): if check_file(filename): if curr_dir == "/": ips = get_ips_for_file(curr_dir + filename) else: ips = get_ips_for_file(curr_dir + '/' + filename) read_from_node(filename, ips[0], '/received_files')
def get_parameter_store_value(token): try: response = ssm.get_parameter(Name=f"token-transfers-{token.lower()}", WithDecryption=False) print("INFO: Get Parameter Store", response['Parameter']['Value']) return json.loads(response['Parameter']['Value']) except: print("INFO: Paramet...
The main task of the code is to retrieve and process blockchain transaction events for a specific token, paginate through results, filter relevant events, and save them as CSV files in S3. It uses parameters to track progress, fetches transactions in batches, extracts event details, and stores them with timestamps, add...
def process(): params = get_parameter_store_value(token) from_time = params['last_saved_tx_time'] to_time = get_last_processed_transaction_time(token) print("INFO: Params:", params, to_time) params_list_transactions_obj = params_list_transactions(address=token, from_time=from_time, to_ti...
def get_json_log(log_data_z64): """ Decompress the log information provided by the CloudWatch subscription filter. """ log_data_z = base64.b64decode(log_data_z64) log_data = gzip.decompress(log_data_z) # print('log_data: {}'.format(log_data)) log_json = json.loads(log_data) # p...
The code processes CloudWatch logs from GuardDuty malware scans, updating DynamoDB annotations to track scan outcomes for DRS source servers. It handles EC2_SCAN_COMPLETED/SKIPPED events, updating EC2 instance status and EBS volume records to prevent conflicts and enable reporting. The Lambda function decodes logs, ide...
def lambda_handler(events, context): """ SubscriptionFilter updates the DynamoDB annotations to reflect the outcome of every malware scan operation submitted by ProcessCommands. Currently, the GuardDuty malware scan APIs do not allow to identify the outcome of a scan operation individually, at ...
def variableY(cent): oblCorr = calcObliqCorr(cent) x = tanDeg(0.5*oblCorr) return x*x def calcSunML(cent): a = 280.46646 b = 36000.76983 c = 3.032e-4 x = a + cent * (b + cent * c) return math.fmod(x, 360) def calcEccentrEO(cent): x = 0.016708634 - c...
The function calculates the equation of time (difference between apparent and mean solar time) using astronomical parameters like mean longitude, eccentricity, and anomalies. It combines trigonometric terms involving these variables, scaled by conversion factors, to compute a correction value (z) representing the equat...
def equatTime(cent): varY = variableY(cent) meanLongS = calcSunML(cent) eOrbitEx = calcEccentrEO(cent) meanAnomS = calcAnomalSun(cent) TODEG = 180.0/math.pi z = TODEG *(varY * sinDeg(2.0 * meanLongS)\ - 2.0 * eOrbitEx * sinDeg(meanAnomS)\ + 4.0 ...
def _get_free_index(self) -> int: return self._get_sleep_memory_data( FREE_INDEX_OFFSET, FREE_INDEX_OFFSET + 4, "i") def _get_num_elems(self) -> int: return self._get_sleep_memory_data( NUM_ELEMS_OFFSET, NUM_ELEMS_OFFSET + 4, "i") def get_element(self, name: str): return ...
The code's main task is to print diagnostic information about Backup RAM elements. It displays the free index, total elements count, and iterates through the `elements` dictionary to show each element's name and value. This method likely aids in debugging or monitoring memory state by providing a snapshot of stored dat...
def print_elements(self): print(f"Free index: {self._get_free_index()}") print(f"Num elems: {self._get_num_elems()}") print("Backup RAM elements:") for name in self.elements.keys(): print(f"{name}: {self.get_element(name)}")
def reset(self): print("Resetting nv memory...") for i in range(len(alarm.sleep_memory)): alarm.sleep_memory[i] = 0 self._set_free_index(ELEMENTS_OFFSET) self._set_num_elems(0) self.elements = {} def _get_free_index(self) -> int: return self._get_sleep_memory...
The code initializes an object by setting up a dictionary (`self.elements`) that maps element names to their starting indices. It starts at `ELEMENTS_OFFSET`, reads `num_elements` entries, and populates the dictionary by fetching each element's name and size, then incrementing the index by the element's size. If `reset...
def __init__(self, reset: bool = False) -> None: if reset: self.reset() free_index = self._get_free_index() num_elements = self._get_num_elems() if free_index < ELEMENTS_OFFSET: self._set_free_index(ELEMENTS_OFFSET) self.elements = {} index = EL...
def initialize_tf_session(): """ initialize tf InteractiveSession. you can call this multiple times initialize_all_variables -- this will initialize """ global SESSION if SESSION: logging.getLogger(__name__).warn("Closing existing Tensorflow session.") SESSION.close() logging....
This function evaluates a given term or formula using a TensorFlow session. It initializes the session if needed, parses and builds the input, computes feed data, and returns the result of executing the computation graph.
def ask(term_or_formula,feed_dict={}): global SESSION if SESSION is None: initialize_tf_session() _t = None try: _t=_build_formula(_parse_formula(term_or_formula)) except: pass try: _t=_build_term(_parse_term(term_or_formula)) except: pass if _t is...
def initialize_tf_session(): """ initialize tf InteractiveSession. you can call this multiple times initialize_all_variables -- this will initialize """ global SESSION if SESSION: logging.getLogger(__name__).warn("Closing existing Tensorflow session.") SESSION.close() logging....
The function evaluates a list of terms or formulas using a TensorFlow session. It initializes the session if needed, parses each input into a computable form, handles exceptions during parsing, and executes the computations with provided feed data, returning the results.
def ask_m(terms_or_formulas,feed_dict={}): global SESSION if SESSION is None: initialize_tf_session() _ts=[] for term_or_formula in terms_or_formulas: _t = None try: _t=_build_formula(_parse_formula(term_or_formula)) except: pass try: ...
def prep_folders(): if not isdir(PARENT_OUT_FOLDER): mkdir(PARENT_OUT_FOLDER) if not isdir(join(PARENT_OUT_FOLDER, REPORT_FOLDER)): mkdir(join(PARENT_OUT_FOLDER, REPORT_FOLDER)) def get_report_dataframe(report, fights): filename = join(getcwd(), PARENT_OUT_FOLDER, report.get_id_string() + '....
The main task of the code is to generate a comprehensive raid report by fetching data from World of Warcraft's API, including boss kills, raid progression, and Raider IO rankings. It checks for boss kills, prepares data structures, creates a dataframe, retrieves rankings, and constructs a report. If no kills are found,...
def report(): report = models.Report(wcl_api.get_newest_report_json('My Dudes', 'tichondrius', 'us')) fights = models.Fights(wcl_api.get_fights_json(report)) if len(fights.kills) == 0: return "No boss kills found for report: {}".format(report.url) prep_folders() df = get_report_dataframe(r...
def apply_svm(self): target_column = self.target_entry.get() try: # Assuming df is the DataFrame with the loaded data if not self.df.empty and target_column in self.df.columns: # Split the data into features and target X = self.df.drop(target_colum...
The main task of the code is to validate a classification model by selecting a target column and algorithm (e.g., Logistic Regression, Naive Bayes, SVM, DT), executing the corresponding classification process, and displaying results like confusion matrices, classification reports, and accuracy. It ensures the target co...
def validate_classification(self): target_column = self.target_entry.get() algorithm = self.algorithm_var.get() if target_column in self.df.columns: print(f"Target column: {target_column}") print(f"Selected algorithm: {algorithm}") # Check the selected algori...
def display_data(self, df): # Clear previous data in the main table self.data_table.delete(*self.data_table.get_children()) # Update columns in the main table self.data_table["columns"] = tuple(df.columns) for col in df.columns: self.data_table.heading(col, text=col)...
This code handles missing data in a DataFrame based on the specified action (mean, median, or drop). It fills missing values using statistical methods or drops rows with missing data. If categorical variables cause errors during filling, it prompts the user to apply one-hot encoding first. After processing, it updates ...
def handle_cleanup_action(self, action): success = False # Assuming df is the DataFrame with the loaded data if action == "mean": try: self.df.fillna(self.df.mean(), inplace=True) print("Filled missing values with mean.") success = True...
def hide_test2_button(self): self.test2_btn.pack_forget() def handle_cleanup_action(self, action): success = False # Assuming df is the DataFrame with the loaded data if action == "mean": try: self.df.fillna(self.df.mean(), inplace=True) print(...
The code initializes a GUI for a machine learning application, setting up data tables, visualization tools, and buttons for tasks like uploading data, data cleanup (dropping columns, handling missing values), one-hot encoding, and classification (supervised/unsupervised). It also includes navigation, result displays, a...
def __init__(self, master): self.master = master self.df = pd.DataFrame() # Initialize an empty DataFrame # Attributes to store canvas and toolbar references self.tree = ttk.Treeview(self.master, columns=("Category", "Value"), show="headings") self.tree.heading("Categor...
def ifSolvable(initialState): blankPosition = 0 inversion = 0 temp = copy.deepcopy(initialStateASCII) y = len(initialState) for x in range(0, y): #record blank square position if (initialState[x] == ' '): blankPosition = x temp.pop(0) continue ...
The main task of the code is to perform a breadth-first search (BFS) on a puzzle state. It checks if the initial state is solvable, converts it to a graph node, initializes a queue for node expansion, tracks created nodes, and invokes a supporting BFS function. If unsolvable, it outputs an error. The code manages globa...
def bfs (): global id global numCreated, numExpended #Create a queue of expanded nodes queue = [] if (ifSolvable(initialState)): if (len(initialState) == 0): print ('The list is empty') else: p1 = convertToGraph(initialState) queue.append(p1.ident...
def ifSolvable(initialState): blankPosition = 0 inversion = 0 temp = copy.deepcopy(initialStateASCII) y = len(initialState) for x in range(0, y): #record blank square position if (initialState[x] == ' '): blankPosition = x temp.pop(0) continue ...
The main task of the code is to implement a depth-first search (DFS) algorithm to solve a puzzle. It checks if the initial state is solvable, constructs a graph representation, uses a stack for traversal, tracks created nodes via global variables, and handles unsolvable cases by reporting errors. The DFS proceeds via a...
def dfs (): global numCreated, numExpended stack = [] if (ifSolvable(initialState)): if (len(initialState) == 0): print ('the list is empty') else: p1 = convertToGraph(initialState) stack.append(p1.identity) report.append(p1) ...
def ifSolvable(initialState): blankPosition = 0 inversion = 0 temp = copy.deepcopy(initialStateASCII) y = len(initialState) for x in range(0, y): #record blank square position if (initialState[x] == ' '): blankPosition = x temp.pop(0) continue ...
The code implements the Greedy Best-First Search (GBFS) algorithm for solving a puzzle. It checks if the initial state is solvable, initializes a priority queue with the start node using a heuristic, tracks created/expanded nodes globally, and calls a support function to execute the search. If unsolvable, it reports fa...
def gbfs(): global numCreated, numExpended, solution pq = PriorityQueue() q = [] if (ifSolvable(initialState)): if (len(initialState) == 0): print ('the list is empty') else: p1 = convertToGraph(initialState) pq.put([heuristicCalc(p1.state, goalStat...
def ifSolvable(initialState): blankPosition = 0 inversion = 0 temp = copy.deepcopy(initialStateASCII) y = len(initialState) for x in range(0, y): #record blank square position if (initialState[x] == ' '): blankPosition = x temp.pop(0) continue ...
The code implements the A* algorithm to solve a puzzle by initializing a priority queue with the start state's heuristic value, checking solvability, and invoking a helper function for the search process. It tracks node creation/expansion counts, maintains a report of explored nodes, and handles unsolvable cases by rep...
def astar(): global numCreated, numExpended, pqA, solution pqA = PriorityQueue() if (ifSolvable(initialState)): if (len(initialState) == 0): print ('the list is empty') else: p1 = convertToGraph(initialState) pqA.put([heuristicCalc(p1.state, goalStat...
def _read_from_db(self): p_key = self.issues_meta.get("db_partition_key") items_total = [] for lang in self.languages: items = self.db.get({ "key": { "name": "language", "value": lang ...
The code reads issues from a database, processes each issue's metadata, renders templates with dynamic variables, and writes generated markdown files to a destination directory organized by language. It also logs progress and handles template rendering errors by skipping unsupported files.
def run(self): log.debug("Reading issues from DB:\n{}".format(",".join(self.languages))) issues = self._read_from_db() log.debug("Finished reading DB") tmpl_vars = {} for issue in issues: tmpl_vars.update({ "time": issue.get("updated_date"...
def surround(self, row, col): '''Returns a list of coordinates that surround the the given input and the number of mines surrounding the given input''' temp = [] num = 0 for i in range(-1, 2): for j in range(-1, 2): if row + i <= self.rows - 1 and row + i >= 0...
This function determines a move in a grid-based puzzle (likely Minesweeper) by analyzing surrounding cells. It collects logical expressions from neighboring numbers, simplifies them to infer mine placements, and triggers solving actions if deductions are possible. It returns True if a move was made, otherwise False.
def get_move_for_unknown(self, row, col): moved = False expressions = [] all_surround = set() for i in range(-1, 2): for j in range(-1, 2): if row + i <= self.rows - 1 and row + i >= 0 and col + j <= self.columns - 1 and col + j >= 0 and isinstance(self.grid[r...
def is_get_movable(self, row, col): if self.grid[row][col].hidden is False and isinstance(self.grid[row][col], Number): for i in range(-1, 2): for j in range(-1, 2): if row + i <= self.rows - 1 and row + i >= 0 and col + j <= self.columns - 1 and col + j >= 0 and ...
This function determines if a move can be made on a cell at (row, col) by checking if it's movable. If so, it calculates possible mine configurations and resolves the cell if solved. If not, it checks for unknowns adjacent to numbers and handles them. Returns True if a move was made, False otherwise.
def get_move(self, row, col): moved = False if self.is_get_movable(row, col): surround, n_mines = self.surround(row, col)[0], self.surround(row, col)[1] #print("surround: " + str(surround) + " mines placed: " + str(n_mines)) t = self.get_all_combos_unsimplified(surrou...
def find_border_unknowns(self): unknowns = [] for row in self.grid: for col in row: if self.is_unknown_next_to_number(int(col.x), int(col.y)): unknowns.append(col) return self.sort_border_unknows(unknowns) def get_move_for_unknown(self, row, col): ...
The code recursively processes a puzzle by identifying border unknowns, checking if moves can be made, and printing the grid when a move is valid. It tracks hidden and flagged cells, and if their counts remain unchanged, returns False to signal no progress. The function continues recursively until no new moves are poss...
def recursive_unknown_solve(self, hidden, flagged): last = self.find_border_unknowns() if len(last) > 0: #might not be needed for block in last: if self.get_move_for_unknown(int(last[0].x), int(last[0].y)) == True: self.print_grid() hid, flag = sel...
def is_game_won(self): for row in self.grid: for block in row: if isinstance(block, Mine) and block.hidden != block.flagged: return False return True def find_border_numbers(self): nums = [] for row in self.grid: for col in row:...
This recursive function attempts to solve a Minesweeper-like puzzle by iteratively checking border numbers for valid moves, printing the grid when a move is made, and invoking another solver method if no progress is detected. It tracks hidden cells and flags to prevent infinite loops, recursively proceeding until the g...
def recursive_solve(self, hidden=99, flagged=0): #TODO stop from checking from numbers that have already been solved could create a set containing all solved numbers see if change made by keeping track of flagged and hidden if self.is_game_won() == True: return nums = self.find_b...