dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def userValue(): try: value = int(promptAgain('userVal')) if (value > 4): print("Please Enter Number less than 4") return userValue() elif (value == 0): print("Please Enter a Number from 1 to 4") return userValue() return value exce...
The main task of the code is to validate and insert a user-provided number into a specific cell of a matrix (likely a Sudoku grid), ensuring it doesn't duplicate in the row, column, or 3x3 subgrid. If invalid, it recursively prompts the user until a valid number is entered, handling non-numeric inputs with error messag...
def getValue(matrix, x, y): try: askUserValue = userValue() if not checkDuplicate(matrix, x, y, askUserValue, 'row') and \ not checkDuplicate(matrix, x, y, askUserValue, 'col') and \ not checkDuplicate(matrix, x, y, askUserValue, 'subgrid'): matrix[int(x)][int(y)]...
def getAvailableCoordinates(): all_coordinates = set((i, j) for i in range(4) for j in range(4)) used_coordinates = set(coords for cage, _ in cages for coords in cage) available_coordinates = all_coordinates - used_coordinates sorted_coordinates = sorted(list(available_coordinates)) return sorted_co...
The main task of the code is to collect user inputs for cage coordinates in a puzzle, validate them against available positions, format the inputs into tuples, calculate their corresponding sums, and store them in a list for further processing. It repeatedly prompts the user until they confirm by pressing Enter, ensuri...
def getCageInput(): availableCoords = getAvailableCoordinates() print("FORMAT: (row, col)") print("Available coordinates: ", availableCoords) print("NOTE: Just press Enter to close the cage prompt.") cage_sets = [] while True: cages_input = cagePrompt(availableCoords) if cages_in...
def height_func(args, values): result = 0 for arg in args: if is_true(arg, values): result += 1 return result def find_neighbors(args, value): n = len(value) neighbor_heights = [0] * n neighbors = [] for i in range(n): new_value = value.copy() new_value[i]...
The function selects a successor node based on neighbor heights, favoring higher elevations by weighting choices proportionally to height differences. If no higher neighbors exist, it randomly generates a new position unless already at maximum height, in which case it retains the current value.
def choose_successor(args, value): choices = [] k = len(args) current_height = height_func(args, value) neighbors, neighbor_heights = find_neighbors(args, value) l = len(neighbors) # print(neighbor_heights) for i in range(l): if neighbor_heights[i] >= current_height: choi...
def getTerritories(self): return self.territories.values() def getLocation(self, loc, direction = STILL): return self.getLocationXY(loc.x, loc.y, direction) def getSite(self, l, direction = STILL): #logger.debug("getSite") l = self.getLocation(l, direction) #logger.debug("getSite found location %s" % l) ret...
This code identifies frontier locations for each territory by checking adjacent unowned sites. It iterates through each territory's locations, examines four cardinal directions, and adds neighboring unowned sites to the territory's fringe list. If any unowned adjacent sites are found, the original location is marked as...
def defineTerritories(self): for t in self.getTerritories(): for loc in t.territory: frontier = False for dir in CARDINALS: new_loc = self.getLocation(loc, dir) new_site = self.getSite(new_loc) if new_site.owner == 0: frontier = True #logger.debug("New fringe: %s" % new_loc) ...
def list_time_zone(): """ Get all timezones from the timezonedb API /list-time-zone endpoint The API returns a list of time zones in this format: [{ "countryCode":"AD", "countryName":"Andorra", "zoneName":"Europe/Andorra", "gmtOffset":7200, "dst": False },......
The main task of the code is to import timezone data from the TimeZoneDB API into a database, handling errors, truncating existing tables, and inserting new records with timestamps. It uses temporary tables to track import time, avoids duplicates by checking existing entries, and ensures only new data is added to the "...
def populate_data(connection): """ Import data from the TimeZoneDB API into the connected database """ cursor = connection.cursor() # Get timezones time_zones, time_zones_error = list_time_zone() TZDB_TIMEZONES_entries = time_zones # Recoverable error if time_zones_error: l...
def generate_ending_response(user_input, thanks=False): """ Generate a response for ending the conversation. Args: user_input (str): User input message. thanks (bool, optional): Whether to include thanks in the response. Defaults to False. Returns: str: Generated response for e...
The code processes user input to generate context-aware responses, managing conversation states (e.g., feeling, cause, solution) and handling various scenarios like greetings, thanks, or ending dialogues. It classifies inputs, detects out-of-context queries, and uses helper functions to maintain flow, ensuring appropri...
def generate_response(user_input): """ Preprocess the user_input & Generate a response based on the user input and the current conversation context. Args: user_input (str): User input message. Returns: str: Generated response based on the conversation context, loop and user input. ...
def dijkstra_planning(sx, sy, gx, gy, ox, oy, reso, rr): """ gx: goal x position [m] gx: goal x position [m] ox: x position list of Obstacles [m] oy: y position list of Obstacles [m] reso: grid resolution [m] rr: robot radius[m] """ nstart = Node(round(sx / reso), round(sy / reso), ...
The main task of the code is to implement path planning using Dijkstra's algorithm to navigate from a start to a goal position in a grid with obstacles, then apply Dynamic Window Approach (DWA) control to follow the generated path while avoiding obstacles. The code visualizes the path, obstacles, and robot trajectory i...
def main(): print(__file__ + " start!!") #Dijkstra # start and goal position sx = 1.0 # [m] sy = 1.0 # [m] gx = 8.0 # [m] gy = 8.0 # [m] grid_size = 1.0 # [m] robot_size = 1.0 # [m] ox = [5] oy = [5] for i in range(12): ox.append(i) oy.append(0.0...
def dwa_control(x, u, config, goal, ob): # Dynamic Window control dw = calc_dynamic_window(x, config) u, traj = calc_final_input(x, u, dw, config, goal, ob) return u, traj def motion(x, u, dt): # motion model x[2] += u[1] * dt x[0] += u[0] * math.cos(x[2]) * dt x[1] += u[0] * math.si...
The main task of the code is to navigate a mobile robot from an initial position to a specified goal while avoiding obstacles using the Dynamic Window Approach (DWA) algorithm. The code simulates the robot's trajectory, updates its motion based on control inputs, checks for goal arrival, and visualizes the path, obstac...
def main(): print(__file__ + " start!!") # initial state [x(m), y(m), yaw(rad), v(m/s), omega(rad/s)] x = np.array([0.0, 0.0, math.pi / 8.0, 0.0, 0.0]) #x = np.array([-1.0, 1.0, math.pi / 8.0, 0.0, 0.0]) # goal position [x(m), y(m)] goal = np.array([10, 10]) #goal = np.array([11, 9]) # o...
def _matrix_to_paulis(self): """ Convert matrix to paulis, and save it in internal property directly. Note: Conversion from Paulis to matrix: H = sum_i alpha_i * Pauli_i Conversion from matrix to Paulis: alpha_i = coeff * Trace(H.Pauli_i) (dot product of trace) ...
This method converts between different representations of quantum operators (Paulis, grouped Paulis, matrix) based on specified input and output formats. It validates formats, skips conversion if the output already exists (unless 'force' is True), and uses internal methods to perform the actual conversion between forma...
def convert(self, input_format, output_format, force=False): """ A wrapper for conversion among all representations. Note that, if the output target is already there, it will skip the conversion. The result is stored back into its property directly. Args: input_forma...
def _matrix_to_paulis(self): """ Convert matrix to paulis, and save it in internal property directly. Note: Conversion from Paulis to matrix: H = sum_i alpha_i * Pauli_i Conversion from matrix to Paulis: alpha_i = coeff * Trace(H.Pauli_i) (dot product of trace) ...
This method ensures the specified operator representation exists by converting from available representations (paulis, grouped_paulis, or matrix) if needed. It validates the input type, checks for existing data, and triggers conversion methods when the target representation is missing, raising errors for invalid inputs...
def _check_representation(self, targeted_represnetation): """ Check the targeted representation is existed or not, if not, find available represnetations and then convert to the targeted one. Args: targeted_representation (str): should be one of paulis, grouped_paulis and ma...
def _eval_directly(self, quantum_state): self._check_representation("matrix") if self._dia_matrix is None: self._to_dia_matrix(mode='matrix') if self._dia_matrix is not None: avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2) else: avg = ...
The function evaluates quantum circuits using three methods based on input and backend: (1) Direct inner product with a numpy array, (2) Statevector simulation for exact results, or (3) Quantum backend execution to compute measurement mean and standard deviation. It returns the average and standard deviation of the eva...
def eval(self, operator_mode, input_circuit, backend, execute_config={}, qjob_config={}): """ Supporting three ways to evaluate the given circuits with the operator. 1. If `input_circuit` is a numpy.ndarray, it will directly perform inner product with the operator. 2. If `backend` is a s...
def reorder_paulis(self, grouping=None): """ Reorder the pauli terms according to the specified grouping. Args: grouping (str): The name of the grouping, currently supports 'random' and 'default'. 'random' corresponds to the order of Operator.paulis; ...
The main task of the code is to simulate the time evolution of a quantum state under a given Hamiltonian, using either matrix exponentiation or quantum circuit construction. It supports Trotter and Suzuki expansion methods for approximating the evolution, with options for Pauli term grouping and time slicing. The funct...
def evolve(self, state_in, evo_time, evo_mode, num_time_slices, quantum_registers=None, paulis_grouping='random', expansion_mode='trotter', expansion_order=1): """ Carry out the dynamics evolution for the operator under supplied specifications. Args: state_in: The ini...
def payOff(item, sri): sri=sri[0] return (C_item_sri(item, sri)) / sup(item) def hasValue(lst, mem): for node in lst: if(Node.__getValue__(node)==mem): return True return False def supressInTree(node, layer, item): childrenArr=[] if(layer>=0): for child in Node.__getC...
The code suppresses rules in a tree structure that violate p-uncertainty by iteratively selecting items with maximum payoff, removing corresponding rules, updating the window, and accumulating suppression loss. It processes rules of increasing size until none remain, returning the total loss.
def suppress(root,window): window = window[0] root=root[0] #pointer i = 1 loss = 0 while(True): sriT = Node.getSRi([root], i) #all rules of size i+1 if (len(sriT) == 0): break sri = filter(violatesP, sriT) #return all rules that violates p-uncertinty s...
def payOff(item, sri): sri=sri[0] return (C_item_sri(item, sri)) / sup(item) def hasValue(lst, mem): for node in lst: if(Node.__getValue__(node)==mem): return True return False def supressInTree(node, layer, item): childrenArr=[] if(layer>=0): for child in Node.__getC...
The main task of the code is to iteratively suppress items in a tree structure to maintain p-uncertainty constraints. It identifies rules violating these constraints, selects the item with the minimum payoff in those rules, suppresses it in the tree and window, and accumulates suppression costs in 'loss'. The process r...
def suppressMin(root,window): window = window[0] root=root[0] #pointer i = 1 loss = 0 while(True): sriT = Node.getSRi([root], i) #all rules of size i+1 if (len(sriT) == 0): break sri = filter(violatesP, sriT) #return all rules that violates p-uncertinty ...
def trim(s: str) -> str: s = s.strip(' \n.') return s def p1(inv: Inverse): bfs : List[str] = ['shiny gold'] i = 0 while i < len(bfs): b = bfs[i] i += 1 if b not in inv: continue for b2 in inv[b]: if b2 not in bfs: bfs.append(b2...
The code parses a text file to build a graph of bag relationships, where each bag points to the bags it contains. It then constructs an inverse graph to determine which bags can contain each bag. The `p1` function likely computes the number of distinct bags that can contain a specific bag, while `p2` calculates the tot...
def main(): with open('d07/input.txt') as f: inv : Inverse = {} for line in f.readlines(): a, bs = line.replace('bags', ''). replace('bag', '').split('contain') a = trim(a) inv[a] = [] graph[a] = [] for b in bs.split(','): b...
def _getsymlink(self, dangling=True): """create a symlink""" fh, fname = self._getfile() os.close(fh) if dangling: os.unlink(fname) sname = fname + ".symlink" os.symlink(fname, sname) self.rmfiles.append(sname) return fname, sname def _checkDep...
This test case verifies the behavior of deprecated symlink operations, checking error handling when listing/removing extended attributes (xattrs) on symlinks versus their targets. It ensures deprecated functions raise EnvironmentError when used on symlinks, confirms xattrs are only visible on targets, and validates pro...
def testSymlinkOpsDeprecated(self): """test symlink operations (deprecated functions)""" _, sname = self._getsymlink() self.assertRaises(EnvironmentError, xattr.listxattr, sname) self._checkDeprecated(sname, symlink=True) target, sname = self._getsymlink(dangling=False) x...
def _getsymlink(self, dangling=True): """create a symlink""" fh, fname = self._getfile() os.close(fh) if dangling: os.unlink(fname) sname = fname + ".symlink" os.symlink(fname, sname) self.rmfiles.append(sname) return fname, sname def _checkLis...
This test function verifies extended attribute (xattr) operations on symbolic links (symlinks). It checks error handling when listing xattrs on symlinks, validates setting/getting xattrs on symlinks with/without namespaces, and confirms that xattrs on the symlink target differ from those on the symlink itself. It also ...
def testSymlinkOps(self): """test symlink operations""" _, sname = self._getsymlink() self.assertRaises(EnvironmentError, xattr.list, sname) self._checkListSetGet(sname, symlink=True) self._checkListSetGet(sname, symlink=True, use_ns=True) target, sname = self._getsymlink...
def reset_variables(self): self.player_contours = None self.top_players = None self.players = None self.infield_contours = None self.top_infield = None self.infield = None self.infield_cnrs = None self.positions = [] self.expectedPositions = [] d...
The code processes an image to identify and track players' positions on a field. It converts the image to HSV, applies color masks to detect field/dirt, locates bases and players via contours, calculates ideal positions, and returns each player's bottom point with their assigned position. The process resets variables, ...
def process_image(self, image, angle): '''Main image processing routine 1. Reset all central class variables to make sure the last image's processing data is cleared out 2. Convert color from BGR to HSV 3. Find all the pixels in the image that are a specific shade of green or br...
def tractor_beam(arr, k, iterations: Optional[int] = None, intermediate_steps: Optional[int] = None, darkness: bool = False): iterations = iterations or 10000 intermediate_result_steps = intermediate_steps or (iterations + 1) prob_matr = get_probability_matrix(arr, darkness) prev_shape ...
The code generates stippled images from an input array by creating nodes via the tractor_beam function. It saves the stippled image, a TSP file for pathfinding, and optionally a timelapse GIF of intermediate steps. Output is stored in a directory named with parameters like k and filename. The function returns the gener...
def stippling(im_arr: np.ndarray, k: int, filename: str, out_dir: str, iterations: Optional[int], steps: Optional[int], darkness: bool = False): nodes, intermediate_nodes = tractor_beam(im_arr, k, iterations, steps, darkness) output_directory: str = out_dir + filename.split(".")[0] + "_" + str(k) ...
def __next_train_to_load(self) -> Optional[Train]: for t in self.__trains: if self.__can_load(t): return t def __can_start_loaded_trip(self, train) -> bool: if train.location != self.__origin: return False if train.status != TrainStatus.WAITING_IN_QUEUE: ...
The function generates a sequence of events for train operations, including loading, unloading, and trip initiation, based on the current time and train states. It checks conditions for each train to determine applicable events, yielding them as iterators.
def next_events(self, current_time: float = 0.0) -> Iterator[Event]: train_to_load = self.__next_train_to_load() if train_to_load: event = Event(callback=self.__start_loading, callback_args=(train_to_load,), scheduled_time=current_time) ...
def change_fleet_edges(ai_settings, aliens): """Reacts when an alien reaches the edge of the screen.""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets): ...
The function updates alien positions by checking fleet edges and moving aliens. It detects collisions between the ship and aliens, triggering a ship-hit response. It also checks if any aliens reach the screen's bottom, initiating appropriate game responses like ending the game or resetting alien positions.
def update_aliens(aliens, ai_settings, ship, stats, sb, screen, bullets): """ Checks if the fleet has reached the edge of the screen, after which it updates the positions of all aliens in the fleet. """ change_fleet_edges(ai_settings, aliens) aliens.update() if pygame.sprite.spritecollideany...
def check_keydown_events(event, ai_settings, screen, ship, bullets, aliens, stats, sb): 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) ...
This function processes keyboard and mouse events in a game. It checks for quit commands, key presses (calling `check_keydown_events`), key releases (calling `check_keyup_event`), and mouse clicks (triggering `check_play_button` with mouse coordinates). It manages user interactions to control the game state, ship movem...
def check_events(ai_settings, screen, ship, bullets, aliens, stats, sb, play_button): """Handles keystrokes 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_set...
def p1alpha(self, z): return self.b(z) * self.d(z)/(self.a(z)**3) def a(self, z): return np.sqrt((z/self.std_1)**2 + (1/self.std_2)**2 ) def p1beta(self, z): return norm.cdf(self.b(z)/self.a(z)) - norm.cdf(-self.b(z)/self.a(z))
The code computes a probability density function (PDF) by combining two components: a product of a prefactor involving standard deviations and `p1alpha(z)`, multiplied by the derivative of a cumulative distribution function (`p1beta(z)`), plus an additional term with an exponential decay factor and parameters related t...
def pdf(self, z): prefac = self.p1alpha(z) * 1/(np.sqrt(2 * np.pi) * self.std_1 * self.std_2) add_term = 1./(self.a(z)**2 * np.pi * self.std_1 * self.std_2) * np.exp(-self.c/2.) diff_cdf = self.p1beta(z) return prefac * diff_cdf + add_term
def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ #raise NotImplementedError #Checking available actions from Board pos=[] for i , row in enumerate(board): for j , col in enumerate(row): if col == None: pos.app...
The code implements a minimax algorithm with alpha-beta pruning for a two-player game (e.g., Tic-Tac-Toe). It evaluates optimal moves for a given player (AI) by recursively analyzing all possible board states, prioritizing terminal states with utility values. The function alternates between maximizing (AI's goal) and m...
def fighter(board,AI): #Checking AI if AI == X: NAI = O else: NAI = X #Checking Move ans =[] pos=list(actions(board)) for move in pos : Nb=result(board,move) #If Game Not End the Fighter(Recursed) with New Board if terminal(Nb) is False: an...
def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ #raise NotImplementedError #Checking available actions from Board pos=[] for i , row in enumerate(board): for j , col in enumerate(row): if col == None: pos.app...
The function `optimise` determines the optimal moves for a given AI player (X or O) in a game by evaluating all possible next moves using a minimax algorithm. It generates potential moves, recursively assesses their outcomes (via `fighter` or `utility`), and selects moves that maximize/minimize the AI's advantage based...
def optimise(board,AI): #check AI if AI == X: NAI = O else: NAI = X #List for inculcating Moves and Their Min-Max Value ans = [] #Available Option pos=list(actions(board)) #Checking Move for move in pos : Nb=result(board,move) #If Game Doesn't End Then...
def get_fps_games_indexes(file_name): genre_list = create_genre_list(file_name) fps_game_indexes_list = [] for i in range(len(genre_list)): if genre_list[i] == 'First-person shooter': fps_game_indexes_list.append(i) return fps_game_indexes_list def create_sales_list(file_name): t...
The function `when_was_top_sold_fps` determines the production year of the top-selling FPS (First-Person Shooter) game from a dataset. It retrieves indexes of FPS games, extracts sales data and production years, identifies the highest sales value among FPS games, and returns the production year corresponding to that pe...
def when_was_top_sold_fps(file_name): fps_games_indexes_list = get_fps_games_indexes(file_name) sales_list = create_sales_list(file_name) production_year_list = create_production_year_list(file_name) fps_sales_list = [] if fps_games_indexes_list: for i in fps_games_indexes_list: ...
def check_unspents(self): if self.missing_unspents(): raise ValueError("wrong number of unspents. Call unspents_from_db or set_unspents.") def is_signature_ok(self, tx_in_idx, flags=None, traceback_f=None): tx_in = self.txs_in[tx_in_idx] if tx_in.is_coinbase(): return Tru...
The main task of the code is to sign a standard blockchain transaction by iterating through its inputs, using a hash160_lookup dictionary to retrieve private keys and signing each non-coinbase, non-pre-signed input with the specified hash type (defaulting to SIGHASH_ALL). It skips already-signed inputs and handles erro...
def sign(self, hash160_lookup, hash_type=None, **kwargs): """ Sign a standard transaction. hash160_lookup: A dictionary (or another object with .get) where keys are hash160 and values are tuples (secret exponent, public_pair, is_compressed) or None (in which c...
def has_witness_data(self): return any(len(tx_in.witness) > 0 for tx_in in self.txs_in) def missing_unspents(self): if self.is_coinbase(): return False return (len(self.unspents) != len(self.txs_in) or any(self.missing_unspent(idx) for idx, tx_in in enumerate(self.txs...
This function streams a Bitcoin transaction to a file-like object, serializing its version, inputs, outputs, lock time, and optional witness data or unspent outputs based on parameters.
def stream(self, f, blank_solutions=False, include_unspents=False, include_witness_data=True): """Stream a Bitcoin transaction Tx to the file-like object f.""" include_witnesses = include_witness_data and self.has_witness_data() stream_struct("L", f, self.version) if include_witnesses: ...
def get_tag(self) -> str: """ Get a tag of the current node. If ignore_namespace is True then namespace will be removed from a tag. :return: a tag """ tag = self.node.tag if self.ignore_namespace: tag = re.sub(r'{[^}]+}', '', tag) ...
The main task of the code is to convert data from an XML element tree into a Python dictionary. It retrieves the element's tag, processes child nodes, determines if the node is singular or has children, extracts corresponding values, and returns a dictionary with the tag as the key and extracted data as the value.
def get_dict(self) -> Dict: """ Extract data from xml.etree.ElementTree object which has been passed during initialization of an instance :return: extracted data as a python dict """ tag = self.get_tag() self.child_nodes = self._get_child_nodes() if se...
def check_node_data(self, node_data: Dict) -> bool: if node_data.get("@type") != self.key: return False if "#text" not in node_data: return False return True def get_safe_value(self, node_data: Dict) -> Any: try: value = self.get_value(node_data) ...
The main task of the code is to transform a node's data dictionary by validating it, handling errors (if enabled), setting the '#text' field using either a safe or direct value retrieval method, removing type information, and returning the modified node data.
def transform_node(self, node_data: Dict) -> Dict: if self.check_node_data(node_data): if self.ignore_errors: node_data['#text'] = self.get_safe_value(node_data) else: node_data['#text'] = self.get_value(node_data) node_data = self.remove_type_...
def enableAll(self): self.convertVideoButton.setEnabled(True) self.convertVideoButton.setStyleSheet(style_sheet.allPushButtonEnableSS) self.loadConfigButton.setEnabled(True) self.loadConfigButton.setStyleSheet(style_sheet.allPushButtonEnableSS) self.saveConfigButton.setEnabled(Tr...
The main task of the code is to open a file dialog for selecting a video file, validate the selection, set the video file path, enable UI components, initialize a video object, and delete an existing thumbnail. It handles user input for video file selection and updates the application state accordingly.
def selectVidFile(self): self.fileName, status = QtWidgets.QFileDialog.getOpenFileName(self, "Open Video File", r"", f"Video File({self.extensions})") if status: self.vidFile = os.path.normpath(self.fileName) s...
def clean_dirs(): for dir in ['dist', 'build']: shutil.rmtree(dir, ignore_errors=True) for egg in get_files_ext('.egg-info'): shutil.rmtree(egg) def check_installed_tools(): if os.system('pip freeze | grep twine > /dev/null'): print('twine not installed.\n\tUse `pip install twine`') ...
The function `wheel()` performs three main tasks: cleaning specified directories, verifying the presence of required tools, and constructing a wheel package. This sequence ensures a prepared environment for building the wheel, checking dependencies, and generating the final package.
def wheel(): clean_dirs() check_installed_tools() build_wheel()
def wheel(): clean_dirs() check_installed_tools() build_wheel() def comfirme_publish_version(): __init__ = import_module(find_packages()[0]) yesNo = input("do you want to publish version: {} to pypi ? [Y/n]".format(__init__.__version__)) if yesNo.lower() in ['', 'y', 'yes']: return e...
The main task of the code is to publish a Python package by generating a wheel file, confirming the version to be published, uploading the wheel to a repository, and printing Git tag information for version tracking.
def publish(): wheel() comfirme_publish_version() upload_wheel() print_git_tag_info()
def Remove(duplicate): final_list = [] for num in duplicate: if num.strip() not in final_list: final_list.append(num.strip()) return ', '.join(final_list) def read_input_values(provider_id,street,city,state): results = {} results[provider_id] = {} metadata_type = "mail_addres...
The code checks a given tax ID (EIN) by querying a database via an AJAX POST request. It retrieves company details like name, EIN number, address, and phone, parses the address components (street, city, state, ZIP), validates the address using Smarty Streets, and returns the results in JSON format. If no data is found,...
def checktaxid(taxid): headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36', 'x-requested-with': 'XMLHttpRequest' } myquery = '' url = 'https://eintaxid.com/search-ajax.php' if len(taxid) < 2...
def scrapeESPN(delta=0): #MODE_ACTIVE = 0 #MODE_INACTIVE = 1 req = Request("http://www.espn.com/nba/scoreboard/_/date/" + _returntime(delta)) req.headers["User-Agent"] = UserAgent(verify_ssl=False).chrome # Load data scoreData = urlopen(req).read().decode("utf-8") scoreData = scoreData[sc...
The code generates a live sports ticker string by processing game data from ESPN, checking game statuses (pre, in-progress, post), updating logs, and formatting scores, teams, times, and networks for ongoing or completed games. It skips pre-game matches, handles post-game logs, and appends dynamic ticker entries while ...
def ScoreTickBuilder(): games = scrapeESPN() livetickerstr = '' allgamelog = readlog() for game in games: if game['status'] == GAME_STATUS_PRE: continue elif game['status'] == GAME_STATUS_POST: for log in allgamelog: if log[0] == game['tid1'] or lo...
def spawn(): temp = [['ro', [0, 7], False], ['kn', [1, 7], False], ['bi', [2, 7], False], ['ki', [3, 7], False], ['qu', [4, 7], False], ['bi', [5, 7], False], ['kn', [6, 7], False], ['ro', [7, 7], False], ['pa', [0, 6], False], ['pa', [1, 6], False], ['pa', [ 2, 6], False], ['pa', [3, 6]...
The code implements a turn-based game where players alternate making moves on a board. It handles user input for commands like 'help' and 'focus [position X] [position Y]', validates inputs, updates the game state via the `focus()` function, and switches turns between "White" and "Blue" players. The game loop displays ...
def main(): commands = ['help', 'focus [position]'] player = True spawn() while True: print(tableBuilder()) if player: print("\033[92m" + "Player: White" + "\u001b[37m") else: print("\033[92m" + "Player: Blue" + "\u001b[37m") while True: ...
def return_piece_at_location(loc, board): return board[loc[0]][loc[1]] def get_piece_color(piece_position, board): white_pieces = range(1, 7) black_pieces = range(7, 13) piece_type = return_piece_at_location(piece_position, board) if piece_type in white_pieces: return 'white' elif piece_...
The function generates all possible moves for a specified player's pieces on a chessboard. It iterates through each piece, checks if it matches the given color, identifies the piece type, and calls the corresponding move-generating function (e.g., pawn, knight, bishop). Results are stored in a dictionary mapping piece ...
def get_possible_moves(board, color): move_list = {} for row_idx, row in enumerate(board): for p_idx, piece in enumerate(row): piece_index = (row_idx, p_idx) piece_type = return_piece_at_location(piece_index, board) piece_color = get_piece_color(piece_index, board) ...
def get_access_token(refresh_token): res = post(f'{HOST}/api/token', json={"refreshtoken": refresh_token}) if res.status_code != 200: raise RuntimeError(f'ERROR: received a {res.status_code} instead of 200 from /api/token') return res.json() def populate_rows(artist_id): if not os.path.exists(...
The code extracts playlist data for a given artist using a refresh token to maintain access, processes the data to extract emails from descriptions, and appends the results to a CSV file. It continuously refreshes the access token when expired and iterates through playlists until no more are found.
def extract(refresh_token, artist_id): token_response = get_access_token(refresh_token) access_token = token_response['token'] expires_in = int(token_response['expires_in']) expires_at = datetime.utcnow() + timedelta(seconds=expires_in) populate_rows(artist_id) while True: if datetime.u...
def get_text(self, sample): caption_csv = self.get_caption_path(sample) text, start, end, duration = self.get_caption(caption_csv, sample["segment_id"]) encoding = self.tokenizer( text, padding="max_length", truncation=True, max_length=self.max_tex...
The main task of the code is to retrieve and process multimedia data (text, video, and synthetic false data) for a given index, combining them into a structured dictionary. It includes retrying up to 5 times if data retrieval fails, adding false video/text samples, and marking replication status. The result is a dictio...
def get_suite(self, index): result = None max_try = 5 try_time = 0 while result is None: try_time += 1 sample = self.metadata.iloc[index] ret = dict() text, start, end, duration = self.get_text(sample) ret.update(text) ...
def get_video(self, sample): imgs = self.get_raw_video(sample).permute(1, 0, 2, 3) # to cthw imgs_tensor = [self.video_transform(imgs).permute(1, 0, 2, 3)] # to tchw return imgs_tensor def get_text(self, raw_index, sample): text = self._get_caption(sample) encoding = self.token...
The function retrieves a data sample (video and text) from a dataset, retrying with a random index if errors occur. It constructs a dictionary with the video tensor, indices, and text data, adding false video/text entries if specified. The loop ensures successful retrieval before returning the structured result.
def get_suite(self, index): result = None while result is None: # retry_times += 1 sample = self.metadata.iloc[index] # print(sample[1]) try: video_tensor = self.get_video(sample) ret = { "image": video_t...
def initialise(filename): X = {} Y = {} i = 0 f = open(filename, mode = 'r') for review in f: content = json.loads(review) text = content["text"].strip() text_in_lower = text.lower() p_text = re.sub(r'[^\w\s]','',text_in_lower) p_text = re.sub(r'[^\w\s]','',p_...
The main task of the code is to implement a Naive Bayes text classifier using bigram features. It processes training and test datasets, computes log-likelihoods and priors for each class, predicts labels, evaluates accuracy, and saves predictions to an output file. The code focuses on bigram-based feature extraction, m...
def main(): train_filename = sys.argv[1] trainX,trainY = initialise(train_filename) test_filename = sys.argv[2] testX,testY = initialise(test_filename) output_filename = sys.argv[3] # **************** UNCOMMENT TO RUN THE MODEL ON RAW WORDS ***************** # dict,class_occur,class_vocab =...
def get_pos(x, y): s_x = x // gd.square_length s_y = y // gd.square_length return s_x, s_y def get_square(board, pos): x, y = pos if x < 0 or y < 0: return None try: square = board.data[y][x] except IndexError: return None else: return square def toggle_tu...
This function handles a chess piece move by checking if the target position is a valid move for the selected piece. If valid, it updates the board, switches turns, checks for checkmate, highlights the new position, and removes move hints.
def move_piece(board, pos1): x2, y2 = pygame.mouse.get_pos() pos2 = get_pos(x2, y2) piece = get_square(board, pos1).piece if piece: am = piece.get_available_moves(board, pos1) if pos2 in am: board.update_board(pos1, pos2) toggle_turn() display_checkmat...
def get_pos(x, y): s_x = x // gd.square_length s_y = y // gd.square_length return s_x, s_y def turn_all_squares_inactive(board): for col in board.data: for square in col: if square.is_active: square.toggle_active() if square.is_in_danger: s...
This function handles mouse input for moving a game piece on a board. It detects left-click presses to select a valid piece (of the current player's color), highlights available moves, displays a temporary visual during drag, and executes the move when the click is released. It returns status flags and positions to tra...
def move(screen, board, moving, pos1): left_click = pygame.mouse.get_pressed()[0] if left_click: x1, y1 = pygame.mouse.get_pos() if not moving: # left click downpress turn_all_squares_inactive(board) remove_all_squares_hint(board) pos1 = get_pos(x...
def train(args,net,train_loader, optimizer, scheduler, criterion, epoch): losses = AverageMeter() Avgacc = AverageMeter() meanIoU = AverageMeter() net.train() for idx,(images, labels) in enumerate(train_loader): images, labels = images.to(args.device), labels.to(args.device) labels...
The code trains a PSPNet model for semantic segmentation with 150 classes using SGD optimizer and a learning rate scheduler. It loads data, initializes the model, and trains it over multiple epochs, validating performance and saving the best model based on accuracy and IoU. It supports resuming training from a checkpoi...
def main(): args = argparse.ArgumentParser() args = get_arguments() args.num_classes=150 args.save_folder = './save/'+args.arch args.device = torch.device('cpu') if torch.cuda.is_available(): args.device = torch.device('cuda',args.gpu_id) train_loader, val_loader = get_datalo...
def register(msg_received): first_name = msg_received["first_name"] lastname = msg_received["last_name"] username = msg_received["username"] email = msg_received["email"] select_query = "SELECT * FROM users where username = " + "'" + username + "'" db_cursor.execute(select_query) records = ...
The code defines a Flask route handler function `chat()` that processes incoming JSON requests. It checks the "subject" field in the request data and routes the request to corresponding functions like `register()`, `login()`, `verify()`, `send()`, or `receive_chats()` based on the subject value. If the subject is unrec...
def chat(): msg_received = flask.request.get_json() msg_subject = msg_received["subject"] if msg_subject == "register": return register(msg_received) elif msg_subject == "login": return login(msg_received) elif msg_subject == "verify": return verify(msg_received) elif ms...
def to_upper_camel_case(s): return sub(r"(_|-)+", " ", s).title().replace(" ", "") def get_parameters(post_info): '''Returns each parameter and its type in a json dictionary''' if 'parameters' in post_info: return post_info['parameters'][0]['schema']['properties'] return {} def get_endpoint_return_type(endp...
This function generates C# async methods for API endpoints, converting endpoint names to camel case, determining request types (GET/POST), handling parameters, and writing HTTP request code with caching logic to a file. It constructs method signatures, parameter dictionaries, and uses conditional formatting for cached ...
def create_endpoint(f, endpoint, post_info): endpoint_function = to_upper_camel_case(endpoint) params = get_parameters(post_info) endpoint_return_type = get_endpoint_return_type(endpoint) param_list = build_function_params(params) param_dict = build_dict_params(params) print(endpoint_function) print(param...
def build_object_variables(params: dict): ''' Builds the parameters into the public variables of an object Example: public string actor; public string payeePublicKey; public string payerPublicKey; ... ''' var_list = [] for p_name, p_info in params.items(): var = build_param(p_name, p_inf...
This code generates a C# class representing a transaction object, writing it to a file. It constructs the class with fields, a constructor, and methods like GetContract(), GetName(), and ToJsonObject(), using helper functions to process input parameters into variables, assignments, and JSON serialization logic.
def create_transaction_object(f: TextIOWrapper, obj_name: string, params: dict): ''' Creates the object for the transaction with the given name for the provided parameters of that object. ''' # lang_obj_name = to_upper_camel_case(obj_name) if params != None else '' object_vars = build_object_variables(param...
def callsp(spname,args): #print(spname,args) try: with pymssql.connect(server,user,password,database) as conn: with conn.cursor(as_dict=True) as cursor: #cursor = conn.cursor(as_dict=True) cursor.callproc(spname, args) r=[] for ...
The code defines a `click` function handling UI interactions based on coordinate inputs, managing a multi-page system for user authentication (login/signup), data entry (foods/ingredients/meal plans), and database operations via stored procedures. It processes user actions like updating profiles, deleting accounts, nav...
def click(coordinate): global page,username,name,userpassword,startrow x=coordinate.x y=coordinate.y #detect coordinate on canvas and choose event if page==0: if 650<x<750 and 400<y<450: #log in username=simpledialog.askstring(title="username", prompt="input your...
def list_noaagridsatb1_files(dir, suffix='.v02r01.nc', to_remove=['GRIDSAT-B1.','.v02r01.nc']): ''' To scan through the sapecified dir and get the corresponding file with suffix. ''' import os import pandas as pd xfiles = [] for root, dirs, files in os.walk(dir, followlinks=True): # Loop through th...
The code trains a convolutional autoencoder on NOAA-GridSat-B1 netCDF4 data using command-line arguments for configuration. It processes input data, initializes the autoencoder architecture, trains the model for specified epochs with batch processing, and saves the trained model, encoder, and training history. Key task...
def main(): # Configure Argument Parser parser = argparse.ArgumentParser(description='Building convolutional autoencoder .') parser.add_argument('--datapath', '-i', help='the directory containing NOAA-GridSat-B1 data in netCDF4 format.') parser.add_argument('--output', '-o', help='the prefix of output f...
def decideMotion(self, ballCoordinate, selfCoordinate,blue_fw_l,blue_fw_r,redFw): robotHeadingAngle = self.getRollPitchYaw()[2] turningAngle = Functions.calculateTurningAngleAccordingToRobotHeading(ballCoordinate, selfCoordinate, robotHeadingAngle) if turningAngle > 50: return self.motions.turnLe...
The code controls a robot in a soccer simulation, handling tasks like standing up when fallen, responding to opponent ball priority, navigating to the ball within the penalty area, executing shooting motions, returning to a fixed position, and turning. It uses sensor data and predefined motions to adjust the robot's ac...
def run(self): self.printSelf() count_0=0 flag = 0 flag1 =0 fixedCoordinate = [3.1, -0.00573, 0.342] origin = [0.0723,-0.0798,0.0799] goto_Coordinate=[0,0,0] while self.robot.step(TIME_STEP) != -1: if self.isNewBallDataAvailable(): self.getSupervisorData() # Use th...
def parameters(): args = sys.argv reference_name = args[1] reads_name = args[2] seed = int(args[3]) match = int(args[4]) mismatch = int(args[5]) gap = int(args[6]) margin = int(args[7]) if margin > 3 or margin < 0: print('margin has to be 0-3') exit() r...
The main task of the code is to align reads and their complements to a reference genome using FM-index and Burrows-Wheeler (BW) transformations. It processes input parameters, generates alignment indices, computes global alignment scores and edit transcripts for each read, sorts results by alignment quality, and return...
def main(): # ask for input parameters reference_name, reads_name, seed, match, mismatch, gap, margin = parameters() # process reference file reference = read_reference(path + '\\' + reference_name) # extract reads and get their complements reads, complements = return_reads_compl...
def process_scenario(self, sc): result = process_scenario(self.agent, sc, self.preprocess_function) reward = self.reward_function(result, sc) self.agent.reward(reward) return result, reward def process_scenario(agent, sc, preprocess): scenario_metadata = sc.get_ta_metadata() if ...
The code trains an agent on multiple scenarios, collecting performance metrics (rewards, detection rates, etc.), comparing it with heuristic agents if enabled, and optionally saving results, plotting graphs, and running validations. It aggregates statistics per scenario, logs progress, and returns the average NAPFD sco...
def train(self, no_scenarios, print_log, plot_graphs, save_graphs, collect_comparison=False): stats = { 'scenarios': [], 'rewards': [], 'durations': [], 'detected': [], 'missed': [], 'ttf': [], 'napfd': [], 'recall':...
def cli_args() : import argparse parser = argparse.ArgumentParser( add_help = False, description = "Emotet 2019 - Get Configuration Toolkit" ) optional = parser._action_groups.pop() required = parser.add_argument_group("required arguments") required.add_argument( "--sample", "-s", action ...
The main task of the code is to extract Emotet's configuration from a provided sample file by analyzing its PE structure, verifying a Yara signature, and parsing encrypted data. It checks for Emotet's presence, reads the file, processes the configuration using the detected signature, and exits with errors if the signat...
def main() : params = cli_args() print("Emotet 2019 - Get Configuration Tools\n\t by mekhalleh [www.pirates.re]\n") ## Get image base address, Yara signature and show PE informations: print("%s" % ("=" * 40)) pe, signature = pe_info(params.sample) if(not(signature)) : exiting("No known Emotet signature ...
def cli_args() : import argparse parser = argparse.ArgumentParser( add_help = False, description = "Emotet 2019 - Unpacking Payload Toolkit" ) optional = parser._action_groups.pop() required = parser.add_argument_group("required arguments") required.add_argument( "--sample", "-s", action ...
The main task of the code is to unpack a packed PE (Portable Executable) file using a Yara signature to identify the packer. It retrieves PE information, checks for a known packer signature, and if found, unpacks the payload to specified output files. If no valid signature or unsupported packer is detected, the tool ex...
def main() : params = cli_args() print("Emotet 2019 - Unpacking Payload Toolkit\n\t by mekhalleh [www.pirates.re]\n") ## Get image base address, Yara signature and show PE informations: print("%s" % ("=" * 40)) pe, signature = pe_info(params.sample) if(not(signature)) : exiting("No known packer signature...
def run_multiple_times(number_of_times): time_array = [] for i in range(number_of_times): time_array.append(run_me_loop_and_time_it(10000000, 50)) return sum(time_array) / len(time_array) def run_multiple_times_with_printing(number_of_times): time_array = [] for i in range(number_of_times)...
The main task of the code is to benchmark and compare the execution times of different Python implementations (standard, with printing, and using NumPy) against a predefined GO runtime. It calculates and prints speed ratios, showing how many times faster GO is compared to Python variants, highlighting performance diffe...
def main(): avg_time = run_multiple_times(2) avg_time_with_printing = run_multiple_times_with_printing(2) avg_time_numpy = run_multiple_times_numpy(10) time_for_go = 0.003264804569999999 print(f"Python without printing is {avg_time_with_printing / avg_time } times faster than python with printing") ...
def set_mode(self, mode: Union[Mode, int], filter: bool = False): """ Issue 'set_mode' command to MHB8748 :param mode: See :py:class:`Mode`. :param filter: Enable or disable noise filter. """ logger.debug(f'set_mode: mode={mode}, filter={filter}') mode = int(mode...
The code initializes a serial connection to an ADC device, configures its mode by sending repeated commands to exit test mode, verifies communication pathways, performs a calibration measurement, and reverts to the initial mode, ensuring proper device functionality and readiness for data acquisition.
def __init__(self, port: str, skip_init: bool = False, init_mode: Mode = Mode.VDC_150V): logger.info(f'AdcConnection init: port={port}, skip_init={skip_init}') self.p = serial.Serial(port, baudrate=115200) self.p.read_all() if not skip_init: logger.info(f'Set...
def safe_add_all_sockets(self, sockets: list[Socket], notify=False, commit=True): sockets_splitted = split_by_n(sockets, 333) # slqlite has parameter limit of 999 new_hosts_c = 0 total_socks_to_add = 0 total_to_load = len(sockets) total_passed = 0 for sockets in sockets_s...
This function adds servers to a database while avoiding duplicates by checking existing entries via socket IDs. It retrieves existing servers, maps them, and appends only new servers to the database. If an output path is provided, it logs server details there. Returns counts of new IPs, sockets, and added servers.
def safe_add_all_servers(self, servers: list[MServer], output_to: str = ''): servers_to_add: list[MServer] = [] socks: list[Socket] = [s.socket for s in servers] new_ips_c, new_socks_c = self.safe_add_all_sockets(socks) servers_from_db = self.get_servers(socket_id_in=[s.id for s in socks...
def add_ball(self): # Check if a ball already exists and delete it if self.ball is not None: self.ball.delete() paddle_coords = self.paddle.get_position() # Draw the ball in the center of the paddle, (x1+x2)/2 x = (paddle_coords[0] + paddle_coords[2]) * 0.5 self.ball = Ball(self.canvas, x, 310) # "Fix"...
The `setup_game` method initializes game elements by adding a ball, updating lives display, rendering a start instruction text, and binding the spacebar to trigger the game start. It prepares the game state and user interaction for the game to begin.
def setup_game(self): self.add_ball() self.update_lives_text() self.text = self.draw_text(300, 200, 'Press Space to Start') self.canvas.bind('<space>', lambda _: self.start_game())
def terminal(board): """ Returns True if game is over, False otherwise. """ # Game is over when a winner is found or if there are no more possible actions game_is_over = (winner(board) != None) or (len(actions(board)) == 0) return game_is_over def player(board: list): """ Returns player ...
The code implements the minimax algorithm to determine the optimal move for the current player on a tic-tac-toe board. It checks if the game is terminal, returning `None` if so. For non-terminal states, it delegates to `optimize_score` to evaluate possible moves, with `maximize=True` for player 'X' (aiming to maximize ...
def minimax(board): """ Returns the optimal action for the current player on the board. """ if terminal(board): return None if player(board) == X: return optimize_score(board, maximize=True)[1] else: return optimize_score(board, maximize=False)[1]
def crawl(directory): """ Parse a directory of HTML pages and check for links to other pages. Return a dictionary where each key is a page, and values are a list of all other pages in the corpus that are linked to by the page. """ pages = dict() # Extract all links from HTML files for f...
The main task of the code is to compute and display PageRank results for a given corpus using two methods: sampling and iteration. It first validates input, crawls the corpus, calculates PageRank via sampling with a specified number of samples, prints the results, then computes PageRank iteratively and prints those res...
def main(): if len(sys.argv) != 2: sys.exit("Usage: python pagerank.py corpus") corpus = crawl(sys.argv[1]) ranks = sample_pagerank(corpus, DAMPING, SAMPLES) print(f"PageRank Results from Sampling (n = {SAMPLES})") for page in sorted(ranks): print(f" {page}: {ranks[page]:.4f}") ...
def stage1_trigger(): global lock global stage if not lock: stage = 1 # global should_abort lock = True GPIO.output(led1, GPIO.LOW) # sio.start_background_task(sio.emit('stage1_start')) log('---------------------------------------') log('[STAGE 1 Stage 1 Starting...') log('[GPIO] S...
This function handles stage-based operations with a lock mechanism. It checks the global 'stage' variable and triggers corresponding actions: stage 0 calls stage1_trigger(), stage 1 calls stage2_trigger(), and stage 2 calls abort(). The function exits early if 'lock' is True, ensuring mutual exclusion. Debug informatio...
def btn1_event(): global lock global stage print(f'[DEBUG] Lock is {0}, Stage: {1}'.format(lock, stage)) if lock is True: return if stage == 0: stage1_trigger() if stage == 1: stage2_trigger() if stage == 2: abort()
def bech32_decode(bech): """Validate a Bech32 string, and determine HRP and data.""" if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech)): return None, None bech = bech.lower() pos = bech.rfind('1') if pos < 1 or pos + 7 > len(b...
This function tests Bech32 encoding/decoding for BLS secret keys by validating that decoding a Bech32 string produces the correct HRP and data, re-encoding matches the original string, byte conversion matches expected data, and tampered strings (with added/removed/modified characters) correctly fail decoding. It ensure...
def test_bls_bech32(bech32_str, hrp, bytes_data): # test Bech32 encoding/decoding for BLS secret keys h, d = bech32_decode(bech32_str) assert h == hrp assert bech32_str == bech32_encode(h, d) assert bech32_str_to_bytes(bech32_str) == bytes_data assert bech32_decode(bech32...
def train_model(): train, valid, y_train, y_valid, label_index, silence_paths = get_data() rand_silence_paths = silence_paths.iloc[np.random.randint(0, len(silence_paths), 500)] silences = np.array(list(map(load_wav_by_path, rand_silence_paths))) # model = load_model('model.model') # model = get_m...
The main task of the code is to train two models (`train_model` and `train_silence_model`), validate their predictions (`validate_predictions`), and generate final predictions (`make_predictions`) for a machine learning workflow. This sequence likely prepares models for tasks like classification, regression, or audio p...
def main(): train_model() train_silence_model() validate_predictions() make_predictions()
def get_unleashed_service(): api_id = '5abcd551-d6d6-4280-8c56-9e6add21a3ce' api_key = 'pm4ybdmwtfnhczzu1kuw5l0c6tlc4q4k' service = Unleashed.Client(api_key, api_id) return service def get_unleashed_pagination(endpoint, options=None, page=None, service=None): if service is None: service = ge...
The function retrieves all items from a specified endpoint by paginating through all available pages. It initializes a pagination object, determines the total number of pages, and iteratively fetches items for each page, aggregating them into a single list. If no service is provided, it defaults to a predefined service...
def get_unleashed_all_items(endpoint, options=None, service=None): if service is None: service = get_unleashed_service() pagination = get_unleashed_pagination(endpoint, options=options, service=service) number_of_pages, page_number = 0, 0 if pagination is not None and 'NumberOfPages' in paginati...
def splitSubjects(cwd, data_folder, seed, y_ind, test_size, features=20, cycle=True, norm=True, sequence_length=30, signals="all", avg_num_steps=1): #print(signals) path = cwd + '/' + data_folder os.chdir(path) # cd to given data path folders = os.listdir(path) # get folders in path folders.sort() ...
This function loads and splits datasets into training, development, and test sets based on the specified `data_type`. It dispatches to different splitting methods (`splitSubjects`, `splitConditions`, etc.), handling variations in data structure, normalization, sequence length, and other parameters. The output consists ...
def loadData(data_type, cwd, seed, y_ind, train_size, test_size, features, norm, folder_name, sequence_length, signals, avg_num_steps=1): if data_type == "subjects": x_train, y_train, x_dev, y_dev, x_test, y_test = splitSubjects(cwd, folder_name, seed, y_ind, test_size, features, True, norm, seq...
def sfm_pipeline(self, use_noise=False, use_BA=False, draw_config=False, final_vis=False): pts_3d = self.pts_3d K = self.K img_w, img_h = self.img_w, self.img_h pose1, pose2 = self.pose1, self.pose2 x1s = project(pts_3d, K, pose1) x2s = project(pts_3d, K, pose2) ...
The main task of the code is to perform Structure-from-Motion (SfM) by iteratively refining 3D point cloud reconstruction and camera pose estimation. It initializes with initial poses and points, then loops through subsequent camera poses to compute common visible points, project 2D-3D correspondences, and apply PnP ca...
def q10(self): p1, p2, pts = self.sfm_pipeline(draw_config=True, final_vis=True) pts_old, pts, mask = self.filter_pts(p1, p2, pts) # self.visualize_final_view(all_pts, camera_poses) all_pts = pts.copy() camera_poses = [p1, p2] for i in range(2...
def parse_subject(word_list): skip(word_list, 'stop') next_word = peek(word_list) if next_word == 'noun': return match(word_list, 'noun') elif next_word == 'verb': return ('noun', 'player') else: raise ParserError("Expected a verb next.") def parse_verb(word_list): skip(...
The code's main task is to parse a list of words into subject, verb, and object components using helper functions, then construct a Sentence object from these parsed elements.
def parse_sentence(word_list): subject = parse_subject(word_list) verb = parse_verb(word_list) object = parse_object(word_list) return Sentence(subject, verb, object)
def get_files_for_corner_points(self, box, var, timepoint): # retrieve the corner points. corner_points = self.parse_corner_points(box) print(Fore.RED + 'corner_points = self.parse_corner_points(box)') print(Fore.BLACK + '') print(corner_points) databas...
The function recursively splits a spatial box into sub-boxes that map to individual database files. It checks if the box's axis ranges align with a single database file (considering periodic boundaries). If not, it splits the box along the problematic axis, recursively processing each sub-box until all sub-boxes corres...
def recursive_single_database_file_sub_boxes(self, box, var, timepoint, single_file_boxes): db_files = self.get_files_for_corner_points(box, var, timepoint) print(Fore.RED + 'db_files = self.get_files_for_corner_points(box, var, timepoint)') print(Fore.BLACK + '') print(db_files...
def create_hyperlink(link: Link): # <w:hyperlink w:id="rID123"> # <w:r> # <w:rPr> # <w:rStyle w:val="aa"/> # </w:rPr> # <w:t>Description</w:t> # </w:r> # </w:hyperlink> # create external link relationship rel_id = create_rela...
The function `append_content` appends various content types to a paragraph. It recursively processes lists/tuples, directly adds XML elements, converts `Link` objects to hyperlinks, `Text` objects to styled text records, and strings to text records, appending them to the paragraph.
def append_content(paragraph, content: Any): if isinstance(content, list) or isinstance(content, tuple): for c in content: append_content(paragraph, c) elif isinstance(content, etree._Element): paragraph.append(content) elif isinstance(content, Link): # add link rec...
def get_format(self, asset_id, name): """ Get an asset's format from its name Args: asset_id (str): The asset id name (str): The name of a format Returns: A format """ response = self.__get(f"{ICONIK_FILES_API}/assets/{asset_id}/formats...
The main task of the code is to delete specified asset files from a given storage by iterating through provided format names. For each format, it retrieves associated file sets and purges them if they exist, using the asset ID and storage ID to ensure correct targeting. The function handles multiple formats and ensures...
def delete_asset_files(self, asset_id, format_names, storage_id): """ Delete asset files of given formats from a storage, if they exist Args: asset_id (str): The asset id format_names (list of str): The format name storage_id (str): The storage id """ ...
def get_collection_contents(self, id_, object_types): """ Get the contents of a collection from its id Args: id_ (str): The collection id object_types (list of str): Optional list of object types to return Returns: A list of objects """ ...
This function recursively deletes asset files of specified formats from a collection and all its subcollections within a given storage. It traverses collection contents, processing subcollections recursively and deleting matching asset files using delete_asset_files for each asset encountered.
def delete_collection_files(self, collection_id, format_names, storage_id): """ Delete asset files of a given format from a storage for the given collection, and all subcollections within that collection. Args: collection_id (str): The collection id format_names (...
def _input(self) -> str: return input(self._get_input_choices()) def run_choice(self, selected: str) -> None: if selected.lower() != "q": self.kill() choices = self._get_choices() choices[self._server][selected.lower()]() def _default(self) -> None: options = self._ge...
The code continuously prompts for user input, processes the selected option via `run_choice`, and handles invalid selections by defaulting to `self._default()` using a try-except block. The infinite loop ensures persistent interaction until manually interrupted.
def run(self) -> None: while True: selected = self._input() try: self.run_choice(selected=selected) except KeyError: self._default()
def _get_mods_to_update(self) -> Optional[Dict[str, str]]: mods = self._get_mods() if self._repair is None: return mods try: return {self._repair: mods[self._repair]} except KeyError: print( f"Mod {self._repair} does not exist in the li...
This method updates specific MODs by identifying those needing updates, performing the updates, and then processing the updated MODs through lowercasing their names, creating symbolic links, and copying key files. If no updates are needed, it logs that all MODs are already updated.
def _update_mods_only(self) -> None: mods_to_update = self._get_mods_to_update() updated_mods = self._update_mods(mods_to_update) if updated_mods is None: self._logger.log("All MODs are updated") print() return None self._lower_case_mods(updated_mods) ...
def occupy_huts() -> List[str]: """Randomly populate the `huts` list with occupants""" huts: List[str] = [] occupants = ["enemy", "friend", "unoccupied"] while len(huts) < 5: computer_choice = random.choice(occupants) huts.append(computer_choice) return huts def process_user_choice()...
The code's main task is to control a game where the player selects a hut, checks for enemies, and engages in combat if an enemy is present. The player can choose to attack or flee, with health status updates displayed. The game ends in a win if the enemy is defeated or a loss if the player's health reaches zero.
def play_game(health_meter: dict): """The main control function for playing the game""" huts = occupy_huts() idx = process_user_choice() reveal_occupants(idx, huts) if huts[idx - 1] != "enemy": print_bold("Congratulations! YOU WIN!!!") else: print_bold("ENEMY SIGHTED! ", end="")...
def show_theme_message(width: int): """Print the game theme in the terminal window""" print_dotted_line() print_bold("Attack of The Orcs v0.0.5:") msg = ( "The war between humans and their arch enemies, Orcs, was in the " "offing. Sir Foo, one of the brave knights guarding the southern "...
The main task of the code is to run a game application in a loop, allowing users to play repeatedly. It initializes game settings, displays theme messages and missions, resets player health before each session, executes the game logic, and prompts users to continue playing or exit after each round.
def run_application(): """Top level control function for running the application.""" keep_playing = "y" width = 72 health_meter = {} show_theme_message(width) reset_health_meter(health_meter) show_game_mission() while keep_playing == "y": reset_health_meter(health_meter) ...
def Vigenere_TextStrip(self,text): strippedText = "" for letter in text: if letter.isalpha(): strippedText += self.AlphaUpper[self.AlphaLUDict[letter]] return strippedText def Vigenere_getEveryNthLetter2List(self,text,keyLength): text = self.Vigenere_TextStrip...
This function decrypts a Vigenère cipher by calculating chi-square statistics for each possible Caesar key on letter groups derived from the text. It splits the text into lines based on key length, decrypts each line with all possible Caesar shifts, computes chi-square scores comparing observed vs. expected English let...
def Vigenere_CHI2(self,text,keyLength): text = self.Vigenere_TextStrip(text) lines = self.Vigenere_getEveryNthLetter2List(text,keyLength) bestCHIscores = [] for line in lines: CHIlineScores = [] for decryptKey in range(0,len(self.AlphaUpper),1): de...
def Vigenere_TextStrip(self,text): strippedText = "" for letter in text: if letter.isalpha(): strippedText += self.AlphaUpper[self.AlphaLUDict[letter]] return strippedText def Vigenere_getOccurencesByNGramAgressive(self,text,N): #text = string, N = int ...
The function determines the most likely key length for a Vigenère cipher by analyzing N-gram frequencies, calculating spacing factors, and validating candidates with the Index of Coincidence (IC). It returns the period with the highest IC score, indicating the probable key length for decryption.
def Vigenere_getKeyPeriod(self,text,minKey,maxKey,N): #text = string, minKey, maxKey, N = int text = self.Vigenere_TextStrip(text) occurences = self.Vigenere_getOccurencesByNGramAgressive(text,N) #occurences = [['ABC',0,4,80...],['HWS',5,20...]...] spacings = self.Vigenere_getKey...
def generate_maze(self): return [[Cell(row, col) for col in range(self.maze_cols)] for row in range(self.maze_rows)] def carve_maze(self): # Start carving the maze from the top left cell self.carve_maze_util(self.maze[0][0]) def determine_path_to_end(self): start_cell = s...
The code initializes a 40x40 maze, generates it using a randomized DFS algorithm to carve paths by removing walls, and determines the route from the top-left to the bottom-right corner.
def __init__(self): self.maze_rows = 40 self.maze_cols = 40 self.maze = self.generate_maze() # Carve the maze using randomized dfs algorithm => remove walls self.carve_maze() # Determine the path from the top left corner to the bottom right one self.path = self....
def is_ascii(s): return s >= 33 and s < 127 def log(self, message, style=0): self.print(self.height-1, 0, "> ".format(message), style) def show_list(self): if len(self.symbols) > 0: self.filter_symbols() coords, items_numbers = self.get_grid(1, 3, self.wid...
This code handles user input in a curses-based UI by checking key presses against predefined bindings, updating the search pattern for ASCII inputs, logging invalid keys, and refreshing the display with updated content and state tracking.
def draw(self): if self.key_press in self.keybindings: self.stdscr.clear() self.keybindings[self.key_press]() elif is_ascii(self.key_press): self.stdscr.clear() self.search_pattern += chr(self.key_press) else: if self.key_press != -1: ...
def draw_spinner(self): self.print(self.height-1, self.width-2, get_spin_sign(self.tick)) def reload(self): for symbol, coin in self.loaded_coins.items(): coin.fetch_value(self.default_curr) def log(self, message, style=0): self.print(self.height-1, 0, "> ".format(message), style) de...
The main task of the code is to run an infinite loop that continuously updates a spinner animation, periodically refreshes loaded coin data every 600 ticks (approx. 10 seconds), redraws the interface, and maintains a 20 FPS update rate using sleep(0.05). The loop clears the screen, reloads data, and logs updates when c...
def mainloop(self): while True: self.draw_spinner() if not self.tick % 600 and self.tick and len(self.loaded_coins) > 0: self.stdscr.clear() self.reload() self.log('Refresh loaded coins') self.draw() sleep(0.05) ...
def load(image_file): image = tf.io.read_file(image_file) image = tf.image.decode_jpeg(image) w = tf.shape(image)[1] w = w // 2 input_image = image[:, :w, :] real_image = image[:, w:, :] input_image = tf.cast(input_image, tf.float32) real_image = tf.cast(real_image, tf.float32) return input_image,...
The main task of the code is to preprocess training images by loading a pair of images, applying random jittering for data augmentation, normalizing pixel values to a standard range, and returning the processed input and real images for machine learning model training.
def load_image_train(image_file): input_image, real_image = load(image_file) input_image, real_image = random_jitter(input_image, real_image) input_image, real_image = normalize(input_image, real_image) return input_image, real_image
def parse_reactions(reaction_data): species = set() reactions = OrderedDict() for k, data in enumerate(reaction_data): reactants = parse_side(data["before"]) products = parse_side(data["after"]) named = data["named"] R = data["name"] reversible=data["reversible"] ...
The main task of the code is to analyze multistability in a reaction system by parsing reaction data, constructing contribution and influence graphs, identifying cycles, and testing for hoopings to assess system behavior. It returns results of the hoopings test and the influence graph for further analysis.
def test_multistability(reaction_data): species, reactions = parse_reactions(reaction_data) contribution_graph = construct_contribution_graph(species, reactions) GI = construct_influence_graph(contribution_graph) cycles_info = retrieve_cycles_info(GI) return test_hoopings(reactions, cycles_info), GI
def getbestsalesmen(self): #initiate a temporary order temporder = np.empty([len(self.men), 2], dtype = np.int32) #write the indexes of the route to temporder before ordering changes them for number in range(len(self.men)): temporder[number] = [number, 0,] #get length of path for all route ...
The code performs a genetic algorithm to optimize a traveling salesman route over a specified number of iterations. It tracks the best and worst route lengths, updates generations, applies mutations, and logs performance metrics. The main task is to iteratively refine the route solution, print progress, and save result...
def calculate(self, iterations): from time import time start = time() #get best and bestlength best = np.array(self.getbestsalesmen())[...,0][-1] bestlength = np.array(self.getbestsalesmen())[...,1][-1] #print best and bestlength at start print(self.men[best]) print('best length: ', best...
def initializeFirstGenereation(self): for i in range(500): self.env.append(self.genereteDNA()) def isGoalGen(self, gen): if self.utilityFunction(gen) == 0: return True return False def crossOverAndMutant(self): for i in range(1,len(self.env),2): firstGen = self.env[i-1][:] second...
The code implements a genetic algorithm to solve a problem by iteratively generating new generations through crossover, mutation, and selection. It checks each generation for a goal state; if found, it returns the solution. If not, it continues evolving until the goal is met, tracking the number of iterations required.
def solveGA(self): self.initializeFirstGenereation() for gen in self.env: if self.isGoalGen(gen): return gen count = 0 while True: self.crossOverAndMutant() self.env = self.makeSelection() count +=1 if self.goalIndex >= 0 : try: print(count) ...
def set_hadoopconfiguration(self, sts_token): try: if sts_token: self.spark.sparkContext._jsc.hadoopConfiguration().set("fs.s3.awsCredentialsProvider","org.apache.hadoop.fs.s3.TemporaryAWSCredentialsProvider") self.spark.sparkContext._jsc.hadoopConfiguration().set("fs...
The code processes unencrypted CSV data from S3, transforms it using specified schemas, writes the result as Parquet files to a destination bucket, creates Hive tables for the data, and applies RBAC-based tagging. It handles delta/incremental loading, validates data presence, and manages Hadoop configurations for secur...
def execute_unencrypted(self, s3_client, keys, processing_dt, sts_token, collection, initial_spark_schemas): path = [f's3://{self.s3_src_bucket}/{key}' for key in keys] table_name = f"{collection}_delta" if self.load_type == "delta" else f"{collection}_incremental" if self.load_type == "incremental" el...
def generate_prediction(transf_c2r,pts): pred = np.copy(pts) for i in range(pred.shape[0]): pred[i] = apply_transf(transf_c2r,pts[i]) return pred def fit_calibration(pts_from,pts_to): x = generate_fit_data(pts_from) coeff,res,_,_ = np.linalg.lstsq(x,pts_to,rcond=None) return coeff,res de...
The main task of the code is to calibrate a model by fitting coefficients to minimize errors between predicted and true 3D points. It visualizes calibration results using 3D quiver plots, scatter plots, and error metrics (sum/max squared errors). The function returns calibration coefficients and fitted predictions, ana...
def error_fit_calibration(transf_c2r,pts,true_pts): true_pts_pred = generate_prediction(transf_c2r,pts) coeff,_ = fit_calibration(true_pts_pred, true_pts) print("Error calibration coefficients:") print(coeff) x = generate_fit_data(true_pts_pred) fitted_pred = x @ coeff ...
def RemindDevicesDirectMode(self): for d in self.devices: d.set_mode(0) def OncePerSecond(self): self.now = datetime.now() self.palette.main_hsv = int(time.time()) % 360 self.cached_wheel = None if self.now.second % 10 == 0 and self.frame_times: frame_tim...
The main task of the code is to render animation frames at a consistent frame rate (FPS) by calculating time per frame, rendering each frame, and sleeping if necessary to maintain timing. It also tracks frame durations, updates frame counts, and triggers a "OncePerSecond" method periodically to handle tasks requiring s...
def RenderForever(self): self.start = datetime.now() sec_per_frame = 1 / self.fps self.RemindDevicesDirectMode() self.OncePerSecond() while True: begin = time.time() self.frame += 1 self.RenderAnimationFrame() elapsed = time.time(...
def get_user_input(): ''' Asks user whether or not they want to call all intermediate modules. ''' print("\n----2020 Election Analysis----") print("\nDo you want to run all intermediate modules?") print("\nEnter Yes to go through all intermediate analysis.") print("\nEnter No to open website...
The main task of the code is to prompt the user for input and execute intermediate analysis steps if the input is "Y", or open a website if "N". It handles invalid inputs by recursively prompting the user again.
def go(): ''' Main function to get user input and run intermediate analyses ''' run_analysis = get_user_input() if run_analysis == 'Y': do_all_intermediate_steps() elif run_analysis == 'N': print('Opening website...') else: print('''Incorrect entry. Enter "Y" or "N".'...
def display_post_message_windows(self, version: str) -> None: path = self.get_windows_path_var() message = POST_MESSAGE_NOT_IN_PATH if path and str(self.bin_dir) in path: message = POST_MESSAGE self._write( message.format( aptos=colorize("info", ...
The code determines the appropriate method to display a post-message based on the operating system and shell environment. If on Windows, it uses `display_post_message_windows`; if the shell is "fish", it uses `display_post_message_fish`; otherwise, it defaults to the Unix version `display_post_message_unix`. The functi...
def display_post_message(self, version: str) -> None: if WINDOWS: return self.display_post_message_windows(version) if SHELL == "fish": return self.display_post_message_fish(version) return self.display_post_message_unix(version)
def checkout_git_branch(branch): """Checkout the specified git branch. This assumes the working directory is aptos-core""" subprocess.run(["git", "fetch"]) subprocess.run(["git", "checkout", branch]) subprocess.run(["git", "log", "-1"]) def get_genesis_and_waypoint(network): """Clones the genesis blob and way...
The main task of the code is to configure and launch a blockchain fullnode by validating required environment variables, checking out a specified Git branch, initializing node configurations, retrieving network parameters, spawning the fullnode process, waiting for it to start, and monitoring its synchronization status...
def main(): # Ensure we have all required environment variables REQUIRED_ENVS = [ "BRANCH", "NETWORK", "BOOTSTRAPPING_MODE", "CONTINUOUS_SYNCING_MODE", "DATA_DIR_FILE_PATH", "NODE_LOG_FILE_PATH", ] if not all(env in os.environ for env in REQUIRED_ENVS): raise Exception("Missing requi...
def get_version(self): latest_version = self.latest_release_info["tag_name"].split("-v")[-1] self._write(colorize("info", "Latest CLI release: {}".format(latest_version))) if self._force: return latest_version, None binary_path = self.bin_path try: out =...
The main task of the code is to execute an installation process by determining the target and version, handling potential errors during retrieval, and performing the installation while managing exceptions. It returns 0 for success, 1 for retrieval errors, and propagates installation errors via exceptions.
def run(self) -> int: try: version, _current_version = self.get_version() except ValueError: return 1 if version is None: return 0 try: target = self.get_target() except: return 1 if target is None: ...
def pickFile(): print() Tk().withdraw() file = askopenfilename() return getHexOf(file) def fixAlignmentof(file1, file2): #?? Add blank characters at end of file1 if line doesn't align files = [] # blank characters at end of files if they are different sizes if(len(file1) != len(file2)): if(len(file1) > len(fi...
The main task of the code is to compare two hexadecimal files by aligning them and providing a menu-driven interface for users to view files side-by-side, identify differences, export discrepancies to a text file, or exit. It uses functions to handle file alignment, display comparisons, and manage user interactions wit...
def main(): file1Hex = pickFile() file2Hex = pickFile() files = fixAlignmentof(file1Hex, file2Hex) file1Hex = files[0] file2Hex = files[1] isRunning = True while(isRunning): print('_______________________') print(' Orange HexCompare ') print('_______________________\n') print('Select an option from b...
def prepare_FUPPREDICTOR(data_dir, instruction_dir, discrepency_dir): """Read the FUPPREDICTOR raw dataset, correct discrepencies, fix follow-up weights, replace wrong values with None, fill NAs as instructed in the instructions csv file, and then one-hot encode the variables as instructed. Args: ...
The function reads, formats, and prepares multiple raw data files from specified directories, returning six structured pandas DataFrames (df_FUPPREDICTOR, df_FUPOUTCOME, df_BASELINE, df_AD1, df_FUPDISCONT, df_GENOTYPE) for analysis. It delegates data processing to specialized helper functions, ensuring each dataset is ...
def read_format_rawdata(data_dir, instruction_dir, discrepency_dir): """Reads, format, and prepare all the raw data. Args: data_dir (string): Path to the raw data excel file. instruction_dir (string): Path to the instructions excel file. discrepency_dir (string): Path to the discrepency...
def find_tools(text): TOOLS = get_tools_wrapper() tools_for_this_step = [] for TOOL in TOOLS: if TOOL in text: tools_for_this_step.append(TOOL) return tools_for_this_step def find_methods(text, methods): methods_for_this_step = [] for method in methods: if method in t...
The code parses a recipe URL to extract and structure cooking directions, ingredients, methods, tools, and time details into a JSON file. It splits instructions into steps, identifies associated tools/methods/ingredients per step, and compiles everything into a standardized recipe representation for storage.
def get_directions(url): parse = url.split('/') name = parse[-2] fetchURL(url) f = open("url.txt", "r") s = f.read() TOOLS = get_tools_wrapper() dirs = findDirection(s)["recipeInstructions"] methods = get_method()[0] + get_method()[1] ingredients = get_ingredients_withURL(url) di...
def mutate_noise_blocks(self, strength): dim = max(sizeX, sizeY) block_size = random.randint(1, dim) noise = np.ones([(dim//block_size + 1)*block_size, (dim//block_size + 1)*block_size, 3]) noise_blocks = np.random.normal(0, strength, [dim//block_size+1, dim//block_size+1, 3]) *...
The main task of the code is to randomly apply one of three mutation operations (noise blocks, smoothing, or contrast increase) to an object based on probability thresholds. The decision is determined by a random value compared against thresholds [0.5, 0.25], selecting `mutate_noise_blocks` for 50% chance, `smoothen` f...
def mutate(self, strength): #if random.random() <= thresh: # if random.random() <= 0.6: # self.mutate_noise(strength) # else: # self.mutate_noise_blocks(strength) #else: # if random.random() <= 0.5: # self.smoothen(strength) ...
def _prepare_posts(self, headlines, n=4): logging.info('Grouping posts...') final_messages_keys = [headlines[i:i+n] for i in range(0, len(headlines), n)] return final_messages_keys def create_layout(self, name, headlines, cont=False): blocks = self.format_header_block(name, cont) ...
The main task of the code is to send batches of headlines to Slack channels via webhooks. It prepares a specified number of headlines, logs progress, and formats each batch into a message using `create_layout`. The first message avoids continuation formatting, while subsequent ones include it. It submits each message t...
def send_messages(self, name, headlines, channel=None, webhook=None, n=4): channel = channel or self.default_channel final_headlines = self._prepare_posts(headlines, n=n) logging.info(f"Sending {len(final_headlines)} to Slack.") for index, headlines in enumerate(final_headlines): ...
def setShapeAt(self, x, y, shape): self.board[(y * Board.BoardWidth) + x] = shape def removeFullLines(self): numFullLines = 0 statusbar = self.GetParent().statusbar rowsToRemove = [] for i in range(Board.BoardHeight): n = 0 for j in range(Board.BoardW...
The main task of the code is to handle the dropping of a game piece by placing its blocks on the game board, check for and remove completed lines, and generate a new piece if the game is not paused. It iterates over the piece's four blocks, updates their positions, triggers line removal, and initiates a new piece when ...
def pieceDropped(self): for i in range(4): x = self.curX + self.curPiece.x(i) y = self.curY - self.curPiece.y(i) self.setShapeAt(x, y, self.curPiece.shape()) self.removeFullLines() if not self.isWaitingAfterLine: self.newPiece()
def pause(self): if not self.isStarted: return self.isPaused = not self.isPaused statusbar = self.GetParent().statusbar if self.isPaused: self.timer.Stop() statusbar.SetStatusText('paused') else: self.timer.Start(Board.Speed) ...
This code handles keyboard input for a Tetris-like game, controlling piece movement (left/right/down/up), rotation, pausing, and dropping. It checks if the game is active and not paused, then processes specific keys to move the current tetromino, rotate it, or trigger actions like pausing/dropping, while skipping unhan...
def OnKeyDown(self, event): if not self.isStarted or self.curPiece.shape() == Tetrominoes.NoShape: event.Skip() return keycode = event.GetKeyCode() if keycode == ord('P') or keycode == ord('p'): self.pause() return if self.isPaused: ...
def save_metrics(prefix_fname, metrics, sample_start_ind=0): head, tail = os.path.split(prefix_fname) if head and not os.path.exists(head): os.makedirs(head) assert metrics.ndim == 2 file_mode = 'w' if sample_start_ind == 0 else 'a' with open('%s.csv' % prefix_fname, file_mode, newline='') a...
The function saves motion-related results by computing and storing pixel distribution metrics between ground truth and generated data, and optionally visualizing input/output distributions and generated images, based on model parameters and flags like draw_center and only_metrics.
def save_motion_results(task_dir, results, model_hparams, draw_center=False, sample_start_ind=0, only_metrics=False): context_frames = model_hparams.context_frames sequence_length = model_hparams.sequence_length pix_distribs = results['pix_distribs'][:, context_frames:] gen_pix_d...
def resize_walls(walls, factor): """Increase the environment by rescaling. Args: walls: 0/1 array indicating obstacle locations. factor: (int) factor by which to rescale the environment.""" (height, width) = walls.shape row_indices = np.array([i for i in range(height) for _ in range(factor)]) col_ind...
The code initializes a point navigation environment with customizable maps, noise parameters, and reward settings. It processes wall configurations (resizing, randomization), defines action/observation spaces, sets start/goal positions, and prepares for dense rewards or path recording. The environment supports dynamic ...
def __init__(self, walls=None, resize_factor=1, action_noise=1.0, percent_random_change=0.0, start=None, goal=None, noise_sample_size=None, random_seed=0, dense_reward=True, ...