dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def pixel_space_to_robot_frame(pixel_x, pixel_y): """ image wise (in pixels), it will probably be something like (0,0) _____________ | | | | |___________| (robot) robot frame (in meters) is like x ^ | y <--- (sourced fr...
The code implements a Tic-Tac-Toe game where a robot plays by detecting the game board via computer vision. It captures video, identifies the board's position and dimensions, converts pixel coordinates to robot frame coordinates, and uses these to update the game state. The robot scans the board ('s'), determines optim...
def main(): gameboard = [['', '', ''], ['', '', ''], ['', '', '']] # if platform.system() == 'Windows': # cap = cv2.VideoCapture(1, cv2.CAP_DSHOW) # else: # cap = cv2.VideoCapture('./images/testVid3.mp4') ret, frame = cap.read() if not ret: print...
def arg_parser(): # Arg parser parser = argparse.ArgumentParser( description=TOOL_DESCRIPTION, epilog="Enjoy the program!") # Add arguments parser.add_argument("-f", help="proj info file", metavar="proj_info_file", type=str, required=Fals...
The main task of the code is to generate and save project build information. It parses input arguments, constructs a build info string using project name, configuration, and system details, writes this data to a specified file, and outputs a success message with version information. The process involves argument handli...
def main(): # Get invocation arguments file, sw_proj_name, build_cfg, pc_name, host_os = arg_parser() # Create build_info_str = create_build_info(sw_proj_name, build_cfg, pc_name, host_os) # Write to file write_proj_info(file, build_info_str) print("") print("===================...
def get_rgb(self, index: int) -> TensorType[3, 480, 640]: rgb = Image.open(f"{self.get_item_base_path(index)}r.png", "r") # rgb = io.imread(f"{self.get_item_base_path(index)}r.png") rgb = F.pil_to_tensor(rgb) # rgb = rgb.float() return rgb def get_depth(self, index: int) -> Tenso...
The main task of the code is to retrieve and process a dataset sample by index. It constructs a `CameraData` object containing RGB, depth, point cloud, segmentation, and grasp data for the given index. If a transformation is defined, it applies it to the sample before returning the processed data.
def __getitem__(self, index): sample = CameraData( rgb=self.get_rgb(index), depth=self.get_depth(index), points=self.get_point_cloud(index), segmentation=self.get_segmentation(index), pos_grasps=self.get_pos_grasps(index), neg_grasps=self.g...
def _sample_beam(self, fc_feats, att_feats, att_masks=None, opt={}): beam_size = opt.get('beam_size', 10) batch_size = fc_feats.size(0) p_fc_feats, p_att_feats, pp_att_feats, p_att_masks = self._prepare_feature(fc_feats, att_feats, att_masks) # let's assume this for now assert ...
This function generates sequences using either greedy sampling or beam search based on input features and options, producing output sequences and their log probabilities. It initializes hidden states, prepares features, and iteratively samples next words, stopping when all sequences complete.
def _sample(self, fc_feats, att_feats, att_masks=None, opt={}): sample_method = opt.get('sample_method', 'greedy') beam_size = opt.get('beam_size', 1) sample_n = int(opt.get('sample_n', 1)) if beam_size > 1: return self._sample_beam(fc_feats, att_feats, att_masks, opt) ...
def execute_microbit (fn, par): if fn == 'TE': send_result_num (temperature ()) else: raise def execute_display (fn, par): if fn == 'SP': display.set_pixel (int (par[0]), int (par[1]), int (par[2])) send_ok () elif fn == 'CL': display.clear () send_ok () ...
The code parses a command string by splitting it into object, function, and parameters. It routes the command to specific handler functions (e.g., `execute_microbit`, `execute_display`) based on the object type. If the object is unrecognized or an error occurs, it triggers an error response via `send_error()`. The main...
def execute (cmd): try: par = cmd.split (':') obj = par[0] fn = par[1] del par[:2] if obj == 'MI': execute_microbit (fn, par) elif obj == 'DI': execute_display (fn, par) elif obj == 'BU': execute_button (fn, par) elif obj == 'PI': execute_pin...
def sample_state(self): return np.array([[np.random.uniform(-self.car.max_steering_angle, self.car.max_steering_angle)], [np.random.uniform(0, self.car.max_theta)], [np.random.uniform(-self.car.max_x, self.car.max_y)], [np.random.unifor...
This function selects the state with the lowest cost from nearby states in a best-first search algorithm. It samples a random state, identifies nearby states, and returns the nearest state with the minimum cost from the active vertex set, ensuring optimal selection for path planning or optimization tasks.
def best_first_selection(self): x_rand = self.sample_state() x_near, inds = self.near(x_rand) if len(x_near) == 0: return self.nearest(x_rand, self.G.V_active) else: best_i = inds[0] for i in inds: if self.cost_active[i] < self.cost_act...
def nearest(self, x_rand, var): if isinstance(var[0], np.ndarray): nearest = var[-1] nearest_i = len(var) - 1 for i, node in enumerate(var): if self.euclidan_dist_norm(nearest[1:], x_rand[1:]) > self.euclidan_dist_norm(node[1:], x_rand[1:]): ...
This function prunes dominated nodes in a graph by removing the nearest state's representative (x_peer) from active nodes and adding it to inactive nodes. It updates the state's representative and cost, then iteratively removes edges and updates the graph structure if x_peer is a leaf node in inactive list. The process...
def prune_dominated_nodes(self, x_new, x_new_cost): s, ind = self.nearest(x_new, self.S) s_new = S() s_new.state = np.copy(s.state) s_new.rep = copy(s.rep) x_peer = s_new.rep if x_peer is not None: for i, act in enumerate(self.G.V_active): if n...
def best_first_selection(self): x_rand = self.sample_state() x_near, inds = self.near(x_rand) if len(x_near) == 0: return self.nearest(x_rand, self.G.V_active) else: best_i = inds[0] for i in inds: if self.cost_active[i] < self.cost_act...
This function performs sampling-based motion planning by iteratively selecting nodes, propagating paths via Monte Carlo methods, checking collision-freeness, and updating a graph structure with optimal nodes. It prunes dominated paths, maintains active/inactive nodes, and publishes trajectory data, returning the final ...
def sst_planning(self): for i in tqdm(range(self.N)): x_selected, ind_selected = self.best_first_selection() x, ips_t = self.monte_carlo_prop(x_selected) x_new = x[-1] dist = self.euclidan_dist_norm(x[0], x_new) if self.collision_free(x): ...
def theta_size(X): return X.shape[1] + 1 def cost_function(self, x, y, sample_weight=None): if sample_weight is None: w = np.ones(y.shape) else: w = sample_weight m = x.shape[0] h = self.probability(self.theta, x) return -1 / m * w.T.dot(y * np.lo...
This code implements gradient descent optimization for a linear model, minimizing a cost function by iteratively adjusting parameters (theta) using weighted training data. It initializes theta randomly, updates it via gradient steps with a specified learning rate, and stops when the cost falls below a tolerance thresho...
def fit(self, X, y, sample_weight=None, lr=0.01, max_iterations=100, tolerance=10 ** -3): if sample_weight is None: sample_weight = np.ones(y.shape) else: sample_weight = sample_weight self.theta = np.random.randn(self.theta_size(X)) iterations = 0 ...
def set_corrected_query(self, corrected_query): self.corrected_query = corrected_query def get_same_id_set(self, word_set): """ search every word separately and return the same doc id set :param word_set: {word} :return: same_id_set: {doc_id} """ word_list = list(...
The code conducts a multi-phase search to rank documents by relevance. It first finds exact matches using stemmed query words, then expands results with synonyms via lemmatization and WordNet. If results are insufficient, it performs single-word searches. Scores combine distance and TF-IDF/BM25 factors, merging exact, ...
def conduct_search(self): """ conduct search and rank search results with distance, and tf-idf(bm25) factors :return: search_result_list: a list of ranked ids [id1, id2, ...] """ # corrected_query = Speller(self.search_query) corrected_query = self.search_query se...
def _get_postings(self, term): posting_list = self.indexer.inverted_index.get(term, None) if posting_list: list_of_doc_id = posting_list.traverse_list() list_of_doc_id_with_skip = posting_list.traverse_skips() return list_of_doc_id, list_of_doc_id_with_skip ...
This code processes a list of queries by tokenizing each query, retrieving postings lists and skip pointers for terms, and applying various DAAT-based retrieval methods (with/without skip pointers and sorting). It stores results, document counts, and comparison metrics in a structured dictionary for each query and meth...
def run_queries(self, query_list): output_dict = {'postingsList': {}, 'postingsListSkip': {}, 'daatAnd': {}, 'daatAndSkip': {}, 'daatAndTfIdf': {}, 'daatAndSkipTfIdf': {}, } ...
def fetch_support_resistance_levels(data, date, INTRA_DAY): spotprice = get_underlying_asset_value(data) data = date_filter(data, date) support_peaks = get_peaks(data, 'Put_OI', INTRA_DAY, 'Put_change_in_OI') resistance_peaks = get_peaks(data, 'Call_OI', INTRA_DAY, 'Call_change_in_OI') support_...
The main task of the code is to determine the market trend (bullish or bearish) by analyzing support and resistance levels from given financial data. It calculates the count of key support and resistance levels, and if at least one exists, it concludes the trend as "Bullish"; otherwise, "Bearish". The result is returne...
def get_trend(data, date, INTRA_DAY): support_key_levels, resistance_key_levels = fetch_support_resistance_levels(data, date, INTRA_DAY) snum = get_supp_num(support_key_levels) rnum = get_resis_num(resistance_key_levels) trend = '' if (rnum + snum > 0): trend = 'Bullish' els...
def track_tokens_filter(lexer, tokens): lexer.at_line_start = at_line_start = True indent = NO_INDENT for token in tokens: token.at_line_start = at_line_start if token.type == "COLON": at_line_start = False indent = MAY_INDENT token.must_indent = False ...
The main task of the code is to filter and yield tokens from a lexer, applying indentation and tracking filters, and optionally appending an ENDMARKER token at the end to signify input completion.
def token_filter(lexer, add_endmarker=True): token = None tokens = iter(lexer.token, None) tokens = track_tokens_filter(lexer, tokens) for token in indentation_filter(tokens): yield token if add_endmarker: lineno = 1 if token is not None: lineno = token.lineno ...
def __load_index_file(self, file_path): index_file_path = os.path.expanduser(file_path) if not os.path.exists(index_file_path) or os.stat(index_file_path).st_size == 0: # return an empty json object return self.__EMPTY_INDEX_JSON else: try: wit...
The code initializes an index by loading an existing index file from the given path, refreshing it with updated data, and optionally saving the refreshed index back to the file if `save_index` is True. It uses a default empty index structure if the file is not found or invalid, ensuring the index is always in a valid s...
def __init__(self, index_file_path, save_index=True): """ Initialize a new index for the given index file path. :param index_file_path: The file path of the index file. :param save_index: Whether to save the index after refreshing it. Defaults to True. """ self.__index_fi...
def low_points_horiz(line): return [(i, n) for i, n in enumerate(line) if (i == 0 or line[i - 1] > n) and ((i + 1) == len(line) or line[i + 1] > n)] def is_vert_low(i, j, v, all): higher = False for x in [i - 1, i + 1]: if x >= len(all) or x < 0: continue higher = v >...
The code identifies basins in a grid by locating low points, grouping connected regions, sorting them by size, and outputting the product of the three largest basin sizes.
def part_two(input): basins = [] # start at low points lph = [(index, low_points_horiz(line)) for index, line in enumerate(input)] out = [] for first_index, lprow in lph: for second_index, lp in lprow: if is_vert_low(first_index, second_index, lp, input): out.appe...
def set_state(self,state:dict|None=None): accepted_keys = ["stage","data","attempt","query"] if self.state is None: self.state = {} if state is not None: for key,val in state.items(): if key not in accepted_keys: raise Exception("Illegal state key is set.") self.state[key] = val file_path = f...
The function scrapes job data from a given link by extracting a job ID, checks if it already exists in stored data, and if not, attempts to scrape the job page while handling exceptions. It logs errors, captures screenshots on failures, and returns scraped data or None if the job ID exists.
def scrap_a_job_link(self,link:str): job_id = job_id_pattern.findall(link)[0] self.set_state({"data":job_id}) if self.job_data and not self.job_data.exists(job_id): try: scraped_data = self.scrape_job_page(link,job_id) return scraped_data except WebDriverException as e: self.logger.error(f"Webdr...
def get_backup_path(self,file_name_stub:str): folder = os.environ["BACKUP_FOLDER"] file_name = file_name_stub + ".csv" return f"{folder}/{file_name}" def set_state(self,state:dict|None=None): accepted_keys = ["stage","data","attempt","query"] if self.state is None: self.state = {} if state is not No...
This function processes a job search query by crawling relevant links, resuming from a previous state if needed, scraping data from each link, generating match columns based on a threshold, and storing results. It avoids duplicate processing, manages state transitions (e.g., from link listing to individual scraping), a...
def run_sequence(self,query:str,match_threshold=70): links_backup_path = self.get_backup_path("crawl_links") self.crawl_time = datetime.now() start_page = 0 if self.state is not None: # TODO: The logic is flawed. The query check must be done at parent routine self.set_state({"attempt":self.state["attemp...
def set_numkey(self, numkey): """ Sets a specific key Parameter _numkey: the key to be pressed Precondition: is a key on the qwerty keyboard """ self._numkey = numkey def alien_fire(self): """ Helper function: determines the aliens that fire bolts to the ...
The main task of the code is to orchestrate game mechanics by calling multiple functions for updates: handling input (set_numkey), enemy actions (alien_fire), projectile movement/deletion (moveBolts, deleteBolts), power-up management (change_PU, col_detectorPU), collision detection (col_detector), and game state tracki...
def caller(self,press,timer): """ calls the rest of the functions for update function """ self.set_numkey(press) self.alien_fire() self.moveBolts(timer) self.deleteBolts() self.change_PU(timer) self.col_detectorPU() self.col_detector() ...
def get_ship(self): """ Returns ship object """ return self._ship def get_speed(self): """ Returns a number value (int) of the ships speed. """ return self._speed def MoveAliens(self, timer): """ Helper function: - Moves alien objec...
The main task of the code is to update the game state by moving the ship, aliens, and laser bolts based on user input and elapsed time. It handles ship movement (left/right), alien movement, spacebar input for shooting, and adds a new laser bolt if the player presses the spacebar and no existing bolts are active. The f...
def update(self, timer, input): """ Moves ship, aliens, and laser bolts Parameter timer: The time in seconds since last update call Precondition: timer is a number (int or float) Parameter input: the input from the keys Precondition: input is a valid key inputted by the...
def read_data(args): data = pd.read_csv(args.data) targets = data['target'].tolist()[:100] if 'goal' in data.columns: goals = data['goal'].tolist()[:100] else: goals = [""] * len(targets) return list(zip(goals, targets)) def multiple_gcg(model, tokenizer, conv_template, instruct...
The code performs a Gradient-based Contrastive Generation (GCG) attack on a language model using training and test data splits. It loads a model and tokenizer, prepares conversation templates, reads CSV data, and executes multiple GCG iterations with either single or batch updates. Results are logged with parameters an...
def main(args): # Load model model, tokenizer = load_model_and_tokenizer( args.model_path, low_cpu_mem_usage=True, use_cache=False ) template_name = 'llama-2' if 'Llama' in args.model_path else 'vicuna' conv_template = load_conversation_template(template_name) data = re...
def combine(dir: str, start: str, end: str): if os.path.exists(dir + start + end): os.remove(dir + start + end) pass out_file = open(dir + start + end, "a") for idx in range(1, 31): with open(dir + start + str(idx).zfill(2) + end, "r") as f: out_file.write(f.read()) ...
The code processes network matching experiments by analyzing data from multiple configurations (e.g., "NetMatch 200/80") with varying penalties, states, and mutations. It reads graph files, organizes experimental data, generates statistical summaries, and visualizes results via boxplots comparing fitness metrics. The s...
def main(): print("START") folder_names = os.listdir(inp) mode_itms = [["200", "NetMatch"], ["80", "NetMatch"]] # mode_itms = [["80", "NetMatch"]] mode_info = ["NM200", "NM80"] # mode_info = ["NM80"] dub_graph_files = ["dublin_graph.dat", "dublin_graph80.dat"] # dub_graph_files = ["dubli...
def _initializeRatios(self, M_0, air:Atmosphere) : self._tau_r = getStagnationTemperatureRatio(CONST.kappa, M_0) self._pi_r = getStagnationPressureRatio(CONST.kappa, M_0) self._pi_d = self._pi_dmax * getRamRecovery(M_0) self._tau_l = self._c_pt * self._T_t4 / (getHeatCapacity(CONST.kappa, CONST.R) * air....
The code performs aerodynamic and thermodynamic analysis for a flight system. It validates flight speed positivity, computes Mach number, and if initialized, calculates fuel ratios, turbine energy balance, exit conditions, thrust, energies, and performance parameters. It raises errors for invalid inputs or uninitialize...
def performAnalysis(self, flight_speed:np.ndarray, flight_conditions:Atmosphere) : if np.all(flight_speed > 0) : M_0 = flight_speed / flight_conditions.speed_of_sound else : raise ValueError('Flight speed must be positive. Given value : ' + str(flight_speed)) if self._initialized : self._initialize...
def load_phrases(spark, path, encoding): """ Load phrases file :param spark: SparkSession :param path: str :param encoding: str :return: DataFrame """ return spark.createDataFrame( load_and_decode(spark, path, encoding), StringType() ).select(undersores_to_spaces(F.split("va...
The main task of the code is to process text data using Spark by loading configuration files, building a vocabulary from phrases and collections, normalizing a corpus, generating token statistics, and saving results as CSV files. It utilizes Spark for distributed processing, including vocabulary lookup, corpus transfor...
def main(config_path): conf = ConfigParser() conf.read(config_path) staging_dir = pathlib.PosixPath(conf.get("vspace_conf", "stagingloc")) corpus_path = staging_dir / conf.get("vspace_input", "corpus") logging.info("conf file %s" %config_path) index_path = staging_dir / conf.get("vspace_input"...
def mouse_control(self): mouse_dx, mouse_dy = pg.mouse.get_rel() if mouse_dx: self.rotate_yaw(delta_x=mouse_dx * MOUSE_SENSITIVITY) if mouse_dy: self.rotate_pitch(delta_y=mouse_dy * MOUSE_SENSITIVITY) def keyboard_control(self): key_state = pg.key.get_pressed() ...
The main task of the code is to update the object's state by handling mouse and keyboard controls, checking health status, updating tile positions, and picking up items. It extends a parent class's update method via `super().update()`, integrating input management, positional updates, and game state maintenance in a co...
def update(self): self.mouse_control() self.keyboard_control() super().update() # self.check_health() self.update_tile_position() self.pick_up_item()
def is_preprocessed(self, idx): return os.path.isfile(self.get_x_filename_preprocessed(idx)) def get_x_filename(self, idx): return self.data[idx]['x'] def get_x_filename_preprocessed(self, idx): return os.path.join(self.preprocess_dir, os.path.basename(self.get_x_filename(idx))) def get_x_filena...
This function loads a medical image, checks if it's preprocessed, and if not, reads the image using SimpleITK, preprocesses it into a label and image, then saves the preprocessed image and lung mask to specified files.
def get_x(self, idx): if not self.is_preprocessed(idx): sitk_image = sitk.ReadImage(self.get_x_filename(idx)) label,image = preprocess(sitk_image) sitk.WriteImage(image, self.get_x_filename_preprocessed(idx), False) sitk.WriteImage(label,self.get_x_filename_lungma...
def __len__(self): return len(self.data) def get_x_filename(self, idx): return self.data[idx]['x'] def get_x_filename_preprocessed(self, idx): return os.path.join(self.preprocess_dir, os.path.basename(self.get_x_filename(idx))) def get_x_filename_lungmask(self, idx): return os.path.join(...
This function generates lists of file paths for images, preprocessed images, and lung masks, optionally filtering unprocessed/lesion-masked files based on `check_preprocess`. It returns these path lists along with the number of items processed, handling "all" as a special case to include all available files.
def get_path_list(self,num_imm,check_preprocess = False): if num_imm == "all": num_imm = self.__len__() else : pass a = [self.get_x_filename(x) for x in range(self.__len__())][:num_imm] b = [self.get_x_filename_preprocessed(x) for x in range(self.__len__(...
def getActiveTender(self): session = self.getSession() response = session.get("http://localhost:9999/v1/tenders") return response.json() def retrieveOrderBook(self, ticker, length): session = self.getSession() response = session.get( "http://localhost:9999/v1/securiti...
The code evaluates whether to accept a tender for "RITC" based on arbitrage opportunities, market sentiment, and order book depth. If the tender's price difference exceeds a threshold (0.12) and market conditions (e.g., sentiment, bid/ask volume) align with the action (BUY/SELL), it accepts the tender and returns its q...
def debateTender(self): tender = self.getActiveTender() if len(tender) <= 0: return None tenderId = tender[0][self.TENDER_ID] tenderAction = tender[0]["action"] orderBook = self.retrieveOrderBook("RITC", 75) sentiment = self.determineMarketSentiment("RITC") ...
def getLimitPrice(self, ticker, orderType): orderBook = self.retrieveOrderBookSmall(ticker) if orderType == "BUY": return orderBook["bids"][0][self.PRICE] else: return orderBook["asks"][0][self.PRICE] def determineMarketSentiment(self, ticker): orderBook = self.re...
The function places aggressive limit orders to exit a position by dynamically adjusting order prices based on market sentiment. It iteratively sends limit orders (BUY/SELL) with incremental price adjustments (delta) and modifies delta size depending on sentiment thresholds, processing the total quantity in chunks until...
def placeAggressiveExitTenderLimitOrders(self, ticker, quantity, price, action): # If changing to use price, use +0.10 instead of -0.01 delta = 0.07 limitSellPrice = self.getLimitPrice(ticker, "SELL") limitBuyPrice = self.getLimitPrice(ticker, "BUY") sentiment = self.determineMar...
def getLimitPrice(self, ticker, orderType): orderBook = self.retrieveOrderBookSmall(ticker) if orderType == "BUY": return orderBook["bids"][0][self.PRICE] else: return orderBook["asks"][0][self.PRICE] def getQuantityForOrder(self, quantity): if quantity >= 10000: ...
This function places conservative limit orders to exit a trade by repeatedly sending smaller orders at adjusted prices. Depending on the action (BUY/SELL), it adds or subtracts 0.10 from the given price, splits the total quantity into manageable portions using getQuantityForOrder, and submits limit orders until the ful...
def placeConservativeExitTenderLimitOrders(self, ticker, quantity, price, action): # If changing to use price, use +0.10 instead of -0.01 delta = 0.00 limitSellPrice = self.getLimitPrice(ticker, "SELL") limitBuyPrice = self.getLimitPrice(ticker, "BUY") while quantity > 0: ...
def delete_post(message): request_to_bot('deleteMessage', { 'chat_id': message['message']['chat']['id'], 'message_id': message['message']['message_id'], }) def request_to_bot(request_type, data): return requests.post(BOT_URL + request_type, data) def post_media(message, user): post_id = ...
This function handles callback queries from a bot, processing user actions like finishing a post, adding Instagram/Twitter accounts, or selecting Facebook pages. It sends instructional messages, updates user statuses, and interacts with APIs to manage social media account links, ensuring proper setup for post-sharing f...
def is_callback_query(message): delete_post(message) user = BotUser.objects.get(user_id=message['from']['id']) if message['data'] == 'finish_post': request_to_bot('sendMessage', { 'chat_id': message['message']['chat']['id'], 'text': 'Post joylanyabdi...' }) po...
def add_account(user, message, text): if user.extra_status == '1': request_to_bot('sendMessage', { 'chat_id': message['chat']['id'], 'text': 'Iltimos birinchi accountingizni qo\'shing', }) else: user.extra_status = '1' user.save() request_to_bot('sendM...
The code processes incoming messages to manage user interactions for setting up Telegram and Instagram accounts, handling media/text inputs for posts, verifying channel permissions, and facilitating cross-platform content posting. It checks user status, creates or updates user records, and triggers actions like sending...
def is_message(message): user_id = message['from']['id'] try: user = BotUser.objects.get(user_id=user_id) # get user with user_id except: user = BotUser.objects.create(name=message['from']['first_name'], username=message['from']['username'], user_id=user_id, status='start') # create user ...
def get_base(n, k): res = {} for r in range(n): res[r] = Node(n, r, k) return res def reduce(aut, r): cycle = get_cycle(aut, r) for fr in get_incoming(aut, r): inc_s = aut[fr].get_edge(r) for to in aut[r].nxt: out_s = aut[r].get_edge(to) if to == r: ...
The function generates a regular expression from an automaton constructed with parameters n and k. It reduces the automaton by iteratively merging states using a selection process until only one state remains, then formats the resulting transition as a regex pattern enclosed in ^ and $ symbols.
def get_regex(n, k): aut = get_base(n, k) while len(aut) > 1: reduce(aut, select(aut)) return "^" + bracket(remove_leading(aut[0].nxt[0])) + "$"
def make_random_proteins(self, max_size, number_of_proteins): ''' Make some random proteins :param max_size: Max size of the proteins :param number_of_proteins: The number of them :return: Dict {id: group, len, sequence} ''' proteins = {} for protein in...
The main task of the code is to calculate BDM (Burrows-Wheeler Data Matters) values for biological sequences (genes/proteins) from input files or randomly generated proteins. It processes sequences in specified directories, filters files by type, computes BDM metrics for different window sizes, and stores results in pi...
def calculate_bdms(self, bdm, pickle_out, type, grouping, data_directory): ''' Calculates all the BDM values for files of sequences :param bdm: initialized bdm class :param pickle_out: str, The file to save these values to :param type: str, either 'genes' or 'proteins' :...
def get_neighbours(tiles): neighbours = defaultdict(list) for name in tiles: for name2 in tiles: if len(neighbours[name]) == 4: break if (len(neighbours[name2]) == 4 or name2 in neighbours[name] or name == name2): continue ...
The code arranges tiles into a grid structure, starting by identifying corner tiles with two neighbors, placing them first, and then filling the grid. It then processes the completed grid in part2 to check against a 'monster' parameter, likely verifying if the monster can be placed or if the tile arrangement blocks it.
def solve(tiles, monster): neighbours = get_neighbours(tiles) m = 10 - 2 n = int(sqrt(len(tiles))) grid = [["" for _ in range(n)] for _ in range(n * m)] corners = [n for n, t in neighbours.items() if len(t) == 2] part_1(corners) current = corners[0] current_t = place_first_corner(grid...
def clear_grid(): for i, j, k in grid_m: grid_v[i, j, k] = [0, 0, 0] grid_m[i, j, k] = 0 grid_v.grad[i, j, k] = [0, 0, 0] grid_m.grad[i, j, k] = 0 grid_v_out.grad[i, j, k] = [0, 0, 0] def compute_inplane_F_tmp(f: ti.i32): for p in range(0, n_quadrature_particles): ...
The code performs a forward pass in a simulation, updating grid and particle states. It clears the grid, computes in-plane forces, applies SVD for deformation, transfers data between particles and grid (p2g/g2p), executes grid operations, and updates particle states based on the input parameters `s` and `grad_update` f...
def forward(s, grad_update): clear_grid() compute_inplane_F_tmp(s) inplane_svd() p2g(s, grad_update) grid_op(s) g2p(s) update_particle_state(s)
def clear_grid(): for i, j, k in grid_m: grid_v[i, j, k] = [0, 0, 0] grid_m[i, j, k] = 0 grid_v.grad[i, j, k] = [0, 0, 0] grid_m.grad[i, j, k] = 0 grid_v_out.grad[i, j, k] = [0, 0, 0] def clear_inplane_SVD_grad(): zero = ti.Matrix.zero(real, 2, 2) for i in range(0, n_...
This function performs a backward pass in a simulation, computing gradients for particle-grid interactions, updating states via operations like p2g, g2p, and in-plane SVD, then propagating gradients through these steps to adjust parameters during optimization.
def backward(s, grad_update): clear_grid() clear_inplane_SVD_grad() compute_inplane_F_tmp(s) inplane_svd() p2g(s, grad_update) grid_op(s) g2p(s) update_particle_state(s) update_particle_state.grad(s) g2p.grad(s) grid_op.grad(s) p2g.grad(s, grad_update) inplane_svd_gr...
def ed_choose(app: GameApp): choices = ["_e_asy", "_m_edium", "h_a_rd", "_q_uit", "_?_"] shortcuts = list("emaq?") positions = [2, 8, 17, 22, 28] y = app.game.height + 1 cursor = app.cursor app.stdscr.addstr(y, 0, ":") for s in choices: ed_add_selection(app, s) choice = 0 app...
This code implements a text-based Minesweeper game using the curses library. It allows users to select difficulty levels, control a cursor with keyboard inputs, sweep/mark cells, and restarts the game upon winning/losing. The core tasks include handling game state transitions, cursor movement, user input processing, an...
def c_main(stdscr: "curses._CursesWindow") -> int: dims = {"easy": game.EASY, "medium": game.MEDIUM, "hard": game.HARD} app = GameApp(stdscr, game.create_game(*game.EASY)) mv = { "b": lambda x, y: game.prev_unswept(app.game.board, x, y), "h": lambda x, y: (x - 1, y) if x > 0 else (x, y), ...
def guide_get_feature(stub): guide_get_one_feature(stub, routeguide_pb2.Point( latitude=409146138, longitude=-746188906)) guide_get_one_feature(stub, routeguide_pb2.Point(latitude=0, longitude=0)) def guide_list_features(stub): rectangle = routeguide_p...
The code defines a function `run()` that connects to a gRPC server on a specified port (default 50051), creates a `RouteGuideStub`, and sequentially invokes four gRPC methods: `GetFeature`, `ListFeatures`, `RecordRoute`, and `RouteChat` to demonstrate client-side operations for a RouteGuide service.
def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. port = '50051' if os.environ.get("SERVER_PORT"): port = os.environ.get("SERVER_PORT") with grpc.insecure_channel...
def _lnprior(self, theta): logprior = 0 for arg, par in zip(theta, self.free_parameters): mean, std = self._priors[par] logprior += _log_gaussian(arg, mean, std) return logprior def _F(self, theta): free_parameters = dict(zip(self.free_parameters, theta)) ...
This method computes the log probability of given parameters theta by combining the log prior, calculated terms (F, N_T_inv, T_bar), and returns the result or its negative based on ret_neg, facilitating likelihood optimization.
def __call__(self, theta, ret_neg=False): r""" This method computes the log probability at a point in parameter space specified by `pars` and any additional `kwargs` that may overwrite members of the `pars` dictionary. Parameters ---------- theta: ndarray Arr...
def setupMethod(self): options = uc.ChromeOptions() # default directory to data folder in current working directory (cwd) prefs = {"download.default_directory": DEFAULT_DOWNLOAD_FOLDER} options.add_experimental_option("prefs", prefs) options.add_argument('--disable-dev-shm-usage'...
The main task of the code is to execute a full login process by initializing setup methods, navigating to a specific website (tracking.pbpstats.com), and performing teardown operations to clean up resources after the login session. This method likely automates browser interactions for logging into the PBPStats tracking...
def __fullLogin(self): self.setupMethod() self.goTo("https://tracking.pbpstats.com/") self.teardownMethod()
def print_iter(self): if not self.verbose: return print( f"Player hand: {self.player}\t\t sum: {self.sum_hand(self.player)}") print( f"Dealer hand: {self.dealer}\t\t sum: {self.sum_hand(self.dealer)}") return def hand_to_state(self, player, dealer): ...
This code simulates a Blackjack game, tracking states, actions, and rewards for reinforcement learning. It iterates through player/dealer moves, records transitions (SARSP), and appends terminal states to a dataset. The main task is to model game dynamics, handle player decisions (hit/stick), evaluate outcomes, and sto...
def play_game(self): # Only for "input" mode if self.verbose: print("New Game!\n") # Iterate through game done = False while(not done): # Only for "input" mode self.print_iter() # Current state/action/reward state = se...
def play_game(self): # Only for "input" mode if self.verbose: print("New Game!\n") # Iterate through game done = False while(not done): # Only for "input" mode self.print_iter() # Current state/action/reward state = se...
The main task of the code is to run a specified number of games (`self.num_games`), executing `play_game()` followed by `reset()` for each iteration. It then prints statistical results via `print_stats()` and generates a CSV file of game data (`sarsp_arr`) if the policy used was a random policy (`self.action_type == "r...
def play_games(self): # Iterate through num_games for i in range(self.num_games): self.play_game() self.reset() # print(self.sarsp_arr) self.print_stats() # Output CSV file of runs if a random_policy was used if self.action_type == "random_policy...
def fetch_by_query(self, query): resp = requests.get(self.url + "/api/v1/query_range", { "query": query, "start": self.start, "end": self.end, "step": 15 }, headers=self.headers) print(resp.request.url) if not resp.ok: raise Ex...
The function fetches container CPU usage metrics from a Prometheus server using a predefined query, saves the retrieved data to files, calculates the average CPU usage over the query's time range, and returns this average as a dictionary.
def fetch_container_cpu_usage(self): cpu_query = 'rate(container_cpu_usage_seconds_total[1m])' data, query_url = self.fetch_by_query(cpu_query) save_to_file_datasets_within_query_time_range(data, "cpu", self.json_output_dir, self.filename_suffix, query_url) avg_cpu_dict = get_average_wit...
def fetch_by_query(self, query): resp = requests.get(self.url + "/api/v1/query_range", { "query": query, "start": self.start, "end": self.end, "step": 15 }, headers=self.headers) print(resp.request.url) if not resp.ok: raise Ex...
The function fetches container memory usage data using a predefined metric, saves the retrieved data to files with specified parameters, calculates the average memory usage within the query's time range, and returns the computed average as a dictionary.
def fetch_container_memory_usage(self): mem_query = 'container_memory_usage_bytes' data, query_url = self.fetch_by_query(mem_query) save_to_file_datasets_within_query_time_range(data, "mem", self.json_output_dir, self.filename_suffix, query_url) avg_mem_dict = get_average_within_query_ti...
def clean_data(path, aggregation = "15-mins"): df = read_data(path) # If transactions less than or equal to 5, assumes station is closed. if aggregation == "15-mins": df = df.mask(df <= 5, 0) to_drop_stations = ['(40000) cable portal tunal', '(40001) juan pablo ii'...
This function processes time-series transaction data with spatial and temporal features for machine learning. It cleans data, extracts exogenous variables, constructs time windows, generates features/labels, converts data to tensors, handles spatial embeddings, splits train/test sets, and prepares an adjacency matrix f...
def tf_data(transactions_path, stations_path, adjancency_path, aggregation, train_date, max_transactions=None, max_stations=None, date_range = None): df = clean_data(transactions_path, aggregation = aggregation) stations_df = read_stations(stations_path) exog_vars = l...
def get_blocking_probability(self, numerical=False): temp1 = dict() if numerical: ro = self.get_traffic_intensity() theta = (self.s-1.0)/(self.s+1.0) f = (sqrt((9.0+theta)/(1.0-theta))-2)*theta/(8.0+8.0*theta) for soc_r in self.soc_rs: temp...
The function calculates the system revenue for each state of charge (SOC) level by considering the reward from serving non-blocked electric vehicles, adjusted by average waiting and charging costs. It uses blocking probability, mean waiting time, and mean charging time to compute revenue per SOC level, returning a dict...
def get_system_revenue(self): #TODO add calculation results too temp1 = dict() reward = lambda x: self.reward["m"]*x+self.reward["n"] p_k = self.get_blocking_probability() mean_t_w = self.get_mean_waiting_time() mean_t_ch = self.get_mean_charging_time() for soc_r ...
def insert_into_file(filename, start, end, insert): text = filename.read_text() i0 = text.index(start) i1 = text.index(end) out = text[:i0 + len(start) + 1] out += indent(insert, ' ') out += text[i1 - 5:] filename.write_text(out) def generate_enums(enums): out = '' defines = dict(...
The function `generate_cython()` automates the insertion of generated Cython code into specific `.pxd` files. It inserts enums into `_types.pxd`, app functions into `app.pxd`, and request functions into `request.pxd`, using predefined markers. Struct insertion is commented out. The task involves updating Cython interfa...
def generate_cython(): # _types.pxd path = ROOT_DIR / 'datoviz/_types.pxd' insert_into_file(path, ENUM_START, ENUM_END, generate_enums(ENUMS)) # app.h path = ROOT_DIR / 'datoviz/app.pxd' insert_into_file(path, FUNCTION_START, FUNCTION_END, generate_functions(APP_FUNCTIONS)...
def open_whatsapp(driver: WebDriver) -> None: """Open WhatsApp Web if it is not already open. :param driver: The Selenium driver. """ if driver.current_url == WHATSAPP_WEB_URL: return None driver.get(WHATSAPP_WEB_URL) logger.debug("Waiting for the chatlist-header to appear") WebDri...
The function reads new WhatsApp messages from unread chats using Selenium, compares them with previously seen messages stored in the state, and returns a dictionary of new messages per chat along with the updated state. It handles pagination, avoids duplicates, and adjusts polling delays to minimize resource use while ...
def read_whatsapp_messages( driver: WebDriver, state: WhatsAppChatState ) -> tuple[dict[ChatName, list[WhatsAppMessage]], WhatsAppChatState]: """Read new messages from the next chat which has any. :param driver: The Selenium driver. :param state: Last returned state from this function. :return: The...
def level3_decrypt(data): return level3_encrypt(data) def level2_decrypt(data): return level2_encrypt(data) def level1_decrypt(data): return level1_encrypt(data)
The code decrypts data by first decoding it from base64, then sequentially applying three decryption levels (level3, level2, level1), and finally converting the resulting bytes to a string.
def decrypt(data): data = base64.b64decode(data) data = level3_decrypt(data) data = level2_decrypt(data) data = level1_decrypt(data) return data.decode()
def solve(sudoku, n = 0): """ Uses the solver method to solve a puzzle. This method was built in order to avoid recursion depth errors. Returns True if the puzzle is solvable and false if otherwise""" if n < 30: s = solver(sudoku) if s != False: return s else: ...
The code generates a Sudoku puzzle with a unique solution by iteratively removing numbers from a solved Sudoku grid. It checks if each removal preserves the uniqueness of the solution. If removing a number leads to no solution or multiple solutions, it retains that number. The process continues until all cells are chec...
def puzzleGen(sudoku): """ Generates a puzzle with a unique solution. """ cells = [i for i in range(81)] while cells != []: copy_s = copy.deepcopy(sudoku) randIndex = random.choice(cells) cells.remove(randIndex) copy_s[randIndex].reset() s = solve(copy_s) if s...
def perfectSudoku(): '''Generates a completed sudoku. Sudoku is in the correct format and is completly random''' result = False while result == False: s = sudokuGen() result = sudokuChecker(s) return s def puzzleGen(sudoku): """ Generates a puzzle with a unique solution. """ cell...
The main task of the code is to generate and output a Sudoku puzzle of a specified difficulty level (Easy, Medium, Hard, or Insane). It repeatedly generates puzzles using `perfectSudoku()` and `puzzleGen()` until the generated puzzle matches the requested difficulty, as determined by the third element of the returned t...
def main(level): """ Input the level of difficulty of the sudoku puzzle. Difficulty levels include ‘Easy’ ‘Medium’ ‘Hard’ and ‘Insane’. Outputs a sudoku of desired difficulty.""" t1 = time.time() n = 0 if level == 'Easy': p = perfectSudoku() s = puzzleGen(p) if s[...
def get_partition(self, id1, id2): new_x = [] new_y = [] new_x_err = [] new_y_err = [] for i in range(self.size()): t = self.runid[i] if t >= id1 and t < id2: new_x.append(self.x_data[i]) new_y.append(self.y_data[i]) ...
This function generates a scatter plot of x vs y data with optional error bars, fitting, and time formatting. It handles data partitioning by run IDs, applies time formatting to x-axis, adds fit curves, labels, and legends, and saves or displays the plot based on input parameters.
def make_plot(self, fit=None, errorbars=False, x_time_formated=False, runid_partitions=None, broken_time_axis=False, legend=True, save_dir=None, rename_x=None): x = self.x_data y = self.y_data x_err = self.x_data_err y_err = self.y_data_err if runid_partitions: partit...
def logging(): #OPTION TO ENABLE LOGGING TO EXTERNAL FILE, WILL ONLY DISPLAY IF CONDUCTING ONE TEST IN ORDER TO NOT DESTROY DRIVES global log_enabled print("Would you like to log the test in an external file?") m_log = str(input()).lower() if m_log == "yes": log_enabled = True space() ...
The main task of the code is to handle user input for the number of Collatz Conjecture tests, validate the input as an integer, and execute either logging (for one test) or the collatz function (for multiple tests) while managing invalid input alerts and restarting the process if needed.
def rs_launch(): #INCLUDES INTEGER CHECK FOR NUMBER OF TESTS TO CONDUCT global tests global invalid_number print("Collatz Conjecture Random Value Solver") print("") print("LOGGING IS AVAILABLE WHEN CONDUCTING ONE TEST") print("") if invalid_number == True: print("INVALID INPUT DETEC...
def logging(): #OPTION TO ENABLE LOGGING global log_enabled print("") print("Would you like to log the test in an external file?") m_log = str(input()).lower() if m_log == "yes": log_enabled = True space() collatz() elif m_log == "no": log_enabled = False ...
This function launches a Collatz Conjecture solver, validates user input as an integer, and handles invalid entries by resetting the interface. It stores the validated number in 'baseNum' and triggers logging if valid, otherwise marks input as invalid for re-entry.
def ns_launch(): #INCLUDES INTEGER CHECK FOR NUMBER OF TESTS TO CONDUCT global baseNum global invalid_number print("Collatz Conjecture Solver") print("") if invalid_number == True: print("INVALID INPUT DETECTED") print("") print("Enter value to test:") str_baseNum = str(inpu...
def format_agent_task_pairs(agent_task_pairs): for pair in agent_task_pairs: pair["content"] = pair.copy() pair["type"] = "task" if "task" in pair else "loop" for key in pair.copy(): if key != "type" and key != "content": del pair[key] def add_tasks_to_gateways( ...
The function generates a BPMN structure by integrating agent-task pairs with parallel and exclusive gateways. It formats input data, combines gateways, sorts them by distance, adds tasks to gateways, nests gateways hierarchically, and merges all elements into a sorted list of BPMN components for visualization.
def create_bpmn_structure( agent_task_pairs: list[dict], parallel_gateway_data: list[dict], exclusive_gateway_data: list[dict], process_info: list[dict], ) -> list[dict]: """ Creates a BPMN structure from the agent-task pairs, parallel gateways and exclusive gateways. The BPMN structure can ...
def calc_orig_multi(v, w, fid, labeled, unlabeled, tau, alpha, gamma2): N = v.shape[0] classes = fid.keys() num_class = len(classes) ofs = min(classes) if -1 in fid.keys(): y = np.zeros(N) # this will already be in the expanded size, as if (H^Ty) y[fid[1]] = 1. y[fid[-1]] =...
The function `run_test_AL` performs active learning (AL) using spectral methods to iteratively refine a classification model. It initializes a solution with eigenvectors/eigenvalues, computes initial error, and iteratively selects the next best samples to label (via `run_next_EEM`), updating the model and tracking erro...
def run_test_AL(X, v, w, fid, ground_truth, tag2=(0.01, 1.0, 0.01), test_opts=(10, False)): ''' Inputs: X : (N x d) data matrix with the data points as columns v : (N x N) eigenvectors (as columns) w : (N, ) eigenvalues numpy array fid : dictionary with fidelity indices (class_i,...
def calc_orig(v, w, B, fid, labeled, unlabeled, tau, alpha, gamma2): N = v.shape[0] y = np.zeros(N) # this will already be in the expanded size, as if (H^Ty) y[fid[1]] = 1. y[fid[-1]] = -1. N_prime = len(labeled) w_inv = (tau ** (2 * alpha)) * np.power(w + tau**2., -alpha) # diagonalizatio...
The code performs active learning (AL) by iteratively selecting the most informative data points to label, updating a classification model, and tracking classification errors. It initializes a model using eigenvectors/eigenvalues, computes initial classification accuracy, then iteratively refines the model by querying ...
def run_test_AL(X, v, w, fid, ground_truth, tag2=(0.01, 1.0, 0.00001), test_opts=(10, False)): ''' Inputs: X : (N x d) data matrix with the data points as columns v : (N x N) eigenvectors (as columns) w : (N, ) eigenvalues numpy array fid : dictionary with fidelity indices (class...
def is_solved(self, node: tuple[int]) -> bool: is_solved = (node == self.final_solution) Debug('is_solved=', is_solved) return is_solved def get_priority(self, node_tuple): return Heuristic.out_place(node_tuple) + self.get_Manhattan_distance(node_tuple) def expand_node(self, node: tupl...
The code implements a heuristic search algorithm to solve a problem by exploring nodes in a priority queue. It starts with the root node, expands it into child nodes, and evaluates each child's priority. Nodes are added to the heap if unvisited, and the process repeats until a solved node is found. The solution path is...
def solve_using_heuristics(self) -> list[str]: solved = False #print('is solved =',self.is_solved(self.root_tuple)) if self.is_solved(self.root_tuple): return [] root_tree = Tree(self.root_tuple,None) priority = self.get_priority(root_tree.node) priority_root_...
def train(X,Y,alpha): out = forward(X) backword(X,out,Y,alpha) def forward(X): global w1,w2,a2,a3,b1,b2 z2 = np.dot(X,w1)+b1 a2 = sigmod(z2) z3 = np.dot(a2, w2)+b2 a3 = sigmod(z3) return a3 def acuracy_neural(p_out,Y): p_out = np.round(p_out) cnt = 0 for i in range(len(Y)):...
This code trains a neural network with one hidden layer using gradient descent. It initializes weights and biases, trains on provided data over specified epochs, calculates mean squared error, and evaluates accuracy on both training and test data. The function prints cost and accuracy metrics for each dataset.
def neural_network(train_data,Y,test_data,test_y,epoch = 10000,alpha = .1): global w1, w2, b1, b2 # removing first column of 1's train_data = np.delete(train_data,np.s_[:1],axis=1) test_data = np.delete(test_data,np.s_[:1],axis=1) # initializing weight & bias w1 = np.random.randn(in_si...
def get_NR_curve_t(s): """De newton-raphson benadering, x_(n+1) = x_n - f(x)/f'(x)""" # set t0 t = t_min + s/arc_length_Bezier2(B2, t_max)*(t_max-t_min) # print("init t0", t) for it in range(5): t -= (arc_length_Bezier2(B2, t)-s)/f(t) # print("it t", t) return t def eval_Bezier2(...
The function `do_animation(s)` animates a point along a Bezier curve by updating its position (`V_pos`) and velocity vector (`V_vec`) based on parameter `s`. It calculates a normalized time `t`, evaluates the Bezier curve at `t`, computes the velocity direction from the curve's derivative, scales it by speed, and check...
def do_animation(s): global animation_done global V_pos global V_vec speed = 1/2 u = s*speed # normalized t t = get_NR_curve_t(u) if (t > t_max): # animation_done = True else: # new position V_pos = eval_Bezier2(B2, t) # velocity vector v =...
def get_NR_curve_t(s): # set t0 t = t_min + s/Simpson_sum(t_min, t_max)*(t_max-t_min) # print("init t0", t) for it in range(5): t -= (Simpson_sum(t_min, t)-s)/f(t) # print("it t", t) return t def eval_Bezier3(P, t): # P(t) = (1-t)^3 * P[0] + 3(1-t)^2tP[1] + 3(1-t)t^2*P[2] + t^3P[...
This function animates an object along a Bezier curve by calculating its position (V_pos) and velocity vector (V_vec) at parameter t, normalized from input s. It checks if t exceeds t_max to signal animation completion (animation_done). The velocity vector is derived from the Bezier curve's derivative, scaled to mainta...
def do_animation(s): global animation_done global V_pos global V_vec speed = 2 u = s*speed t = get_NR_curve_t(u) # berekent genormalizeerde t if (t > t_max): animation_done = True else: V_pos = eval_Bezier3(B3, t) # positie v = eval_dBezier3(B3, t) # snelheid...
def norm(x): escalar = internalProduct(x, x) return math.sqrt(escalar) def distVector(x, y): return np.subtract(x, y) def project(x, y): return np.multiply(findLambda(x, y), normalize(x))
The code calculates the distance between a vector `x` and its projection onto another vector `y` by computing the norm of the vector difference between `x` and its projection. This measures how far `x` lies from the line defined by `y` in a geometric sense.
def distanceToProjection(x, y): return norm(distVector(x, project(x, y)))
def _probabilityOfFormingBigram(self, w1, w2): # Cap odds at 100 to not have NaN error x = min(self._getRelativeStrengthScore(w1, w2) - 1.0, 100) return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) def _createBigram(self, word_A, word_B): return (word_A.decode() + ' ' + word_B.de...
The code computes weighted scores for each word in a sequence by considering both unigram and bigram probabilities. It uses dynamic programming, iterating backward from the last word, to combine scores from adjacent words. For each position, it calculates the probability of forming a bigram with the next word (case1) a...
def _scoreWeights(self, words): memory = [{}] * len(words) memory[len(words) - 1] = {words[len(words) - 1]: 1.0} for i in range(len(words) - 1, 0, -1): p = self._probabilityOfFormingBigram(words[i-1], words[i]) bigram = self._createBigram(words[i-1], words[i]) ...
def var_map(var_id, prob, var_num, resolution=5): app_prob = 0.5 s = 0.5 new_var = [] op = [] for i in range(resolution): if prob == app_prob: break new_var.append(var_num + i + 1) s *= 0.5 # In op, 0: or, 1: and if prob > app_prob: ap...
This code processes an input file containing clauses, normalizes variables based on probabilistic mappings, rewrites clauses accordingly, and outputs a transformed CNF file. It tracks variable and clause counts, applies resolution rules, and ensures output compliance with CNF standards while measuring processing times.
def main(argv): resolution = 3 filename = argv[1] outfile = argv[2] if len(argv) > 2 else filename.replace( '.sdimacs', '-05.sdimacs') f = open(filename, 'r') lines = f.readlines() f.close() var_num = 0 c_num = 0 t = 0 # map variables f = open(outfile, 'w') ma...
def is_same_game() -> bool: #check if RSS feed and top game from file is the same return get_newest_file_game() == get_newest_RSS_game() def email() -> None: #Google removed less-secure-apps now must use app password #https://stackoverflow.com/questions/72480454/sending-email-with-python-google-disables...
The main task of the code is to check if the current game matches the previous one using `is_same_game()`. If they differ, it sends an email notification via `email()` and updates the game list using `update_game_list()` to reflect the change. This ensures timely alerts and data synchronization when game states change.
def main() -> None: if not is_same_game(): email() update_game_list()
def _build_state_mappings_and_states(self): index = 0 for rr in range(self.nrows): for cc in range(self.ncols): if (rr, cc) in self.walls: self.coord2index[(rr, cc)] = -1 else: self.coord2index[(rr, cc)] = index ...
The code defines a `_build` method that constructs core components of a Markov Decision Process (MDP). It first maps states and initializes state representations, then defines valid action sets for each state, and finally calculates transition probabilities between states. Together, these steps establish the environmen...
def _build(self): self._build_state_mappings_and_states() self._build_action_sets() self._build_transition_probabilities()
def end_turn(self): if self.game.gameover: self.game = self.network.send((self.game, self.player_number)) return True self.game.players[self.player_number].end_turn() self.on_render() self.game.curr_turn = (self.game.curr_turn + 1) % self.game.num_players ...
This code handles mouse and quit events in a game. It checks for game-over conditions when no moves are possible, updates game state, and delegates mouse clicks to button, pile, or card selection handlers. The function renders the updated interface and returns selection results.
def on_event(self, event): if event.type == QUIT: self._running = False if event.type == MOUSEBUTTONDOWN: if not self.game.possible_moves(self.game.players[self.player_number]): if self.game.deck.get_deck_size() > 0: if self.moves_made < 2: ...
def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE) self._running = True #setting the caption pygame.display.set_caption('The Game') #setting the Clock self.clock = pygame.time.Clock...
This code manages a game loop for a player, handling turn-based gameplay, UI updates, and network communication. It initializes the game, displays player info, processes events during the player's turn, waits for others' turns, checks for game over conditions (e.g., empty deck), and sends/receives game state updates vi...
def on_execute(self): if self.on_init() == False: self._running = False display_info = f"Welcome! You are player {self.player_number}" notification_rect = self.display_text(display_info, self.windowWidth//3 + 25, 10, self.notification_rect) self.notification_rect = notificat...
def drawBorder(self, left: int, top: int, width: int) -> None: pygame.draw.rect(self.surface, COLORS["black"], pygame.Rect( left, top, PIECESIZE, width )) pygame.draw.rect(self.surface, COLORS["black"], pygame.Rect( left, top, width, PIECESIZE )) pygame.dr...
The `render_game_field` method clears the game surface, draws the background and sidebar, renders landed pieces on the grid, and visualizes the current and next game pieces. It updates the game's visual state by iterating through the grid, applying colors to filled cells, adding borders, and drawing active pieces.
def render_game_field(self) -> None: self.surface.fill(COLORS["background"]) pygame.draw.rect( self.surface, COLORS["secondaryBackground"], pygame.Rect(self.width - 200, 0, 200, self.height) ) for row in range(self.game.getGameHeight()): for col in r...
def control_game_movement(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: self.spedUp = True elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: self.game.move_left() elif event.key == pygame.K...
This method processes Pygame events to handle game state transitions (MENU → PLAYING), player input for movement, reset (KEY_R), and pause (KEY_P). It updates the game logic at adjusted tick speeds, renders the game field and text, and maintains the display update loop for smooth gameplay.
def tick(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if (self.game.gameState == GameState.MENU): if event.type == pygame.KEYDOWN: self.game.gameState = GameState.PLAYING if (s...
def get_best_split(data): classes=list(set(row[-1] for row in data)) best_score=2/3 best_feature=0 best_value=0 best_groups=None features=random_features(len(data[0])-1) features=np.append(features,len(data[0])-1) features=features.tolist() data_red=data[:,features] for feature i...
The code constructs a decision tree by recursively splitting the dataset. It starts with the best split of randomly selected data points, then recursively partitions subsets until the maximum depth is reached or the subset size falls below the minimum threshold. The function returns the root node of the built tree stru...
def build_tree(data,max_depth,min_size): root=get_best_split(random_points(len(data),data)) split(root, max_depth, min_size, 1) return root
def reduce_data(train_set, test_set, selected_features): train_set_red = train_set[:, selected_features] test_set_red = test_set[:, selected_features] return train_set_red, test_set_red def feature_selection(train_set, train_labels, **kwargs): return [0,6] def build_tree(data,max_depth,min_size): ro...
The code implements an ensemble classifier using 100 decision trees. It first performs feature selection on the training data, trains 100 trees with 5 features each, predicts on the test set for each tree, and aggregates results by taking the mode of predictions across all trees to produce the final classification outp...
def alternative_classifier(train_set, train_labels, test_set, **kwargs): train_set,test_set=reduce_data(train_set, test_set, feature_selection(train_set,train_labels)) train_labels=np.array(train_labels).reshape((-1,1)) data=np.concatenate((train_set,train_labels),axis=1) predictions=np.zeros((100,len(t...
def _refresh_creds_if_needed(self): if self._calendar_auth and self._calendar_auth.refresh_token: self._calendar_auth.refresh(Request()) def _get_app_calendar_id(self, calendar_name) -> Union[str, None]: """ Retrieve the id of a calendar with the specified name if one exists ...
This code initializes a Google Calendar API utility by setting up authentication credentials, creating a Calendar service, and managing the application's calendar ID. It refreshes credentials if needed, builds the API service, and automatically retrieves or creates a calendar if none is provided. The user object is sto...
def __init__(self, calendar_credentials: Credentials, calendar_id: str = None, user: User = None): """Init GoogleCalendarUtil for Google Calendar API Calls calendar_credentials: the credentials to authenticate each API call with calendar_id: the id of the calendar created for this application IF...
def input_username(self): '''Asks the user to enter a username''' username = input ('Username: ') return username def input_password(self): '''Asks the user to enter a password''' password = input('Password: ') return password def input_new_password(self): '''Asks...
The main task of the code is to repeatedly prompt and send username/password credentials to a server until the user is authorized, handling different authentication states (e.g., requesting username, password, or new password). Once authorized, it triggers the `trigger_forum_start()` method to initiate forum functional...
def manange_registered_client(self, conn, recieved_state): '''Keeps sending the username nad password until the user is not authorised and if it is authorised then triggeer the stat of trigger_forum_start()''' while recieved_state != USER_AUTHORISED: ...
def find_num_msgs(Thread_Title): ''' Find the number of messages added in the thread does not take into consideration file uploads''' for thread in SERVER_STATE['Threads']: if thread['name'] == Thread_Title: num_messages = last_msg_num(Thread_Title) return num_messages def che...
This function handles deletion requests by validating message numbers, thread existence, and authorship. If valid, it deletes the message; otherwise, it sends error responses via a connection.
def DLT_process_and_exception_handle (msg_num, Thread_Title, username, conn, t_lock): '''Excpetion handling for DLT and then execution of the real create functionality if no error raised''' if msg_num < 1 or msg_num > find_num_msgs(Thread_Title): conn.send(bytes(INVALID_MESSAGE_NUMBER, FORMAT)) ...
def input_username(self): '''Asks the user to enter a username''' username = input ('Username: ') return username def manage_new_client(self, conn): '''Manage the new client by sending the new password and then start the forum if the user is not already logged in''' new...
The function manages user authorization by communicating with a server. It requests a username, checks login status, handles re-logins, prompts for passwords, and routes to either `manage_new_client` or `manange_registered_client` based on server responses, ensuring proper authentication and session management.
def Manage_authorization(self, conn): '''Manage the authorisation of the user it starts by getting from the server USERNAME_REQUIRED and then asks the user to give a name and then sends the username and if the server gives back that the use is already logged in the authorisation begins again and...
def get_password(self, username): '''get the password of user''' for dets in self.registered_users: if dets['username'] == username: return dets['password'] def get_usernames(self): '''get the list of all registered usernames''' all_users = [users['username'] ...
This function handles re-authentication for an already registered client by verifying their password. If the username is already logged in, it notifies the client. If the password is incorrect, it repeatedly prompts for the password or a new username (treated as a new client if invalid). Upon successful authentication,...
def handle_already_registered_client(self, conn, addr, username): '''cheks if the client is not in logged in users and then asks for the password and follows the smae process unitl it has found the right password , also allows the other user to login ifthe invalid password is added and if ...
def get_usernames(self): '''get the list of all registered usernames''' all_users = [users['username'] for users in self.registered_users] return all_users def handle_new_client(self, conn, addr, username): ''' If it is a new user then firstly checks if it is not logged in just i...
The main task of the code is to authorize a client by managing two-way communication, verifying if the provided username is already logged in or registered. If the username is logged in, it alerts the client; if not registered, it triggers `handle_new_client`, otherwise `handle_already_registered_client`, ensuring prop...
def authorise(self, conn, addr): '''For the authorising the client it manages the two way communication and sends and recieve the messages acoording to the state, if the username is already in the logged in users then the process will start again, otherwise if it is a new user the handle_new_cl...
def __get_data_type(pkl_files): for pkl_file in pkl_files: saved_data = gnu.load_pkl(pkl_file) return saved_data['demo_type'], saved_data['smpl_type'] def __get_smpl_model(demo_type, smpl_type): smplx_model_path = './extra_data/smpl/SMPLX_NEUTRAL.pkl' smpl_model_path = './extra_data/smpl//ba...
The main task of the code is to visualize SMPL (Skinned Multi-Person Linear) models from loaded .pkl files using a specified renderer (pytorch3d or opendr). It parses input arguments, identifies the SMPL model type, loads the appropriate model, initializes a visualizer, and renders the prediction results from the provi...
def main(): args = DemoOptions().parse() # load pkl files pkl_files = gnu.get_all_files(args.pkl_dir, ".pkl", "full") # get smpl type demo_type, smpl_type = __get_data_type(pkl_files) # get smpl model smpl_model = __get_smpl_model(demo_type, smpl_type) # Set Visualizer assert args...
def handle_greeting_intent(event): response = table.query(KeyConditionExpression=Key('identity').eq('1')) data = response['Items'][0] suggestions = data['suggestions'] status = data['isFirstTime'] if not status: return { 'dialogAction': { "type": "ElicitInte...
The code routes user intents to specific handlers: Greeting, Dining Suggestions, or Thank You, logging details and raising an error for unimplemented intents.
def handleServices(event): logger.debug('Service userId={}, intentName={}'.format(event['userId'], event['currentIntent']['name'])) intent_type = event['currentIntent']['name'] # Handle the Bot's Services if (intent_type == 'GreetingIntent'): return handle_greeting_intent(event) elif(...
def wav_samples(channels, sample_width=SAMPLE_WIDTH, raw_samples=False): channels = (channels,) if not raw_samples: # we have audio waveforms, so sample/pack them first channels = sample_all(channels, width=sample_width) return interleave(channels) def _pyaudio_callback(wavgen): def cb(a...
The code defines a `play` function to stream audio data using PyAudio, supporting both blocking and non-blocking modes. It initializes a PyAudio stream, configures output parameters, and either plays audio in chunks (blocking) or returns the stream for asynchronous playback (non-blocking). It handles exceptions, ensure...
def play(channels, blocking=True, raw_samples=False): if not pyaudio_loaded: raise Exception("Soundcard playback requires PyAudio. Install with `pip install pyaudio`.") channel_count = 1 wavgen = wav_samples(channels, raw_samples=raw_samples) p = pyaudio.PyAudio() stream = p.open( fo...
def neural_network(input, weights): hid = vect_mat_mul(input, weights[0]) pred = vect_mat_mul(hid, weights[1]) return pred def check_collisions(self) -> list: coming = [self.lights[i] and self.directions[i] for i in range(4)] if ((self.lights[0] and self.directions[0] > 0) or (self.lights[2]...
The code updates a neural network's weights to optimize movement decisions in a simulated environment. It processes neural outputs to control lights, adjusts goals based on collision detection, calculates error deltas, and applies gradient descent to refine weights. Collision penalties and score adjustments are managed...
def tick(self): neuro_out = neural_network(self.directions, self.weights) for i in range(4): self.lights[i] = neuro_out[i] > 0 goal = neuro_out if self.check_collisions(): # print("Collision detected!") # self.score -= 10 self.collisions...
def fitPoly(xs,ys,n): return mleFit(addPolyTerms(xs,n),ys) def addPolyTerms(x,n): xs = addBias(x) for i in range(2,n+1): xs = np.column_stack((xs,x**(i))) #print(i) return xs def view_data_segments(xs, ys): """Visualises the input file with each segment plotted in a different colour....
This function calculates the sum of squared errors for a polynomial regression model of degree `n` trained on `trainXs` and `trainYs`, evaluated on `testXs` and `testYs`. It fits the polynomial, computes predictions, and returns the error. If `doPlot` is True, it plots the polynomial curve and training data segments.
def calcPolyError(trainXs, testXs, trainYs, testYs,doPlot=False,n=3): A = fitPoly(trainXs,trainYs,n) #print(A.shape) polyXs = addPolyTerms(testXs,n) #print(polyXs) # print("\n\n ",n) # print(A) # A,__ ,_ ,___= np.linalg.lstsq(polyXs,testYs,0) # print(A) # A = np.flip(np.polyfit(train...
def load_points_from_file(filename): """Loads 2d points from a csv called filename Args: filename : Path to .csv file Returns: (xs, ys) where xs and ys are a numpy array of the co-ordinates. """ points = pd.read_csv(filename, header=None) return points[0].values, points[1].values...
The main task of the code is to visualize a specific segment of data points from a file. It loads coordinates, divides them into segments of 20 points, and displays the segment at index `segnums` using plotting functions. The code also calculates a trigonometric error for the selected segment before rendering it.
def showseg(file,segnums): xs,ys = load_points_from_file(file) #reconstructionError = np.empty(10) numSegs = len(xs) // 20 for i in range(numSegs): if i == segnums : cutXs = xs[20*i:20*i+20] cutYs = ys[20*i:20*i+20] calcTrigError(cutXs,cutXs,cutYs,cutYs,True) ...
def relative_to_assets(path: str) -> Path: return ASSETS_PATH / Path(path) def graph_feature_average_degree_Press(parent = None): frequencyBand = parent.FB.get() if frequencyBand == 'Choose frequency band': parent.children['label_asterisk'].config(text="Choose frequency band first") return ...
This code initializes a GUI window for analyzing EEG recordings, displaying graph features (e.g., average degree, transitivity) of treatment and control groups. It provides buttons to generate graphs, load datasets, select frequency bands, and export results. The interface visualizes analysis parameters and allows user...
def __init__(self, file_name_treatment, file_name_control, precentage, files_name, freqToListOfGraphs_treatment_group_individuals, freqToListOfGraphs_control_group_individuals): window = Tk() window.title("Analyze Data") window.geometry("1170x687") window.configure(bg = "#FFFFFF") ...
def check_added_ingress(self, ingress): namespace_name = ingress.metadata.namespace ingress_name = ingress.metadata.name ip_addresses_object = ingress.status.load_balancer.ingress or None if ip_addresses_object is None: logging.debug( 'Ingress %s could not ...
This code monitors Kubernetes Ingress resources across all namespaces using a watcher. It processes events (ADDED/DELETED/MODIFIED) by logging changes and triggering corresponding validation checks via `check_added_ingress`, `check_deleted_ingress`, and `check_modified_ingress` methods, ensuring proper handling of Ingr...
def start(self): for event in self._watcher.stream( self._networking_api.list_ingress_for_all_namespaces ): match event['type']: # type: ignore case Config.ADDED: logging.debug('--> Added detected') self.check_added_ingress...
def download_voc2007(root): path_devkit = os.path.join(root, 'VOCdevkit') path_images = os.path.join(root, 'VOCdevkit', 'VOC2007', 'JPEGImages') tmpdir = os.path.join(root, 'tmp') # create directory if not os.path.exists(root): os.makedirs(root) if not os.path.exists(path_devkit): ...
This code initializes a VOC2007 dataset loader, setting paths for images and annotations, downloading data if requested, reading image splits, parsing bounding boxes, and constructing a binary label matrix indicating object presence. It maps image paths to indices, populates labels using object categories, and stores p...
def __init__(self, root, set, transform=None, download=False, target_transform=None): self.root = root self.path_devkit = os.path.join(root, 'VOCdevkit') self.path_images = os.path.join(root, 'VOCdevkit', 'VOC2007', 'JPEGImages') self.transform = transform self.target_transform =...
def download_voc2007(root): path_devkit = os.path.join(root, 'VOCdevkit') path_images = os.path.join(root, 'VOCdevkit', 'VOC2007', 'JPEGImages') tmpdir = os.path.join(root, 'tmp') # create directory if not os.path.exists(root): os.makedirs(root) if not os.path.exists(path_devkit): ...
This code initializes a VOC2007 dataset loader, setting up paths, handling download, reading image splits and bounding boxes, and preparing class labels for classification tasks. It configures transformations and stores dataset metadata for use in machine learning workflows.
def __init__(self, root, set, transform=None, download=False, target_transform=None): self.root = root self.path_devkit = os.path.join(root, 'VOCdevkit') self.path_images = os.path.join(root, 'VOCdevkit', 'VOC2007', 'JPEGImages') self.transform = transform self.target_transform =...
def get_parser_args(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() parser_eval = subparsers.add_parser('eval', help='Evaluate') parser_eval.add_argument('--dataset', type=str, default="cifar10", nargs="+", help="Dataset(s) to use for the benchmark. Can be the name of a d...
The main task of the code is to determine the operation mode based on the `base.which` attribute. If `base.which` is "eval", it executes `main_eval(base)`; if "build", it runs `main_build(base)`. If `base` lacks the "which" attribute, it prints help and exits. This function acts as a dispatcher for evaluation or build ...
def main(): parser, base = get_parser_args() if not hasattr(base, "which"): parser.print_help() return if base.which == "eval": main_eval(base) elif base.which == "build": main_build(base)
def help(): print(""" Search Syntax: python3 database_search.py <json file> <search expression> Returns all users matching the search expression Search expression: > (a or b) and not (c or d) Returns all accounts followed by a or b but excludes all accounts followed by c or d Data Syntax: ...
The code processes a social network JSON file, either displaying available users or identifying those matching a specified expression. It parses the network structure, extracts users and their follows, removes duplicates, and checks each user against the expression using a matching function, then outputs the list of ma...
def main(): if args[1] == "-h": help() return with open(args[1], "r") as fp: net = json.load(fp) if args[2] == "-d": print("Data available for:") for user in net: print(user, end = ", ") print("") return expr = get_tree(args[2]) ...
def write(message_type, message=''): """ Write a message to Cobalt Strike. Message can be anything serializable by `serialization.py`. This includes primitives, bytes, lists, dicts, tuples, and callbacks (automatically registered). :param message_type: Type/label of message :param message: Mess...
The function `handle_message` processes incoming messages based on their type/name. It executes specific actions: dispatching callbacks, evaluating Python code, toggling debug mode, stopping scripts, or handling errors for unrecognized messages. It ensures proper message handling by routing each type to its correspondi...
def handle_message(name, message): """ Handle a received message according to its name :param name: Name/type/label of message :param message: Message body """ #debug('handling message of type {}: {}'.format(name, message)) if name == 'callback': # dispatch callback callba...
def fork(): """ Tell Cobalt Strike to fork into a new thread. Menu trees have to be registered before we fork into a new thread so this is called in `engine.loop()` after the registration is finished. """ global _has_forked if _has_forked: raise RuntimeError('Tried to fork Cobalt ...
The code defines a function `loop()` that continuously processes messages from a pipe indefinitely, handling each message or logging errors if messages lack a name. It optionally calls `fork()` first if `fork_first` is True, ensuring forked processes handle messages. Exceptions during message handling are caught and lo...
def loop(fork_first=True): """ Loop forever, handling messages. Does not return until the pipe closes. Exceptions are printed to the script console. :param fork_first: Whether to call `fork()` first. """ global _has_forked if fork_first and not _has_forked: fork() for name, m...
def write(message_type, message=''): """ Write a message to Cobalt Strike. Message can be anything serializable by `serialization.py`. This includes primitives, bytes, lists, dicts, tuples, and callbacks (automatically registered). :param message_type: Type/label of message :param message: Mess...
The function `call` executes a sleep/aggressor function with specified arguments, handling execution context (forking, synchronization). It prepares parameters, manages callbacks, and sends tasks via `write`. If `sync=True`, it waits for the function's return value through `read_pipe_iter()`, returning it upon receipt....
def call(name, args=None, silent=False, fork=None, sync=True): """ Call a sleep/aggressor function. You should use the `aggressor.py` helpers where possible. :param name: Name of function to call :param args: Arguments to pass to function :param silent: Don't print tasking information (! operat...
def change_info(message: Message): try: chat_id = message.chat.id markup = types.ReplyKeyboardMarkup(row_width=2) name_btn = types.KeyboardButton('Change name') age_btn = types.KeyboardButton('Change age') gender_btn = types.KeyboardButton('Change gender') back_btn = types.KeyboardButton('Back') markup....
This function processes user-provided names in a messaging app. It validates name length, updates the database with the new name if valid, handles 'Back' navigation, and manages exceptions. If invalid, it prompts the user again.
def process_name(message: Message): try: chat_id = message.chat.id name = message.text if name == 'Back': return change_info(message) if len(name) >= MIN_NAME_LEN and len(name) <= MAX_NAME_LEN: # user = users.get(chat_id) # if user: # user.name = name # else: # users[chat_id] = User(name) ...
def is_natural_age(n: str): try: float(n) except ValueError: return False else: return float(n).is_integer() \ and float(n) > 0 and float(n) < 200 def menu(message: Message): try: chat_id = message.chat.id markup = types.ReplyKeyboardMarkup(row_width=2) info_btn = ty...
This function processes user age input by validating it, updating the database with the age, and navigating to a menu or handling 'Back' requests. If invalid, it prompts re-entry. Exceptions are logged and handled gracefully.
def process_age(message: Message): try: chat_id = message.chat.id age = message.text if is_natural_age(age): age = int(age) # user = users[chat_id] # user.age = age db.update_row(chat_id, 'age', age) menu(message) elif age == 'Back': change_info(message) else: msg = bot.reply_to(message...
def set_gender(message: Message): try: chat_id = message.chat.id markup = types.InlineKeyboardMarkup() markup.row( types.InlineKeyboardButton('female', callback_data='female'), types.InlineKeyboardButton('male', callback_data='male') ) msg = bot.send_message(chat_id, sentences['get_gender'], reply_mar...
This function processes user messages to handle profile modification commands (name, age, gender) by sending prompts and registering next steps, providing a 'Back' option, and delegating unknown commands. It uses exception handling for error management.
def process_info(message: Message): try: chat_id = message.chat.id param = message.text markup = types.ReplyKeyboardMarkup() back_btn = types.KeyboardButton('Back') markup.add(back_btn) if param in ['Change name', '/change_name']: msg = bot.send_message(chat_id, sentences['get_name'], reply_markup=mark...
def is_natural_age(n: str): try: float(n) except ValueError: return False else: return float(n).is_integer() \ and float(n) > 0 and float(n) < 200 def set_gender(message: Message): try: chat_id = message.chat.id markup = types.InlineKeyboardMarkup() markup.row( ty...
This function processes user input to validate and store their age in a database. If the input is a valid natural number, it converts it to an integer, updates the user's age in the database, and proceeds to collect gender information. If invalid, it prompts the user again. Exception handling ensures errors are managed...
def process_age_step(message: Message): try: chat_id = message.chat.id age = message.text if is_natural_age(age): age = int(age) # user = users[chat_id] # user.age = age db.update_row(chat_id, 'age', age) set_gender(message) else: msg = bot.reply_to(message, sentences['get_age']) bot.regi...
def menu(message: Message): try: chat_id = message.chat.id markup = types.ReplyKeyboardMarkup(row_width=2) info_btn = types.KeyboardButton('Info') settings_btn = types.KeyboardButton('Settings') markup.add(info_btn, settings_btn) msg = bot.send_message(chat_id, sentences['menu'], reply_markup=markup) b...
This function processes user gender input by updating the database if the input is 'male' or 'female', navigating to 'change_info' for 'Back', or prompting again for invalid inputs, while handling exceptions.
def process_gender(message: Message): try: chat_id = message.chat.id gender = message.text if gender in ['male', 'female']: # user = users[chat_id] # user.gender = gender db.update_row(chat_id, 'gender', gender) menu(message) elif gender == 'Back': change_info(message) else: set_gender(mes...
def get_info(message: Message): try: chat_id = message.chat.id # user = users[chat_id] data = db.get_data(chat_id) print(data) user_data = '' for tupl in data: user_data = '''Name: {} \nAge: {} \nGender: {} '''.format(tupl[0], tupl[1], tupl[2]) # user_data = '''Name: {} \nAge: {} \nGender: {} ...
This function processes incoming messages by routing commands to appropriate handlers. It checks the message text to trigger info retrieval, settings changes, or other commands via check_any_command. If no valid command is found, it displays a menu. Exceptions are caught and handled with process_exception, ensuring the...
def process_menu(message: Message): try: chat_id = message.chat.id param = message.text if param in ['Info', '/info']: get_info(message) elif param in ['Settings', '/settings']: change_info(message) else: func = check_any_command(param) if func: func(message) else: menu(message) excep...
def get_obstacle_paths(self): return [convert_points_polygon_to_lines(obstacle) for obstacle in self.robot_data['obstacles']] def get_obstacles(self): return [{tuple(point) for point in obstacle} for obstacle in self.robot_data['obstacles']] def get_edge_limiter(self): real_edge_limiter_name = s...
This code initializes a navigation graph for a robot, processing obstacle data, setting up edge constraints, and preparing for pathfinding. It constructs a graph with start/goal positions, obstacle paths, and applies edge limiters to manage movement constraints. The `discover_edges()` method likely identifies valid con...
def __init__(self, robot_data, edge_limiter_name=None, is_report=False): self.graph = Graph() self.robot_data = robot_data self.edge_limiter_name = edge_limiter_name self.is_report = is_report self.locations = [tuple(robot_data['start']), tuple(robot_dat...