dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def create_output(self, filename: str): """ Combines various other functions to import the file and \ create a dictionary that has all four required fields Parameters: filename (str): The path to the file to be imported Returns: coords (d...
The main task of the code is to process a dataset by importing it from a given file path, formatting the data, and outputting the results. The method `run` orchestrates this workflow by calling three key steps: creating output from the file, formatting it, and returning the formatted output. It does not return a value ...
def run(self, filename: str): """ Main function for interacting with the class. \ Handles the importing, formatting, and outputting \ of the data set. Parameters: filename (str): The path to the file to be imported Return: None ...
def reinitialize_constructor_parameters(self): self.task_type = "" def create_process_folder(self, pname, folder): """ creating process folder """ try: folder.mkdir(parents=True, exist_ok=False) self.set_process_out_folder(pname, True) except F...
The main task of the code is to parse tlog entries for different system components (e.g., ONMOPAY, GRIFF, PRISM), identify error conditions or issues in the log data, create output folders for processing, and invoke a DaemonLogProcessor to handle relevant logs based on predefined rules. It dynamically selects processin...
def parse_tlog(self, pname, tlog_header_data_dict, ctid_map=None): """ tlog parser method """ self.reinitialize_constructor_parameters() if pname == "ONMOPAY": folder = Path(f"{self.outputDirectory_object}/{self.hostname}_issue_onmopay") elif pnam...
def parse_logger(self, pname, log4j2_path, sub_process=None): """ Logger reference call to appender """ try: if pname == "CONSUMER_SERVICE" or pname == "PAYCORE_SERVICE"\ or pname == "PAYCORE_WEBAPI_SERVICE" or pname == "CALLBACK_DELIVERY_SERVICE"\ ...
The main task of the code is to parse log configuration paths from a JSON file for different services (e.g., ONMOPAY, GRIFF, PACKS, PRISM) based on the provided `process_name`. It extracts `PROCESS_HOME_DIR` and `NLOG_CONFIG` values, replaces placeholders in log paths (e.g., `${sys:catalina.home}`) with actual paths, a...
def parse_transaction_logging(self, process_name): """ Parse log paths """ search_date = datetime.strftime(self.start_date, "yyyy-MM-dd") pname = process_name if pname == 'ONMOPAY': try: for sub_service in self.config[self.hostname][pn...
def calc_performance(self, measure): ''' Stores performance given a threshold for prediction. ''' self.roc_auc = self.auc_roc(self.y_test, self.y_pred_probs) if self.ks == [] and self.thresholds != []: self.threshold = measure self.precision = self.precisi...
This method writes model performance metrics and related data to files using specified thresholds or ks values. It saves results for each measure, prepares output files if needed, and stores metadata, group information, unit-level details, and feature importances when the report type is 'full'
def performance_to_file(self, pickle_path='Not enabled'): ''' Write results to file. ''' self.pickle_path = pickle_path if self.thresholds != []: measures = self.thresholds elif self.ks != []: measures = self.ks for measure in measures: ...
def _format_classes(self): return '\n\n'.join(str(class_) for class_ in self.classes) def _format_fields(self): return _format_constant_fields(self.fields) def _indent(text): return textwrap.indent(text, ' ')
The code generates a string representation of a class by formatting its classes/fields, substituting variables like name, javadoc, and indented body into a predefined template, then returning the constructed string.
def __str__(self): body = self._format_classes() or self._format_fields() return _CLASS_TEMPLATE.substitute( name=self.name, javadoc=self.javadoc, body=_indent(body), )
def get_clean_address(fs: gcsfs.GCSFileSystem): address_base_path = "gs://homehuntr-storage/address" all_addresses = fs.ls(address_base_path) address_data = [] for i in all_addresses: with fs.open(f"gs://{i}", "r") as f: address_data.append(json.loads(f.read())) address_info = p...
The code processes and aggregates data from multiple sources (cleaned addresses, directions, destinations, transit scores) to generate a comprehensive summary. It writes the cleaned address data, transit scores, summary metrics, and an aggregated output table (obt) into Delta format in a Google Cloud Storage bucket, ov...
def summarize_data() -> None: out_base_path = "gs://homehuntr-storage/delta/gold" fs, token = common.get_gcp_fs() address_cleaned = get_clean_address(fs) direction_df = get_direction_df(token) destination_df = get_destination_df(fs) transit_score_df = get_transit_score( direction_info=d...
def get_origin( fs: gcsfs.GCSFileSystem, address: Optional[str] = None, uid: Optional[str] = None ) -> Place: """ Obtains details about an address given either an address string or a uid (existing address) """ place_id = None if uid is not None: # when get_directions is called as part o...
The function `get_directions` checks if precomputed directions for transit and bicycling exist between an origin (from address/UID) and multiple destinations. If not, it triggers direction generation for each mode. It only proceeds when `refresh_directions` is True, avoiding redundant recalculations.
def get_directions( address: Optional[str] = None, uid: Optional[str] = None, refresh_directions: bool = False, ) -> None: """ address argument: get_directions being called independently uid argment: get_directions being called as part of pipeline from main.py """ modes = ["transit", "bi...
def extract_election_votes(filename, column_names): """ Returns a list of integers that contains the values in each row of the column_names """ list_integers = [] # Reads CSV file into a dictionary # First row of the file serves as dictionary keys # Rest of the rows are dictionary valu...
The code processes Iranian election data by reading, cleaning, and analyzing vote counts for specified candidates. It generates a histogram of digit distributions from the data and compares it to random samples to assess statistical significance. Key tasks include calculating the MSE between observed and uniform distri...
def main(): # Problem 1: Read and clean Iranian election data and # Problem 2: Plot the election data # (change the name of the iran csv file to your input file.) # (change the names of candidates to your desired candidates) election_data = extract_election_votes("election-iran-2009.csv", ...
def bet(self): pass def deal(self): self.player.new_hand(self.shoe) self.dealer.new_hand(self.shoe) def _print_hidden_hands(self): _print_line() self.dealer._print_hidden_hand() self.player._print_revealed_hand() def natural_twenty_one_settlement(self): if self.de...
This code manages a blackjack game round by handling betting, dealing cards, revealing hidden hands, checking for natural blackjack, executing player and dealer turns, and settling bets based on game outcomes.
def play(self): self.bet() self.deal() self._print_hidden_hands() if self.player.hand.total_value == 21: self.natural_twenty_one_settlement() else: self.player_turn() if self.player.is_bust(): self.settle() else: ...
def load(self, path): self.samples, self.sample_rate = librosa.load(path) self.duration = librosa.get_duration(self.samples) self.n_samples = len(self.samples) def filter(self, mode="conv"): self.samples = self.samples[self.get_filter(mode=mode)] self.n_samples = len(self.samples...
The main task of the code is to preprocess a voice file by loading it from the specified path, applying a filtering process, and saving the processed result to a target path, which defaults to the original path if not specified. This function handles audio data preprocessing steps including loading, filtering, and outp...
def preprocess_voice(self, path, goal_path=None): if goal_path == None: goal_path = path self.load(path) self.filter() self.write(goal_path)
def load_file(self, path="files/transcriptions/transcript.csv"): df = pd.read_csv(path, sep="|") vals = df.values self.all_filenames = vals[:, 0] self.all_transcriptions = vals[:, 1] self.n_entrys = len(df) def edit_text(self, path="files/transcriptions/transcriptions.csv"): ...
The main task of the code is to clean and validate a transcript CSV file by loading data, editing text, extracting durations and quoted content, preparing transcriptions, filtering valid entries, ensuring corresponding WAV files exist, and saving the processed results to a new CSV file. This workflow standardizes and v...
def cleanup_transcript(self, source="files/transcriptions/transcriptions.csv", file="files/transcriptions/transcript_clean.csv"): self.load_file(source) self.edit_text() self.get_all_durations() self.get_all_inside_quotes() self.prep_all_transcriptions() self.filter_valid...
def train_mini_batch(model, feats, labels, batch_size, criterion, optimizer, lamb=1): """ Train MLP for large datasets. Process the data in mini-batches. The graph is ignored, node features only. lamb: weight parameter lambda """ model.train() num_batches = max(1, feats.shape[0] // batch_size) ...
The main task of the code is to train an inductive multi-layer perceptron (MLP) model using mini-batch training with early stopping based on validation performance. It splits data into training, validation, and test sets, trains the model, evaluates it periodically, and returns final predictions and scores on validatio...
def run_inductive_mlp( conf, model, obs_g, g, obs_feats, obs_labels, feats, labels, indices, criterion, evaluator, optimizer, logger, loss_and_score ): obs_idx_train, obs_idx_val, obs_idx_test, idx_obs, idx_test_ind = indices batch_size = conf["batch_...
def predict(self, image): image_h, image_w, _ = image.shape image = cv2.resize(image, (self.input_size, self.input_size)) image = self.feature_extractor.normalize(image) input_image = image[:,:,::-1] input_image = np.expand_dims(input_image, 0) dummy_array = np.zeros((1,...
The code evaluates a model's object detection performance on a dataset by calculating mean Average Precision (mAP) for each class. It processes each image to gather predicted boxes and ground-truth annotations, compares them using IoU thresholds, tracks true/false positives, and computes average precision per class. Th...
def evaluate(self, generator, iou_threshold=0.3, score_threshold=0.3, max_detections=100, save_path=None): """ Evaluate a given dataset using a given model. code originally from https://github.com/fizyr/keras-retinane...
def refresh_user_settings(self): """Reloads ``self.user_settings`` from ``self.user_settings_file``. This allows the user to update the \ user settings file with different inputs between Neutrino commands. """ self.user_settings = t.load_yaml_settings( self.user_settings...
This code provides a temporary command-line interface (CLI) for testing/debugging a Neutrino system during development. It processes user inputs to execute commands like retrieving data (accounts, ledger, orders), managing API keys, streaming data, and updating software. The CLI runs in a loop until the user quits, han...
def interact(self): """Temporary rudimentary command line interface that executes neutrino-related commands from user input. \ The jankiness of this implementation and availability of modules such as ``argparse`` are well understood. \ This is simply used for flexible testing/debugging during de...
def _convert_integer_to_float(operations: TotalOperation): operations = copy.deepcopy(operations) operations.awaited_result = float(operations.awaited_result) for i in range(len(operations.start_number)): operations.start_number[i] = float(operations.start_number[i]) for single_op in operations....
The main task of the code is to validate a sequence of operations by checking if they meet specific criteria, such as correct result presence, operation validity, number availability, and mandatory operation usage. It returns `True` if all checks pass, otherwise `False`, ensuring the operations conform to defined rules...
def operation_is_valid(operations: TotalOperation) -> bool: try: operations = _convert_integer_to_float(operations) _awaited_result_is_present(operations.list_operation, operations.awaited_result, operations.start_number) _operation_result_check(operations.list_operation) _update_ava...
def add_item_button_click(self): self.close_window() execute_add_item_window(self.json_data) print(self.json_data) execute_manage_list_window(self.json_data) def remove_item_button_click(self): if self.list_have_itens(): self.close_window() execute_remov...
This code initializes a GUI window with predefined buttons and a background image. It sets up 5 buttons with specific paths, positions, sizes, and associated functions for managing items (add, remove, view, save, exit). The window dimensions, background image, and button configurations are hardcoded, using JSON data fo...
def __init__(self, json_data = {}): super().__init__(400,700) self.json_data = json_data self.number_of_buttons = 5 self.buttons_paths = [r"\manage_window_images\img0.png", r"\manage_window_images\img1.png", r"\manage_window_im...
def start(self, **kwargs): """ Start running. Initialize start time and epoch. You can set the attributes to be used at this runtime. If not set, the default value is used. Arguemnts is the same as the constructor. Args: n_iter (int): Number of iterat...
This method updates a progress bar by advancing its state, aggregating provided values with specified weights, calculating progress ratio, and managing display notes. It stores values/times if enabled, updates temporary time tracking, and automatically steps the bar when complete, ensuring visual updates and iteration ...
def update( self, value: Optional[Union[Number, List[Number]]] = None, weight: Union[Number, List[Number]] = 1, advance: int = 1, auto_step: bool = True, note: Optional[str] = None, ): """ Update progress bar and aggregate value. Args: ...
def read_options(options_file_name): """Read the list of geologic period options from the input text file and make sure they are all unique, then return a list of strings. """ # Read options from TXT file, expecting one per non-blank line with open(options_file_name, 'r') as options_file: options = [line.strip...
The main task of the code is to assign students to options while adhering to constraints on minimum and maximum per-option allocations. It reads student and option data, calculates feasible distribution limits, validates constraints, and employs a recursive algorithm to find optimal student-option pairings. The solutio...
def main(): # Read the options list and student data from the appropriate input files # The students file will also tell us how many choices each student gets options = read_options(OPTIONS_FILE) students, n_choices = read_student_data(STUDENTS_FILE, options) # Determine a few other important numbers from the ...
def has_weight(self, weight): return weight.get_name() in self.get_descendant_weights() def findInput(inputs, elem, name): for e in inputs: if(e.get_name() == 'i0' and ('w' + name) == elem.get_name()): return e elif(e.get_name()[0] == 'i' and ('w' + e.get_name()[1:] + name) == el...
This function computes the derivative of the output with respect to a given element 'elem' in a neural network context. It handles two cases: if 'elem' has a weight, it calculates the derivative using the element's output and its activation function's derivative. Otherwise, it combines the derivatives from relevant wei...
def compute_doutdx(self, elem): weights = self.my_weights inputs = self.my_inputs output = 0.0 if(self.has_weight(elem)): e = findInput(inputs, elem, self.my_name) output = (e.output() * self.output() * (1 - self.output())) else: output = self....
def compute_flag_delta(old_centroids, new_centroids): # returns True if and only if every delta is less than eps. flag_delta = True for i in range(len(old_centroids)): delta = euclidean_distance(old_centroids[i], new_centroids[i]) if delta >= eps: flag_delta = False brea...
This function implements the K-means clustering algorithm, reading data from a file, validating inputs, initializing centroids, and iteratively assigning data points to clusters while updating centroids until convergence or max iterations. It returns final centroids and cluster assignments.
def k_means_algorithm(K, max_iter, file_path): flag_K = 1 < K flag_iter = 1 < max_iter < 1000 flag_file = True # Initialize flag_file here data_points = [] try: with open(file_path) as file: for line in file: vector = line.rstrip().split(',') vec...
def __find_path(self) -> List[int]: parent = [-2 for _ in range(self.__node_count)] queue = [self.__source_node] parent[self.__source_node] = -1 queue_index = 0 while queue_index < len(queue): node = queue[queue_index] queue_index += 1 for neig...
This code computes the maximum flow in a network using a path-finding algorithm. It repeatedly finds augmenting paths from the source to the destination, calculates the maximum possible flow increase along each path, and updates the residual capacities of edges accordingly. The process continues until no more augmentin...
def solve(self): if self.__max_flow is None: self.__max_flow = 0 parent = self.__find_path() while parent[self.__destination_node] != -2: for last in self.__adjacency_list[self.__destination_node]: if parent[last] != -2 and not self.saturated(last, self.__...
def getExpressions(key): buffer=getFromS3(f"expressions/{key}.json") with io.BytesIO(buffer.read()) as file: return json.load(file) def master(expressions, key): speechMarks = getSpeechMarks(key) speechMarksBySentence=getSentenceSpeechMarks(speechMarks) processor(expressions,speechMarksBySen...
The main task of the code is to retrieve expressions using a key, process them via the `master` function, save structured data (`sampleProps` and processed output) to Amazon S3 with key-specific filenames, and return the processed output. The key is sourced from an environment variable by default.
def main(key=os.environ.get("key")): expressions=getExpressions(key) output= master(expressions,key) saveToS3(json.dumps(sampleProps),f"props/{key}.json") saveToS3(json.dumps(output),f"renderIds/{key}.json") return output
def invokeLambda(functionName,data): response = lambdaClient.invoke( FunctionName=functionName, InvocationType="RequestResponse", LogType="None", Payload=data, ) def saveStatus(status, key, query, renderIds=None): print(status) saveToS3( json.dumps(dict(status=sta...
The main task of the code is to process a query through a multi-phase AI tutor workflow. It invokes Lambda functions for phases 1-2, voice generation, and processing, while tracking progress via saveStatus() with a key and query. It waits for rendering results, updates statuses (e.g., "rendered"), and handles errors by...
def main(query, key=os.environ.get("key")): print(key) try: invokeLambda("ai_tutor_phase1", json.dumps(dict(query=query, key=key))) saveStatus("phase1", key, query) invokeLambda("ai_tutor_voiceGen", json.dumps(dict(key=key))) saveStatus("voiceGen", key, query) invokeLambd...
def sphinx_builder(): try: from sphinx.setup_command import BuildDoc except ImportError: class NoSphinx(Command): user_options = [] def initialize_options(self): raise RuntimeError('Sphinx documentation is not installed, run: pip install sphinx') ...
This code defines a Python package setup using setuptools, configuring documentation generation with Sphinx, test execution with pytest, and package metadata. It sets up command-line options for building docs, running tests with coverage, and specifies dependencies, entry points, and other setup parameters for package ...
def setup_package(): # Assemble additional setup commands cmdclass = {} cmdclass['docs'] = sphinx_builder() cmdclass['doctest'] = sphinx_builder() cmdclass['test'] = PyTest # Some helper variables version = os.getenv('GO_PIPELINE_LABEL', VERSION) docs_path = os.path.join(__location__, ...
def login_hein(self, hein_username, hein_password): page = self.firefox.new_page() try: page.goto(self.URLS["HEIN_SIGN_IN_URL"]) page.fill("#username", hein_username) page.fill("#password", hein_password) page.click('input[type="submit"]') # At...
The code's main task is to authenticate to multiple academic databases (Hein, Westlaw, SSRN) using provided credentials via a browser context, handling 2FA prompts when required. It closes an existing browser session if prior authentication failed, then sequentially logs in to each service through dedicated methods, en...
def login( self, hein_username, hein_password, westlaw_username, westlaw_password, ssrn_username, ssrn_password, ): """Logs in to the database services. Using the BrowserContext, navigates to the log in urls for Westlaw, Hein, etc. and...
def interpolate(nets, args, x_src, s_prev, s_next, masks): ''' returns T x C x H x W ''' B = x_src.size(0) frames = [] # masks = nets.fan.get_heatmap(x_src) if args.w_hpf > 0 else None alphas = get_alphas() for alpha in alphas: s_ref = torch.lerp(s_prev, s_next, alpha) x_fake = ...
This function generates a video by interpolating latent vectors from a source image using a mapping network. It computes average latent representations for each target label, interpolates between them with a given psi value, and creates frames by smoothly transitioning between these interpolated vectors. The resulting ...
def video_latent(nets, args, x_src, y_list, z_list, psi, fname): latent_dim = z_list[0].size(1) s_list = [] for i, y_trg in enumerate(y_list): z_many = torch.randn(10000, latent_dim).to(x_src.device) y_many = torch.LongTensor(10000).to(x_src.device).fill_(y_trg[0]) s_many = nets.mapp...
def interpolate(nets, args, x_src, s_prev, s_next, masks): ''' returns T x C x H x W ''' B = x_src.size(0) frames = [] # masks = nets.fan.get_heatmap(x_src) if args.w_hpf > 0 else None alphas = get_alphas() for alpha in alphas: s_ref = torch.lerp(s_prev, s_next, alpha) x_fake = ...
This function generates a video by interpolating frames between a source image and reference frames using neural networks. It processes inputs with style encoding, heatmap generation, and frame interpolation, appending results to create a video saved as specified.
def video_ref(nets, args, x_src, x_ref, y_ref, fname, camera=None): video = [] if camera is None: masks = nets.fan.get_heatmap(x_src, Privacy=False) if args.w_hpf > 0 else None else: # x_ref = camera(x_ref) x_src = camera(x_src) masks = nets.fan_priv.get_heatmap(x_src, Privac...
def fitness_score(my_map,initial_pop): r=[] for member in initial_pop: score=0 for i in range(len(member)-1,0,-1): for j in my_map[member[i-1]]: if j[0]==member[i]: score+=j[1] r.append((member,score)) return r def selectparent(x): ...
The code evolves a population using genetic algorithm techniques: it selects parents based on fitness, performs crossover to generate offspring, applies mutation, adds new random members, and sorts the combined population to retain the fittest individuals for the next generation.
def new_population(current_copy, my_map, source, destination): currently= current_copy children=[] pop_size=len(currently) x = fitness_score(my_map,current_copy) y = selectparent(quicksort(x)) parents= y.copy() n=len(parents) for i in range(n//2): parent1 = parents.pop() ...
def new_member(my_map,source,destination): check=True member=[source] current=0 while check: if member[current]!=destination: prospect=my_map[member[current]] i= random.randint(0,len(prospect)-1) member.append(prospect[i][0]) current+=1 els...
The code implements a recursive genetic algorithm to evolve paths from a source to destination on a map. It initializes a population, evaluates fitness, selects the fittest, and iterates for up to 10 generations. Each generation generates new paths, sorts them by fitness, and prints the fittest solution. The process co...
def genetic_algo(gen_no, current_pop, my_map, source, destination): max_gen=10 pop_size=3 if gen_no==0: current_pop=[] for i in range(pop_size): current_pop.append((new_member(my_map,source,destination))) fitness = quicksort(fitness_score(my_map,current_pop)) fit...
def get_block(ip): try: command = subprocess.check_output('docker run --rm --name '+container_name+' kali-tool:2.0 rdap '+ip+' --json || true', shell=True) json_data = json.loads(command) block = json_data['handle'] return block except: return '' def get_domain(domain): ...
The code processes a list of new subdomains by resolving their IP addresses, structuring metadata (like domain, IP block, nameserver), and sending this data to a specified API endpoint for monitoring. It also triggers network scanning (nmap) and HTTP checks (httpx) while logging findings and avoiding duplicates.
def parse(): for line in list_new_subdomains: dic_subdomain['server.address'] = line.rstrip('\n') dic_subdomain['server.domain'] = line.rstrip('\n') try: dic_subdomain['server.ip'] = socket.gethostbyname(line.rstrip('\n')) except: dic_subdomain['server.ip'] = ...
def init(): os.system('sh '+homedir+'/recon/indexes/monitoring/delete_subdomain_index_temp.sh '+target+' > /dev/null 2>&1') os.system('sh '+homedir+'/recon/indexes/monitoring/create_subdomain_index_temp.sh '+target+' > /dev/null 2>&1') os.system('sh '+homedir+'/recon/scripts/monitoring/monitoring_subdomain....
The main task of the code is to initialize a process, retrieve existing subdomains, identify new subdomains, and parse the collected data. It orchestrates subdomain discovery and analysis, likely for security, monitoring, or domain management purposes.
def main(): init() get_subdomains_existing() get_new_subdomains() parse()
def __parse_char_native(self, c): '''this method exists only to see in profiling results''' m = self.native.parse_chars(c) return m def __parse_char_legacy(self): '''input some data bytes, possibly returning a new message (uses no native code)''' header_len = ...
This function processes incoming byte data, appending it to a buffer and parsing it into messages using either native or legacy methods. It updates tracking variables for total bytes/packets received, handles testing discrepancies between parsing methods, and resets the buffer when empty to optimize memory. If a valid ...
def parse_char(self, c): '''input some data bytes, possibly returning a new message''' self.buf.extend(c) self.total_bytes_received += len(c) if self.native: if native_testing: self.test_buf.extend(c) m = self.__pa...
def preorder(self: T) -> list: return self.pre_order_helper(self.root) def inorder(self: T) -> list: return self.in_order_helper(self.root) def postorder(self: T) -> list: return self.post_order_helper(self.root)
The code defines an iterator method that returns different tree traversal sequences based on the `_iter_format` value: preorder (0), inorder (1), or postorder (2). It uses Python's `iter()` to wrap the corresponding traversal method, enabling iteration over tree nodes in the specified order.
def __iter__(self: T) -> Iterator: if self._iter_format == 0: return iter(self.preorder()) if self._iter_format == 1: return iter(self.inorder()) if self._iter_format == 2: return iter(self.postorder())
def get_onsetsline(sig, struct_len): """ Detects and calculates the onset line for a given signal :param sig: The signal requiring the calculation :param struct_len: The length of the signal :return: The value of the onset line """ ret1 = erode(sig, struct_len) ret2 = dilate(ret1, s...
The function `get_features` extracts key temporal and amplitude-based features from a processed signal. It identifies onsets, peaks, and returns in the signal, calculates their time intervals (e.g., onset-to-peak, peak-to-return), and computes amplitudes relative to baseline levels. These features include timing metric...
def get_features(sig, fs=1/60, thd=0.25): """ Extracts features from a given processed signal. :param sig: The signal requiring the extraction :param fs: The frequency of the signal, defaults to 1/60 :param thd: Added threshhold variable, defaults at 0.25 :return: The series of features fro...
def q_sample(self, x_start, t, noise=None): """ Diffuse the data (t == 0 means diffused for 1 step) """ if noise is None: noise = torch.randn(x_start.shape, device=x_start.device) assert noise.shape == x_start.shape return ( self._extract(self....
This code performs iterative image reconstruction by reversing a diffusion process. It initializes a noisy version of the input image x0 at time t-1, then iteratively denoises it through t steps. At each step k (from t-1 down to 0), it applies a constraint function, generates a denoised sample using a neural network (d...
def reconstruct(self, x0, t, denoise_fn, noise_fn=torch.randn, constrain_fn=lambda x, t:x): assert t >= 1 t_vec = torch.empty(x0.shape[0], dtype=torch.int64, device=x0.device).fill_(t-1) encoding = self.q_sample(x0, t_vec) img_t = encoding for k in reversed(range(0,t)): ...
def __peek(self) -> Token: return self.__tokens[self.__current_token_idx] def __parse_show_statement(self) -> StatementNode: self.__advance() value_nodes: List[ValueNode] = [] while self.__peek().ttype != TokenType.NEWLINE: value_nodes.append(self.__parse_value()) ...
This method parses a statement by checking the current token type and delegating to specific parsing functions. It increments a counter for opcodes, adjusts it for PUSH/POP, and routes to handlers for SHOW, binary operations, jumps, labels, returns, and equality statements, returning the corresponding StatementNode.
def __parse_statement(self) -> StatementNode: self.__num_opcodes += 1 if self.__peek().ttype == TokenType.SHOW: return self.__parse_show_statement() elif self.__peek().ttype in [TokenType.ADD, TokenType.SUB, TokenType.MUL, TokenType.DIV, TokenType.MOD]: return self.__par...
def make_tree(arr , i): if i == len(arr): return [None, i] operators = ['+', '-', '*', '/', '^', 'log', 'e', 'sin', 'cos'] fire = Node(arr[i]) if arr[i] not in operators: return [fire, i+1] i += 1 if arr[i-1] == 'log' or arr[i-1] == 'sin' or arr[i-1] == 'cos': [fire.lef...
The code's main task is to parse an input array into a tree structure using `parse_func`, then generate and display the tree via `make_tree`, `print_node`, and `print_tree` functions, likely for visualizing hierarchical data or syntax structures.
def parser (arr): print(make_tree(parse_func(arr),0)[0]) print_node(make_tree(parse_func(arr),0)[0]) print_tree(make_tree(parse_func(arr),0)[0] , 0)
def GenerateMovesMidgameEndgame(board): if board.count('W') == 3: L = GenerateHopping(board) else: L = GenerateMove(board) return L def flip_board(board): return ([ 'B' if value=='W' else 'W' if value=='B' else value for value in board]) def get_num_of_black_blocked(board): count = 0...
This function evaluates a board state in the midgame phase of a game (likely Nine Men's Morris), calculating a heuristic score based on piece counts, blocked pieces, and mills. It prioritizes wins when a side has ≤2 pieces or no moves, rewards mills, penalizes high blocked-piece ratios, and adjusts for piece and move d...
def improved_static_midgame(board): num_black_pieces = board.count('B') num_white_pieces = board.count('W') L = GenerateMovesMidgameEndgame(flip_board(board)) num_black_moves = len(L) if (num_black_pieces <= 2): return 10**300 elif (num_white_pieces <= 2): return -10**300 eli...
def get_field_string( fields = None ): "" if fields is None or fields=='': fields_string='*' else: fields=convert_to_iterator(fields) fields_string='","'.join(fields) fields_string=f' "{fields_string}" ' return fields_string def get_where_string( ...
The main task of the code is to retrieve rows from a SQLite database table with optional filtering, field selection, and result limits. It constructs and executes a SQL query, returns results as a list of dictionaries, and optionally replaces values with predefined codes using metadata. The function supports flexible d...
def get_rows( table_name, database_filepath, filter_by = None, # a dict fields = None, # or a list of field names limit = None, # pandas = False, replace_codes = False, metadata_filename = None, # needed if using replace codes verbose = False ...
def color_mapping(value): gray_scale = int(value * 255) return f'#{gray_scale:02x}{gray_scale:02x}{gray_scale:02x}' def on_square_click(event, canvas, grid, i, j, square_size): global last_visited_square global color_change_interval global increase_mode last_visited_square = (i, j) if i...
The function `draw_grid` renders a grid of colored squares on a canvas, where each square's color is determined by its value via `color_mapping`. It binds click and drag events to individual squares for interaction, and links key presses to a processing function, enabling dynamic grid manipulation through user input.
def draw_grid(canvas, grid, square_size): for i, row in enumerate(grid): for j, value in enumerate(row): color = color_mapping(value) rectangle = canvas.create_rectangle(j * square_size, i * square_size, (j + 1) * square_size, (i + 1) *...
def gen_added_property(value, space, key, depth, immut): """ This function creates a string which contains an added property """ string = '' ADDED = '+ ' if isinstance(value, dict): string += f'{space}{ADDED}{key}: ' string += f'{gen_json_string(value, depth + 1, immut)}\n' e...
The function `inner` generates a formatted string representing differences between JSON objects, using indentation and specific markers for added, deleted, changed, or unchanged keys. It recursively processes nested structures, adjusting spacing based on depth to visually represent hierarchical data differences.
def inner(diff, depth): string = '' SPACES = 4 step = SPACES * depth - 2 space = ' ' * step IMMUT = ' ' for key in diff: value = gen_json_value(diff.get(key).get('value')) state = diff.get(key).get('state') if state == 'added': ...
def load_populations(): pop_df = pandas.read_csv("CenterPop.csv", dtype={"COUNTYFP": str }) pop_df.rename( columns={"COUNAME": "County", "COUNTYFP": "CountyCode", "POPULATION": "Population", "LATITUDE": "Pop_Latitude", "LONGITUDE": "Pop_Longitude"}, inplace=True ) pop_df["County"] = [ name+str(" County") for n...
The code loads and merges regional data (national, states, counties) into a combined dataframe, analyzes fire data with population metrics, calculates fire distances from counties, and visualizes trends by overlaying scatter plots of fire events onto regional data lines. It also prints sorted fire statistics for analys...
def main(): # ggd.update_pickle_them() national_df, states_df, counties_df, provinces_df, cities_df = ggd.load_pickle_them() # print(national_df) mega_df = pandas.concat([national_df, states_df, counties_df, provinces_df], axis=1) # print(mega_df) stateslist = list(states_df.columns) countieslist = list(counti...
def load_pickle_them(): # if the files aren't saved, the dataframe is returned empty. print("Loading data from pickled files...") national_df = load_national_from_pickle() states_df = load_states_from_pickle() counties_df = load_counties_from_pickle() # provinces_df = load_provinces_from_pickle() cities_df...
The main task of the code is to load multiple dataframes from pickled files, update each dataframe using a string parameter, and then save the updated dataframes back to files. The function handles national, states, counties, provinces, and cities dataframes, applying the same update and save process to each.
def update_pickle_them(): # load from pickled files: national_df, states_df, counties_df, provinces_df, cities_df = load_pickle_them() # update the dataframes: national_df = update_by_stringparam("national", national_df) states_df = update_by_stringparam("states", states_df) counties_df = update_by_str...
def InitialiseBoard(): global TicTacToe TicTacToe = [["." for i in range(3)] for j in range(3)] def SinglePlayerGame(): global User1SinglePlayer, Computer,TicTacToe U1 = "X" Comp = "0" print("Symbol User 1: ", U1) DisplayTicTacToe() i = random.randint(0, 1) if i == 0: L_play ...
The code presents a menu for a game, allowing users to choose between playing against the computer (SinglePlayerGame), multiplayer mode (StartgameMultiplayer), or exiting. It validates input, runs the selected game mode, displays scores after each session, and loops until the user selects "END".
def Menu(): option = int(input("1: Play With Computer\n2:Multiplayer\n3:END: ")) while option < 1 or option > 3: print("Incorrect Option: ") option = int(input("1: Play With Computer\n2:Multiplayer\n3:END: ")) while option != 3: if option == 1: InitialiseBoard() ...
def inventory_filesystem(): """ Composes an inventory of all attaches filesystems and finds files with the SUID or GUID bits set. :return: a list of tuples containing (file, modification time, hash) """ results = [] #### # Get a list of mounted disks. mount_info = subproces...
The main task of the code is to scan the filesystem for dangerous items, cross-reference them with an input file if provided, sort the results alphabetically, and output the findings to a file or email. It generates a list of dangerous items, prints their count, writes the sorted list to an output file if specified, an...
def main(in_file=None, out_file=None, mail_to=None): # Get the inventory of everything on the filesystem and then sort it # alphabetically. filesystem_inventory = inventory_filesystem() # Cross-reference in_file with inventory, if applicable. if in_file: print("Cross-referencing found i...
def fromword(s): return frombyte(s[0:1]) + 256 * frombyte(s[1:2]) def fromdword(s): return fromword(s[0:2]) | (fromword(s[2:4]) << 16) def asciz(s): #i = string.find(s, "\0") i = s.find(b"\0") if i != -1: s = s[:i] return s def frombyte(s): #return ord(s[0]) return s[0]
This function parses a .FNT binary font file into an internal font description, extracting metadata like face name, size, attributes, and character bitmaps. It validates the font type, skips vector fonts, reads character metrics, and decodes each character's bitmap data from the file. The result is a structured font ob...
def dofnt(fnt): "Create an internal font description from a .FNT-shaped string." f = font() f.chars = [None] * 256 version = fromword(fnt[0:]) ftype = fromword(fnt[0x42:]) if ftype & 1: sys.stderr.write("This font is a vector font\n") return None off_facename = fromdword(fnt[0x69:]) if off_facen...
def fromword(s): return frombyte(s[0:1]) + 256 * frombyte(s[1:2]) def fromdword(s): return fromword(s[0:2]) | (fromword(s[2:4]) << 16) def gotoffset(off,dirtables=dirtables,dataentries=dataentries): if off & 0x80000000: off = off &~ 0x80000000 dirtables.append(off) else: dataentries.append...
The function processes a directory table in a resource by iterating through entries, checking if their type matches a given value, and invoking a callback with the entry's offset if it matches.
def dodirtable(rsrc, off, rtype, gotoffset=gotoffset): number = fromword(rsrc[off+12:]) + fromword(rsrc[off+14:]) for i in range(number): entry = off + 16 + 8*i thetype = fromdword(rsrc[entry:]) theoff = fromdword(rsrc[entry+4:]) if rtype == -1 or rtype == thetype: gotoffset(theo...
def fromdword(s): return fromword(s[0:2]) | (fromword(s[2:4]) << 16) def nefon(fon, neoff): "Finish splitting up a NE-format FON file." ret = [] # Find the resource table. rtable = fromword(fon[neoff + 0x24:]) rtable = rtable + neoff # Read the shift count out of the resource table. shift = fromword(fon...
The function `dofon` processes a `.FON` file by checking its MZ header, locating the NE/PE header, and delegating to `nefon` or `pefon` based on the detected format. If neither is found, it returns an error. This enables splitting `.FON` files into `.FNT` components for further processing.
def dofon(fon): "Split a .FON up into .FNTs and pass each to dofnt." # Check the MZ header. if fon[0:2] != b"MZ": sys.stderr.write("MZ signature not found\n") return None # Find the NE header. neoff = fromdword(fon[0x3C:]) if fon[neoff:neoff+2] == b"NE": return nefon(fon, neoff) elif fon[neoff...
def search_windows(img, windows, clf, scaler, color_space='RGB', spatial_size=(32, 32), hist_bins=32, hist_range=(0, 1), orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0, spatial_feat=True, hist_feat=True, ...
The main task of the code is to process an image to detect lane lines and vehicles using a combination of lane line fitting with IIR filtering and a heatmap-based vehicle detection approach. It applies calibration, thresholding, and perspective warping for lane detection, while using HOG, color, and spatial features wi...
def process_image(img, single_img=False, fname=''): also_lanes = True # also plot the lane lines ## ## define function vars - both for the vehicles and lane line detection n_frames_history = 15 # history length heat_map_th = 5 # heat map threshold for a single frame snapshot_trig = 940 # snapsho...
def log(message): print("[SystemServer] {}".format(message)) return def on_did_initialize(args): log("Initializing OPEL daemons...") # Execute prerequisites on system server run_command("mkdir -p " + gOpelDataDir) run_command("hciconfig hci0 piscan") initialize_ipcrm() run_command(gOpel...
The main task of the code is to run an OPEL system with Python 3 and root privileges, handling signal-based process management. It checks Python version and root access, parses debug flags, registers signal handlers for child process termination (SIGCHLD) and user interrupts (SIGINT), initializes the system, and enters...
def main(): # Check python version if (sys.version_info[0] < 3): log("You are trying to use Python version {}.{}.{}" .format(sys.version_info[0], sys.version_info[1], sys.version_info[2])) log("OPEL requires Python 3.0+.") return # Check if this is ro...
def _train_step(self, batch): """Train model one step.""" # parse batch batch = [b.to(self.device) for b in batch] z, c, y, _ = batch # calculate loss for generator y_ = self.model["generator"](z, c) y, y_ = y.squeeze(1), y_.squeeze(1) sc_loss, mag_loss =...
The main task of the code is to train a model for one epoch by iterating through batches, performing training steps, checking intervals for logging, evaluation, saving, and early termination, then updating epoch counters and logging progress. It handles batch-wise training, interval checks, and epoch completion trackin...
def _train_epoch(self): """Train model one epoch.""" for train_steps_per_epoch, batch in enumerate(self.data_loader["train"], 1): # train one step self._train_step(batch) # check interval self._check_log_interval() self._check_eval_interval() ...
def _ruler_label(self, base: int) -> tuple[float]: """ Draw a label on the ruler returns the coordinates of the label """ x: float = self.left_margin + self._base_center(base) y: float = self.bottom_margin+self._ruler_font_height self.drawing.add(String(x, y, str(base + 1), te...
This method draws ruler marks by placing heavy ticks at specified bases and light ticks between them. It calculates spacing between consecutive heavy ticks, then generates minor light ticks at intervals determined by the number of minor ticks, ensuring even distribution along the ruler.
def _ruler_marks(self, marked_bases: list) -> None: """ Draw marks on the ruler """ mark_locations: list = [] for index, base in enumerate(marked_bases): mark_locations.append(self._ruler_label(base)) self._ruler_heavy_tick(base) if index: ...
def _sort_similar(self) -> list[int]: """ Sort sequences by similarity to the reference sequence returns list of indexes""" return sorted(range(len(self.matches_list)), key=lambda x: len(self.matches_list[x])) def _indexes_by_tree_order(self) -> list[int]: """ Get the indexes of the se...
This method sets up a drawing canvas for visualizing sequence alignments. It calculates dimensions, initializes the drawing area, sorts sequences by similarity or tree, and draws titles, rulers, sequence labels, and baselines with color-coded mutations. It prepares parameters for rendering plots in SVG or other formats...
def _setup_drawing(self, *, plot_type: str, output_format: str="svg", title: str=None, sort: str="similar", mark_width: float=1, scale: float=1, sequence_labels: bool=True): """ Setus up the drawing """ self.plot_type: str = plot_type self.output_format: str = output_format sel...
def foundHelices(resList,n): """Found all n-helices (3, 4 or 5 type) and assign the structural element (G, H or I)""" for res in range(0,len(resList)): if (resList[res].structure != NONE): continue # no overwrite if (isHelix(resList,res,n)): # start (>>) and end (<<) pattern position...
The function assigns secondary structure elements to residues in a specified priority order: 4-helices (H), beta-bridges (B), beta-strands (E), 3/5-helices (G/I), n-turns (T), and bends (S). It modifies the input residue list (`resList`) by calling specialized functions to identify and assign each structure type sequen...
def SSassignment(resList): """Assignment of secondary structure elements in this order : 1. 4-helices (H) 2. isolated beta-bridge (B) 3. beta-strands (E) 4. 3-helices (G) 5. 5-helices (I) 6. n-turns (T) 7.bends (S)""" foundHelices(resList,4) # alpha-helice...
def check_ROS(): global nodenames, topicnames #print('----------------------------------------') #print('Check ROS...') nodenames = [] topicnames = [] r = True try: nodenames = rosnode.get_node_names() #print(' -- Nodes: %s' %nodenames) topicnames = rospy.get_publish...
The main task of the code is to initialize a ROS node and check various robotic components (robot status, sensors, cameras, TFs, and nodes) in a ROS environment. It first verifies ROS availability, then systematically validates hardware and software functionalities for a robot system, ensuring all critical systems are ...
def main(): r = check_ROS() if (r): rospy.init_node('marrtino_check') #check_simrobot() check_robot() check_social() check_odom() check_sonar() check_laser() check_rgb_camera() check_depth_camera() check_tfs() #check_kinect(...
def __memory_access(self, split_line): lines = [] lines += self.__set_address(split_line[1], split_line[2]) if split_line[0] == 'pop': lines += self.__pop() elif split_line[0] == 'push': lines += self.__push() return lines def __functions(self, cmds): ...
The function `translate_instruction` translates a line of VM code into assembly code by identifying the command type and delegating to specific helper methods. It appends a comment, splits the input line, and routes processing to `__memory_access` for `push/pop`, `__functions` for 3-argument commands or `return`, `__pr...
def translate_instruction(self, line, index): """ Receives a line of vm code and translates command. :param index: :param line: line of code to translate. :return: the lines of translated assembly code. """ lines = [] lines.append("//Translating vm command...
def ResetAllNodes(): global grid for y in grid: for x in y: x.reset() def AStar(start, goal, dijkstra = None): if dijkstra is None: dijkstra = False global currentPath start.g = 0 start.calculateH(goal, dijkstra) start.calculateF() openSet = [start] closedSet = [] whil...
The function initializes pathfinding by resetting all nodes, attempting to find a path using A* or Dijkstra's algorithm from the start to goal node. If no path is found, it clears the current path. It then calls FindPath on the goal node to determine or update the path.
def InitPathFinding(): ResetAllNodes() if not AStar(startDragable.node, goalDragable.node, isDijkistra): global currentPath currentPath = [] FindPath(goalDragable.node)
def getParamTypeFromfileAddress(dataFileAddress): if dataFileAddress.endswith('.run'): paramsType = 'paramFile' elif dataFileAddress.endswith('.list'): paramsType = 'listFile' else: print('Error: parameter/case type cannot be set. Please provide .list or .run file. ') sys.exi...
The function `readParamsFile` reads parameters from a specified file. It determines the file type using `getParamTypeFromfileAddress`, then either reads cases directly from a 'paramFile' or parses a CSV file using a specified delimiter. The parsed cases are returned as the result.
def readParamsFile(paramsFile, paramValDelim=','): paramsFileType = getParamTypeFromfileAddress(paramsFile) if paramsFileType == 'paramFile': cases = readCases(paramsFile) else: cases = readcasesfromcsv(paramsFile, paramValDelim) return cases
def StringReverse(str): revStr="" for i in range ((len(str)-1),-1,-1): revStr+=str[i] return revStr def AddZero(str): for i in range(len(str),maxlen): str+='0' return str def twosComplement(str): compStr="" for i in range (len(str)): if str[i]=='0': compStr+='1' els...
This code subtracts two binary numbers represented as strings by converting the second number to its two's complement, adding it to the first number, and returning the result along with a borrow flag (1 if no carry, 0 otherwise).
def Subtracter(str1,str2): str2=StringReverse(AddZero(StringReverse(str2))) #print(str2) compStr2=twosComplement(str2) #print (compStr2) diff,carry=Adder(str1,compStr2) if carry==0: burrow=1 else: burrow=0 return diff,burrow
def findKeySize(cipher): pos = [] for sz in range(2, 40): pos.append((sz, scoreKeySize(cipher, sz))) pos.sort(key = lambda x: x[1]) return [x[0] for x in pos] def solveVignere(cipher, sz): key = [] ans = [0] * len(cipher) for i in range(sz): part = [] for j in range(i, len(cipher), sz): part.append(ciph...
The code decrypts a ciphertext using the Vigenère cipher by testing top key sizes, scores decryption results, and outputs the highest-scoring candidates with their keys and decrypted text.
def solve(ciphertext): keySize = findKeySize(ciphertext) possible_answer = [] for sz in keySize[:3]: res, key = solveVignere(ciphertext, sz) possible_answer.append((res, getScore(res), key)) possible_answer.sort(key = lambda x: x[1], reverse = True) for ans in possible_answer: print(ans[2], ans[1]) print(...
def GradientUpdate(self,batch): ''' Compute the average derivatives of the negative log-likelihood on a batch of data Input: batch -> [M,num_vis] binary array containing M configurations''' # Compute the positive phase of the gradients: # derivatives on the bat...
This code trains a model (likely an RBM) to approximate a target probability distribution using gradient descent. It iteratively updates parameters via mini-batches, computes KL divergence and overlap between model/target distributions, tracks measurement statistics (sz/sx), and visualizes training progress. The goal i...
def Train(self,training_data,target_prob = None,plot=None): frequency = 10 sz = [] sx = [] sz_err = [] sx_err = [] kl = [] ov = [] num_batches = int(training_data.shape[0]/self.batch_size) plt.ion() if (plot is not None): plt....
def GradientUpdate(self,batch): ''' Compute the average derivatives of the negative log-likelihood on a batch of data Input: batch -> [M,num_vis] binary array containing M configurations''' # Compute the positive phase of the gradients: # derivatives on the bat...
The code trains a model by iteratively performing gradient updates on the training data. Every 10 epochs, it computes the negative log likelihood (NLL) as a loss metric using the partition function and model probabilities, printing the epoch number and NLL to monitor training progress.
def Train(self,training_data): frequency = 10 for k in range(1,self.num_iter): self.GradientUpdate(training_data) if (k%frequency==0): Z = self.PartitionFunction() # Compute Negative Log Likelihood rbm_prob = self.Probability(traini...
def initialize_parameters(X, L): #hparameters layer 1 parameters = {} f1= 4 stride1 = 1 pad1 = 2 # same m, n_H1, n_W1, n_L1 = X.shape num_filters_first = 8 #hparameters layer 2 f2= 2 stride2 = 1 pad2 = 2 # same n_L2 = num_filters_first #number of layers n...
This function trains a convolutional neural network using momentum optimization. It initializes parameters, performs forward propagation with pooling, computes cross-entropy cost, executes backpropagation, updates weights via momentum (with adjustable learning rate), and logs costs every 10 iterations. The model learns...
def convolutional_model(X, Y, learning_rate = 0.68, num_iterations = 50, print_cost = True): costs = [] parameters = initialize_parameters(X_train, 3) v,s = initialize_velocity(parameters) for i in range(num_iterations): AL, caches, pool_caches, parameters, dA_caches = L_model_forward(X, parame...
def initialize_velocity(parameters): L = len(parameters) //2 v = {} s = {} for i in range(L): v["dW"+str(i + 1)] = np.zeros((parameters["W" + str(i+1)].shape)) s["dW"+str(i + 1)] = np.zeros((parameters["W" + str(i+1)].shape)) v["db"+str(i + 1)] = np.zeros((parameters["b" + ...
This function trains a multi-layer neural network using gradient descent with momentum. It performs forward propagation, computes the cost, executes backward propagation to calculate gradients, and updates parameters using momentum-based optimization. The training process iterates for a specified number of steps, track...
def L_layer_model(X,Y, layers_dims, parameters, learning_rate = 0.68, num_iterations = 1000, print_cost = False): #np.random.seed(1) v,s = initialize_velocity(parameters) costs = [] for i in range(num_iterations): AL, caches = L_model_forward(X, parameters) cost = compute_cost(...
def initialize_parameters_deep(layers_dims):#initialize W and b #np.random.seed(1) parameters = {} L = len(layers_dims) parameters = initialize_He(parameters, layers_dims, L) return parameters def random_mini_batches(X,Y, mini_batch_size = 64): np.random.seed(0) m = X.shape[1] ...
The code trains a deep neural network using either mini-batch gradient descent (with multiple epochs and random mini-batches) or standard gradient descent (with random learning rate exploration). It initializes parameters, iterates over epochs/mini-batches, applies the L-layer model with specified hyperparameters, and ...
def training(X, Y, mini_batch_bool, num_epochs, num_iterations, layers_dims): m = X.shape[0] # number of training examples if mini_batch_bool == 1: cost_total = 0 parameters = initialize_parameters_deep(layers_dims) for i in range(num_epochs): mini_batches = random_min...
def get_config(file = '/home/pes2ug19cs020/BigData/project/yah/Current_Config.json'): os.chdir(os.getcwd()) with open(file,'r') as f: config = json.loads(f.read()) return config def get_status_datanodes(): config = get_config() nlogpath = config["namenode_log_path"] with open(os.path.join(nlogpath,"namenode_log...
The code implements a distributed file storage system by splitting a source file into blocks, replicating each block across multiple datanodes based on a hash function and replication factor, updating namenode metadata, and logging operations. It ensures data redundancy by writing chunks to specified datanode paths, tr...
def put(source,dest): config = get_config() nlogpath = config["namenode_log_path"] dlogpath = config["datanode_log_path"] file_number = 1 file_name,exe = os.path.splitext(os.path.basename(source)) fs_path = config['fs_path'] destination = os.path.join(fs_path,dest) dictionary = get_status_datanodes() if ...
def _enemy_encounter(self, player_luck_value): k = random() # TODO: Make the possibility calculation possible... tmp = max(default_ememy_encounter, min_enemy_encounter) # Create the object instead of calling function... if 0 < k and k < tmp: return self._enemy_fight...
This function handles player movement in a grid-based game. It calculates the next position based on input direction, checks the target cell's content (goal, treasure, or empty), and triggers appropriate actions: moving the player, checking for enemy encounters, handling treasure collection, and updating the hidden map...
def _move_player(self,str_direction): pos_move = direction[arrow_key_to_directions[str_direction]] next_player_pos = (self.player.object_pos[0] + pos_move[0],self.player.object_pos[1] + pos_move[1]) # If there is a collision, then it will simply draw the map. if self.or...
def _exit_game(self): clear() selection_list = ["Yes", "No"] cursor_not_selected = " " cursor_selected = ">" tmp_cursor = deepcopy(selection_list) cursor_selection = 1 while True: self._draw_hidden_map() for i in range(le...
The function `_manipulate_map` processes user input to control game actions. It listens for key presses: 'n' to exit the game, arrow keys to move the player, and the escape key to open a player menu. The loop continues until an exit or movement action is successfully executed.
def _manipulate_map(self): while True: character = getch() # This condition will be removed later. if character == b"n": if self._exit_game(): break else: if character in ["UP_KEY", "DOWN_KEY", "LEFT...
def load_data(self): saved_json_file_path = os.path.join(save_data_folder, save_data_file_name) # Read all player's data. try: with open (saved_json_file_path, 'r') as f: json_data = json.loads(f.read()) except: print('Error while loading game...'...
The code initializes a maze/game environment by setting up grid dimensions, player, and symbols (goal/treasure). It either loads pre-existing data or creates a new level, then clears the screen, draws a hidden map centered on the player, and manipulates the map for gameplay. The main task is to configure game state and...
def __init__(self, load_data = False): # Amount to reveal. self.default_amount_to_reveal = default_amount_to_reveal self.width = width self.height = height # Set the symbols below this line: self.goal_symbol = "\033[93m" + "G" + "\033[0m" self....
def new_board(): board = [] for i in range(3): row = [] for j in range(3): row.append(None) board.append(row) return board def render(board): # top row formatting print(" 0 1 2") print(" ------") # insert printing of first row of board ...
The code implements a Tic-Tac-Toe game with customizable players (bots or humans) using command-line arguments. It alternates turns between two players, applying different AI strategies (random, win-focused, or minimax) based on specified bot types. The game validates moves, updates the board, and checks for a winner o...
def main(): # board = [ # ['O', 'X', None], # [None, None, None], # ['X', 'O', None] # ] # implementing command line arguements to select players if len(sys.argv) == 3: player_name = [] for i in range(1, 3): player_name.append(sys.argv[i]) # play is actually li...
def __backup(self, path): backupPath = re.sub(r'\.md', '.backup.md', path) backupCleanedPath = self.__removeFileTokenFromPath(backupPath) os.rename(path, backupCleanedPath) return backupCleanedPath def __isNotionLink(self, line): isNotionLink = re.search(rf'{self.NOTION_FILE_TOKEN}', urllib.parse.un...
This code processes a source file by replacing Notion links' URLs with modified versions, writing the result to a cleaned file. It reads from a backup of the original file, applies regex to identify links, removes specific tokens from URLs, and writes the updated content, finally deleting the backup file.
def createTargetFile(self): # get source file backupPath = self.__backup(self.__path) print("---->>> FILE ---->>>>", self.__path) fin = open(backupPath, 'rt') fout = open(self.cleanedPath, 'w+') newLine = '' for line in fin: newLine = line print("newLine", newLine) if self....
def pre_process_data(self, dataset: str) -> pd.DataFrame: # TODO: open dataset here and save it to disk as dask once is processed return self.data_quality_check(price) def calculate_features(self, price: pd.DataFrame): # TODO: save the dataset and return dataset name or payload for next proces...
The main task of the code is to load a dataset from a constructed file path, preprocess it, calculate features and labels, split the data into training/validation/test sets, scale the data, and train models. The code includes TODOs for command-line invocation, dynamic file naming, and transitioning to Dask for dataset ...
def run(self): # TODO: invoke this function from command line # TODO: build the name of the file in a function # TODO :move dataset handling by dask file_name: str = const.ROOT_FOLDER + self._descriptor["dataset"]["folder"] + \ self._descriptor["dataset"]["stora...
def get_data_from_sql(self, tabelName, columnToOrder, n): self.data = self.sh.get_n_laste_entries_from_table_by_order_colum(tabelName, columnToOrder, n) def transform_data_to_ml_input(self, columnsToDrop=None): """ data is transformed to the input shape of the model :param columnsToDrop...
This function retrieves the last 'n' entries from a SQL table, preprocesses them, generates predictions using a machine learning model, formulates trading decisions, and stores these decisions in a specified SQL table.
def load_last_n_sql_to_ml_predict_save_decision(self, inputTableName, outputTableName, columnToOrder, lookBackNo, columnsToDrop=None): """ This function loads the last n entries from a sql table, makes a prediction and saves the trading decision to ...
def _expand_a(self, seed): """ExpandA(): Expand "seed" into a k*ell matrix A.""" a = [[None for _ in range(self.ell)] for _ in range(self.k)] # matrix rejection sampler for i in range(self.k): for j in range(self.ell): # XOF( 'A' || row || col || seed ) ...
This code generates a cryptographic key pair (public key 'vk' and secret key 'msk') using lattice-based operations. It involves creating a seed, expanding it into a matrix, encoding/decoding vectors, adding noise, and performing NTT-based matrix-vector multiplication. The process ensures secure key generation with homo...
def keygen(self): """Raccoon keypair generation.""" # --- 1. seed <- {0,1}^kappa seed = self.random_bytes(self.as_sz) # --- 2. A := ExpandA(seed) A_ntt = mat_ntt(self._expand_a(seed)) # --- 3. [[s]] <- ell * ZeroEncoding(d) ms = [ self._zero_encoding()...
def _expand_a(self, seed): """ExpandA(): Expand "seed" into a k*ell matrix A.""" a = [[None for _ in range(self.ell)] for _ in range(self.k)] # matrix rejection sampler for i in range(self.k): for j in range(self.ell): # XOF( 'A' || row || col || seed ) ...
The function generates a digital signature for the hash `mu` using the Raccoon lattice-based signature scheme. It computes a signature by expanding a matrix from a seed, adding noise to vectors, performing polynomial multiplications, and verifying bounds on the resulting values. The core steps involve creating a challe...
def sign_mu(self, msk, mu): """Signing procedure of Raccoon (core: signs the mu hash).""" # --- 1. (vk, [[s]]) := [[sk]], (seed, t) := vk [ caller ] (seed, t, ms_ntt) = msk # --- 2. mu := H( H(vk) || msg ) [ caller ] # --- 3. A := ExpandA(see...
def decode_sk(self, b): """Decode a signing key from bytes.""" # decode public key vk, tr, l = self.decode_pk(b) seed, t = vk # expand shares 1, 2, .. d-1 ms = [[None for _ in range(self.d)] for _ in range(self.ell)] for j in range(1, self.d): k...
The code generates a detached cryptographic signature from byte data using a secret key. It decodes the key, processes the message into a buffer, signs it iteratively, and pads the result to a fixed size with zeros to ensure consistent output length.
def byte_signature(self, msg, sk): """Detached signature generation directly from/to bytes.""" msk, tr, _ = self.decode_sk(sk) mu = self._buff_mu(tr, msg) sig_b = [] while len(sig_b) != self.sig_sz: sig = self.sign_mu(msk, mu) sig_b = self.encode_sig(sig) ...
def connection_plsql(): conn_string = "host='" + str(cfg['plsql_staging']['host']) + "' dbname='" + str( cfg['plsql_staging']['dbname']) + "' user='" + str( cfg['plsql_staging']['user']) + "' password='" + str(cfg['plsql_staging']['password']) + "' port = '" + str( cfg['plsql_staging']['port...
The main task of the code is to retrieve and process data related to "discovery" and "citations" from a database using a PLSQL connection. It establishes a database connection, executes specific functions for discovery and citations, logs progress, handles errors, and ensures the connection is closed properly. The code...
def bibliography(): conn_plsql = None try: conn_plsql = connection_plsql() if conn_plsql: logger.info("#######LEGACY##########") # legacy_studies(conn_plsql) logger.info("#######XML##########") # xml_studies(conn_plsql) logger.info("###...
def _enqueue_node(heap_orders): """ Store the order of each Leonardo heap created when enqueueing node from array to keep track the position of each heap in the original array :param heap_orders (list): :return: """ heap_orders_len = len(heap_orders) # Case 1: Order of final two heaps ar...
The function `_leonardo_heapify` transforms an input array into a series of Leonardo heaps, a specialized heap structure used in sorting algorithms. It iterates through each element, enqueues nodes into an auxiliary list `heap_orders`, and adjusts heap structures using `_trinkle` and `_sift` to maintain order. The prim...
def _leonardo_heapify(arr, arr_len, **kwargs): """ Create a series of Leonardo heaps from the array to be sorted :param arr (list): array to be sorted :param arr_len (int): length of the array :param kwargs (dict): :return: heap_orders (list): auxiliary array to store the order of each heap ...
def _get_left_child_heap_order(heap_order): """ Get the heap order of the left child of a node :param heap_order (int): :return: left_child_heap_order (int) """ left_child_heap_order = heap_order - 1 # A heap with order 1 doesn't have any children if left_child_heap_order < 0 or heap_ord...
The main task of the code is to sort an array by repeatedly dequeuing the maximum node from Leonardo heaps. It processes the array from right to left, removing heap orders and maintaining heap properties through trinkle and sift operations on exposed child nodes, ensuring the structure remains valid after each dequeue.
def _dequeue_node(arr, arr_len, heap_orders, **kwargs): """ Sort the array by dequeueing the max node from Leonardo heaps :param arr (list): array to be sorted :param arr_len (int): length of the array :param heap_orders (list): auxiliary array to store the order of each heap :param kwargs: ...
def getCurrentJoke(): jokeNumber = getJokeNumber() jokes = Joke.objects.all().filter(override=True) print(jokes) if not jokes: # When no jokes are featured with the admin jokes = Joke.objects.all() current_joke = jokes[jokeNumber] else: current_joke = jokes[0] return cur...
The code gathers context data for a joke, including the joke content, user interaction (like status), comments, like count, user profile picture (default or personalized), and joke author information, then returns this structured data in a dictionary for use in a web template or response.
def getContext(request): currentUser = request.user currentJoke = getCurrentJoke() if currentUser.is_anonymous: profile_pic = "joke/img/anonymous_dad.jpeg" else: picnumber = getPicNumberUser(currentUser) profile_pic = "joke/img/"+picnumber+".jpeg" #Check if user liked t...
def heapify_down(self, idx=1): while self.child_present(idx): larger_child_idx = self.get_larger_child_idx(idx) child = self.heap_list[larger_child_idx] parent = self.heap_list[idx] # loops create key variables for the parent and child for key in child...
This code removes an element with a specified key from a heap structure. It checks if the heap is empty or if the key exists, then swaps the target element with the last element, removes it, and restructures the heap using heapify operations to maintain order. It handles edge cases like empty heaps and single-element h...
def remove_by_key(self, remove_key): if self.count == 0: print(f"{self.name} is empty") return keys = [] # loop adds keys to the keys list for element in self.heap_list: if element != None: for key in element: keys.a...
def get_reg(x): # returns reg number (1-7), bitness (8, 16, 32, 64), whether the register is a r8-r15 reg, bitness = (x.value-1) % 8, (x.value-1) // 8 return reg, 2**[0, 0, 1, 2, 3, 0, 1, 2, 3, 3][bitness]*8, (bitness > 4) & 1 def write_instruction(opcode, operand1, operand2=None, mod_rm=b'', sib=b'', address_size...
This code generates machine code for a MOV instruction, handling register and immediate operands. It determines the correct opcode based on operand types and bitness, writes the instruction, and updates internal state for address patches. It also manages function/data references by storing addresses for later patching,...
def MOV(self, operand1, operand2): fname = None dname = None address_size = 0 if type(operand2) == str: if operand2 in self.function_addresses.keys(): fname = operand2 operand2 = Address(disp=self.function_addresses[operand2]) address_size = 4 elif operand2 in self.d...
def compare_namespaces(): obj = {} main_instance = MASTER_INSTANCE main_instance_api = get_CDAPendpoint(PROJECT_ID, REGION, main_instance) main_nslist = get_namespaces(main_instance_api, token) if MASTER_INSTANCE not in INSTANCES: INSTANCES.insert(0, MASTER_INSTANCE) obj['Namespace'] ...
The main task of the code is to compare differences in namespaces, plugins, pipelines, preferences, and secure keys across systems, then export these differences into separate sheets of an Excel file for analysis and reporting.
def compare_instances(): ns_diff = compare_namespaces() # Get difference of namespaces plugin_diff = compare_plugins() # Get difference of plugins pipeline_diff = compare_pipelines() # Get difference of pipelines preference_diff = compare_preferences() # Get difference of preferences securekeys_diff...
def create_dataset(url=data_url, file=data_file): """ Prepare the given data for analysis. :return: one `DataFrame` with all the data. """ if not exists(file): wget.download(url) # Note that spark.read.csv can read .gz (compressed) files. # Pandas can also read .gz (compressed) files...
This function performs cross-validated regression using multiple models (Linear, GLM, Decision Tree) with parameter tuning. It trains and evaluates models on split data, selects the best performer via specified metric (e.g., R²), and returns the optimal model. The process involves creating pipelines with shared preproc...
def single_pipeline_multiple_regressions(params: Dict = None, folds=2, metric='r2', limit=None): """ :param params: Regression parameters (for all regression types) unless customized :param folds: Folds for CrossValidator :param metric: Metric for CrossValidator :param limit: If not None, then limit...
def fill_hand(self): return self.draw(), self.draw() def usable_ace(self, person): if person == 0: if 1 in self.player and sum(self.player) <= 11: return True else: return False if person == 1: if 1 in self.dealer and sum(self.d...
This code simulates a Blackjack game episode, tracking player and dealer actions, including hitting decisions based on hand sums and usable aces. It records states (player sum, dealer showing, ace status) and actions, checks for busts, and determines the outcome by comparing final scores, considering ace values. The ep...
def simulate(self): # current sum [12..21], dealer showing [1..10], usable ace [yes, no] self.player = np.array(self.fill_hand()) self.dealer = np.array(self.fill_hand()) episode = [] player_usable_ace = self.usable_ace(0) if player_usable_ace: while self.pl...
def fill_hand(self): return self.draw(), self.draw() def init_policy(self): # when sum less than 20, keep hit, do no care other things self.policy[:-2][:][:] = 1 def init_player(self): while self.player_sum() < 12: self.hit(0)
The code initializes a game environment, setting up player and dealer hands using `fill_hand()`, and initializes a 3D policy array for decision-making. It calls `init_policy()` to define the agent's strategy and `init_player()` to configure the player's state, preparing the environment for reinforcement learning or gam...
def __init__(self): self.player = np.array(self.fill_hand()) self.dealer = np.array(self.fill_hand()) self.policy = np.zeros((10, 10, 2)) self.init_policy() self.init_player()
def fill_hand(self): return self.draw(), self.draw() def init_player(self): while self.player_sum() < 12: self.hit(0) def player_sum(self): if self.usable_ace(0): return sum(self.player) + 10 else: return sum(self.player) def get_state(self): r...
This code simulates a single episode of a game (likely blackjack) where a player follows a policy to decide actions (hit/keep) while interacting with a dealer. It initializes hands, explores starting actions, executes policy-guided decisions, checks for busts, and determines the outcome by comparing player/dealer hands...
def simulate(self): self.player = np.array(self.fill_hand()) self.dealer = np.array(self.fill_hand()) self.init_player() assert self.player_sum() >= 12 episode = [] es_and_hit = True episode.append(self.get_state()) # explore start, for each state-action...
def extract_additional_conditions(raw_input): """ This will extract any additional conditions provided. Currently these are accepted within double parenthese like so: when a member draws a firearm and acquires a target ((under section: REPORTING THE USE OF FORCE)) :param raw_input: :return: ...
The code searches sentences for specified phrases, checks for positive indicators using regex, and returns a tuple indicating success (True) with context or failure (False) with found phrases. It handles optional additional conditions, checks enumerated lists, and returns matched content with sections if applicable.
def perform_search(self, phrases_to_search, positive_indicator_phrases): """ This will search each sentence for specific phrases. Then it will use a list of additional phrases to determine a positive indicator. It will also return the phrase found with the regex. If the positive indicator was no...
def get_backup_mhls(self): """search the verifier folder (or the day folder) for mhls, and return a list of the mhl filename """ folder_to_scan = self.get_folder_to_scan() mhl_list = [os.path.join(folder_to_scan, file) for file in os.listdir(folder_to_scan) if file.endswit...
This code initializes a backup management system by configuring source folders, processing media files (MHLS), grouping backups, validating against scanned files, and generating a report. It sets up logging, ignored files, and handles dual backups, ensuring media synchronization and backup integrity according to specif...
def __init__(self, root_folder, source_folders=None, backup_pattern="", backup_trim=0, dual_backups=True, add_roll_folder=1, manager=None, require_ale=False): if not source_folders: self.source_folders = ["Camera_Media", "Sound_Media"] else: self.source_folders ...
def clean_instances(self): for k in list(self.instances.keys()): if self.instances[k] == 0: for i_id in list(TOTAL_INSTANCES.keys()): if i_id.startswith(str(k.id)): del TOTAL_INSTANCES[i_id] del self.instances[k] # ...
This function processes a game move by updating the board and game state based on the result ('M', 'H', 'S'), managing instances of possible game states, checking win conditions, and returning the total number of valid states. It handles ship sinking logic, creates new instances when ships are sunk, and ensures consist...
def move(self, move, result=''): #if self.instance_depth == 0: #print(f"ID: {self.id} | Depth {self.instance_depth} | Executing move {move} with result {result}, has instance: {self.instances_created()}") self.clean_instances() # if depth is exceeded and there are still hit points...
def evaluate_available_words(self): viable = [] for word in self.words: viable.append(scripts.getFilteredList(word, VOCAB[str(len(word))], self.letters_used)) self.viable = viable def core_game_stage_three(self): print(f"{colors.BOLD + colors.BLUE}Entering Stage 3...") ...
The main task of the code is to determine the optimal next move in a word-guessing game by evaluating viable word options, calculating their unigram probabilities, and selecting the word with the highest information gain. The loop continues until all letters are used, with a threshold check to trigger a stage-three str...
def core_game_stage_two(self): while self.letters_left > 0: print(f"{colors.BOLD + colors.BLUE}Current Phrase: " + (" ".join(self.progress))) self.evaluate_available_words() words = [] info_list = {} total_combinations = 1 for ...
def check_win(self): return self.ships_sunk == len(DEFAULT_SHIP_SIZES) def eval_state(self): # remove any non-needed instances self.clean_instances() unfound_hit_points = sum(self.remaining_ships) - np.count_nonzero(self.game_state == 2) p = np.zeros((BOARD_SIZE, BOARD_SIZE), d...
The code implements a game-playing agent that iteratively evaluates the game state, selects the best move based on a probability matrix, executes the move, and tracks the number of moves until a win condition is met. It prints the current move, probability matrix, and board state, then terminates if the move is invalid...
def run(self): while not self.check_win(): self.move_count += 1 p = self.eval_state() best_move = unravel_index(p.argmax(), p.shape) print(f"Move #{self.move_count} | ID: {self.id} | Depth {self.instance_depth} | Executing best move {best...
def make_move(self, guess, can_lie=True, custom_name=''): print(f'''Letters Guessed: "{'", "'.join(self.letters_used)}"''') question = f"Guess #{self.counter}: Is there a {guess}? " if custom_name: question = f"Guess #{self.counter}: Is there a {custom_name}? " # Q1 ...
This code initializes a game with stages, setting up a progress tracker with placeholders, adding special characters, and transitioning to subsequent game stages. It prepares the game state by initializing attributes, handling initial moves for specific characters, and invoking core game logic for stages 1 and 2.
def __init__(self, length): self.can_lie = True self.counter = 2 self.letters_used = [] self.length = length self.letters_left = length self.progress = ["█"] * self.letters_left self.order = ["e", "a", "r", "i", "o", "t", "n", "s"] self.fails = [...
def load_config(config_path): global CLIENT_ID global CLIENT_SECRET with open(config_path) as f: for line in f: d = line.strip().split(':') d = list(map(lambda x: x.strip(), d)) assert len(d) == 2 k, v = d if k == 'CLIENT_ID': ...
The main task of the code is to load configuration settings from a file, authenticate to obtain a token, and then retrieve and print the "Story of the Day" (SOTD) content. The `main()` function orchestrates these steps sequentially: first loading the config, then handling authentication, and finally fetching and displa...
def main(): load_config('./conf.txt') auth_and_get_token() print(get_sotd())
def _verify_youtube_link(self,link: str) -> str | None: """ Verify YouTube link and return a simple link. Args: - link (str): The YouTube link to verify. Returns: - str | None: The verified link if valid, otherwise None. If the link is a valid playlist link, it...
This code initializes a YouTube object by validating a provided link, fetching HTML data, extracting necessary JSON and configuration data, and instantiating either a PlayList or YouTube subclass based on the link type, handling errors for invalid links or connection issues.
def __init__(self,link): """Initialize a YouTube object with the ytInitialPlayerResponse JSON data extracted from HTML data. Parameters: html_data (str): The HTML data from which the ytInitialPlayerResponse JSON data will be extracted. Returns: None """ ...
def colored(string, color): """ Return the input string with specified color in ANSI escape sequence. Parameters: - string (str): The input string to be colored. - color (str): The color name. Supported color names are 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white', 'black', 'gray', an...
The function downloads a YouTube video, handling audio separately if the video lacks it. It uses temporary files to download video and audio, then combines them with ffmpeg. If the video already has audio, it downloads directly. Returns True on success, False otherwise, with error handling and cleanup of temporary file...
def video_downloader_youtube(video_staus_if_audio:bool,link_video:str,dict1:dict,attempt_to_download:int,output_path:str,ffmpeg_path:str)->bool: ''' Downloads video from a YouTube link. Args: video_status_if_audio (bool): Indicates whether the video has audio available. link_video (str): Th...
def download_file_with_resume(url, filename, retry=1,downloaded_bytes=0):#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! fix it when i will make my own request library try: headers = {'Range': f'bytes={downloaded_bytes}-'} re...
The function downloads audio from a YouTube link using a temporary file, adds metadata (title, artist) and cover art via FFmpeg, saves the processed audio to a specified path, and handles errors by checking download success and cleaning up temporary files.
def audio_downloader_youtube(link_of_music:str, path_to_save:str, ffmpeg_path:str, title_video:str , artist_name:str , thumbnail_link:str)->None: """ Downloads audio from a YouTube link and saves it to the specified path. Args: link_of_music (str): The YouTube link of the music video. p...
def euler_from_quaternion(x, y, z, w): # """ # Convert a quaternion into euler angles (roll, pitch, yaw) # roll is rotation around x in radians (counterclockwise) # pitch is rotation around y in radians (counterclockwise) # yaw is rotation around z in radians (counterclockwise) # """ t0 = +2...
This code processes laser scan data by converting local sensor readings into global coordinates using the robot's transformation and orientation. It filters valid points, applies rotation/translation transformations, and prepares data for clustering. The task involves coordinate transformation, data filtering, and peri...
def laserCallback(self, laserscan): if (self.iter % TIME_PERIOD == 0): self.global_laserscan_list = list() self.local_laserscan_list_x = [0] * len(laserscan.ranges) * TIME_PERIOD self.local_laserscan_list_y = [0] * len(laserscan.ranges) * TIME_PERIOD self.local_l...
def get_status(self, gid): game = self.get_game(gid) return { "title": game["name"], "myturn": game["gamedata"]["clock"]["current_player"] == self.uid, "turn": len(game["gamedata"]["moves"]), "opponent": self._get_opponent_name(game["players"]), ...
The main task of the code is to check the status of a game, handle game termination, and notify the player if it's their turn. It updates the game state, sets a timer, and logs alerts when applicable. The function ensures the game data remains current and triggers notifications only when the turn hasn't advanced since ...
def notify_task(self, gid): self.log.info("Checking status of game {}...".format(gid)) status = self.get_status(gid) if gid not in self.games: self.log.info("Game {} has ended.".format(gid)) self.games.pop(gid, None) return # only notify if there has...
def _parse_fixed_length_data(self, original_record, column, null_table): """ Parse fixed-length data from record :param original_record: unmodified record :param column: column this data belongs to :param null_table: null table of the row """ column_name = column....
The function parses a data record by first extracting null bitmaps to identify missing values, then processes fixed-length fields. It handles version-specific data unpacking and separates variable-length columns for dynamic parsing. Finally, it uses metadata to parse variable-length data, ensuring proper column mapping...
def _parse_row(self, record): """ parse record (row) of data. First parse all fixed-length data field and then parse the relative length data. :param record: the current row data :return: """ original_record = record reverse_record = record[::-1] # Records...