dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def set_target(self): if self.personality == "speedy" or self.personality == "slow": return self.app.player.grid_pos else: if self.app.player.grid_pos[0] > COLS // 2 and self.app.player.grid_pos[1] > ROWS // 2: return vec(1, 1) if self.app.player.grid_...
The code updates an entity's position by setting a target, moving towards it if not already at the target, and converting pixel-based coordinates to grid-based coordinates for positioning. It checks movement timing and adjusts grid_pos based on pixel position, buffer offsets, and cell dimensions.
def update(self): self.target = self.set_target() if self.target != self.grid_pos: self.pix_pos += self.direction * self.speed if self.time_to_move(): self.move() self.grid_pos[0] = (self.pix_pos[0] - TOP_BOTTOM_BUFFER + self.a...
def createUsers(self): fake = Faker() for _ in range(100): user = Users( name=fake.name(), email=fake.ascii_company_email() ).save() self.users.append(user) def createGenres(self): endpoint = "https://api.spotify.com/v1/recommen...
The main task of the code is to initialize an application by loading and creating multiple data entities (users, genres, languages, artists, albums, tracks, podcasts, playlists, and events) using a provided access token. It systematically populates the application's data structures, utilizing progress tracking for larg...
def __init__(self, accessToken): super().__init__() self.accessToken = accessToken self.createUsers() console.print("Users loaded!", style="bold red") self.createGenres() console.print("Genres loaded!", style="bold red") self.createLanguages() console.prin...
def update_mask(self): if self.ep_count % self.change_interval == 0: add_actions = [] # add new actions that were never seen before curr_no_actions = np.where(self.action_tracker == 0)[0] if len(curr_no_actions) >= self.change_add_count: l = l...
The `reset` method initializes the environment to default conditions, preparing for a new episode. It updates the action mask, resets reward states, step counters, and episode count, then generates the initial state and dynamic obstacles. The method returns the starting state, action mask, and a flag indicating environ...
def reset(self): """ Sets the environment to default conditions :return: Starting state and the set of actions for the next trajectory """ change_flag = self.update_mask() # Update the mask for next step onwards self.set_rewards() self.steps_taken = 0 s...
def is_terminal(self): if self.in_region(self.curr_pos, self.G1): return 1 elif self.steps_taken >= self.max_steps: return 1 else: return 0 def valid_pos(self, pos): flag = True # Check boundary conditions if not self.in_region(pos, [0...
This code simulates an agent's movement in an environment by applying actions, calculating rewards, handling collisions, and updating the agent's state. It checks action validity, applies motion effects with optional noise, validates new positions, updates rewards for movement and goals, and tracks terminal states. The...
def step(self, action): assert self.action_mask[action] # check if the action selected is in the current set of active actions self.steps_taken += 1 reward = 0 # Check if previous state was end of MDP, if it was, then we are in absorbing state currently. # Terminal state has a...
def get_movements(self, n_actions): """ Divides 360 degrees into n_actions and assigns how much it should make the agent move in both x,y directions usage: delta_x, delta_y = np.dot(action, movement) :param n_actions: :return: x,y direction movements for each of the n_a...
This code initializes a reinforcement learning environment for an agent navigating a 2D space with obstacles. It sets up action/observation spaces, movement parameters, reward mechanisms (step/collision/reward), lidar sensing, and continual learning features. The environment supports dynamic task changes over episodes,...
def __init__(self, n_actions=4, debug=True, max_step_length=0.2, max_steps=30, max_episodes=1e5, change_interval=-1, change_count=3): self.debug = debug self.ep_count = 0 # G...
def navClicked(self,startPoint,stopPoint,chargeRange,hotelRange): # handles inputs from the UI and passes them to eva print("Button clicked") if(self.liveScrapeVar.get()): # check if live data is enabled self.liveScrapePopUp() # get confirmation from user if(self.livedata==False)...
This code initializes a GUI application for a navigation tool called EVantage. It sets up a window with input fields for origin, destination, charge/hotel ranges, checkboxes for pandemic/crime alerts and live data, buttons to navigate, clear inputs, or use sample data, and a status display. The interface is configured ...
def __init__(self, master): master.geometry("600x450") master.title("Welcome to EVantage") master.resizable(0,0) ttk.Frame.__init__(self, master) self.pandemicStatusVar = tk.BooleanVar() self. crimeStatusVar = tk.BooleanVar() self.liveSc...
def get_closed_pulls(days_ago): """ Retrieves closed pulls from n days_ago """ now = datetime.now() ago = timedelta(days=days_ago) start = now - ago date_range = start.strftime("%Y-%m-%d") + ".." + now.strftime("%Y-%m-%d") return retrieve_paginated_results(CLOSED_ISSUE_QUERY.replace("_RA...
This function processes closed GitHub pull requests by retrieving data, storing it in a temporary table, merging it into a main closed table, updating maintainers, and optionally cleaning up temporary files. It uses a timestamped temp table, saves results to a JSON file, and handles cleanup based on configuration flags...
def handle_closed_pulls(ctx, days_ago): """ CLI command that runs the closed pulls workflow. """ # Closed issue processing flow: # - Query last period. # - Insert into temp table # - Run merge from temp table -> closed table # - Run queries to update maintainers # - Optinally drop te...
def save_json_lines(results, filename): """ BigQuery accepts JSON in the JSON Lines format where each object, where that object will correspond to a row in a table once uploaded. """ with open(filename, "w", encoding='utf-8') as output: for pull in results: output.write(json.dump...
The main task of the code is to execute a CLI workflow for handling open pull requests by retrieving paginated results, saving them as JSON lines in a temporary file, uploading the data to BigQuery, updating table columns, and maintaining maintainer data. The script also manages temporary file preservation based on use...
def handle_open_pulls(ctx): """ CLI command that runs the open pulls workflow. """ open_file_name = f"{tempfile.gettempdir()}/open_pulls.json" file_path = Path(open_file_name) open_pulls = retrieve_paginated_results(OPEN_ISSUE_QUERY) save_json_lines(open_pulls,open_file_name) # Ove...
def get_buying_power(self) -> float: self.logger.info("Getting buying power") account = self.cb_client.get_account(self.usd_account_id) usd_balance = float(account["account"]["available_balance"]["value"]) self.logger.info(f"$USD balance: {usd_balance} as of {datetime.utcnow()}") ...
This function evaluates buy/sell conditions for a trading asset by checking buying power, price thresholds, and open positions. It logs decisions, places buy/sell orders when conditions are met, tracks profits, and persists results to a database. If no trades are made, it records the skip reason. It updates current pri...
def compute_decisions(self): now = datetime.utcnow() self.logger.info(f"============ computing decisions for {self.asset_config.symbol} in {self.enviorment} @ {now} ============") decisions = [] buying_power = self.get_buying_power() has_enough_buying_power = buying_power > self....
def enough_time_passed_for_decision_computation(self): if self.last_decision is None: return True now = datetime.utcnow() time_delta = now - self.last_decision return time_delta.total_seconds() > DECISION_BUFFER def setup_logger(trx_id): logger = logging.getLogger(trx_id)...
The main task of the code is to repeatedly check if sufficient time has elapsed since the last decision, generate a unique transaction ID, configure logging for each decision cycle, and compute new decisions when conditions are met. The loop runs while `self.running` is True, with a sleep interval between iterations, a...
def run(self): while self.running: if self.enough_time_passed_for_decision_computation(): # provision a new logger for this decision transaction_id = uuid.uuid4() trxId = str(transaction_id) self.logger = setup_logger(trxId) ...
def setup_space(self): self.mystep = 0 self.max_job_size = config.getfloat('parameters', 'max_job_size') self.queue_size = config.getfloat('parameters', 'queue_size') self.num_servers = config.getint('parameters', 'num_servers') self.queue = [self.queue_size] * (self.num_servers ...
This code initializes a simulation environment by setting up spatial structures, time tracking components, loading job data from a CSV database, configuring server service rates from a configuration file, and initializing server objects and job tracking variables. The main task is to prepare a simulation framework for ...
def __init__(self): self.setup_space() self.wall_time = WallTime() self.timeline = Timeline() df = pd.read_csv(config.get('database', 'database')) self.num_stream_jobs = len(df) service_rates = config.get('parameters', 'service_rates').split('[')[1].split(']')[0].split(',...
def mode(self, args): """Check whether the mode is specified or is gene or genome.""" if not args.mode: return GENE else: if args.mode not in [GENE, GENOME, CHROMOSOME]: self.die("Mode not recognized. Please use gene or genome.") elif args.mode...
The code processes genetic data by generating chains, converting BED files to BigBed format, and organizing outputs. It checks the mode (GENE or other), creates chains if in GENE mode, loads chains, converts BED to BigBed, validates outputs, moves results to a shared folder, and cleans up. The main task is to generate ...
def run(self, args): f = open(os.path.join(TEMP_DIR, OUT), "w") if self.mode(args) == GENE: if self._make_chain_from_gene(args) == SUCCESS: if self.hg_load_chain(args): self.bed_to_bigbed(args) self._check_gbib() else: ...
def get_bedtobigbed(): if not _is_already_installed(Binary.BED_TO_BIGBED): status = download_binary(Binary.BED_TO_BIGBED) return SUCCESS if status else FAILED else: return SUCCESS def get_hgloadchain(): if not _is_already_installed(Binary.HG_LOAD_CHAIN): status = download_bin...
The main task of the code is to create a directory if it doesn't exist, retrieve status information from four specific binary tools (BED_TO_BIGBED, HG_LOAD_CHAIN, BIG_CHAIN, BIG_LINK), compile these statuses into a dictionary, validate them using a check_stats function, and return True upon successful validation.
def main(): os.mkdir(LOCATION) if not os.path.exists(LOCATION) else None bedtobidbed_status = get_bedtobigbed() hgloadchain_status = get_hgloadchain() biglink_status = get_biglink() bigchain_status = get_bigchain() stats = { Binary.BED_TO_BIGBED: bedtobidbed_status, Binary.HG...
def empty(self): if len(self.Heap) <=1: return True else: return False def size(self): return len(self.Heap) -1 def maxHeapify(self, i): if not self.isLeaf(i): if ((self.Heap[i]< self.Heap[self.leftChild(i)]) or (self.Heap[i]< self.Hea...
The main task of the code is to remove and return the maximum element from a max-heap. It replaces the root (maximum value) with the last element, removes the last element, and then restores the heap property by calling maxHeapify on the root. This ensures the remaining elements maintain the max-heap structure after ex...
def extractMax(self): if self.empty(): return None popped = self.Heap[self.root] self.Heap[self.root] = self.Heap[self.size()] del self.Heap[-1] if not self.empty(): self.maxHeapify(self.root) return popped
def _get_current_basis(self): basis = np.zeros( (self.current_features_[0].value.shape[0], len(self.current_features_)) ) for i, f in enumerate(self.current_features_): basis[:, i] = self.current_features_[i].value return self.process_basis_features(basis) def _bu...
This method updates the model's fitness by building a linear model from the current basis and target values `y`, then applying a specified fitness algorithm. If set to `ZERO_OUT`, it removes features with zero coefficients; if `COEFFICIENT_RANK`, it ranks features by their coefficients' magnitude. The process adjusts t...
def _update_fitness(self, y): basis, _ = self._get_current_basis() model, coefs, mse_path = self._build_linear_model(basis, y) if self.fitness_algorithm == ZERO_OUT: self._remove_zeroed_features(model) elif self.fitness_algorithm == COEFFICIENT_RANK: self._rank_by...
def _get_basis_for_predictors(self, X): infix_features = list(map(lambda x: x.infix_string, self.best_features_)) basis = get_basis_from_infix_features( infix_features, self.predictor_names_, X, self.best_scaler_, self.variable_type_indices, ...
This function builds multiple candidate models by iteratively updating feature values with basis transformations, evaluating model fitness, and storing each model along with its associated features and scalers. It loops while `num_additions` is positive, updating features, scoring models, and appending results to lists...
def build_multi_candidate_models(self): while self.num_additions > 0: self.current_features_ = self.best_features_ basis_values = self._get_basis_for_predictors(self.X).T for i, f in enumerate(self.current_features_): f.value = basis_values[i] self...
def _init_features(self, feature_names, X): """ Init the features the model will begin evolving. If feature names have not been specified they are generated as x1, x2, ..., xk. Parameters ---------- feature_names : list of strings Names of the features. ...
This code implements an evolutionary algorithm for feature selection and model optimization. It iteratively generates and evaluates models using candidate features, tracks the best-performing model, and updates features based on fitness scores. The process continues for a set number of generations, refining models by a...
def fit(self, X, y, feature_names=None): self.mse_log = [] self.X = X self.y = y self.models_ = [] self.features_ = [] self.scalers_ = [] self.validation_scores_ = [] self.statistics_ = Statistics() self.response_variance_ = np.var(y) self....
def choose_category(self): print('Choose a category:') pprint.pprint(options) try: user_choice = int(raw_input()) return options.get(user_choice) except: print("Oops! You must enter a number. Exiting game.") def get_category_cards(self, category): if category == 'All': return self.cards elif cat...
The code's main task is to run a quiz game focused on data structures and algorithms. It begins by greeting the user, selects a category, retrieves related questions, iterates through each to ask them, and concludes the game. The method orchestrates the flow from category selection to question delivery and game termina...
def play(self): print('Let\'s go over some data structures and algorithms!') category = self.choose_category() category_cards = self.get_category_cards(category) for card in category_cards: self.ask_question(card) self.end_game(category, category_cards)
def standby_control_law(self, agent: Agent): agents_to_avoid = [agt for agt in self.swarm_agent_list if agt.name in agent.xy_auto_avoid_agents_list] objective = [agent.standby_position[0], agent.standby_position[1]] omega = numpy.pi / (2 * horizontal_distance([agent.x_boundaries[0], agent.y_boun...
The function manages a swarm of drones by applying state-specific control strategies (e.g., takeoff, landing, consensus, manual) to enabled agents when the system is ready to fly. It also checks if all agents pass battery/position tests, sets readiness, and logs agent statuses, positions, and flight enablement status f...
def flight_sequence(self): if self.ready_to_fly: for agent in self.swarm_agent_list: if agent.enabled and agent.state != 'Not flying': if agent.state == 'Standby': self.standby_control_law(agent) if agent.state == 'Take...
def squareUnderAttack(self, r, c): # first switch to the opponents move self.whiteToMove = not self.whiteToMove # generate all of its moves oppMoves = self.getAllPossibleMoves() self.whiteToMove = not self.whiteToMove # switch the turns back # check if any of those moves...
The function `getCastleMoves` generates valid castling moves for a king by checking if the king is not in check, the path between the king and rook is unoccupied and not under attack, and if castling rights (king/queen side) are active. It delegates to helper methods to add legal castling moves to the provided list, en...
def getCastleMoves(self, r, c, moves): # 1st check if the king is inCheck as the king can't escape the check by castling if self.squareUnderAttack(r, c): return # 2nd check if the squares in between the king and the rook is vacated or not # 3rd check to see if any of those sq...
def getAllPossibleMoves(self): moves = [] for r in range(len(self.board)): # number of rows # number of columns in a given row for c in range(len(self.board[r])): turn = self.board[r][c][0] # the piece color if (turn == "w" and self.whiteToMove) ...
This function generates all valid moves by first creating potential moves, then validating each by simulating the move and checking if the king is in check. Invalid moves are removed, castling moves are added, and checkmate/stalemate states are determined. The original game state is restored before returning the valida...
def getValidMoves(self): tempEnpassantPossible = self.enpassantPossible tempCastleRights = CastleRights( self.currentCastlingRights.wks, self.currentCastlingRights.bks, self.currentCastlingRights.wqs, self.currentCastlingRights.bqs, ) # the...
def step(self): loss = 0 batch_size = 0 delays = [] losses = [] start_time = time.time() for worker_ in self.workers: start_time = time.time() worker_loss, batch_size_ = worker_.compute_gradients(self.running_itr) self.compute_gradients...
This code trains a machine learning model over multiple epochs. It iterates through batches, executes training steps, tracks loss and time metrics, updates learning rates, and periodically evaluates performance. Exceptions during training are logged, and progress is printed at specified intervals. The training loop res...
def train(self): num_iter_per_epoch = len(self.partitions[0]) // self.batch_size + 1 self.running_itr = 0 for epoch in range(self.num_epochs): self.epoch = epoch self.loss_meter.reset() self.time_meter.reset() for itr in range(num_iter_per_epoch): ...
def init_wl(args): """ Initialize and return workload information from configuration file args - arguments from command line input """ wl_df = pd.read_csv(args.workload_conf_file) workloadinfo = {} for row_turple in wl_df.iterrows(): row = row_turple[1] workload_name = ro...
The code processes command-line arguments to analyze workload data by initializing workload information, partitioning the workload for processing, and determining maximum load conditions.
def process(args): """ General procedure of analysis args - arguments from command line input """ workloadinfo = init_wl(args) process_by_partition(args, workloadinfo) process_lc_max()
def warning(msg, force=False): log.write("Warning: " + msg + "\n") log.flush() if args.verbose or force: print(f"{ansi.WARNING}Warning:{ansi.ENDC} {msg}") def combineResults(values): values = [x["value"]+":"+x["type"] for x in values] return ", ".join(values) def parseResults(s): values ...
The code executes a WebAssembly test by invoking a function, parsing its output, and comparing it against expected results. It constructs a command from test parameters, skips blacklisted tests, runs the invocation, captures output, and checks for errors/traps. It logs results, updates statistics (success/failure/skipp...
def runInvoke(test): test.cmd = [test.action.field] displayArgs = [] for arg in test.action.args: test.cmd.append(arg['value']) displayArgs.append(formatValue(arg['value'], arg['type'])) test_id = f"{test.source} {test.wasm} {test.cmd[0]}({', '.join(test.cmd[1:])})" if test_id in b...
def set_os_offline(self): '''Set OS state to OFFLINE.''' os_state = self.read_os_state() if os_state == VENode.OS_ST_ONLINE: self._update_os_state(VENode.OS_ST_TERMINATING) self._update_os_state(VENode.OS_ST_OFFLINE) elif os_state == VENode.OS_ST_OFFLINE: se...
The main task of the `recover` method is to transition the system from an UNAVAILABLE state by setting the OS to OFFLINE, waiting for the VE node to reach OFFLINE or ONLINE status (accounting for potential race conditions), and executing cleanup operations to ensure proper recovery, regardless of the VE's final state.
def recover(self): '''Recover from UNAVAILABLE. ''' # set os_state to OFFLINE self.set_os_offline() # wait for ve_state set to OFFLINE self._log("Wait for VE node set to OFFLINE or ONLINE") # Since ve_state can be changed to ONLINE before OS launcher # com...
def _log(self, msg, prio=LOG_INFO): '''Output a message with specified priority.''' out="[launcher#%d] %s" % (self._veno, msg) syslog(prio, out) def read_os_state(self): with io.open(self._osstate_filename, 'rb') as f: s = int(f.read()) self._log("os_state = %s (%...
The code initiates the VE OS launcher by ensuring the OS is in the OFFLINE state, transitioning it to ONLINE via start_veos, then waiting for a state change to trigger termination. It logs debug info, validates prerequisites, and manages state transitions for the virtual environment.
def start(self): '''Start VE OS launcher.''' # start with WAIT_VEONLINE self._log("start", LOG_DEBUG) assert(self.osproc == None) # check os_state os_state = self.read_os_state() if os_state != self.OS_ST_OFFLINE: self._log("WARNING: os_state is not OF...
def _log(self, msg, prio=LOG_INFO): '''Output a message with specified priority.''' out="[launcher#%d] %s" % (self._veno, msg) syslog(prio, out) def read_state(self): '''Read ve_state and update _state.''' self._file.seek(0, io.SEEK_SET) s = int(self._file.read()) ...
This method waits for the VE OS daemon process termination, checks its exit status, logs errors if abnormal, transitions the OS state to TERMINATING/OFFLINE, performs cleanup, and exits. It handles state recovery, updates OS states, and ensures proper termination flow without returning.
def finalize_veos(self): '''Wait for termination of VE OS daemon process. A caller exits after catching termination of VE OS with the exit status of VE OS daemon. This method never returns. ''' # SIGCHLD state here self._log('Finalize VE OS', LOG_DEBUG) ...
def _log(self, msg, prio=LOG_INFO): '''Output a message with specified priority.''' out="[launcher#%d] %s" % (self._veno, msg) syslog(prio, out) def test_SIGCHLD(self): '''Test signals received. If SIGCHLD has been caught, obtain the exit status and exit. If a caugh...
The code terminates the VE OS daemon process by sending a termination signal, waiting for its exit via SIGCHLD, and forcibly killing it if necessary. It checks if the process is already dead, initiates termination, waits for confirmation, and finalizes cleanup. If termination fails, it forcefully kills the process and ...
def terminate_veos(self): '''Terminate VE OS daemon process. This method requests VE OS to exit by sending a signal, and wait for its termination. ''' # WAIT_VEONLINE or READY self._log("terminate VE OS") if not self.osproc: # WAIT_VEONLINE -> NO...
def get_mating_pool(gen): mating_pool = [] for i in range(len(gen)): # mirip dengan roulette wheel [terpilih] = random.choices( gen, weights=[fitness(kromosom) for kromosom in gen]) mating_pool.append(terpilih) return mating_pool def crossover(kromosom1, kromosom2, prob=...
The code generates the next generation in an evolutionary algorithm by selecting parent pairs from the current generation, performing crossover to create offspring, applying mutation, and combining the top-performing individuals from the current generation with the mutated offspring to form the next generation.
def next_generation(gen): mating_pool = get_mating_pool(gen) next_gen = [] for i in range(0, len(gen), 2): anak1, anak2 = crossover(mating_pool[i], mating_pool[i+1]) next_gen.append(mutasi(anak1)) next_gen.append(mutasi(anak2)) result = [] gen.sort(key=lambda x: fitness(x), r...
def getWord(words): RanIndex = random.randint(0, len(words) -1) return words[RanIndex] def get_Responce(word, points): #Displays the mystory word gameShow(word) print("\nYou have {} remaining guesses!".format(points)) #Getting the user's respoce guess = input("Guess a letter or the entire w...
The code implements a word-guessing game where players have 5 attempts to guess letters or the entire word. Correct guesses earn points based on word length and remaining attempts. The game resets with a new word after successful completion, allows exiting via '!', and displays the correct word if the player runs out o...
def start(self): global score, pastAns #point system and 1st word word = getWord(self) print("We will now start the game. You will have 5 chances to guess a letter or the entire word!", "\nIf you would like to solve the word, please type in what you think the word is.", "\nDoing...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
This function simulates a turn-based battle between active good and bad guys. If inClosing is True, it's a fight to the death. It uses global variables to track participants, inventory, and tools. Each turn, a random attacker from either side strikes with a random item, with possible outcomes like defeat, blocking, or ...
def fight(inClosing): """If there are active good guys and active bad guys, then it starts a fight between good guys and bad guys. If the inClosing parameter is True, it's a fight to the death.""" global bad_guys global good_guys global inventory global Tools global Prizes global inactive_go...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function `goto()` determines the destination for the good guys, either via a pre-set "Visit" goal, random selection, or user input. It updates the current place, handles movement using active vehicles (e.g., rocket ship), prints narrative actions, and manages bad guys by moving them to an inactive list when the goo...
def goto(): """This function is used when the good guys go somewhere.""" global place global Places global PlaceTypes global goals global active_vehicles global inactive_bad_guys global bad_guys good_guy_check() if findGoal("Visit") and random.randint(0,1) == 1: for goal ...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The main task of the code is to print the good guys' inventory, listing each item with its quantity, properly pluralized and formatted. It counts duplicates, adjusts item names for pluralization, and formats the output with commas and "and" before the last item, using a custom print function.
def print_inventory(): """Prints the good guys' inventory, and how much of a certain item.""" global inventory global good_guys global last_list if last_list != "inventory": last_list = "inventory" good_guy_check() inventory_dictionary = {} for item in inventory: ...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The main task of the code is to assign a vehicle to the "good guys" by randomly selecting, allowing user input, or choosing based on a goal (e.g., "Visit Outer space"). It generates story text describing how the vehicle is acquired—via shopping (with money checks) or finding an abandoned one (with broken/fixable condit...
def get_vehicle(): """Gives the good guys a vehicle to travel with.\nIt is true that the good guys can travel anywhere on foot, but that would be hard in real life.""" global Vehicles global active_vehicles global inventory global good_guys global goals good_guy_check() r = random.randin...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The main task of the code is to introduce a new good guy into the story by updating the global list of good guys, then narrating their introduction with a random choice of phrasing: either stating they joined existing good guys or that the group met them. The function manages character addition and story progression th...
def new_guy(): """Introduces a good guy in the middle of the story.""" global good_guys good_guy_check() global inactive_good_guys introduce(good_guys, True) print(' ',end=' ') if random.randint(0,1) == 1: storyprint(good_guys[-1]+" came over and joined the good guy(s).", "\n") e...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The code checks if game goals are completed by evaluating conditions against global variables like inventory, locations, and active items. It processes goals starting with "Meet," "Leave," "Take," "Destroy," or "Visit," updating progress, removing completed goals, awarding prizes, and printing status updates. Prizes li...
def goal_check(): """Checks if any goals are completed.""" global goals global Tools global inventory global Places global good_adjectives global good_guys global bad_guys global bad_adjective global Animals global Vehicles global inactive_good_guys global inactive_ba...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function `destroy_vehicle` randomly selects and removes an active vehicle, generates a narrative describing its destruction, and may result in the death of a good guy. It uses global variables to track active vehicles, good guys, and death terms, adjusting output based on vehicle type and random chance.
def destroy_vehicle(): """Destroys a vehicle. Some good guys may die from the crash.""" global good_guys global death_terms global active_vehicles good_guy_check() if len(active_vehicles) > 0: print(' ', end=" ") wrecked_vehicle = random.choice(active_vehicles) active_veh...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function `lose_item()` randomly selects and removes an item from the inventory, then simulates its loss through either a bad guy stealing it (and possibly destroying it) or the item breaking/being lost by the good guy, using randomized conditions and story-printing for narrative feedback.
def lose_item(): global inventory global good_guys global bad_guys good_guy_check() if len(inventory) > 0 : lost_item = random.choice(inventory) inventory.remove(lost_item) print(' ',end=' ') if random.randint(0,2) == 1 and len(bad_guys) > 0: storyprint(ra...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function `natural_disaster()` randomly selects and simulates a natural disaster (earthquake, flood, tornado, etc.), generating narrative descriptions of its impact on characters (good and bad) and locations. It determines character safety, potential deaths, and location changes based on random conditions, updating ...
def natural_disaster(): """Makes a random natural disaster happen.""" global place global Places global good_guys global bad_guys global death_terms global inactive_bad_guys global PlaceTypes good_guy_check() startPlace = place disaster = random.randint(0, 6) starts = (" ...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
This function simulates a good guy (or group) getting trapped in a room or cage, with attempts to escape using inventory items. It handles random outcomes of escape attempts, updates character statuses, and manages transitions between active/inactive good guys or relocation to new locations if escape fails.
def trapped(): """A good guy gets trapped in this function.""" global good_guys global inactive_good_guys global place global last_list global Places global PlaceTypes global inventory good_guy_check() free = False if random.randint(0,1) == 1 and len(good_guys) > 1: v...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function simulates the good guys getting lost in a dynamic environment, handling random events like character separation, reuniting, encounters with inactive characters, and location changes. It updates global lists of active/inactive characters and places, using conditional logic to alter the narrative based on ra...
def lost(): """The good guys get lost in this function.""" global good_guys global place global Places global PlaceTypes global inactive_good_guys global inactive_bad_guys global bad_guys good_guy_check() print(' ',end=' ') if place == "a Forest": storyprint("The good...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function 'confused()' simulates a scenario where a randomly selected good guy becomes confused, mistakenly believes a bad guy is their friend, and defects to the bad guys' side. It updates the global lists of good and bad guys, prints narrative text describing the event, and handles the character's allegiance switc...
def confused(): """Not finished yet""" global good_guys global bad_guys global inactive_bad_guys global inactive_good_guys good_guy_check() """The good guys get confused in this function.""" storyprint(" The good guy"+is_plural(good_guys)+" got confused.", "\n") if len(bad_guys) > 0...
def SaveDraftAs(): global TextLines global startTimes global endTimes global totaltimelapsed global WorkingFile WorkingFile = filedialog.asksaveasfilename(initialdir=WorkingDir, title = "Save Draft file",filetypes = (("BroCColi Drafts","*.dat"),("all files","*.*"))) if WorkingFile != '': ...
The main task of the code is to save session data—including timestamps and text lines—into a file specified by `WorkingFile`. If no file is specified, it prompts to save as a new file. It serializes the data using `pickle`, updates the UI with a "Saved draft" message, and triggers a display refresh.
def SaveDraft(): global TextLines global startTimes global endTimes global totaltimelapsed if WorkingFile == "Not Specified": SaveDraftAs() else: saved_data = {"starts" : startTimes, "ends" : endTimes, "Texts" : TextLines, "time" : totaltimelapsed} save_file = open(WorkingFile,...
def Time_convert(sec): mins = sec // 60 hours = mins // 60 mins = mins % 60 sec = sec % 60 if len(str(mins)) == 1: DisMins = "0" + str(mins) mins = DisMins if len(str(sec)) == 1: DisSecs = "0" + str(sec) sec = DisSecs if len(str(hours)) == 1: DisHrs = "0" + str(hours) h...
(Pause function stops the timer by setting running to False, updates the accumulated totaltimelapsed with the elapsed time since StartTime, converts this to a timestamp, triggers AddTimes() if addingtimes is True, and updates UI elements to reflect paused state by changing colors of PauseRec1, PauseRec2, and PlayTriang...
def Pause(addingtimes): global totaltimelapsed global running global Timestamp global StartTime canvas.itemconfig(PauseRec2, fill="red") canvas.itemconfig(PauseRec1, fill="red") canvas.itemconfig(PlayTriangle, fill="") running = False timepassed = int(time.time()) - StartTime tot...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function introduces a bad guy into a narrative, randomly selecting a crime and determining their activity status. It interacts with global variables tracking characters and locations, generating story segments where the bad guy commits a crime, engages with good guys, or remains inactive. The function includes cond...
def introduce_bad_guy(): """Introduces bad guy""" global bad_guys global inactive_bad_guys global inactive_good_guys global good_guys global Places global PlaceTypes global Tools global place good_guy_check() isActive = random.randint(0, 1) r = random.randint(0, 3) s ...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The main task of the code is to simulate a random elevator ride for the good guys, where characters (good or bad) may enter/exit, directions change, and unexpected events like breakdowns or fights occur, affecting the story's progression and character statuses.
def elevator(): """When this function is called, the good guys take an elevator ride. Who will they find in there?""" global Places global PlaceTypes global good_guys global bad_guys global inactive_good_guys global inactive_bad_guys good_guy_check() doors = "closed" elev_directi...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function `new_mission()` generates a random task for "good guys" in a game, selecting from mission types like "Take," "Destroy," "Visit," or "Meet." It ensures tasks are unique, uses global variables for game state, and dynamically creates goals by selecting items, places, or characters. It also handles communicati...
def new_mission(): """This function gives the good guys a goal to work towards.""" global goals global Tools global inventory global Places global good_adjectives global good_guys global bad_guys global bad_adjective global Animals global Vehicles global inactive_good_guy...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The main task of the code is to provide a tool to the good guys by selecting it from goals, user input, or random choices, while managing inventory and money. It checks for "Take" or "Destroy" goals, handles shopping logic with money, updates inventory, and ensures the tool is acquired or denied based on conditions.
def get_tool(): """Gives the good guys a tool.""" global Tools global inventory global good_guys good_guy_check() if findGoal("Take") and random.randint(0,1) == 1: for goal in goals: if goal.startswith("Take"): new_tool = goal.replace("Take ", "") ...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function `goal_resolve` processes and resolves a randomly selected goal from the global `goals` list by executing corresponding actions (e.g., meeting characters, moving locations, acquiring/destroying items). It updates game state variables like inventory, locations, and character lists, generates narrative output...
def goal_resolve(): """This function resolves a goal if there are any goals.""" global goals global Tools global inventory global Places global good_adjectives global good_guys global bad_guys global bad_adjective global Animals global Vehicles global inactive_good_guys ...
def Pause(addingtimes): global totaltimelapsed global running global Timestamp global StartTime canvas.itemconfig(PauseRec2, fill="red") canvas.itemconfig(PauseRec1, fill="red") canvas.itemconfig(PlayTriangle, fill="") running = False timepassed = int(time.time()) - StartTime tot...
The main task of the code is to manage playback state transitions by comparing the lengths of global time lists (startTimes, endTimes) and TextLines. It pauses or resumes playback based on whether startTimes exceed endTimes, and triggers Play/ Pause actions conditionally to synchronize timing data with text lines durin...
def AddPp(): global startTimes global endTimes global TextLines if running == True and len(startTimes) > len(endTimes): Pause(True) if len(TextLines)>len(endTimes): Play(False) else: if running == True: Pause(False) Play(True) ...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
The function `location_specific()` handles narrative events based on the current game location, modifying character statuses, inventory, goals, and story progression. It triggers location-specific challenges like radiation in Chernobyl, pirate battles in the Open ocean, or encounters with ghosts in a Haunted house, dyn...
def location_specific(): """This function does something different, depending on the location.""" global goals global Tools global inventory global Places global PlaceTypes global good_adjectives global good_guys global bad_guys global bad_adjective global Animals global ...
def good_guy_check(): """Checks if there are active good guys. If not, then this function will introduce or re-introduce good guys.""" global good_guys global inactive_good_guys if len(good_guys) == 0: if len(inactive_good_guys) > 0: good_guys = inactive_good_guys inactiv...
This function processes the use of items from the inventory in a narrative game, modifying game state (e.g., removing items, altering character statuses, changing locations) through conditional logic. It handles item-specific actions like combat, stealth, traversal, and story progression, using randomness for outcomes ...
def use_item(): global inventory global place global PlaceTypes global good_guys global bad_guys global inactive_good_guys global goals global inactive_bad_guys global death_terms good_guy_check() if len(inventory) > 0: used_item = random.choice(inventory) if ...
def saveAnswer(index): opted='' #Empty String (1: Checked 0: Unchecked) if option1.get()==1: opted+='1' #Means Checked if option2.get()==1: opted+='2' if option3.get()==1: opted+='3' if option4.get()==1: opted+='4' print('save Answer, opted=', opted) answerList[index]=opted def c...
This function handles navigation between questions in a quiz application. It updates the current question index based on user input ('F' to finish, 'P' for previous, 'N' for next), saves the current answer, updates the displayed question, and adjusts button states. It ensures index boundaries are respected and terminat...
def navigationClick(value): #08-Aug global index, totalQuestions, previousIndex #Without writing variable as global, a new local variable created previousIndex=index #Store previous index value saveAnswer(previousIndex) #OR saveAnswer(index) 10-Aug #changeButtonState(previousIndex) #Update value...
def make_path_absolute(self, path): if path is not None: path = pathlib.Path(path) if path.is_absolute(): path = path.resolve() else: path = self.music_root/path return path def exists(self, label_name): scanner = LabelScanner(s...
This code adds a label to a specified path by managing associated files. It handles directories and files differently: for directories, it ensures the label exists or creates it, while for files, it checks for existing labels and updates files accordingly. The 'new' parameter controls whether the label must be newly cr...
def add(self, label_name, path, new): fnames = LabelFilenamePair(label_name) abspath = self.make_path_absolute(path) if abspath.is_dir(): if not new and not self.exists(label_name): print(f"Label {label_name} doesn't exist") exit(1) (abspat...
def make_path_absolute(self, path): if path is not None: path = pathlib.Path(path) if path.is_absolute(): path = path.resolve() else: path = self.music_root/path return path def exists(self, label_name): scanner = LabelScanner(s...
This code removes a specified label from a given file or directory by modifying associated label files. It checks if the label exists, handles directory and file cases differently, and updates or deletes entries in label tracking files. It ensures the label is removed and provides feedback via print statements.
def remove(self, label_name, path): fnames = LabelFilenamePair(label_name) abspath = self.make_path_absolute(path) if abspath.is_dir(): if not self.exists(label_name): print(f"Label {label_name} doesn't exist") exit(1) (abspath/fnames.all_e...
def list_labels(self, path=None): if path is None: labels = LabelScanner(self.music_root, {}).get_existing_labels() else: labels = LabelScanner(self.music_root, self.all_songs_in(path), allow_missing=True).get_nonempty_labels() for s in sorted(labels): print(s...
This code defines a command-line interface (CLI) parser for managing music labels and songs. It sets up subcommands like 'list-labels', 'list-songs', 'exists', 'has', 'add', and 'remove', each with specific arguments. The parser maps these commands to corresponding methods, enabling users to interact with a music datab...
def arg_parser(self): parser = argparse.ArgumentParser() parser.add_argument("--mpd", default="/run/mpd/socket") subparsers = parser.add_subparsers() sp = subparsers.add_parser('list-labels') sp.add_argument("path", nargs='?') sp.set_defaults(func=lambda: self.list_label...
def _generate_round_keys(self, private_key: np.array) -> list: working_array = np.zeros((4, 44), dtype=np.ubyte) round_constants = [None, int('1', 16), int('2', 16), int('4', 16), int('8', 16), int('10', 16), int('20', 16) , int('40', 16), int('80', 16), int('1b', 16), int('36', 16)] ...
This function performs AES encryption on a 16-byte plaintext using a given key. It initializes the state with key-plaintext XOR, applies 9 rounds of AES transformations (substitution, shifting, mixing, and key addition) using precomputed round keys, then executes a final round. The result is converted to a string and r...
def _encode_16(self, key: str, plaintext: str) -> str: """encodes a 16 byte string """ key_array = Converter.make_array(key) plaintext_array = Converter.make_array(plaintext) # generate round keys round_keys = self._generate_round_keys(Converter.byte_to_hex(key_array)) ...
def _generate_round_keys(self, private_key: np.array) -> list: working_array = np.zeros((4, 44), dtype=np.ubyte) round_constants = [None, int('1', 16), int('2', 16), int('4', 16), int('8', 16), int('10', 16), int('20', 16) , int('40', 16), int('80', 16), int('1b', 16), int('36', 16)] ...
This function decodes a 16-byte AES ciphertext using a given key. It generates round keys, applies inverse AES rounds (9 main rounds + final round), and XORs the result with the key to retrieve plaintext. The process involves array conversion, hexadecimal operations, and bitwise XOR to reverse AES encryption securely.
def _decode_16(self, key: str, cyphertext: str): """decodes a 16 byte string""" key_array = Converter.make_array(key) cyphertext_array = Converter.make_array(cyphertext) # generate round keys round_keys = self._generate_round_keys(Converter.byte_to_hex(key_array)) # Add...
def getWidth(self): return self.width def getHeight(self): return self.height def getTile(self, x, y): if (not self.__isTileValid(x, y)): raise ValueError("Coordinates must be at least 0 and less than max.") return self.board[x][y]
The main task of the code is to randomly place a specified number of bombs on a grid. It generates random coordinates, checks if a tile is bomb-free, and places a bomb there if so, repeating until all bombs are placed.
def __placeBombs(self): i=0; while i<self.bombNr: randomX=random.randint(0, self.getWidth()-1) randomY=random.randint(0,self.getHeight()-1) tile = self.getTile(randomX, randomY) if (not tile.isBomb()): tile.setBomb() i+=1
def getHeight(self): return self.height def getWidth(self): return self.width def getTile(self, x, y): if (not self.__isTileValid(x, y)): raise ValueError("Coordinates must be at least 0 and less than max.") return self.board[x][y] def __isTileValid(self, x, y): if (n...
The main task of the code is to calculate and assign the number of adjacent bombs to each non-bomb tile in a grid. It iterates through every tile, checks its 8 surrounding cells, counts bombs, and sets the tile's number accordingly. This is typical for Minesweeper-style games to indicate nearby mines.
def __placeNumbers(self): for y in range(self.getHeight()): for x in range(self.getWidth()): if (not self.getTile(x, y).isBomb()): tileNumber=0 for j in range(-1, 2, 1): for i in range(-1, 2, 1): ...
def getTile(self, x, y): if (not self.__isTileValid(x, y)): raise ValueError("Coordinates must be at least 0 and less than max.") return self.board[x][y] def __isTileValid(self, x, y): if (not isinstance(x, int) or not isinstance(y, int)): raise TypeError("Coordinates mus...
The function uncovers a tile at coordinates (x, y) if it's covered and not flagged. If the tile is a bomb, it stops. If it's empty ("air"), it recursively uncovers all valid adjacent tiles that are not bombs, propagating the uncover action across connected safe tiles in a Minesweeper-like game.
def uncover(self, x, y): tile = self.getTile(x,y) if (tile.isCovered() and not tile.isFlag()): tile.uncover() if (tile.isBomb()): return if (tile.isAir()): for j in range(-1, 2, 1): for i in range(-1, 2, 1): ...
def getHeight(self): return self.height def getWidth(self): return self.width def getTile(self, x, y): if (not self.__isTileValid(x, y)): raise ValueError("Coordinates must be at least 0 and less than max.") return self.board[x][y]
This method generates a string representation of a grid by iterating over each tile, appending its string form with spacing, and formatting it into a multi-line structure for display.
def __str__(self): string = "" for y in range(self.getHeight()): for x in range(self.getWidth()): tile = self.getTile(x, y) string += tile.__str__() + " " string+="\n" return string
def __areProportionsValid(self, width, height): if (not isinstance(width, int) or not isinstance(height, int)): raise TypeError("Tile number must be integer.") if (width<1 or height<1): raise ValueError("Width and height must be possitive integers.") def __isBombNrValid(self, b...
The code initializes a game board with specified height, width, and bomb count. It validates dimensions and bomb number, creates a 2D grid, places bombs, and calculates adjacent numbers for each cell.
def __init__(self, height, width, bombNr): self.height=height self.width=width self.bombNr=bombNr self.__areProportionsValid(height, width) self.__isBombNrValid(height, width, bombNr) self.board=[[0 for i in range(self.width)] for j in range(self.height)] self.__...
def getTile(self, x, y): if (not self.__isTileValid(x, y)): raise ValueError("Coordinates must be at least 0 and less than max.") return self.board[x][y] def __isTileValid(self, x, y): if (not isinstance(x, int) or not isinstance(y, int)): raise TypeError("Coordinates mus...
This function uncovers neighboring tiles around (x,y) if the count of adjacent flags matches the current tile's value. It first checks if the tile is not covered, counts nearby flags, then uncovers valid adjacent tiles when the flag count equals the tile's type, avoiding self-referential checks.
def uncoverNearbyTiles(self, x, y): nearbyFlagCount=0 tile = self.getTile(x, y) if (not tile.isCovered()): for j in range(-1, 2, 1): for i in range(-1, 2, 1): if (self.__isTileValid(x+i,y+j)): if (tile.is...
def __gen_data(): obj = load_obj("./hrp2/RL_com._reduced.obj") ineq = as_inequalities(obj) ok_points = [[0, 0, 0], [0.0813, 0.0974, 0.2326], [-0.3387, 0.1271, -0.5354]] not_ok_points = [[-0.3399, 0.2478, -0.722], [-0.1385, -0.4401, -0.1071]] return obj, ineq, ok_points, not_ok_points def rotate_ineq...
This function tests if rotating inequalities using a transformation matrix correctly classifies points as inside or outside a 3D object. It applies the matrix to generated data points, checks if transformed "valid" points are inside the rotated inequalities, and ensures "invalid" points are outside, verifying the rotat...
def test_rotate_inequalities(): tr = np.array( [ [1.0, 0.0, 0.0, 0.0], [0.0, 0.98006658, -0.19866933, 2.0], [0.0, 0.19866933, 0.98006658, 0.0], [0.0, 0.0, 0.0, 1.0], ] ) data = __gen_data() ineq = rotate_inequalities(data[1], tr) ok_p...
def isSatisfyKKT(self, i): gxi =self.calc_gxi(i) yi = self.trainLabelMat[i] if (math.fabs(self.alpha[i]) < self.toler) and (yi * gxi >= 1): return True elif (math.fabs(self.alpha[i] - self.C[i]) < self.toler) and (yi * gxi <= 1): return True elif (self.alp...
This code implements the Sequential Minimal Optimization (SMO) algorithm for training a Support Vector Machine (SVM). It iteratively updates Lagrange multipliers (alphas) by selecting pairs of data points, enforcing KKT conditions, computing error terms, and adjusting the bias term. Parameters are refined until converg...
def train(self, iter = 100): iterStep = 0; parameterChanged = 1 while (iterStep < iter) and (parameterChanged > 0): iterStep += 1 parameterChanged = 0 for i in range(self.m): if self.isSatisfyKKT(i) == False: E1 = self.calcEi(i) ...
def create_png(pixels, intersection, colors, image_stack): color_arr = assign_colors(colors) base_color = color_arr[0] mixed_color = color_arr[1] secondary_color = color_arr[2] data = np.full((1, pixels, 3), fill_value=base_color, dtype=np.uint8) py_path = os.path.abspath(__file__) py_dir =...
The main task of the code is to generate a GIF animation by creating a series of layered images using pixel data and color schemes, then stitching them into a single animated GIF file named 'filename'. The 'create_png' function likely generates individual image frames, which are collected in 'image_stack' and combined ...
def create_bar(pixels, colors, intersection, filename): image_stack = [] create_png(pixels, intersection, colors, image_stack) stitch_gif(filename, image_stack) cleanup()
def setRange(self, p_int, p_int_1): super().setRange(int(p_int), int(p_int_1)) def update_default(self, default): self._default = default if self._default is not None: self.reset_default() def update_display(self, val=None): if val is None: val = self.value() ...
The code initializes a horizontal slider UI component with customizable range, step size, and display settings. It sets up a label, adjusts the slider's range based on input values, configures display formatting, connects value changes to update methods, and initializes default values. The slider includes a secondary d...
def __init__(self, default, display_name, vmin=None, vmax=None, div=1, step=1, dtype=None): super().__init__(Qt.Horizontal) self.label = W.QLabel(display_name) self._dtype = dtype self._div = div if None not in (vmin, vmax): self.setRange(vmin * self._div, vmax * self...
def load_model_for_test(FLAGS, input_shape, n_classes=5, generator=None, FLAGS_ORIGINAL=None, new_fname=None): print('------------ BUILDING MODEL ------------\n') print('Model n_classes : %s ' %n_classes) if generator is not None: print('Features shape: %...
(The main task of the code is to parse command-line arguments for configuring model evaluation parameters, load a pre-trained model, generate test data, and evaluate the model's accuracy (with Bayesian Monte Carlo sampling if enabled) on test samples, saving results to a specified output path. It handles noise/shock se...
def main(): parser = argparse.ArgumentParser() parser.add_argument("--log_path", default='', type=str, required=True) parser.add_argument("--TEST_DIR", default='data/test_data/', type=str, required=False) parser.add_argument("--models_dir", default='models/', type=str, required=False) pars...
def func1(self,a): # for action 1😁👌 b = 255/np.log(a*255 + 1) return (lambda x: b*np.log(a*x + 1)) def func2(self,a): #for action 2 b = 255/np.log(a*255 + 1) return (lambda x: (np.exp(x/b) -1)/a) def lin_stretch(self, x_min, x_max): return (lambda x: 255*(x - x_min)/(x_max - x_min)) def adaptive_one(self): ...
This code transforms a deteriorated image using a parameter-driven approach. It applies different image processing functions (e.g., linear stretching, sigmoid, adaptive methods) based on the input value 'a'. Each pixel is modified using the selected function, and the result is stored as a uint8 array. The transformatio...
def transform_image(self, a): """Receives the deteriorated image and modifies it""" if a == 0: do: Callable = self.func1(1/40) elif a == 1: do: Callable = self.func2(1/40) elif a == 2: do: Callable = self.sigm_ref elif a == 3: do: Callable = self.sigmoid elif a == 4: x_min, x_max = self.imd.m...
def get_player_name(self): self.print_slow("Welcome to the Text Adventure Game!") self.print_slow("What's your name?") self.player_name = input("> ") def print_slow(self, text): for char in text: print(char, end='', flush=True) time.sleep(0.05) print() def...
The main task of the code is to initialize and start a text-based adventure game. It prompts the player for their name, introduces a narrative scenario in a dark forest with two path choices, and directs the game flow by calling either the "left" or "right" path methods based on user input, establishing the first decis...
def start_game(self): self.get_player_name() self.print_slow(f"Hello, {self.player_name}! Let the adventure begin.") self.print_slow("You find yourself in a dark forest. There are two paths ahead.") choice = self.get_user_choice(["Go left", "Go right"]) if choice == 1: ...
def create_daily_change(self) -> pd.DataFrame: """ Creates return series from wide stocks data (please choose one price type, default is adj_close) :return: a dataframe with returns for given price type """ data = self.preprocess() dly_chg = data.pct_change(1) sel...
The function generates a DataFrame containing stocks' mean returns, volatility (standard deviation), and their respective sectors. It calculates these metrics using either daily or monthly price changes, merges them with sector data from a database, and returns a structured DataFrame with columns: symbol, mean, vol, an...
def create_mean_var_df(self, daily_freq: bool = True) -> pd.DataFrame: """ Create a dataframe containing data about stocks' mean return and variance, and the respective sectors :param daily_freq: boolean, True if you want to use daily price change frequency, False if monthly :return: ret...
def load_instance_names(path): with open(path) as f: return [tuple(line.strip().split('/', 1)) for line in f] def create_runtime_df(all_instances): df = pd.DataFrame() for dataset, _ in all_instances: for alg in ['qp', 'sgc', 'weight', 'layer', 'branch']: path = f'{DATA_DIR}/sta...
The code processes runtime and quality data from multiple datasets and algorithms, aggregates results, computes closure sizes, and generates visualizations (figures 1-7) for a research paper, saving outputs as SVG files. It combines data from small, medium, and large instance groups, loads runtime statistics, and creat...
def main(): small_instances = load_instance_names(f'{SCRIPT_DIR}/target_small.txt') medium_instances = load_instance_names(f'{SCRIPT_DIR}/target_medium.txt') large_instances = load_instance_names(f'{SCRIPT_DIR}/target_large.txt') all_instances = small_instances + medium_instances + large_instances ...
def disable_all(self): disable(self.main) disable(self.buttons_frame) disable(self.organize_menu) def cwd(self, path): try: self.status.set_error_status("") os.chdir(path) return True except FileNotFoundError: self.enable_all() ...
The main task of the code is to organize files in a specified directory by their extensions. It creates subdirectories named after each file extension, moves files into their corresponding subdirectories, and tracks changes in an undo list for potential reversal. The function disables UI elements during processing, upd...
def organize_by_ext(self): self.disable_all() path = self.path.get() if not self.cwd(path): return self.undo_list['path'] = path self.undo_list['dirs'].clear() # os.chdir(path) list_ = [file_ for file_ in os.listdir(path) if os.path.isfile(file_)] ...
def disable_all(self): disable(self.main) disable(self.buttons_frame) disable(self.organize_menu) def cwd(self, path): try: self.status.set_error_status("") os.chdir(path) return True except FileNotFoundError: self.enable_all() ...
The main task of the code is to organize files in a specified directory by moving them into subfolders named after their last modified date. It disables operations, retrieves the target path, lists files, and iterates through them to create date-named directories if they don't exist, then moves files into these folders...
def organize_by_dom(self): self.disable_all() path = self.path.get() if not self.cwd(path): return self.undo_list['path'] = path self.undo_list['dirs'].clear() # os.chdir(path) list_ = [file_ for file_ in os.listdir(path) if os.path.isfile(file_)] ...
def disable_all(self): disable(self.main) disable(self.buttons_frame) disable(self.organize_menu) def cwd(self, path): try: self.status.set_error_status("") os.chdir(path) return True except FileNotFoundError: self.enable_all() ...
The main task of the code is to organize files in a specified directory by moving them into subdirectories named after their creation dates. It disables operations, retrieves the target path, lists all files, determines each file's creation date, creates date-named directories if they don't exist, moves files into thes...
def organize_by_doc(self): self.disable_all() path = self.path.get() if not self.cwd(path): return self.undo_list['path'] = path self.undo_list['dirs'].clear() # os.chdir(path) list_ = [file_ for file_ in os.listdir(path) if os.path.isfile(file_)] ...
def disable_all(self): disable(self.main) disable(self.buttons_frame) disable(self.organize_menu) def cwd(self, path): try: self.status.set_error_status("") os.chdir(path) return True except FileNotFoundError: self.enable_all() ...
This function organizes files in a specified directory by their file types. It disables operations, lists files, categorizes them using predefined formats, creates target directories if needed, moves files accordingly, updates status tracking, and re-enables operations. It handles exceptions, tracks moved files, and ma...
def organize_by_type(self): self.disable_all() path = self.path.get() if not self.cwd(path): return self.undo_list['path'] = path self.undo_list['dirs'].clear() list_ = [file_ for file_ in os.listdir(path) if os.path.isfile(file_)] nof = len(list_) ...
def organize_by_type(self): self.disable_all() path = self.path.get() if not self.cwd(path): return self.undo_list['path'] = path self.undo_list['dirs'].clear() list_ = [file_ for file_ in os.listdir(path) if os.path.isfile(file_)] nof = len(list_) ...
The `organize` method determines the organization strategy by checking the selected index in `organize_options`, then calls corresponding functions like `organize_by_type`, `organize_by_ext`, etc., to execute file or data organization based on user selection. It acts as a dispatcher for different categorization rules.
def organize(self): if self.organize_options.current() == 0: self.organize_by_type() elif self.organize_options.current() == 1: self.organize_by_ext() elif self.organize_options.current() == 2: self.organize_by_doc() elif self.organize_options.current(...
def create_socket(): try: global host global port global s # socket host = "" port = 9999 s = socket.socket() # socket created except socket.error as msg: print("socket creation error"+str(msg)) def bind_socket(): try: global host glo...
The main task of the code is to set up a server socket by creating a socket, binding it to a specific address and port, and then accepting incoming client connections. This sequence initializes a network server capable of receiving and processing client requests.
def main(): create_socket() bind_socket() socket_accept()
def movies_with_price(self): rented_movies = '' for movie in self.rented_movies: if self.catalog[movie] == 'Regular': rented_movies += f' {movie} {self.calculate_regular_movie_price(movie)} \n' elif self.catalog[movie] == 'Child': rented_movies += f' {movie} {self.calculate_childs_movie_price(movie)} ...
The main task of the code is to generate a formatted customer statement by inserting dynamic data like customer details, movie prices, total cost, and loyalty points into a template string. If formatting errors occur, it defaults to omitting the total and points fields, returning a partially populated statement.
def get_statement(self): try: self._statement = self._statement.format(self.customer, self.movies_with_price(), self.calculate_total(), self.calculate_points()) except: self._statement = self._statement.format(self.customer, '') return self._statement
def is_royal_flush(self): if self.is_straight_flush() and self.cards[0].rank == 10: return True else: return False def is_straight_flush(self): if self.is_flush() and self.is_straight(): return True else: return False def is_four_of_a_kind(...
This method determines and returns the highest-ranking poker hand type by evaluating conditions in a specific priority order, using helper methods like is_royal_flush() and is_straight_flush(), ultimately returning labels such as "Royal Flush" or "High Card" based on the hand's characteristics.
def _get_hand_type(self): """ This method will return the hand type of the hand. Returns: str: The hand type of the hand. """ if self.is_royal_flush(): return "Royal Flush" elif self.is_straight_flush(): return "Straight Flush" ...
def modell(n, Hgens): R = Integers(2**n) return [[R(h[0]), R(h[1]), R(h[2]), R(h[3])] for h in Hgens] def borels(Hgens, n, previous=False, previousB = None): output = [] if n == 1: for v in P1[n]: if is_eigenvector(Hgens, v): output.append(v) return output ...
This function checks if the subgroup generated by Hgens is either Borel modulo ell^m and Cartan modulo ell^{n−m} for some m ≤ n, or contained in a specific A_{a,c,b} subgroup structure. It iterates over m, computes modular reductions, evaluates Borel/Cartan conditions, and verifies congruence properties for potential c...
def in_A(Hgens, n): #m = a+b, the power of ell mod which it is Borel previous = False previousB = None for m in range(1, n+1): Hgens_m = modell(m,Hgens) B = borels(Hgens_m, m, previous, previousB) #first check condition of being Borel mod ell^m and Cartan mod ell^{n...
def modell(n, Hgens): R = Integers(ell**n) return [[R(h[0]), R(h[1]), R(h[2]), R(h[3])] for h in Hgens] def independent_vectors(v, n): for w in V[n]: if v[0]*w[1] - v[1]*w[0] % ell != 0: break ind_vecs = [] for i in range(ell): for j in range(1,ell): ind_vecs....
This function checks if there exists a pair of vectors [v, w] from borels_nminus1 such that, after changing the basis of Hgens_nminus1, the transformed generators satisfy specific divisibility conditions involving exponents of ell. It computes minimal values from these generators and verifies if a derived structure is ...
def in_A_minimal(Hgens, n, borels_nminus1): Hgens_nminus1 = modell(n-1,Hgens) for v in borels_nminus1: iv = independent_vectors(v, n-1) for w in iv: CB_Hgens = change_basis(Hgens_nminus1, [v, w]) beta_min_val = n-1 delta_minus_alpha_min_val = n-1 ...
def modell(n, Hgens): R = Integers(ell**n) return [[R(h[0]), R(h[1]), R(h[2]), R(h[3])] for h in Hgens] def borels(Hgens, n, previous=False, previousB = None): output = [] if n == 1: for v in P1[n]: if is_eigenvector(Hgens, v): output.append(v) return output ...
The function checks if the input Hgens satisfies Borel-Cartan conditions modulo powers of a prime ell. It iterates over m from 1 to n, verifying if Hgens mod ell^m is Borel and mod ell^{n-m} is Cartan. If not, it checks containment in specific A_{a,c,b} subgroups by evaluating valuations and basis changes. Returns True...
def in_A(Hgens, n): #m = a+b, the power of ell mod which it is Borel previous = False previousB = None for m in range(1, n+1): Hgens_m = modell(m,Hgens) B = borels(Hgens_m, m, previous, previousB) #first check condition of being Borel mod ell^m and Cartan mod ell^{n...
def in_cartan(Hgens, n): vecs = [] for v in P1[n]: if len(vecs) == 1: w = vecs[0] if (v[0] * w[1] - w[0] * v[1]) % ell == 0: continue if is_eigenvector(Hgens, v): vecs.append(v) if len(vecs) == 2: return True return Fals...
The function `check_conclusions` determines whether specific algebraic conditions on a group element `Hgens` are satisfied. It returns `True` if `Hgens` lies in the Cartan subgroup, generates non-empty Borel subgroups, or meets criteria for `A_minimal` structures; otherwise, it returns `False`. This checks structural p...
def check_conclusions(n, label, Hgens, borels_nminus1): if in_cartan(Hgens, 1): return True borels_n = borels(Hgens, n, previous = True, previousB = borels_nminus1) if len(borels_n) > 0: return True if in_A_minimal(Hgens, n, borels_nminus1): return True re...
def make_list_of_data(file_name): data = [] for line in open(file_name + ".txt", "r"): label = line.split(":")[0] nn = ZZ(line.split(":")[1]) level = ZZ(line.split(":")[2]) index = ZZ(line.split(":")[3]) Gammabar_gens = ast.literal_eval(line.split(":")[4]) nu2 = Z...
The main task of the code is to analyze data from a file to identify primes and their combinations that generate counterexamples via fiber products with low genus. It processes groups with small genus, checks fiber products between groups and modular curves X₀(p), and collects primes/their products in a set `L` that le...
def test_bad_file(file_name): L = set([]) small_gps = [] data_list = make_list_of_data(file_name) #print data_list for d in data_list: if d[-1] <= 1: small_gps.append(d) ell = d[2].prime_factors()[0] L.add(ell**d[1]) for badgp in small_gps: #pr...
def borels(Hgens, n, previous=False, previousB = None): output = [] if n == 1: for v in P1[n]: if is_eigenvector(Hgens, v): output.append(v) return output if previous: B = previousB else: B = borels(modell(n - 1, Hgens), n - 1) for v in B: ...
This function identifies subgroups that fail specific mathematical conditions related to Borel subgroups. It reads subgroup data from a file, checks if they are contained in a Borel subgroup modulo $ \ell^{n-1} $, verifies conclusions and hypotheses, and collects subgroups that violate these rules into a list called 'b...
def check_lift_exceptional_subgroups(n, string="gl2_"): N = ell**n bads = [] for line in open(string + str(N) + ".txt", "r"): label = line.split(":")[0] gens = line.split(":")[1] Hgens = ast.literal_eval(gens) #print('checking ', label) #is it contained in a borel mo...
def get_clicked_cell_index(self): col = self.knifwin.tableWidget.currentColumn() row = self.knifwin.tableWidget.currentRow() index = col, row return index def checked_btn_clicked(self): dice1 = None dice2 = None dice3 = None dice4 = None dice5 = No...
This function calculates the sum of selected dice values from a Kniffel game, updates the corresponding table cell with the sum, recalculates totals, and advances to the next player. It checks clicked dice, sums their values, writes the result into the clicked cell, and triggers total calculation and player transition.
def entry_throw_top_part(self): # get the sum of selected dies and writes it into the clicked cell index_x, index_y = self.get_clicked_cell_index() # automatically calls next_player() and calculates if index_y < 6 and index_x == PLAYER: # the whole Kniffelblatt throw_value = 0 ...
def parse_log_file(log_path): with open(log_path,'r') as f: log = f.readlines() for line in log: if "chi^2" in line: M = int(line.split("(")[1].split(" ")[0]) if "Total Observed scale" in line: h2g = float(line.split(":")[1].strip().split(" ")[0]) return (M, h2g) def parse_results_file(results_path,...
The code aggregates and summarizes genetic trait analysis results across multiple tissues. It processes log and results files for each tissue, compiles statistics like SNP proportions, heritability estimates, and enrichment metrics into a DataFrame, then exports the summary as a TSV file. It also identifies and saves t...
def main(path, prefix, trait, iteration): TISSUES = ["ADIPOSE_TISSUE","ADRENAL_GLAND","ARTERIAL_BLOOD_VESSEL","BLOOD","BLOOD_VESSEL","BONE_ELEMENT", "BONE_MARROW","BRAIN","BREAST","COLON","CONNECTIVE_TISSUE","EAR","EMBRYO","ENDOCRINE_GLAND", "EPITHELIUM","ESOPHAGUS","EXOCRINE_GLAND","EXTRAEMBRYONIC_COMPONEN...
def readLeadTissues(root,trait): with open(f"{trait}.lead_tissue","r") as f: lead_tissues = f.readlines() lead_tissues = list(map(lambda s: s.strip(), lead_tissues)) return lead_tissues def evaluateFirstIteration(ancestry, trait, iteration, isQuant, root, lead_tissues): # Intialize structures master = [] result...
The main task of the code is to evaluate a trait across iterations using either first-iteration logic (if iteration=1) or subsequent-iteration logic, leveraging ancestry data, lead tissues, and quantitativeness flags. It orchestrates trait analysis by routing to specialized evaluation functions based on the iteration c...
def main(ancestry, trait, iteration, isQuant, root): print(f'Evaluating iteration {iteration} for {trait}') lead_tissues = readLeadTissues(root,trait) # First iteration, follow first iteration logic if iteration == 1: evaluateFirstIteration(ancestry, trait, iteration, isQuant, root, lead_tissues) # Subsequent...
def _add_files(self, files, debug=False): if debug: print(f"Adding files to internal dataframe...") if not files: if debug: print(f"No files to add found.") return df = pandas.DataFrame(files, columns=["path"]) if debug: ...
The main task of the code is to iterate through a specified directory path, collect all files and subdirectories, separately process them via `_add_files` and `_add_directories`, handle duplicates with `_update_duplicates`, and optionally output debug logs about the operation.
def iterate(self, path, debug=False): if debug: print(f"Iterating through {path}") all_files = [file_path for file_path in pathlib.Path(path).rglob("*")] files = [file_path for file_path in all_files if file_path.is_file()] directories = [file_path for file_path in all_files...
def get_end_effector_transform(self): return self.arm.fkine(self.arm.q) def _perform_ik_search(self, t, q0=None): q0 = self.arm.q if q0 is None else q0 # Use Newton Raphson since it accepts joint limit constraints return self.arm.ik_NR(t, q0=q0, joint_limits=True, slimit=100) def _get_r...
The code generates a trajectory from a specified or current end-effector position to a target point, adjusting coordinates with base and tool offsets. If `rapid` is True, it interpolates joint states directly; otherwise, it uses a planned path. The function handles coordinate transformations and inverse kinematics to c...
def get_trajectory(self, end, start=None, rapid=False): """Get trajectory to arbitrary point""" self.end_effector_pos = self.get_end_effector_transform() end = self.base_offset * end * self.inv_tool_offset # If rapid, just interpolate joint states if rapid: start = ...
def create_robot_interface(self): self.create_joint_controls("Robot Joint Control 1", 1, 6, 1, 0) self.create_joint_controls("Robot Joint Control 2", 2, 3, 2, 0) # Disable robot control panels if E-STOP is pressed if self.estop.get_state(): self.disable_controls() def create...
This code initializes a GUI for robot and printer plate control, setting up a Tkinter window with E-STOP, Start buttons, status indicators, and frames for robot/plate controls. It links interface elements to shared variables for real-time updates and enables interaction with simulation/robot systems.
def __init__(self, r1=None, r2=None, plates=None, robot_can_move=None, obstructions=None, estop=None, simulation_running=None): self.tk = tk.Tk() # Capture shared variables self.robot_1 = r1 self.robot_2 = r2 self.plates = plates self.estop = estop self.simulatio...
def load_instruments(self): self.instruments = Instrument.load_instruments(self.symbol_map, self.startdate, self.enddate) def load_histories(self, instruments, download_article_content=False): ''' load cached ArticleHistory objects ''' for instrument in instruments: ...
The `load_all` method's main task is to load cached dataframes by sequentially calling `load_instruments`, `load_histories` for instrument histories, `load_data` with cached data, and `load_source_df`, aggregating financial data components for further processing or analysis.
def load_all(self): ''' load cached dataframes ''' self.load_instruments() self.load_histories(self.instruments) self.load_data(from_cache=True) self.load_source_df()
def extract_param(request, name): if 'querystring' not in request: return None params = urllib.parse.parse_qs(request['querystring']) if name not in params: return None return params[name][0] def random_songs(collection, limit): term = generate_word_stem(3) forward = random.cho...
This Lambda function handles GET requests for two endpoints: '/random' to retrieve random songs based on a collection and limit, and '/songs' to fetch paginated song data using parameters like collection, index, query, and token. It validates required parameters, processes requests, and returns responses or errors (400...
def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] q = '?' + request['querystring'] if 'querystring' in request else '' print(f'method={request["method"]}, path={request["uri"]}{q}') if request['method'] == 'GET' and '/random' in request['uri']: collection = ext...
def full_board(board): """Checks if the board is completely filled Args: board (list): game board as a 2D-list Returns: bool: True if the board is full """ for col in range(7): if board[0][col] == 0: return False return True def print_board(board): """Pr...
The main task of the code is to implement a turn-based Connect Four game loop where a human player competes against an AI. The loop alternates between player and AI moves, validates inputs, updates the game board, checks for game-ending conditions (win/draw), and uses iterative deepening for AI decision-making.
def game_loop(): PLAYER_PIECE = 1 AI_PIECE = 2 PLAYERS = ["AI", "PLAYER"] TURN = random.choice(PLAYERS) BOARD = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0...
def is_cell_walkable(self, mapdata, x, y): """ Function returns true if a cell is within the boundary, not unknown, and not an obstacle :param mapdata [OccupancyGrid] The map information. :param x [int] The X coordinate in the grid. :param y [int] ...
The code implements the A* algorithm to find a path from a start to a goal on a grid map. It checks if start/goal positions are walkable, uses a priority queue to explore nodes, calculates costs with Euclidean distance, and reconstructs the path from goal to start. It also handles exceptions by republishing emergency p...
def a_star(self, mapdata, start, goal): """ Using A* algorithm to calculate an path. :param mapdata [OccupancyGrid] The map data. :param start [(int, int)] The initial point (a grid coordinate). :param goal [(int, int)] The goal point (a grid coordinate). :r...
def grid_to_index(self, x, y): """ Returns the index corresponding to the given (x,y) coordinates in the occupancy grid. :param x [int] The cell X coordinate. :param y [int] The cell Y coordinate. :return [int] The index. """ index = y * self.map.info.width + x ...
The code performs dilation and erosion on a frontier grid to expand and refine frontier regions. It duplicates the map, identifies frontier cells (≥90% occupancy), and expands them by setting adjacent cells to 100% occupancy (dilation). It then appends world coordinates of these cells, removes duplicates, and prepares ...
def dilateAndErode(self, frontierGrid): ''' Function dilates existing frontier cells :param frontierGrid [Occupancy Grid] The grid of frontier cells to dilate :return [Occupancy Grid] ''' padding = 0 #Padding for the cells dilut...
def grid_to_index(self, x, y): """ Returns the index corresponding to the given (x,y) coordinates in the occupancy grid. :param x [int] The cell X coordinate. :param y [int] The cell Y coordinate. :return [int] The index. """ index = y * self.map.info.width + x ...
The function calculates the C-Space by expanding obstacles in the map using a specified padding (default 3 cells). It inflates obstacles by marking neighboring cells as 100% obstacles, converts coordinates to world positions, and publishes the updated grid for Rviz visualization. The result is an OccupancyGrid with thi...
def calc_cspace(self,msg): """ Calculates the C-Space, i.e., makes the obstacles in the map thicker. Publishes the list of cells that were added to the original map. :param padding [int] The number of cells around the obstacles. :return [OccupancyGrid] The C-Spac...
def grid_to_index(self, x, y): """ Returns the index corresponding to the given (x,y) coordinates in the occupancy grid. :param x [int] The cell X coordinate. :param y [int] The cell Y coordinate. :return [int] The index. """ index = y * self.map.info.width + x ...
This function performs a depth-first search (DFS) to identify connected frontier cells in a grid map. It recursively explores 8-directional neighbors of a given point, adding unvisited frontier indices (value 100) to the current frontier group in `groupList` and marking them as visited in `visitedList`. The search cont...
def recursiveDFS(self, gridMap, point, visitedList, groupList): ''' Function recursively searches nodes for frontier indices using a DFS search algorithm :param gridMap [OccupancyGrid] The map to search :param point [int, int] A point to seach from :param visitedList [list<int>] ...