dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def headers(self): headers = {"user-agent": "okhttp/3.14.9", "content-type": "application/json"} if self.access_token: headers["Authorization"] = "Bearer " + self.access_token logging.info("Headers") logging.info(headers) return headers def response...
The main task of the code is to fetch the BTC/USD exchange rate from Chivo Wallet's API, validate the response tokens, log the result, and return the rate as a float. If tokens are invalid, it recursively retries the request.
def price(self): url = "https://app.chivowallet.com/api/v1/rate/1/BTC/USD/" response = requests.get(url, headers = self.headers()) json_result, valid_tokens = self.response_recover_tokens(response) if not valid_tokens: #Try again logging.info('Not valid tokens try rec...
def headers(self): headers = {"user-agent": "okhttp/3.14.9", "content-type": "application/json"} if self.access_token: headers["Authorization"] = "Bearer " + self.access_token logging.info("Headers") logging.info(headers) return headers def response...
The main task of the code is to retrieve a user's first name from an API endpoint by sending a GET request, validating response tokens, and storing the result. If tokens are invalid, it recursively retries. Upon success, it logs and returns the user's first name as `self.user_name`.)>
def get_user_name(self): url = "https://app.chivowallet.com/api/v1/users/" response = requests.get(url, headers = self.headers()) json_result, valid_tokens = self.response_recover_tokens(response) if not valid_tokens: #Try again return self.get_user_name() se...
def headers(self): headers = {"user-agent": "okhttp/3.14.9", "content-type": "application/json"} if self.access_token: headers["Authorization"] = "Bearer " + self.access_token logging.info("Headers") logging.info(headers) return headers def response...
The code fetches user balance data from an API, parses the JSON response, and updates the USD and BTC balances. It retries if the token validation fails, logs the result, and stores the values in instance variables for later use.
def update_balance(self, show = False): url = "https://app.chivowallet.com/api/v1/balances/" response = requests.get(url, headers = self.headers()) json_result, valid_tokens = self.response_recover_tokens(response) if not valid_tokens: #try again return self.update_ba...
def truncate(f, n): '''Truncates/pads a float f to n decimal places without rounding''' s = '{}'.format(f) if 'e' in s or 'E' in s: return '{0:.{1}f}'.format(f, n) i, p, d = s.partition('.') return '.'.join([i, (d+'0'*n)[:n]]) def headers(self): headers = {"user-agent": "okhttp/3.14....
The function prepares a BTC-to-UDS currency conversion purchase by truncating BTC and calculated UDS amounts, sending a GET request to an API endpoint, validating the response tokens, and retrying if invalid. It logs the URL, response, and original BTC value for debugging.
def prepare_dollars_purchase(self): btc_amount = truncate(self.BTC, 8) uds_amount = truncate(float(btc_amount) * self.purchase_price , 2) url = "https://app.chivowallet.com/api/v1/refill/available/currencies/"+uds_amount+"/?pay="+btc_amount response = requests.get(url, headers = self.he...
def headers(self): headers = {"user-agent": "okhttp/3.14.9", "content-type": "application/json"} if self.access_token: headers["Authorization"] = "Bearer " + self.access_token logging.info("Headers") logging.info(headers) return headers def response...
The main task of the code is to validate a password by sending it to a specified API endpoint via a POST request, processing the response to check for valid tokens, and retrying the validation if the tokens are invalid.
def validate_password(self): url = 'https://app.chivowallet.com/api/v1/commerce/check/pin/' password_data = {"password" : self.password} password_data = json.dumps(password_data) response = requests.post(url, headers = self.headers(), data = password_data) json_result, valid_t...
def headers(self): headers = {"user-agent": "okhttp/3.14.9", "content-type": "application/json"} if self.access_token: headers["Authorization"] = "Bearer " + self.access_token logging.info("Headers") logging.info(headers) return headers def try_json...
The main task of the code is to authenticate using provided or default credentials (phone, DNI, password) to obtain access and refresh tokens from an API endpoint. It constructs a JSON payload with these credentials, sends a POST request to the token endpoint, parses the response, and stores the retrieved tokens in ins...
def obtain_tokens(self, code, dui = None, phone = None, password = None): if not phone: phone = "Somephone" if not dui: dui = "somedui" if not password: password = "code" credentials = {"phone_number": phone, "code":...
def truncate(f, n): '''Truncates/pads a float f to n decimal places without rounding''' s = '{}'.format(f) if 'e' in s or 'E' in s: return '{0:.{1}f}'.format(f, n) i, p, d = s.partition('.') return '.'.join([i, (d+'0'*n)[:n]]) def headers(self): headers = {"user-agent": "okhttp/3.14....
The main task of the code is to prepare a Bitcoin purchase by converting USD to BTC using a specified price, sending a request to an API endpoint, validating the response tokens, retrying if invalid, and logging transaction details including original BTC amount, URL, and response data for tracking and debugging purpose...
def prepare_bitcoin_purchase(self): uds_amount = truncate(self.USD, 2) btc_amount = truncate(float(uds_amount) / self.purchase_price , 8) url = "https://app.chivowallet.com/api/v1/crypto/available/currencies/"+btc_amount+"/?pay="+uds_amount response = reque...
def update_balance(self, show = False): url = "https://app.chivowallet.com/api/v1/balances/" response = requests.get(url, headers = self.headers()) json_result, valid_tokens = self.response_recover_tokens(response) if not valid_tokens: #try again return self.update_ba...
The main task of the code is to execute a dollar purchase process by updating the balance, setting the purchase price, preparing the transaction, validating the user's password, and finalizing the purchase. The 'show' parameter optionally displays the transaction details during execution.
def purchase_dollars(self, show = False): self.update_balance() self.purchase_price = self.price() self.prepare_dollars_purchase() self.validate_password() self.make_dollars_purchase(show = show)
def update_balance(self, show = False): url = "https://app.chivowallet.com/api/v1/balances/" response = requests.get(url, headers = self.headers()) json_result, valid_tokens = self.response_recover_tokens(response) if not valid_tokens: #try again return self.update_ba...
The code facilitates a Bitcoin purchase by updating the user's balance, setting the purchase price, preparing the transaction, validating the password, and executing the purchase, with an optional 'show' parameter to display the process.
def purchase_bitcoin(self, show = False): self.update_balance() self.purchase_price = self.price() self.prepare_bitcoin_purchase() self.validate_password() self.make_bitcoin_purchase(show = show)
def reset(self): self.deck = Deck() self.deck.shuffle() def nextPlayer(self): i = self._current_player_index i+=1 if i > len(self.players) - 1: i = 0 self._current_player_index = i self._current_player=self.players[i] def dealInitialCards...
The `nextRound` method resets all players' states, resets the game instance, advances to the next player, and deals initial cards to prepare for a new round in a turn-based game.
def nextRound(self): for p in self.players: p.reset() self.reset() self.nextPlayer() self.dealInitialCards()
def _set_cur_loc(self): for i, row in enumerate(self.board_state): for j, val in enumerate(row): if val == 1: self.cur_loc = (i, j) return def _get_hider_loc(self) -> Tuple: # Returns None if hider is not in sight, otherwise returns hid...
This function determines the next move for an agent in a hide-and-seek game by evaluating the board state, visible squares, and valid moves. It updates the agent's state (SEARCHING/CHASING), locates the hider if visible, and selects a move: either toward a landmark square when searching or directly toward the hider whe...
def get_action_from_state(self, board_state: List[List[int]], visible_squares: List[Tuple[int, int]], valid_moves: List[Tuple[int, int]]) -> Tuple[int, int]: self.prev_state = self.state self.board_state = board_state self.visible_squ...
def calc_ampl(x): while len(x) > 1: for i, (n, id) in enumerate(x): if is_left(x, i): n_right, id_right = x[i+1] for v in [(n, id), (n_right, id_right)]: x.remove(v) x.insert(i, (3*n + 2*n_right, id[:-1])) return x[0][0] def add(x, y): o, s...
The function recursively processes a list `d` by accumulating its elements into `res` using `add`, then computes the amplitude of the accumulated result with `calc_ampl` when the list is exhausted.
def solve_1(d, res): return calc_ampl(res) if len(d) == 0 else solve_1(d[1:], add(res, d[0]))
def createWorld(m): for mI in range(1, 5): for aI in range(1, 5): if (mI == 1 and aI == 1): continue number = random.randint(0, 3) m[mI][aI] = 2 if number == 1 else 0 renderMatrix(matrix) global process_map global presentationMatrix process...
The code's main task is to navigate and clean a grid-based world by discovering paths, marking visited cells, and updating the environment. It uses a loop to repeatedly find paths, records them in a solution list, and modifies the matrix to reflect cleaned areas. Finally, it renders the cleaned matrix step-by-step base...
def main(): global matrix global process_map global stack global currCol global currLine createWorld(matrix) while (mapNotClean()): path = discoverPath() x = path.get_x() y = path.get_y() aux_list = [] while (path.get_parent() is not None): ...
def createWorld(m):#implementar verificar si la cantidad de cuadros sucios es par global presentationMatrix x= len(presentationMatrix) y=0 for mI in range(1, x-1): for aI in range(1, x-1): if (mI == 1 and aI == 1): continue number = random.randint(0, 3) ...
The main task of the code is to navigate and clean a matrix by discovering paths using two algorithms (discoverPath1 and discoverPath), backtracking to mark explored paths, updating a presentation matrix to visualize robot movements, and handling exceptions by restarting the process. It tracks positions, modifies matri...
def main(): global matrix global process_map global stack global stack1 global currCol global currLine global currCol1 global currLine1 createWorld(matrix) while (mapNotClean()): try: path1 = discoverPath1() x1 = path1.get_x() ...
def __isEndOfTurn(self, body): return body['status'] == 'endOfTurn' def __endTurn(self, body): f_Player = body['firstPlayerIndex'] s_Player = 1 - f_Player f_Card = body['playedCards'][str(f_Player)] s_Card = body['playedCards'][str(s_Player)] b_Card = body['briscola'] ...
The code processes game state transitions by evaluating conditions: if the turn ends, it finalizes the turn; if both players have played, it marks the end; if a neural network is needed, it predicts the next move; otherwise, it plays the final six cards. The main task is to update the game state based on these conditio...
def play(self, body): if self.__isEndOfTurn(body): body = self.__endTurn(body) elif self.__haveBothPlayed(body): body = self.__setEndOfTurn(body) elif self.__useNN(body): body = self.__nnPredict(body) else: body = self.__playFinalSix(body) ...
def _visit_start_page(self): return self._get(path='/') def _user_think_time(self, min=3, max=5): return random.randint(min, max) def _select_dataset(self, params: Union[CheckUrlParams, CheckFileParams]): self._get(path='/dataset') time.sleep(self._user_think_time()) dataset_sele...
The main task of the code is to simulate a user journey for checking a data file by randomly selecting parameters, submitting a request, and verifying its completion status. It navigates through dataset selection, geometry type (if applicable), upload method, and polls the server for results. If the request completes s...
def check_datafile(self): params = config.journey_parameters[random.randint(0, len(config.journey_parameters) - 1)] # self.host_ip_address = self._lookup_host_ip() self._visit_start_page() time.sleep(self._user_think_time()) self._select_dataset(params) time.sleep(self....
def initializeParameterNode(self) -> None: """Ensure parameter node exists and observed.""" # Parameter node stores all user choices in parameter values, node selections, etc. # so that when the scene is saved and reloaded, these settings are restored. self.setParameterNode(self.logic.g...
The main task of the code is to initialize a Slicer module's UI by loading a Qt Designer-created interface, connecting interactive elements (buttons, selectors) to logic functions, setting up MRML scene integration, initializing segmentation logic, and ensuring parameter node readiness. It also collapses advanced optio...
def setup(self) -> None: """Called when the user opens the module the first time and the widget is initialized.""" ScriptedLoadableModuleWidget.setup(self) # Load widget from .ui file (created by Qt Designer). # Additional widgets can be instantiated manually and added to self.layout. ...
def is_us(event: Dict) -> bool: location = (event.get('location', {}) or {}) country = location.get('country') return country == "US" def convert_event(event: Dict) -> Dict: """Builds the JSON object used by the client to render information in the map. Note: local event hosts are using the "venue" ...
The code fetches events from Action Network's API for a specific campaign, filters US-based events, and recursively collects all pages. It returns a list of converted event data, handling pagination by recursively calling itself for subsequent pages until all events are retrieved.
def get_events_from_events_campaign(return_events=None, page=1) -> Dict[str, Dict]: if not return_events: return_events = [] log.info('\nget_events_from events_campaign (action network) -- page %d', page) response = http.request('GET', ...
def __beatPositionQuantised(self, tOns): ''' Returns the quantised beat position at tOns given the IBD's new estimate of perceptual beat. Also returns accuracy as a percentage ''' # Calculate the BP at tOns - given IBD's estimate BP_ons_est = sel...
This function estimates the perceptual beat position (BP) and tempo for a musical onset at time tOns. It initializes beat tracking for the first onset, quantizes subsequent onsets to the nearest beat position, calculates beat weights based on note accuracy, and updates tempo estimates using a line-of-best-fit algorithm...
def onset(self, tOns, note=36): ''' For an onset at tOns, estimate the perceptual beat. Parameters ---------- tOns : float CPU time of onset (latency corrected). note: int. MIDI note number of onset. Returns ------- None. '''...
def add_frame(self, frame): if len(self.F_list) >= self.buffer: self.F_list.pop(0) self.F_list.append(frame) def greedy(self): try: prev_F = self.F_list[-2] except IndexError as e: self.add_frame(self.F_list[-1]) prev_F = self.F_list[-2] ...
The code processes a video frame by adding it to the tracker's frame buffer, applying a greedy algorithm for object tracking, and checking index differences to assess tracking accuracy. It returns a boolean indicating whether tracked indices differ, aiding in frame alignment or error detection in sequential tracking ta...
def track(self, frame): self.add_frame(frame) self.greedy() return self.check_idx_diff()
def install_apt_dependencies(modules=pbl.all_modules): print("----- starting on_before_apt steps -----") for module in modules: _try_run_on_before_apt(module) print("----- starting install apt dependencies -----") deps = _get_union_of_module_string_sets(modules, "required_apt_packages") if d...
The code's main task is to install required software by executing APT package installations, pip dependencies, and custom setup steps for specified modules, defaulting to all modules from `pbl`. It logs progress with start/end messages.
def install_required_software(modules=pbl.all_modules): print("----- starting installing required software") install_apt_dependencies(modules) install_pip_dependencies(modules) run_custom_install_steps(modules) print("----- finished installing required software")
def _get_full_user_bundle(session): print("Loading active tasks") response = session.get(_CURRENT_USER_URL_FRAG) _check_response_and_maybe_exit(response) res = response.json() if not res["isLoggedIn"]: _print_login_failure_message_and_exit() return res def _make_duid(): return "".joi...
The main task of the code is to create a new task in a system by configuring attributes like dartboard, status, assignees, tags, priority, and due date. It validates inputs, maps them to internal identifiers (DUIDs), constructs a task object, and submits it via an API. If specified, it also initiates the task. The func...
def create_task( title, should_begin=False, dartboard_title=None, status_title=None, assignee_emails=None, tag_titles=None, priority_int=None, size_int=None, due_at_str=None, ): config = _Config() session = _Session(config) user_bundle = _get_full_user_bundle(session) ...
def getResults(originalNumbers): results = [] subExpressions = [] for _ in range(2000): nums = originalNumbers.copy() usedNums = [] acc = 0 expression = "" while len(nums) > 0: #handling the the number - not sure why i have to return all values and the fun...
The function `pickXBestNumbersInRange` identifies the combination of `numOfNumbers` values within the range `[lowestNum, highestNum]` that produces the highest maximum value when processed by an external `getResults` function. It evaluates all possible combinations, tracks the best-performing set, and outputs the optim...
def pickXBestNumbersInRange(numOfNumbers, lowestNum,highestNum): numberCollections = list(itertools.combinations(range(lowestNum,highestNum+1),numOfNumbers)) currentHighestNum = 0 currentHighestNumNumbers = [] currentHighestNumResults = None for numbers in numberCollections: results = getRes...
def read_args(): parser = ap.ArgumentParser(description='Command line options and arguments') parser.add_argument('-t', action='store_true', help="Print parse tree that represents underlying sentence structure") parser.add_argument('grmr', help="Grammar file path") parser.add_argument('num_sent', nargs=...
The main task of the code is to generate text based on a probabilistic grammar. It reads command-line arguments, loads a grammar file, parses it into grammar rules and associated probabilities, and then generates output using those rules. The core functionality revolves around parsing and applying probabilistic context...
def main(arguments): g_file = read_args() grammar, prob = read_grammar(g_file) generate(grammar, prob)
def _merge_row(self, join_info, left_data, right_data): should_do_join = False left_table = join_info['left_table'] right_table = join_info['right_table'] join_column = join_info['join_column'] join_column_right = join_info['join_column_right'] left_alias = join_info['le...
This function performs an inner or outer join by iterating through all combinations of rows from two tables, merging them based on join conditions. It tracks executed rows, handles join types (inner, left/right/full outer), and flushes unmatched rows for outer joins. It updates row flags and sends merged results to a h...
def _execute_both_direct(self, join_info, left_table_rows, right_table_rows): rows_executed = 0 for left_row in left_table_rows: left_row_data = left_row["data"] for right_row in right_table_rows: right_row_data = right_row["data"] # Do join based ...
def _merge_row(self, join_info, left_data, right_data): should_do_join = False left_table = join_info['left_table'] right_table = join_info['right_table'] join_column = join_info['join_column'] join_column_right = join_info['join_column_right'] left_alias = join_info['le...
This code performs a left partition join by iterating through left table partitions, merging each left row with all right rows based on join conditions, updating flags, and handling outer join cases by flushing unmatched rows. It manages partition updates and result handling for different join types (LEFT/RIGHT/FULL OU...
def _execute_left_partition(self, join_info, right_table_rows): rows_executed = 0 for left_partition_id in range(self.left_table_last_partition_id+1): left_table_rows = read_from_partition_nonhash(self.join_order, left_partition_id, True) should_update_left_partition = False ...
def _merge_row(self, join_info, left_data, right_data): should_do_join = False left_table = join_info['left_table'] right_table = join_info['right_table'] join_column = join_info['join_column'] join_column_right = join_info['join_column_right'] left_alias = join_info['le...
The code performs a join operation on partitioned tables by iterating through all combinations of left and right partitions. It reads rows from each partition, merges them based on join conditions, updates flags, and handles outer joins by flushing unmatched rows. The process tracks executed rows and updates partitions...
def _execute_both_partition(self, join_info): rows_executed = 0 for left_partition_id in range(self.left_table_last_partition_id+1): print("Change left partition") left_table_rows = read_from_partition_nonhash(self.join_order, left_partition_id, True) should_update_le...
def _merge_row(self, join_info, left_data, right_data): should_do_join = False left_table = join_info['left_table'] right_table = join_info['right_table'] join_column = join_info['join_column'] join_column_right = join_info['join_column_right'] left_alias = join_info['le...
This function performs a join operation between left and right tables by iterating through left rows and right partitions, merging matching rows based on join conditions, updating partition flags, and handling outer joins by flushing unmatched rows. It processes data in chunks, tracks executed rows, and ensures proper ...
def _execute_right_partition(self, join_info, left_table_rows): rows_executed = 0 for left_row in left_table_rows: left_row_data = left_row["data"] for right_partition_id in range(self.right_table_last_partition_id+1): right_table_rows = read_from_partition_nonha...
def _get_left_data(self, left_table, left_alias): # Only get data when fit to memory. Otherwise, load in join execution function session = self.session left_table_rows = None is_data_in_partitions = False left_last_partition_id = -1 left_table_name = left_table ...
The main task of the code is to determine the optimal join strategy based on whether the left and right tables are partitioned, execute the corresponding join operation (e.g., partitioned or in-memory), track data fetching time, and manage result partitioning. It checks partition status, selects the appropriate executi...
def _decide_join(self, join_info): left_table = join_info['left_table'] right_table = join_info['right_table'] join_order = join_info['join_order'] next_join_order = join_order + 1 left_alias = join_info['left_alias'] right_alias = join_info['right_alias'] left_...
def readData(dirPath, targetStart, targetEnd, windowEnd): import pandas as pd dataDf = pd.read_csv(dirPath + 'data_matrix.csv') dataDf.anchor_time = dataDf.anchor_time.apply(lambda x: pd.to_datetime(x, format='%Y-%m-%d %H:%M:%S')) dataDf.death_datetime = dataDf.death_datetime.apply(lambda x: pd.to_da...
The main task of the code is to evaluate and compare the performance of multiple machine learning models (XGBoost, LR, LGBM, MLP) using both full and feature-selected datasets. It trains models, generates cross-validation scores, constructs ensemble models from first-level outputs, and saves results for analysis. The p...
def runPredictions(dirPath, dirName, targetStart, targetEnd, windowEnd): log.info('Reading data') X, XVitalsMax, XVitalsMin, XVitalsAvg, XVitalsSd, XVitalsFirst, XVitalsLast, XLabsMax, XLabsMin, XLabsAvg, XLabsSd, XLabsFirst, XLabsLast, y = readData(dirPath=dirPath, targetStart=targetStart, targetEnd=targetEnd...
def __incrementEP(self, ep): ep = str(int(ep) + 1) if int(ep) < 10: ep = "0" + ep return ep def fancyPrint(self, text, font='digital'): try: subprocess.run(f'figlet -w $(tput cols) -c -f {font} "{text}" | lolcat', shell=True, check=True) except: ...
The function constructs a URL using database entries, increments an episode number, and attempts to download it. On success, it updates the database and returns a delay; on failure, it alerts the user and returns 1.
def downloadFromDB(self, n): url = self.__URL row = list(self.animedb['Downloader'][n].values()) ep = self.__incrementEP(row[3]) for j in range(6): if row[j] == 'N/A': continue elif j == 3: url += ep + "+" else: ...
def __incrementEP(self, ep): ep = str(int(ep) + 1) if int(ep) < 10: ep = "0" + ep return ep def __downloader(self, url): page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') results = soup.find_all('td', class_='text-center') link...
The main task of the code is to download an episode by constructing a URL with the provided name and incremented episode number, attempt the download using a downloader, print a status message, and return a delay value on success or 1 on failure due to unavailability.
def downloadFromInput(self, name, ep): url = self.__URL ep = self.__incrementEP(ep) url += f"{name} {ep}" try: self.__downloader(url) self.fancyPrint(f"DOWNLOADING EP-{ep}", 'digital') return self.__delay except: self.fancyPrint("NO...
def get_operations(lines: list[str]) -> Operations: operations: Operations = [] for line in lines: direction, steps = line.split(' ') steps = int(steps) match direction: case 'U': operations.append((Direction.UP, steps)) case 'D': ...
The code simulates the movement of a rope's tail in two scenarios. Part one tracks unique positions of a single-segment rope's tail after applying moves, while part two does the same for a 10-segment rope. The main task is to calculate and print the number of distinct positions the tail visits in each scenario.
def main(): lines = get_lines(9) operations = get_operations(lines) # part one tail_space: TailSpace = {str((0, 0)): True} tail_space = carry_out_moves(tail_space, operations) print(f'part one answer: {len(list(tail_space.keys()))}') # part two rope = [(0, 0) for _ in range(10)] t...
def update(g, dist_enc,line_num, N_NODES, CATEGORIES, n_times = 5, alpha = 0.8): ''' Parameters ---------- g : WikiGraph dist_enc : array line_num : dict N_NODES : int CATEGORIES : list n_times : int alpha : float Returns ------- curr_dist_enc : array Update ...
The code performs a grid search to identify optimal hyperparameters (alpha and n_iters) for a graph embedding model. It iterates over specified alpha and n_iters values, updates embeddings, scales them, predicts labels, and evaluates accuracy against correct_labels. The best parameter combination achieving the highest ...
def tune_hyperparams(g, initial_embedd, alpha_vals, n_iters_vals, correct_labels, line_num, N_NODES, CATEGORIES): ''' Parameters ---------- g : WikiGraph initial_embedd : array alpha_vals : list n_iters_vals : list correct_labels : dict line_num : dict N_NODES : int CATEGORIE...
def sentenceRepAverage(self): rep_total = 0 for s in self.sentence_objs: rep_total += s.repetitionFinder() self.rep_avg = rep_total/len(self.sentence_objs) def indexSort(self): ini_list = self.hierarchySort() if len(self.sentence_objs) > 2: for n in range(...
The main task of the code is to construct a final paragraph by combining the first sentence, sorted sentences from a list, and optionally the last sentence based on specific conditions. It aggregates word counts and ensures the paragraph includes necessary sentences, particularly when the paragraph is at the start or e...
def formFinalParagraph(self): self.sentenceRepAverage() if len(self.sentence_objs) <= 2: return self.para else: list = self.indexSort() final_para = '\t' final_para += self.first_sentence.strip() + '. ' for sent in list: ...
def open_image(path, level=2): return skimage.io.MultiImage(str(path))[level] def separate_objects_in_image(im): mask = get_resized_mask(im) s = generate_binary_structure(2,2) labels, n = label(mask,structure=s) objs = find_objects(labels) return objs def getContourRect(im): h,w,_ = im.shape...
This function processes an input image by extracting individual objects, generating patches from them using a specified function, and either saving the patches as JPEG files or returning them. It adjusts processing based on image level (resolution), ensures patches meet size thresholds, and handles storage or output ac...
def patch_image(im_id, patch_fn, save_ims=False, save_path='./data', level=2): base_im = open_image(path/f'train_images/{im_id}.tiff', level=level) objs = separate_objects_in_image(base_im) ims = [] for obj_num,obj in enumerate(objs): sliced_im = base_im[obj] if sliced_im.size > (60**2 ...
def detector_error_model_to_discretised_pymatching_graph( model: stim.DetectorErrorModel, num_buckets: int = 1000 ) -> pymatching.Matching: graph = detector_error_model_to_nx_graph(model) graph = discretize_weights(graph, num_buckets) return nx_graph_to_pymatching(graph) def detector_error_model_to_...
The function decodes error syndromes from quantum error correction using PyMatching. It processes detector and observable data from input samples, constructs a graph-based error model, and decodes each syndrome to predict observables. It tracks decoding accuracy (failures), outputs weights/predictions if enabled, and r...
def decode_with_pymatching(model: stim.DetectorErrorModel, samples: np.ndarray, num_buckets: int = 1000, num_neighbours: int = -1, verbose: bool = False, show_time: bool = False, show_failures: bool = False, show_weights: bool = False, max...
def get_feature_list_from_paths(imgs) -> list[np.ndarray]: resized = [sk.transform.resize(img, (128, 64)) for img in imgs] hog_features_list = [compute_hog_features(image) for image in resized] # # hog_features_list = [compute_hog_features(image) for image in imgs] return hog_features_list def calcula...
The main task of the code is to compare reference images with source images by extracting their features, calculating pairwise distances, sorting source images by similarity to each reference image, and displaying the reference image alongside its closest matching source images in order of proximity.
def main(): IMAGES_DIR: Final[Path] = Path().resolve().joinpath("images") reference_path: Path = IMAGES_DIR.joinpath("reference") source_path: Path = IMAGES_DIR.joinpath("source") reference_fns: list[Path] = [ os.path.join(reference_path, image_path) for image_path in os.listdir(referen...
def preprocess_sym(doc): nlp_doc=nlp(doc) d=[] for token in nlp_doc: if(not token.text.lower() in STOP_WORDS and token.text.isalpha()): d.append(token.lemma_.lower() ) return ' '.join(d) def syntactic_similarity(symp_t, corpus): most_sim = [] poss_sym = [] for symp in c...
The code processes user input in a state-driven workflow to diagnose potential diseases. It collects two symptoms, applies syntactic/semantic similarity checks, uses a KNN model for prediction, and provides medical advice or precautions. The global variable 'i' tracks interaction stages: symptom input, disease predicti...
def get_response(inp): global i global sim1,psym1,sym1,sym2,sim2,psym2,all_sym,all_symp_pr,result,sym,all_symp_col if i==1: sym1 = inp sym1=preprocess_sym(sym1) sim1,psym1=syntactic_similarity(sym1,all_symp_pr) if sim1==1: psym1=related_sym(psym1) i=i...
def preprocess_sym(doc): nlp_doc=nlp(doc) d=[] for token in nlp_doc: if(not token.text.lower() in STOP_WORDS and token.text.isalpha()): d.append(token.lemma_.lower() ) return ' '.join(d) def syntactic_similarity(symp_t, corpus): most_sim = [] poss_sym = [] for symp in c...
The function `main_sp` identifies potential diseases based on two user-provided symptoms. It processes each symptom via syntactic/semantic similarity checks, suggesting alternatives if matches fail. It then predicts diseases using the symptoms, iteratively asking for additional related symptoms. Finally, it employs a K...
def main_sp(msg): #main Idea: At least two initial sympts to start with #get the 1st syp ->> process it ->> check_pattern ->>> get the appropriate one (if check_pattern==1 == similar syntaxic symp found) print("Enter the main symptom you are experiencing, "+" \n\t\t\t\t\t\t",end="=>") sym1 = ...
def get_categories(session): """ Synchronously retrieves all categories from mealdb API as JSON. :return: Returns a list of strings of category names. """ response_json = session.get(GET_ALL_CATEGORIES).json() categories = process_categories(response_json) print("There are %d categories of ...
The code's main task is to analyze recipe data by identifying categories with the most recipes and least-used ingredients in Canadian desserts. It uses synchronous and asynchronous HTTP requests to fetch data, processes it to extract category and ingredient counts, generates analysis results, and visualizes findings th...
def perform_analysis(): """ Makes requests necessary to visualize and analyze which categories have most recipes and which ingredient is least used in Canadian deserts. """ # Initialize sessions for making HTTPS requests (synchronous and asynchronous) session = Session() futures_session = F...
def __calculate_leaf(self, y): """ Calculate the leaf node for the decision tree by labeling it with the most occuring class id. An improvement would be to also include the confidence as a Node attribute. Parameters: - y: Target labels. Returns: - node:...
This function recursively constructs a decision tree by selecting the best feature-value split to maximize information gain. It terminates when data is exhausted, depth limits are reached, or minimum samples are unmet, returning leaf nodes. If no informative splits exist (zero information gain), it directly returns a l...
def __build_tree(self, X, current_depth=1): """ Recursively build the decision tree by creating the best splits. Parameters: - X: Input features. - current_depth: Current depth of the tree. Returns: - decision_node: Root node of the decision tree. """ ...
def protobuf_to_json(raw_bytes: bytes) -> str: message, typedef = blackboxprotobuf.protobuf_to_json(raw_bytes) print(message) return message def parse_base_info(data: dict) -> BaseInfo: return BaseInfo( user_id="", nick=str(data.get("2")), title=data.get("4"), clan_id=dat...
The main task of the code is to decode raw byte data from the WarThunder API into a structured WTProfile object by parsing JSON-formatted protobuf data, extracting specific fields like base info, level info, statistics, and battle history, and handling potential error responses.
def decode_profile_from_raw_bytes(raw_bytes: bytes) -> WTProfile: msg_json: dict = json.loads(protobuf_to_json(raw_bytes)) first_msg = msg_json.get("1", None) # sometimes response can be a error message if isinstance(first_msg, numbers.Number): raise ValueError(f"WarThunder API return {first_m...
def draw(self): if self.app.master==None: exit(0) self.app.iteration=self.iteration self.app.update_label("Iteration: "+str(self.iteration)) self.app.update() positives, negatives, neutrals=self.app.get_decisions() self.assign_atoms(positives, negatives, neutr...
The code solves a constraint satisfaction problem (likely a grid puzzle) by iteratively flipping cell values to minimize unsatisfied row/column hint constraints. It uses a combination of greedy and random strategies to select cells for flipping, restarting with random assignments periodically if stuck. The algorithm tr...
def solve(self): board=self.board colHints = self.colHints rowHints = self.rowHints n = self.n self.iteration=0 minUnsatCount=2*n while self.is_quit==False: self.iteration+=1 verbose=self.iteration%10==1 if self.iteration%10000=...
def positive_deduce(n, rowHints, colHints): atoms=set() for axis, hints in enumerate([colHints, rowHints]): for index, hint in enumerate(hints): m=max(hint) if m>n//2: for i in range(n): if i+m>n-1 and i-m<0: atoms.add((...
The code solves a constraint satisfaction problem on an n×n grid using row and column hints. It initializes a random board, applies deterministic deductions for certain cells (positive/negative), then iteratively flips uncertain cells to satisfy constraints. The algorithm combines greedy optimization and random choices...
def solve(n, rowHints, colHints): # TODO # Board is n by n where each entry is Board[row index, col index] # Each hint is a predicate board=np.random.randint(0,2,[n,n]) positiveAtoms=positive_deduce(n, rowHints, colHints) negativeAtoms=negative_deduce(n, rowHints, colHints) for atom in posit...
def my_argsort(arr): """ Determines serial sorting algorithm used. """ # Use mergesort because # - it's stable (affects behaviour of parallel_match if duplicate values exist) # - it's worst case performance is reasonable return argsort(arr, kind='mergesort') def find_splitting_points(arr, r,...
The function `parallel_sort` performs a parallel in-place sort of a distributed array across multiple processors using MPI. It first sorts local data, calculates split points for global ordering, exchanges data between processors via `alltoallv`, and reassembles the sorted array. If `return_index=True`, it also generat...
def parallel_sort(arr, comm=None, return_index=False, verbose=False): """ Sort the input array in place using an iterative scheme to split values between processors. Input: arr - array which will be sorted in place Returns: Sorting index if return_index=True, otherwise None """ ...
def parallel_sort(arr, comm=None, return_index=False, verbose=False): """ Sort the input array in place using an iterative scheme to split values between processors. Input: arr - array which will be sorted in place Returns: Sorting index if return_index=True, otherwise None """ ...
This function performs parallel matching between two arrays using MPI, returning global indices of matching elements in arr2 for each element in arr1. It efficiently handles distributed data by sorting arr2 (if not pre-sorted), distributing search ranges across processes, and using collective communication operations t...
def parallel_match(arr1, arr2, arr2_sorted=False, comm=None): """ For each element in arr1 return the global index of an element with the same value in arr2, or -1 if there's no element with the same value. If arr2_sorted=True we assume that a *parallel* sort has already been done on arr2. This...
def rotate_front(self, turns, way): self.rotate_cube_towards_right() self.rotate_left(turns, way) def rotate_up(self, turns, way): self.arms_solution += [self.down.move(State.FORWARD)] if turns == State.TURN: if way == State.CLOCKWISE: self.arms_solution += [...
This code determines the rotation parameters (number of turns and direction) based on the input action string and performs a rotation on the specified face of a Rubik's cube. It checks for '2' (double turn), apostrophe (anticlockwise), or default (single clockwise) and delegates to the corresponding face rotation metho...
def rotate(self, action): if '2' in action: turns = State.DOUBLE_TURN way = State.CLOCKWISE elif '\'' in action: turns = State.TURN way = State.ANTICLOCKWISE else: turns = State.TURN way = State.CLOCKWISE face = act...
def get_mention_pair_similarity_lemma_value(mention_pairs, mention_map): similarities = [] lemma_sims = [] sent_sims = [] # generate similarity using the mention text for pair in tqdm(mention_pairs, desc='Generating Similarities'): men1, men2 = pair men_map1 = mention_map[men1] ...
The main task of the code is to analyze and visualize the performance of lambda parameters (my_lams) and ns on ECB and GVC datasets for event mention pair similarities. It computes lemma-based and BERTScore similarity metrics, generates plots comparing these metrics across different lambda values, and saves the results...
def run_lambda_analysis(dataset, split, my_lams=None, ns=None): if ns is None: # ns = [i/2 for i in range(10, 15)] ns = [i for i in range(2, 20)] if my_lams is None: my_lams = [0, 0.3, 0.5, 0.7, 0.8, 1.0] # my_lams = [l_/10 for l_ in range(11)] dataset_folder = f'./datasets...
def compute_measurement_model(self, state_i): n = state_i.shape[0] Z_i = np.zeros((n, 6)) for i in range(0, n): Z_i[i] = self.measurement_model(state_i[i]) return Z_i def compute_covariance_matrices(self, Z_i, w_i_hat): z_mean = np.mean(Z_i, axis=0) Sigma_zz...
This code updates the state estimate (mean_k) and covariance matrix (Sigma_k) in a Kalman filter. It calculates the innovation from measurements, applies the Kalman gain to correct the state, and adjusts the covariance. Quaternion operations handle orientation updates, combining the corrected rotation with the original...
def update(self, mean_k, Sigma_k, measurements_array, state_i, Kalman_gain, w_i_hat): Z_i = self.compute_measurement_model(state_i) Sigma_yy, _ = self.compute_covariance_matrices(Z_i, w_i_hat) innovation = self.compute_innovation(state_i, measurements_array) mu_d = Kalman_gain @ innova...
def propagate(self, mean_k, Sigma_k, t_): state_i = self.recompute_gaussian_from_sigma_pts(mean_k, Sigma_k, t_) q_init = Quaternion(scalar=state_i[0,0], vec=state_i[0, 1:4].reshape(3,)) q_mean, error_i = self.gradient_descent(state_i[:, 0:4], init=q_init) w_i = state_i[:, 4:7] #covaria...
This code implements an Unscented Kalman Filter (UKF) to estimate orientation (roll, pitch, yaw) and state (mean, covariance) from IMU data (accelerometer, gyroscope) over time. It initializes with prior state estimates, iterates through time steps, propagates state predictions, computes Kalman gains, and updates estim...
def run_ukf(self, accel, gyro, imu_ts, T): mean_k = self.mean_0 Sigma_k = self.Sigma_0 roll, pitch, yaw = [], [], [] mean, Sigma = [], [] q_init = Quaternion(mean_k[0], mean_k[1:4]) euler_angles_init = q_init.euler_angles() # Store init states roll.appen...
def __check_if_student_exists(self, student_id: str) -> None: '''checks if a student exists Args: `student_id` (str): student id to check if exists. Return `Exception` ''' if self.search_student(student_id): raise Exception(f'Student {student...
This function inserts a student into a doubly linked list before the student with the specified ID. It checks if the target student exists, adjusts node pointers to link the new student correctly, and returns the inserted student. If the list is empty, it inserts at the start. Pointer updates ensure proper navigation b...
def insert_student_at_position(self, student: Student, student_id: str) -> Student: ''' Inserts a student at a position Args: `student (Student)`: student object to insert `student_id` (str): where to insert student object Retu...
def create(A,M,N): for i in range(N): for j in range(M): A[i][j] = random.randint(4, 51) def print1(A): for i in range(len(A)): for j in range(len(A[i])): print(A[i][j], end=' ') print() def calc(A,s,k): for i in range(len(A)): for j in range(len(A[i])...
The main task of the code is to initialize an 8x5 matrix, perform operations like calculating a sum, checking conditions, and modifying the matrix. It prints the original matrix, computes a sum, executes three checks, alters the matrix, and prints the modified version. The functions `create`, `print1`, `calc`, `check1-...
def main(): N = 8 M = 5 A = [[0] * M for i in range(N)] a = [] create(A,M,N) print1(A) print('Original') print('--------------') print('Sum, K= '+str(calc(A, 0, 0))) print('--------------') check1(A,M,a,N) a.clear() check2(A,M,a,N) a.clear() check3(A,M,a,N) ...
def set_matches(self): print(f'{self.globalID} - Setting matcher') #from math import trunc #n_matches = trunc(52/self.numberOfPlayers) n_matches = 4 self.matches = [i+1 for i in range(n_matches)] self.matches += ([i for i in range(n_matches,0,-1)]) def sendScores(self): ...
This code manages a game loop by initializing matches, processing each match sequentially through a while loop, sending scores, and initiating rounds until all matches are completed.
def run(self): print(f'{self.globalID} - Starting game') self.set_matches() while(len(self.matches)!=0): print(f'{self.globalID} - Match {len(self.matches)}') self.sendScores() self.initiateRound(self.matches.pop(0))
def make_snailfish_number(raw_number, parent=None): num = SnailfishNumber() num.parent = parent if isinstance(raw_number, list): num.left = make_snailfish_number(raw_number[0], num) num.right = make_snailfish_number(raw_number[1], num) else: num.value = raw_number return num ...
The main task of the code is to test the "explode" operation of a snailfish number. It creates a nested list structure, converts it into a snailfish number, identifies nodes requiring explosion, applies the explosion process, and prints the resulting list after each operation to validate correctness.
def test_explode(): py_number_list = [[3, [2, [8, 0]]], [9, [5, [4, [3, 2]]]]] number = make_snailfish_number(py_number_list) for to_explode in find_nodes_to_explode(number): print("exploding:", to_explode) explode_snailfish_number(to_explode) print(to_list(number))
def make_snailfish_number(raw_number, parent=None): num = SnailfishNumber() num.parent = parent if isinstance(raw_number, list): num.left = make_snailfish_number(raw_number[0], num) num.right = make_snailfish_number(raw_number[1], num) else: num.value = raw_number return num ...
This code tests the addition of two snailfish numbers by creating them using `make_snailfish_number`, adding them with the `add` function, and printing the result in list format. It verifies the correctness of the addition operation for snailfish numbers, a data structure from the Advent of Code problem, ensuring the i...
def test_add_and_reduce(): a = make_snailfish_number([[[0, [4, 5]], [0, 0]], [[[4, 5], [2, 6]], [9, 5]]]) b = make_snailfish_number([7, [[[3, 7], [4, 3]], [[6, 3], [8, 8]]]]) c = add(a, b) print(to_list(a), "+", to_list(b), "=", to_list(c))
def print_helpmessage(): """Print help message.""" print("usage: mylastool.py <command> [file]") print("examples:") print(" python mylastool.py list") print(" python mylastool.py header A/B/C.LAS") print(" python mylastool.py data A/B/C.LAS") print(" python mylastool.py curves ...
The main task of the code is to parse command-line arguments and process LAS files by listing contents, extracting headers, data sections, or curve mnemonics based on the specified command. It validates inputs, handles errors, and interacts with a container to retrieve and display LAS file information.
def main(argv): """Parse a list of arguments and do magic.""" if len(argv) < 2: print_helpmessage() return 1 command = argv[1] if command not in ('list', 'header', 'data', 'curves'): print('error: unknown command') print_helpmessage() return 1 url = get_con...
def calc_tse(data,centroids,partition): """ Calculates total squared error (TSE) for given data, centroids and partition. Parameters ---------- data : N*V dimensional array with N datapoints The actual coordinates of the datapoints centroids : V dimensional array with C datapoints ...
The function performs the swapping phase of the RS-algorithm to optimize clustering. It iteratively swaps centroids with data points, applies k-means, and checks if the Total Squared Error (TSE) improves. If not, it reverts changes. The goal is to minimize TSE by exploring better centroid-data point assignments over sp...
def swap(data_set,centroids,partition,iterations=30,k=2): """ Performs the swapping part of RS-algorithm. Parameters ---------- data_set : N*V dimensional array with N datapoints The actual coordinates of the datapoints centroids : V dimensional array with C datapoints Predefi...
def define_amount(number): """ If not given, randomly assigns the amount of cluster for RS. Parameters ---------- number : int The number of data points (N) """ if number<10: #a "random" way for less than 10 data points amount= random.uniform(min(2,(number+1)/2),mi...
(The main task of the code is to implement the Random Swap algorithm for clustering. It initializes centroids (randomly or predefined), assigns data points to clusters, and iteratively swaps centroids to optimize clustering. Parameters control iterations, cluster count, and k-means settings. The function returns optimi...
def random_swap(data_set,iterations=30,cl_count=0,k=2,centroids=None): """ Performs Random Swap -algorithm for given parameters. Uses the k_means function implemented in the file. Parameters ---------- data_set : N*V dimensional array with N datapoints The actual coordinates of the da...
def set_params(args): """ Assigns the parameters to user specified ones or defaults Also checks there is enough parameters and some simple user errors. Parameters ---------- args : system arguments """ if (len(args)<2): #No arguments given by user print_help(...
The main task of the code is to perform clustering using a random swap algorithm, handling input parameters, suppressing output if specified, generating clustering results, writing them to a file or printing them, and calculating the mean squared error (MSE) of the solution.
def main(): """ The function to be called when used as a srcipt. """ real_out=sys.stdout #real_out is variable to handle printing data_f,iterations,clusters,k,suppress, write_f =set_params(sys.argv) if suppress: real_out=stop_out_print(real_out,True) solution,part...
def init_argparse() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Run pre-processing on whole dataset or selected subjects", usage="[DATASET_DIR] [SUBCOMMANDS [OPTIONS]]", add_help=False, ) # Required arguments required = parser.add_argument_group("R...
The main task of the code is to execute data processing workflows based on subcommands (e.g., heudiconv, FD_stats, regressors) by parsing arguments, detecting the host environment (Thalamege/Argon), setting up directory structures, managing subject data, and running corresponding processing steps while handling job-spe...
def main(): # Parse command line arguments and separate subcommands parser = init_argparse() subcommands = parse_subcommands(sys.argv, s.DEFAULT_WORKFLOW) # loop through each subcommand and perform relevant functions for subcommand in subcommands: args = parser.parse_args(subcommand) ...
def handle_data(x_data=None, y_data=None): """ Handle the x/y data to make sure they are in arrays and have no-null values. :param x_data: The dataset to train the decision tree with. :param y_data: The result vector we are regressing on. """ # Make into a numpy array if ...
The main task of the code is to train a decision tree regressor by recursively splitting input data into nodes, handling data preprocessing, initializing the tree structure, and optionally pruning the tree to improve generalization. It builds the model's hierarchy by evaluating feature splits and managing node creation...
def fit(self, x_data, y_data): """ Fit (train) the decision tree using an inputted dataset. :param x_data: The dataset to train the decision tree with. :param y_data: The result vector we are regressing on. """ # Adjust the data x_data, y_data = self.handle_data(x...
def chara_rand(self): self.port_src = random.choice(svr_lists.svr_portrait) def perk_allrand(self): for i in range(4): self.perk_rand(i) def item_allrand(self): self.item_rand() self.addon_rand(0) self.addon_rand(1) def offering_rand(self): if sm.get_screen('s...
The code's main task is to trigger randomization processes for character attributes, perks, items, and offerings by sequentially calling four methods: `chara_rand` (character randomization), `perk_allrand` (perk randomization), `item_allrand` (item randomization), and `offering_rand` (offering randomization), ensuring ...
def all_rand(self): self.chara_rand() self.perk_allrand() self.item_allrand() self.offering_rand()
def chara_rand(self): self.killer_num = random.randint(0, len(klr_lists.klr_portrait) - 1) self.port_src = klr_lists.klr_portrait[self.killer_num] self.addons_src[0] = 'Blank' self.addons_src[1] = 'Blank' def perk_allrand(self): for i in range(4): self.perk_rand(i) de...
The code's main task is to generate random values for a character's attributes, perks, add-ons, and offerings by sequentially calling four methods: `chara_rand` (character randomization), `perk_allrand` (perk randomization), `addon_allrand` (addon randomization), and `offering_rand` (offering randomization), likely to ...
def all_rand(self): self.chara_rand() self.perk_allrand() self.addon_allrand() self.offering_rand()
def checkMoreOffer(self): """ This function checks whether more offer links is provided for the product or not. """ try: locator = self.getLocatorsObject() if locator.getMoreOffersUsingClass() in self.driver.page_source: return True els...
The main task of the code is to retrieve available offer details for a product by checking page elements, clicking "More Offer" if needed, and returning the offer text or a default message if no offers are found, while handling exceptions with specific error messages.
def getAvailableOffer(self): """ This function returns offers available """ try: status = self.checkMoreOffer() locator = self.getLocatorsObject() if status: self.clickOnMoreOffer() if locator.getAvailableOffers()[0] in self...
def actualProductLinks(self): """ This function returns the actual product links after filtering. """ try: productLinks = [] count = 0 for link in self.getProductLinks(): if count > 15: break if '?pid=' in link: ...
The function retrieves a product link with more than the specified review count by randomly selecting product URLs, opening them, and checking their review pages until the required review count is met, then returns the link.
def getLinkForExpectedReviewCount(self, expected_review, searchString): """ This function extracts the link of product having more than expected count. """ try: product_links = self.actualProductLinks(searchString=searchString) count = 0 expected_count...
def learn_reward(n, n_steps=1, rdist=None, rewards=None, graph=None, start=None): if graph is None: base = [[1, 2]] graph, perm, start = sample_graph(n,base) # Ensuring that the start node has two children if len(graph[start]) < 2: raise ValueError("The start node must ha...
The code generates a structured set of trial problems for a learning or decision-making task. It creates 10 initial trial sets, then builds a 'main' list with 2 base problems and 60 additional problems (30 of each type), varying parameters like rewards and trial numbers. It also generates introductory, practice, and co...
def make_trials(): n = 10 rewards = [1, 2, 0, -1, -2] rdist = IIDSampler(n, rewards) kws = {'n': n, 'rdist': rdist} trial_sets = [] for _ in range(10): problem = learn_reward(**kws) trial_sets.append(problem) main = [] problem_1 = sample_problem_1(**kws) ...
def game_restart(self): """ If the players decided to play another game, new snakes are created instead of the previous ones. :return: """ snakeLst = [] self.is_a_phs_mode = False for i in range(len(self.snakeList)): color = self.snakeList[i].getColor(...
The code defines a game loop for a snake game, handling keyboard input, updating two snakes' positions, checking collisions, and redrawing the screen. It manages game states (restart, exit), processes player failures, and includes a special PHS mode. The loop runs until the game ends, updating scores and rendering food...
def game_loop(self): """ Runs the game "forever" and catches keyboard events. responsible for drawing the 2 snakes each clock tick. :return: """ game_begin = True Snake.DIS.fill(colors.BLACK) row = 50 col = 50 while not self.game_over: ...
def BSBI_invert(self): self.block = sorted(list(self.block.items()), key=self.comparator) def write_block(self, block_idx): with open(self.output + "/block" + str(block_idx) + ".dat", "w+b") as file: for line in self.block: term_id = int(line[0].split()[0]) fi...
This code processes text files from a directory in blocks to build an inverted index. It divides files into chunks based on size, parses each block, and writes intermediate results. After processing all files, it finalizes the index by merging blocks and writing term identifiers.
def main(self, source_dir): block_idx = 0 file_idx = 0 files = [x for x in Path(source_dir).rglob("*.[tT][xX][tT]")] total_size = sum([os.stat(x).st_size for x in files]) self.block_size = total_size // 10 for x in files: if self.current_size >= self.block_s...
def send_get_help_message(user): logging.info(f'send get_help_message to {user}') get_help_message = OutgoingMessage.objects.get(key='get_help') send_text_message(user, get_help_message, None, True) def send_text_message(user, wab_bot_message, message_text=None, is_failure=False): message_text = message...
The code sends tailored error messages to a user based on their failure count and error details. If the user has 3+ failures, it sends a help request. If the error has specific attributes, it retrieves or generates a message using the error's key. Otherwise, it sends a default "wrong_format" message.
def send_error_message(user, error): if user.failure_count >= 3: send_get_help_message(user) elif error and error.message and hasattr(error, 'params') and \ error.params and error.params.get('custom_message', False): if message := OutgoingMessage.objects.filter(key=error.message).fir...
def send_get_help_message(user): logging.info(f'send get_help_message to {user}') get_help_message = OutgoingMessage.objects.get(key='get_help') send_text_message(user, get_help_message, None, True) def send_text_message(user, wab_bot_message, message_text=None, is_failure=False): message_text = message...
The code sends an "unknown" message to a user if their failure count is less than 3. If their state isn't 'initial' and failure count matches a configured threshold, it retrieves and sends a follow-up message. It handles user interaction logic by checking failure counts, updating user data, and conditionally triggering...
def send_unknown_message(user): if user.failure_count >= 3: send_get_help_message(user) return unknown_message = OutgoingMessage.objects.get(key='unknown') send_text_message(user, unknown_message, None, True) user.refresh_from_db() if user.state.pk != 'initial' and user.failure_coun...
def print_terminal(self, size="small") -> None: ''' Method to print the sudoku to the terminal. Parameters: - size (optional) - either "small" or "big" (default is "small") ''' # Call the respective method to either print a small or big version if size == "s...
This method recursively fills a Sudoku grid using backtracking by trying valid values in empty cells, checking for future validity, and backtracking if invalid. It returns True if a valid solution is found, adding it to seeds if find_all is True, otherwise returns False when no valid configuration exists.
def __fill_backtrack(self, locations:list, find_all=False) -> bool: ''' Recursive method to fill a sudoku with valid values, to create a valid filled in sudoku grid. Parameters: - locations - list of remaining locations in the sudoku which are empty (yet to be filled) - ...
def clear(self) -> None: ''' Method to clear the sudoku by replacing all cells with an empty value. ''' # Create an empty sudoku grid self.__grid = [ [Cell_Value.EMPTY]*9 for i in range(9)] def valid(self, empty_as_valid=False) -> bool: ''' Method to check whethe...
The method `fill` generates a valid filled Sudoku grid by recursively applying backtracking to fill empty cells. It optionally clears the grid or validates existing content, identifies empty cells, shuffles their positions, and solves the puzzle. If `find_all` is True, it collects all valid seeds (partial solutions). R...
def fill(self, clear=False, find_all=False) -> None: ''' Method to fill a sudoku with valid values, to create a valid filled in sudoku grid. Parameters: - clear (optional) - boolean for whether to clear the sudoku before filling it (default is False) - find_all (optional...
def parse_seed(seed): try: return int(seed) except ValueError: # Apparently seeds can be "11a", "11b", etc., whatever that means. match = re.search(r'(\d+)[ab]', seed) if match: return int(match.group(1)) def make_picks_for_round(regions, round, num_teams, teams, last...
The code creates a tournament bracket for either men's or women's sports by collecting user input for regions, reading team data from a CSV file, and simulating matchups. It processes team seeds, resolves conflicts, and generates a bracket through multiple rounds, ultimately determining the winner and displaying the fu...
def main(): print("Which tournament are you making a bracket for, men's or women's? (M/w)") gender = "mens" if input() == "w": gender = "womens" regions = [] # Put the regions in the proper order: upper left, upper right, lower left, lower right available_regions = ["West", "South", "Ea...
def object_key( self, key ) : value = self.expect( 'map_key' ) if value != key : error = "Expected key : '" + key error += "' got '" + value + "'" raise Error( error ) def object_start( self ) : self.expect( 'start_map' ) def object_value( self, key ) : ...
This code parses a JSON-like structure to extract header information, including a UUID, time range (from/to), and schema columns (type and column names). It constructs a list of columns and triggers a callback via `hooks.on_headers` with the extracted data.
def headers( self, hooks ) : self.object_key( 'headers' ) self.object_start() self.uuid = self.object_value( 'uuid' ) begin = self.object_value( 'from' ) end = self.object_value( 'to' ) columns = [] self.object_key( 'schema' ) self.array_start() wh...
def create( self, command ) : headers = self.headers() if headers is None : print( "Error : " + Rest.create.__qualname__ + "() failed. Header is invalid" ) return None else : reply = requests.post( ...
The code submits a job via `self.create(command)`, monitors its status until completion, downloads the result if successful, and parses it if download is not already handled. It returns the file path of the downloaded response or `None` on failure.
def request( self, command ) : path = None # Create a new JOB reply = self.create( command ) if reply is None : print( "Error : " + Rest.request.__qualname__ + "() failed. Job creation failed." ) return path ...
def object_start( self ) : self.expect( 'start_map' ) def object_string( self, key, string ) : self.object_key( key ) value = self.string() if value != string : error = "Expected string : '" + string error += "' got '" + value + "'" raise Error( erro...
This code parses a JSON file from the given path, processes events, checks the 'status' field, and either handles errors or processes headers/rows using provided hooks. It constructs an object with specific metadata and data based on the input file's content.
def do( self, path, hooks ) : stream = open( path, 'r' ) self.events = ijson.basic_parse( stream ) self.uuid = 0 try : self.object_start() self.object_string( 'kind', 'edw#response' ) status = self.object_strings( 'status', [ 'Done', 'Error' ] ) ...
def irt(data, val_data, lr, iterations): """ Train IRT model. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param val_data: A dictionary {user_id: list, question_id: list, is_correct: list}...
The code implements and evaluates an Item Response Theory (IRT) model using sparse matrix data. It tunes learning rate and iterations, visualizes validation accuracy and loss curves, evaluates test accuracy, and plots probability distributions of correct answers for random questions across students, highlighting variat...
def main(): train_data = load_train_csv("../data") # You may optionally use the sparse matrix. sparse_matrix = load_train_sparse("../data").toarray() val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") ################################################################...
def readFile(file): data1=pd.read_csv(file) return data1 def getColumnName(data): col_list=[] for col in data.columns: col_list.append(col) colName=np.array(col_list).reshape(1,len(col_list)) return colName def dataFrameToArray(data): dataArray=data.iloc[:,:].values return d...
The main task of the code is to process input data from a file by reading, transforming, and structuring it into a table and dictionary format. It extracts column names, converts data to an array, filters relevant information, categorizes data based on version, and generates structured outputs for further analysis or p...
def main(file,version): data=readFile(file) colName=getColumnName(data) data=dataFrameToArray(data) newData=np.vstack((colName,data)) parentNode=cp.deepcopy(newData[:,0]) leafData=cp.deepcopy(newData[:,:]) newLeafData=filteredLeafData(leafData) category_list=categoryList(newLeafData) ...
def beepSound(frequency, duration, numberOfBeeps): '''When called produces a number of beeps for the frequency and duration specified''' for i in range(0, numberOfBeeps): winsound.Beep(frequency, duration) def leakTestControlLoop(d, countTimePassed, testSamplingTime): # Lists used to store data, wr...
The code automates a leak check process by pressurizing a system, monitoring pressure and temperature via a LabJack device, and analyzing data over a user-specified duration. It detects leaks (actual or virtual), logs results, displays outcomes, and generates plots if data exists. The program restarts on virtual leaks ...
def text_run(): # Display program start to the user print() print("*" * 100) print(" " * 29, "Initiating Rad.Solutions Leak Check Program") print("*" * 100) # prompt user to pressurize the system input("Pressurize annulus to 18-19 psi. Press Enter when complete: ") d = u3.U3() # d...
def select_entries(): """Retrieves all entries from database""" return Task.select().order_by(Task.date.desc()) def print_entries(index, entries, display=True): """Prints the entries from the database""" single_entry = entries[index] if display: print("Displaying {} of {} entry/entries.\n" .for...
The function displays a list of entries (either from a search or database) and allows navigation through them using 'p' (previous) or 'n' (next). It provides options to delete ('d'), edit ('e'), or return to the main menu ('m'). If no entries exist, it notifies the user. The loop continues until an action is taken or t...
def display_entries(search=None): """Display entries to screen""" if search: entries = search else: entries = select_entries() res = len(entries) if res > 0: index = 0 while True: print_entries(index, entries) display_choices(index, entries) choice = input("\nPlease selec...
def clear(): system('cls' if name == 'nt' else 'clear') def display_entries(search=None): """Display entries to screen""" if search: entries = search else: entries = select_entries() res = len(entries) if res > 0: index = 0 while True: print_entries(index, entries) display_cho...
This function displays search results from a list of entries. It prints either specific fields or full details (name/notes) of matching entries, handles empty results, and pauses for user input before proceeding.
def list_entries(entries, search, field): """Shows list of search results""" clear() if entries: print("Your search results for {}:\n".format(search)) for entry in entries: if field: print(getattr(entry, field)) else: print("Task name: {} \nTask notes: {}".format(en...
def clear(): system('cls' if name == 'nt' else 'clear') def find_by_employee(): """get the employeee name from user and search for""" data = get_task_employee() entries = Task.select().where(Task.employee.contains(data)) list_entries(entries, data, "employee") return entries def find_by_date_range(): """S...
The code presents a search menu allowing users to find worklog entries by employee name, date, or string in task/notes, or return to the main menu. It validates input, executes the selected search function, and returns results or navigates back based on user choice.
def search_menu(): """Search for an entry""" while True: clear() print(""" WORKLOG -------------------------------------------------------- SEARCH MENU [N] - Find by employee name [D] - Find by date [S] - Find by string in task/notes [M] - Back to main menu """) option = input("Please select opti...
def Prop(self,om,p,T,muB,muQ,muS,**kwargs): """ Parton propagator [GeV^-2] """ return 1./(om**2.-p**2.-self.SE(om,p,T,muB,muQ,muS,**kwargs)) def fqdT(self,om,T,muB,muQ,muS): """ Derivative of the distribution function wrt temperature T [GeV^-1] """ xmuq = ...
The function computes the integrand for the DQPM entropy density [GeV³] by combining the propagator, logarithmic terms, and self-energy contributions, returning an expression involving momentum (p), temperature (T), and chemical potentials (μB, μQ, μS) to evaluate entropy density in high-energy physics simulations.
def int_sq(self,om,p,T,muB,muQ,muS,**kwargs): """ Integrand for the DQPM entropy density [GeV^3] """ xprop = self.Prop(om,p,T,muB,muQ,muS,**kwargs) # propagator return -1./(2.*pi)*(4.*pi*p**2.)/((2.*pi)**3)*self.dg*self.fqdT(om,T,muB,muQ,muS)\ *(np.imag(np.log(-1./xpr...
def Prop(self,om,p,T,muB,muQ,muS,**kwargs): """ Parton propagator [GeV^-2] """ return 1./(om**2.-p**2.-self.SE(om,p,T,muB,muQ,muS,**kwargs)) def fqdmuq(self,om,T,muB,muQ,muS): """ Derivative of the distribution function wrt quark chemical potential muq [GeV^-1] ""...
This function computes the integrand for the DQPM quark density in GeV³. It calculates the propagator (xprop) and combines it with self-energy terms (SE) and logarithmic contributions to evaluate the imaginary part of the quark density. The result involves mathematical operations on propagator components, including log...
def int_nq(self,om,p,T,muB,muQ,muS,**kwargs): """ Integrand for the DQPM quark density [GeV^3] """ xprop = self.Prop(om,p,T,muB,muQ,muS,**kwargs) # propagator return -1./(2.*pi)*(4.*pi*p**2.)/((2.*pi)**3)*self.dg*self.fqdmuq(om,T,muB,muQ,muS)\ *(np.imag(np.log(-1./xpr...
def _to_list(x): # type: (Optional[Any]) -> List[Any] """Convert object to a list if it is not a list, None converted to empty list """ if x is None: x = [] elif not isinstance(x, list): x = [x] return x def slot_mappings(self): ...
The function retrieves and validates mappings for a specified slot. It checks if slot mappings exist; if not, it maps the slot to an entity with the same name. The result is converted to a list, and each mapping is validated as a dictionary with a "type" key. Invalid mappings raise a TypeError. The function returns the...
def get_mappings_for_slot(self, slot_to_fill): # type: (Text) -> List[Dict[Text: Any]] """Get mappings for requested slot, else map requested slot to an entity with the same name """ requested_slot_mappings = self._to_list( self.slot_mappings().get(slot_to_fil...
def required_slots(tracker): # type: (Tracker) -> List[Text] """A list of required slots that the form has to fill Use `tracker` to request different list of slots depending on the state of the dialogue """ raise NotImplementedError("A form must implement requir...
The main task of the code is to extract values for slots not currently being requested by checking if user input entities match the slot's entity mappings. It iterates through required slots, identifies applicable mappings, verifies intent alignment, retrieves entity values, and populates a dictionary with extracted sl...
def extract_other_slots(self, dispatcher, # type: CollectingDispatcher tracker, # type: Tracker domain # type: Dict[Text, Any] ): # type: (...) -> Dict[Text: Any] """Extract the values of t...
def extract_other_slots(self, dispatcher, # type: CollectingDispatcher tracker, # type: Tracker domain # type: Dict[Text, Any] ): # type: (...) -> Dict[Text: Any] """Extract the values of t...
The code validates extracted slot values from user input in a dialogue system. It extracts both requested and non-requested slots, applies custom validation logic (via `validate_` methods), and rejects form execution if validation fails. If successful, it returns slot updates as `SlotSet` actions.
def validate(self, dispatcher, tracker, domain): # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict] """Validate extracted value of requested slot else reject execution of the form action Subclass this method to add custom validation and rejection logic ...
def handle_error(self, data): """ Handle an error fetching the laser state. """ self._error = True self.log_error(data) self.reset_pins() msleep(ERROR_TIMEOUT) def log_pins(self, normalized_data): """ Log the output of the pins if they hav...
The main task of the code is to continuously poll a status server for JSON data, handle connection/data errors, normalize the received state information, log/update system pins, and check for a win condition in a loop that sleeps for a defined interval between iterations.
def run(self): """ Start the run-loop. """ while True: # Connect to status server. try: r = requests.get(f"{HOST}{ENDPOINT}") json_data = r.json() except Exception as e: self.handle_error(f"Unable to conn...
def degree(f): d = len(f) - 1 while d > 0: if f[d] != 0: break d -= 1 return d def div_poly(a, b, p): r = a.copy() q = [0] n = degree(b) u = modinv(b[n], p) d = degree(r) while d >= n and (d != 0 or r[0] != 0): v = reduce_poly(mult_poly([u * r[d]], [1 if (i == d-n) else 0 for i in range(d+1)], 0), ...
This function computes the extended greatest common divisor (GCD) of two polynomials `a` and `b` over a finite field defined by prime `p`. It returns the GCD polynomial `a`, along with coefficients `a_0` and `b_0` such that `a_0*a + b_0*b = GCD`. The algorithm uses polynomial division, iterative remainder reduction, an...
def egcd_poly(a, b, p): a, b = a.copy(), b.copy() if degree(b) > degree(a): a, b = b, a a_0, b_0 = [1], [0] a_1, b_1 = [0], [1] zero = True for i in range(len(b)): zero = zero and (b[i] == 0) while not zero: q, r = div_poly(a, b, p) a_0, b_0, a_1, b_1 = a_1, b_1, reduce_poly(add_poly(a_0, neg_poly(mul...
def egcd_poly(a, b, p): a, b = a.copy(), b.copy() if degree(b) > degree(a): a, b = b, a a_0, b_0 = [1], [0] a_1, b_1 = [0], [1] zero = True for i in range(len(b)): zero = zero and (b[i] == 0) while not zero: q, r = div_poly(a, b, p) a_0, b_0, a_1, b_1 = a_1, b_1, reduce_poly(add_poly(a_0, neg_poly(mul...
This function computes the modular inverse of a polynomial 'a' modulo a prime 'p', under the modulus polynomial x^n - 1. It uses the extended Euclidean algorithm for polynomials (egcd_poly) to find the GCD of 'a' and x^n - 1. If the GCD is a constant (degree 0), it returns the reduced inverse polynomial; otherwise, it ...
def invert_poly_prime(a, p, n): u, v, d = egcd_poly(a, [-1] + [1 if i==(n-1) else 0 for i in range(n)], p) if degree(d) == 0: return reduce_poly(mult_poly([modinv(d[0], p)], v, n), p) else: return False
def invert_poly_prime(a, p, n): u, v, d = egcd_poly(a, [-1] + [1 if i==(n-1) else 0 for i in range(n)], p) if degree(d) == 0: return reduce_poly(mult_poly([modinv(d[0], p)], v, n), p) else: return False def reduce_poly(f, q): h = [] for i in range(len(f)): h.append(f[i] % q) return trim(h) def add_poly(f...
The function computes the inverse of a polynomial 'a' modulo $ p^e $ using an iterative method. It initializes 'b' as the inverse modulo $ p $, then iteratively refines 'b' by adjusting the modulus $ p^n $ (doubling $ n $ each step) until $ e $ reaches zero. The result is reduced modulo $ p^{e_1} $, where $ e_1 $ is th...
def invert_poly_comp(a, m, p, e): e_1 = e b = invert_poly_prime(reduce_poly(a, p), p, m) if not b: return False n = 2 while e > 0: b = reduce_poly(add_poly(mult_poly([2], b, m), neg_poly(mult_poly(a, mult_poly(b, b, m), m))), p**n) e = e // 2 n = n * 2 return reduce_poly(mult_poly(b, [1], m), p**e_1)
def SearchForFile(data, Search, printing, lens): with open('Phonebook.txt', 'r+', encoding='utf-8') as data: countSpisok = 0 countLens = 0 for line in data: countLens += 1 searchvalue = line.split(' ') for i in searchvalue: if i.lower() ==...
The code searches the 'Phonebook.txt' file for entries matching a query, displays found results, and allows users to replace specific fields (name, phone number, surname) if a single or multiple matches are found. It handles user input for replacement choices, confirms actions, and provides options to continue or exit,...
def replacement(data, Search, printing, lens): SearchForFile(data, Search, printing, lens) with open('Phonebook.txt', 'r+', encoding='utf-8') as data: if len(printing) > 1: print('were found''\n', *printing, '\n''Multiple values were found, please enter another non-repeatin...
def get_num_players(self): '''Gets the number of players''' return self._num_players def get_save_data(self, players, counter, file_name): '''Asks the player if they would like to load a save, loads saves''' choice_loop = True chosen = False saved_ids = from_file(file_nam...
The function `prompt_data` collects player information by iterating through a specified number of players, prompting each to either load a save file or input their name. It uses `get_save_data` for loading saves and `prompt_names` for new entries, compiling the results into a list of players, which is then returned.
def prompt_data(self, players, file_name): '''Prompts users for their name/save file id''' counter = 0 players = [] while counter < self.get_num_players(): print('\n--------------------------') print('Player {}'.format(counter + 1)) prompt = input('Wou...
def check_split(player): '''Checks if player can split''' if ( player.hand[0][0].value() == player.hand[0][1].value() and player.balance - player.bet[0] >= player.bet[0] and check_ace(player) is True ): return True return False def split_choice(self, player, dealer, count...
This function handles player actions in a card game by checking if players can split their hands, prompting appropriate choices, and managing dealer actions. It iterates through players, triggers split choices if applicable, breaks for the dealer's turn, and calls regular choice prompts for non-empty hands, ensuring ga...
def inital_choice(self, players, dealer): '''Checks for the appropriate prompts for players''' split_counter = 0 for counter, player in enumerate(players): if player.hand_sum() < 21: if not isinstance(player, deal) and check_split(player): self.spl...
def prompt_num_players(self): '''Prompts user for number of players''' while True: try: self.set_num_players(int(input("How many players: "))) if self.get_num_players() < 1 or self.get_num_players() > 4: print("Please input a number from 1 ...
The main task of the code is to initialize a game by prompting for the number of players, collecting player data from a file, adding funds to each player, introducing a dealer, preparing a shuffled deck with multiple merges, and returning the list of players.
def setup(self, file_name): '''Sets the game up''' players = [] self.prompt_num_players() players = self.prompt_data(players, file_name) for player in players: print('\n--------------------------') print('{}'.format(player.name)) add_funds(play...
def check_file(file_name): if from_file(file_name): return file_name else: choice = input('Would you like to enter a different file name? (y,n): ') if choice.lower() == 'y': file = input('Input full file name: ') if from_file(file): print('Data Fil...
This code runs a card game by loading a save file, initializing players (including a dealer), and managing game rounds. It alternates between dealer and player turns, checks for wins, resets variables, and prompts the user to continue or exit. The loop continues until the player chooses to end the game.
def run(self): '''Runs game''' has_dealed = False file_name = 'saves.pckl' file = check_file(file_name) if file is False: print('Exitting Program...') exit() file_name = file players = self.setup(file_name) dealer = players[-1] ...
def __save_params(self): path = f'{self.params.work_dir}/{self.files["params"]}' if os.path.exists(path): base_path = path num = 1 while True: path = f'{base_path}.{num}' if not os.path.exists(path): break ...
This code manages a processing pipeline, handling both fresh execution and restart scenarios. It preprocesses data, collects information, runs BLAT alignment (with optional restart filtering), applies filtering, and performs postprocessing. Key tasks include directory management, parameter saving/loading, conditional e...
def run(self, restart=False): if self.params.is_restart: # Preprocess Checker.isdir(self.params.work_dir) self.__save_params() breakinfo = self.__load_breakinfo() breakinfo = self.__filter_on_restart(breakinfo) else: # Preprocess ...
def dict_to_ordered_arr_np(self, input_dict, ): r""" Sort input parameters Parameters: input_dict (dict [numpy.ndarray]): input dict of (arrays of) parameters to be sorted Returns: n...
The code trains a neural network using a multi-step cooling schedule, adjusting learning rates, batch sizes, and gradient accumulation steps iteratively. It standardizes input/output data, splits datasets into training/validation, employs early stopping based on validation loss, and saves the optimized model with speci...
def train(self, training_parameters, training_features, filename_saved_model, # cooling schedule validation_split=0.1, learning_rates=[1e-2, 1e-3, 1e-4, 1e-5, 1e-6], batch_sizes=[1024, 1024, 1024, 1024, 1024], ...
def __get_today_thoughts(self): thoughts = [] for thought in self.__get_thoughts(): if TimeUtils.is_today(thought.date) and not thought.used: thoughts.append(thought) return thoughts def __write_json(self, thought: Thought): self.local_writing_service.write( ...
The function writes today's thoughts to a local JSON file and uploads them remotely if they exist. If no thoughts are found, it displays an error message; otherwise, it confirms the number of entries processed by showing a success message with the count of thoughts.
def write_data(self): if len(self.__get_today_thoughts()) == 0: self.view.show_message(Environment.get().WRITE_REMOTE_DATA_FAILURE) return thoughts = self.__get_today_thoughts() for thought in thoughts: self.__write_json(thought) self.__write_remot...