dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def list_directories(path): return [ name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name)) ] def list_all_files_with_extension(path,extension): files_list = [x for x in os.listdir(path) if x.endswith(extension)] return files_list def write_from_local_sql(information): writer = Tab...
This function processes files in subdirectories of a specified local path. It iterates through each directory, updates file information with folder names and paths, retrieves files matching a given format, and writes their details to a SQL database using `write_from_local_sql`. The core task is to systematically organi...
def write_foldered_files_to_table(information): for directory in list_directories(information['local_path']): file_info = information.copy() file_info['folder_name'] = directory file_info['local_path'] = file_info['local_path'] + f'\\{directory}' for file in list_all_files_with_exten...
def __create_new_crawler(self): try: self.client.create_crawler( Name=self.glue_crawler_name, Role=self.glue_role, DatabaseName=self.glue_database, Targets={ "S3Targets": [{ "Path": "s3://" +...
The code's main task is to manage AWS Glue crawler operations based on new data partitions or buckets. It checks if neither new_partition nor new_bucket exists, exiting early if so. If a new bucket is detected, it creates a new crawler. Then, it stops the existing Glue crawler and initiates the new one, ensuring update...
def run(self): if (not self.new_partition and not self.new_bucket ): return if self.new_bucket: self.__create_new_crawler() self.__stop_glue_crawler() self.__start_crawler()
def get_glue_df(self, partition_type: str) -> pd.DataFrame: assert partition_type in ['dev', 'train'] glue_df = pd.read_csv( self.glue_qqp_dir + f'/{partition_type}.tsv', sep='\t', error_bad_lines=False, dtype=object) glue_df = glue_df.dropna(axis=0, how='any').reset_index(drop=True)...
The code initializes a KNRM (Kernel Regression for Matching) model for question paraphrase identification using the GLUE QQP dataset. It loads training/dev data, processes tokens, builds vocabulary, configures model parameters (e.g., kernel count, MLP layers), and sets up validation data loaders with custom collation. ...
def __init__( self, glue_qqp_dir: str = 'data/QQP/', glove_vectors_path: str = 'data/glove.6B.50d.txt', min_token_occurancies: int = 1, random_seed: int = 0, emb_rand_uni_bound: float = 0.2, freeze_knrm_embeddings: bool = True, knrm_ker...
def __md(self): """Return the project's metadata structure""" p_l = self.__basepl('metadata') p_l['content'] = 'metadata' return self._call_api(p_l, 'metadata')[0] def __rcv(self): p_l = self.__basepl('version') rcv = self._call_api(p_l, 'version')[0].decode('utf-8') ...
This method configures a REDCap connection by fetching metadata, version, field names/labels, forms, events, and arm data. It handles API errors, extracts key attributes like default ID fields, and sets up internal state for data processing. The configuration includes error checking, data filtering, and initializing va...
def configure(self): try: self.metadata = self.__md() except RequestException: raise RedcapError("Exporting metadata failed. Check your URL and token.") try: self.redcap_version = self.__rcv() except: raise RedcapError("Determination of RED...
def _input_fn(file_pattern: List[Text], tf_transform_output: tft.TFTransformOutput, batch_size: int = 200) -> tf.data.Dataset: """Generates features and label for tuning/training. Args: file_pattern: List of paths or patterns of input tfrecord files. tf_transform_output: A TF...
The code trains a machine learning model using TensorFlow, employing distributed training with MirroredStrategy. It loads transformed datasets, builds a Keras model, trains it with specified steps, and exports the model for serving, including input signature definitions for inference. The process uses TF Transform for ...
def run_fn(fn_args: TrainerFnArgs): """Train the model based on given args. Args: fn_args: Holds args used to train the model as name/value pairs. """ tf_transform_output = tft.TFTransformOutput(fn_args.transform_output) train_dataset = _input_fn(fn_args.train_files, tf_transform_output, ...
def get_log_filename(): filename = '' while not path.exists(filename) or not path.isfile(filename): filename = ask_for_filename() return filename def get_name(type): prompt.choose_name(type) name = input('--> ') return name def get_cooldown_time(): prompt.enter_cooldown_time() cooldown_time = input(...
The function `add_new_graph` collects user input and system data to create a new graph configuration. It prompts for a graph name, retrieves a log file, cooldown time, and metrics, then compiles these into a dictionary. This data is added to a configuration, enabling the graph to be tracked with specified metrics and c...
def add_new_graph(): prompt.lets_add_graph() log_filename = get_log_filename() graph_name = get_name('graph') cooldown_time = get_cooldown_time() prompt.lets_add_metrics() graph_metrics = get_metrics(log_filename) data = { 'name': graph_name, 'filename': log_filename, 'cooldown_time': ...
def read_ref_energy(system_name, filename = "energy"): with open(filename) as fp: for line in fp: # temp = line.strip().split() if line.strip().startswith("Energy at 0K"): CCSDT_0K_energy = float(line.strip().split()[-1]) return CCSDT_0K_energy def read_ref_coo...
This code processes a molecular system by generating an HDF5 file containing reference energy, atomic coordinates, and metadata. It iterates through specified functionals (e.g., GGA_PBE) to process each, storing results in the HDF5 file. The task includes reading input data, writing structured metadata, and invoking pe...
def process_system(system_name, list_of_functionals = ["GGA_PBE","GGA_PBEsol","GGA_RPBE"], MCSH_RADIAL_MAX_ORDER = 5, MCSH_MAX_ORDER = 3, MCSH_MAX_R = 3.0): print("\n==========\nstart system: {}".format(system_name)) system_folder = "./{}/".format(system_name) hdf5_filename = "./raw_data_files/{}_MCSHLegen...
def isClosedShape(originalLine): closedShape = False startPoint = originalLine[0] endPoint = originalLine[-1] if (distanceHelper(startPoint, endPoint) < avgDistBtwnPoints(originalLine)): closedShape = True return closedShape def randResponse(): # respons...
This function handles the end of a drawing action by generating a response based on the last stroke's type (Line, Square, or other). It checks if the shape is closed, creates a response with transformed coordinates, applies constraints, and moves the cursor to the adjusted starting point, updating the app's state for s...
def mouseReleased(app, event): app.userIsDrawing = False app.firstMove = True if not app.userIsDrawing and app.firstMove: if isinstance(app.strokes[-1], Line): if (isClosedShape(app.strokes[-1].getCoords())): app.newResponse = Response(1, app.strokes[-1].getCoords()) ...
def GreetingIntent(intent_request): return { 'dialogAction': { "type": "ElicitIntent", 'message': { 'contentType': 'PlainText', 'content': 'Hi there, how can I help?'} } } def dining_suggestion_intent(intent_request): location = g...
The code routes incoming intent requests to specific handling functions based on the detected intent name. It checks the intent type and calls corresponding functions like GreetingIntent, dining_suggestion_intent, or ThankYouIntent. If the intent is unsupported, it raises an exception. The main task is to dispatch requ...
def dispatch(intent_request): intent_name = intent_request['currentIntent']['name'] # dispatch according to the intent if intent_name == 'GreetingIntent': return GreetingIntent(intent_request) elif intent_name == 'DiningSuggestionsIntent': return dining_suggestion_intent(intent_request)...
def countdown(count): while count > 0: print(f"{count}\r", end="") time.sleep(1) count -= 1 print("Start") def restart_game(): click(c.PAUSE) click(c.RESTART) time.sleep(1) def get_last_pou(): done_flag = 0 last_pou = None while True: time.sleep(0.5) ...
The code automates game interactions by initiating a 5-second countdown, restarting the game, and entering a loop that continuously collects positions (via get_last_pou), prints them, and triggers clicks on those positions using click_list, repeating every 1.5 seconds.
def main(): # pyautogui.mouseInfo() # return countdown(5) restart_game() pou_list = [] while True: pou_list.append(get_last_pou()) print(" ".join(pou[0] for pou in pou_list)) click_list(pou_list) time.sleep(1.5)
def refresh_mining_places_dicts(self): for base in self.ai.townhalls.ready: minerals = self.ai.mineral_field.closer_than(10, base) for mineral in minerals: if mineral.tag not in self.minerals_dict: self.minerals_dict[mineral.tag] = [] gas ...
The code manages worker distribution in a game, refreshing mining locations, removing inactive bases, assigning workers to minerals/gas based on a ratio, and redistributing idle workers while excluding specified tags to optimize resource gathering efficiency.
def distribute_workers(self, minerals_to_gas_ratio=2, excluded_tags=None): self.refresh_mining_places_dicts() self.remove_dead_bases() self.assign_workers(minerals_to_gas_ratio) self.distribute_idle_workers(excluded_tags)
def load_media(self, idx): """Loads the media at the given idx from the scraper Args: idx = the index of the id in self.scraper.media to load. idx will be modded by the length of self.scraper.media so that media is loaded cyclicly by just incremen...
This code initializes a Telegram message tagging GUI, setting up UI components, connecting navigation controls, configuring a scraper for message retrieval, handling Telegram authentication, and managing message/media display with translation features. It ensures proper session setup, filters, and user interaction for ...
def __init__(self): """Constructor""" super().__init__() self.media_idx = 0 self.unscaled_img = None # load in ui uic.loadUi(os.path.join(resource_path, "Main_window.ui"), self) # set window title self.setWindowTitle("Telegram tagger") # insta...
def zero_crossing_rate(x, samplerate=44100): """ args: x: np.array of audio samplerate: sample rate of audio """ return int(np.diff(x > 0).sum()) def avg_energy(x, samplerate=44100): """ args: x: np.array of audio samplerate: sample rate of audio """ return float((x ** 2)...
The code extracts audio features (zero-crossing rate, average energy, bandwidth, spectral centroid, pitch frequency) from a signal using sliding windows. It processes the input signal `y` in overlapping segments, computes specified features for each segment, and returns them as lists. The function allows truncating the...
def extract_features(y, sr=44100, window_size=4096, stride=2048, max_len=65536): if max_len != None: y = y[:max_len] windows = [y[i:i+window_size] for i in range(0, y.shape[0]-window_size, stride)] zero_crossing_rates = [] avg_energies = [] bandwidths = [] spectral_centroids = [] pitch_frequ...
def total_coverage(self, seekers): """ Calculate the total coverage achieved by all the seekers :param seekers: :return: total coverage """ stats = [] for location in seekers[0].visits: stats.append(0) for seeker in seekers: for i i...
The function performs backpropagation in a reinforcement learning algorithm by updating Q-values based on a reward derived from avoiding unsafe locations, using the Q-learning update rule with parameters alpha (learning rate) and gamma (discount factor), while tracking coverage and visit counts to influence reward calc...
def RL_Backprop(self, move_made, reward_multiplier, alpha, gamma, seekers, possible_locations): """ Do the backpropagation for the Reinforcement Learning algorithm :param move_made: seeker's last move :param reward_multiplier: reward multiplier for the reward equation :param alph...
def generate_nodes(self, station_list, Info=Info): """ Generate a list of possible nodes from the required station. This is used in the MCTS :param station_list: List of stations from which to generate the nodes :param Info: Information about the stations :return: List containing...
This function handles the movement of seekers in a reveal round by selecting the optimal move to approach the player's location while avoiding collisions. It calculates Q-values for available nodes, prioritizes reaching the player, and uses backpropagation to update Q-values with reward-based learning parameters alpha ...
def Movement_Reveal_Round(self, possible_location, seekers, player, alpha, gamma, reward_multiplier): """ Handle everything related to the movement of the seekers in a reveal round :param possible_location: location of the player :param seekers: list of seekers :param player: pla...
def SpeedControler(ball): ball.pos[0] = ball.pos[0] + ball.velocity[0] ball.pos[2] = ball.pos[2] + ball.velocity[2] # distancia = velocidad * tiempo # new_position = old_position + velocidad * tiempo ball.velocity[0] = ball.velocity[0]*0.999 ball.velocity[2] = ball.velocity[2] * 0.999 ball....
This code updates a 3D simulation of two spheres by rotating them based on velocity, applying speed control, checking wall and inter-sphere collisions, updating positions, and rendering the scene. It increments a global time variable and prints velocity changes for debugging.
def callback_func(caller, timer_event): global time #print("velocity", sphere.velocity, "last velocity", sphere.last_velocity) # print("pos", sphere.pos, "\n") sphere_actor.RotateX(sphere.velocity[0]*3*0.37) sphere_actor.RotateZ(sphere.velocity[2]*3*0.53) sphere_actor2.RotateX(sphere.veloc...
def train(self, scenes, epoch): start_time = time.time() self.model.train() if self.fix_batch_norm: for m in self.model.modules(): if isinstance(m, (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d)): m.eval() self.ema_restore() self.ema...
The main task of the code is to train a model for a specified number of epochs using given training and validation scenes. It handles learning rate scheduling, skips warnings, trains each epoch, and validates periodically or at the end. The model is saved after each validation step, ensuring progress is preserved.
def loop(self, train_scenes, val_scenes, epochs, start_epoch=0): if self.lr_scheduler is not None: with warnings.catch_warnings(): warnings.simplefilter('ignore') for _ in range(start_epoch * len(train_scenes)): self.lr_scheduler.step() self.e...
def configure_mads(): configure_account_fields(MADS_FILE_NAME) configure_data_fields(MADS_FILE_NAME) configure_email_fields(MADS_FILE_NAME) df = pd.read_excel(io=MADS_FILE_NAME, sheet_name=UNITS_SHEET) df = df.fillna("") df.drop(df.columns[4], axis=1, inplace=True) units = {} f...
The code generates a formatted report document summarizing unit statuses (online/offline/error) based on MADs or VFT configuration. It creates a table with unit names, platform status, Dataplicity status, locations, and remarks, applying color coding to status cells. The report is saved, data is cleaned, and returns st...
def generate_report(mads = False): statusDict = {} rtn = [] document = Document() document.add_heading("Unit Status", 0) table = document.add_table(rows=1, cols=5) heading_cells = table.rows[0].cells heading_cells[0].text = "Unit Name" if mads: heading_cells[1].text = "On MADs" ...
def configure_mads(): configure_account_fields(MADS_FILE_NAME) configure_data_fields(MADS_FILE_NAME) configure_email_fields(MADS_FILE_NAME) df = pd.read_excel(io=MADS_FILE_NAME, sheet_name=UNITS_SHEET) df = df.fillna("") df.drop(df.columns[4], axis=1, inplace=True) units = {} f...
The code generates a report document listing unit statuses (online/offline/error) with color-coded indicators, saves it, and conditionally sends an email based on time and status checks, using MADs or VFT configurations depending on input parameters.
def generate_report(formatted_time="00:00", mads=False, isBlockEmail=False): statusDict = {} # rtn = [] document = Document() document.add_heading("Unit Status", 0) table = document.add_table(rows=1, cols=5) heading_cells = table.rows[0].cells heading_cells[0].text = "Unit Name" if mads:...
def double_digit_left_rule(x, y, z): return replace(y, z, x), y, z def double_digit_right_rule(x, y, z): return x, y, replace(x, y, z) def triple_digit_rule(x, y, z): return x, replace(x, z, y), z
The function applies three transformation rules sequentially: first the triple-digit rule on inputs x, y, z, then the double-digit right rule on the result, and finally the double-digit left rule on the intermediate output. The main task is to process the inputs through these nested rules in a specific order to produce...
def apply_triple_rules(x, y, z): return double_digit_left_rule(*double_digit_right_rule(*triple_digit_rule(x, y, z)))
def equal_numbers(lst): nr_empty = utils.find_empty(lst) nr_zeros = utils.find_zeros(lst) nr_ones = utils.find_ones(lst) marker = 1 if nr_zeros == nr_empty + nr_ones else None marker = 0 if nr_ones == nr_empty + nr_zeros else marker return [marker if x is None else x for x in lst] def apply_tr...
The code recursively applies two transformations—equal_numbers and apply_triple_rules_on_row—to a row until it stabilizes, returning the unchanged row once consecutive transformations produce identical results.
def apply(row): new_row = equal_numbers(row) new_row = apply_triple_rules_on_row(new_row) return new_row if row == new_row else apply(new_row)
def generate_polynomial_features(self, X): """ Maps X to an mth degree feature vector e.g. [1, X, X^2, ..., X^m]. Parameters -------------------- X -- numpy array of shape (n,1), features Returns -------------------- Phi -- numpy array ...
The code performs polynomial regression using stochastic gradient descent (SGD) to minimize least squares error. It fits a (d-1)th-degree polynomial to input data (X, y) by iteratively updating coefficients (self.coef_) with SGD. The algorithm processes each sample, adjusts coefficients via gradient steps, tracks error...
def fit_SGD(self, X, y, eta=0.01, eps=1e-10, tmax=1000000, verbose=False): """ Finds the coefficients of a {d-1}^th degree polynomial that fits the data using least squares stochastic gradient descent. Parameters -------------------- X -- numpy ...
def extract_dictionary(infile): """ Given a filename, reads the text file and builds a dictionary of unique words/punctuations. Parameters -------------------- infile -- string, filename Returns -------------------- word_list -- dictionary, (key, value) pairs are (word, ...
The code performs a text classification pipeline using SVM, including data preprocessing, hyperparameter tuning via cross-validation, model training, evaluation with multiple metrics, feature importance analysis, and optional prediction on held-out data.
def main(): # read the tweets and its labels dictionary = extract_dictionary('../data/tweets.txt') test_extract_dictionary(dictionary) # Turned this into a tuple that returns the vector AND a list of words in order input_data = extract_feature_vectors('../data/tweets.txt', dictionary) X = input_...
def __list_configs__(self, arr = []) -> list: '''List all .config files from a directory''' for file in listdir(self.path): if file.find('.config') > -1: arr.append(file) return arr def loadConfig(self) -> None: if self.configs != []: if len(self.c...
This code initializes a configuration manager by setting default attributes, determining the config file path, listing existing configurations, and conditionally loading or generating a new config based on `auto_load` and `generate_new` parameters. It prepares the object for managing user settings, cooldowns, and other...
def __init__(self, auto_load = True, generate_new = False) -> None: self.channel_id = None self.user_token = None self.ocr_api_key = None self.user_cooldown = None self.bait = None self.auto_buff = None self.buff_length = None self.fish_on_exit = None ...
def _create_cells(self): self._cells = [[Cell(self._win) for _ in range(self._num_rows)] for _ in range(self._num_cols)] for i in range(self._num_cols): for j in range(self._num_rows): self._draw_cell(i, j) def _break_entrance_and_exit(self): self._cells[0][0].has_to...
This code initializes a maze by creating a grid of cells, setting up entrance/exit, breaking walls recursively to generate paths, and solving the maze using DFS and BFS algorithms. It handles randomization via a seed, resets visited states, and executes both solving methods within the constructor.
def __init__(self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None): self._cells = [] self._x1 = x1 self._y1 = y1 self._num_rows = num_rows self._num_cols = num_cols self._cell_size_x = cell_size_x self._cell_size_y = cell_size_y ...
def get_book(tui): tui.clear() book = "" books = [] for dir in os.listdir("output"): dir_fp = f"output/{dir}" if not os.path.isdir(dir_fp) or dir == ".logging": continue books += [dir] if not os.path.isfile(dbfp): with safer.open(dbfp, "w") as dbf: ...
The main task of the code is to process a book using a Tui object in a loop, adjusting speed dynamically. It sets process priority, retrieves the book, and repeatedly calls play_ch with the current speed. If play_ch succeeds, it rechecks the book; if the book is unavailable, it exits. The loop continues until the book ...
def main(tui = Tui()): os.nice(19) book = get_book(tui) if book is None: return 0 while True: speed = get_speed(tui) if play_ch(speed, book,tui) == 1: book = get_book(tui) if book is None: return 0
def get_dest(tui, retries=0): if retries >= 10: tui.place_text("Nothing to synth", row = lines_offset, height=1) exit(0) m = 100000 md = "" m_left = 0 for dir in os.listdir("output"): dir_fp = f"output/{dir}/.working" if not os.path.isdir(dir_fp): continu...
This code synthesizes audio from text blocks into MP3 files using a TTS model. It manages directories, tracks progress via a chapter counter, and updates a UI. If an MP3 file for a chapter doesn't exist, it retrieves text blocks, synthesizes audio, merges files, and increments the chapter counter. The loop continues un...
def main(tui=Tui()): global lines_offset tui.clear_box(row=lines_offset) dest, _= get_dest(tui) ch = 0 model = tts_models[0] while True: dest, last = get_dest(tui) folder = f"output/{dest}" working = f"{folder}/.working" ch_dir = f"{working}/ch" sch_fp = ...
def find_max_fixed(sudoku): old_len = len(sudoku) possibles = calc_possibles(sudoku) sudoku = dict_to_list(possibles) while old_len < len(sudoku): old_len = len(sudoku) possibles = calc_possibles(sudoku) sudoku = dict_to_list(possibles) return sudoku def calc_possibles(sudoku...
This function reduces Sudoku possibilities by recursively selecting cells with the fewest options, testing each possibility, and pruning invalid paths. It limits recursion depth to 3, appending valid states to WRAPPER when all cells have single possibilities.
def reduce_possibility(sudoku, total): if total > 3: raise ValueError("a specfic thing happend") sudoku = find_max_fixed(sudoku) possibles = calc_possibles(sudoku) len_possibles = [] for key in possibles: len_possibles.append([key, len(possibles[key])]) if max([x[1] for x in len...
def handleGetTeam(self, id): self.db = nbaDB() team = self.db.getTeam(id) if team is None: self.handleNotFound() self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(bytes(json.dumps(team), "...
This code handles GET requests by parsing the request path to determine the collection (e.g., "teams" or "stats") and optional member identifier. It routes requests to specific handler methods like handleGetTeam, handleGetTeams, handleGetStat, or handleGetStats based on the parsed path, defaulting to handleNotFound for...
def do_GET(self): print("This code will handle all incoming GET requests.") print("The request path is:", self.path) paths = self.path.split("/")[1:] collection = paths[0] if len(paths) > 1: member = paths[1] else: member = None if collec...
def check_pew_rm(seats_gpdf, allocated_seats, available_seats): pews_to_chk = list() for seat in allocated_seats: pew = seats_gpdf.loc[seats_gpdf['seat_id'] == seat] pew_id = pew.iloc[0]['pew_id'] if pew_id not in pews_to_chk: pews_to_chk.append(pew_id) for pew in pe...
This function performs seat allocation analysis for a venue using geospatial data. It initializes seat availability based on reserved seats and pews, then randomly allocates remaining seats following specific rules for groups of 3, 4, and 5 seats. Metrics like total pews, seats, and allocation patterns are calculated a...
def run_seat_allocation_analysis(seed, in_vec_file, in_vec_lyr, out_vec_file, out_metrics_file): rn_gen = numpy.random.default_rng(seed) gpdf_all = geopandas.read_file(in_vec_file, layer=in_vec_lyr) gpdf_all['allocated_seats'] = gpdf_all['reserved_seats'] gpdf_all['available_seats'] = numpy.ze...
def _get_certificate(self, cert_data): formatted = cert_data.public_bytes(serialization.Encoding.PEM).decode('utf-8') cert_str = "" for line in formatted.split("\n"): if not re.match(r'^-----(BEGIN|END) CERTIFICATE', line): cert_str += line else: ...
The function `enroll_certificates` prepares and submits a certificate enrollment request by gathering TPP and CA certificates, structuring them into a JSON payload with roles, and sending a POST request to the specified enrollment URL for TPP registration.
def enroll_certificates(self, enrolment_url, ca_interm_file_path, ca_root_file_path, tppId, commercial_name, roles="[ \"PSP_AI\", \"PSP_PI\", \"PSP_IC\", \"PSP_AS\" ]"): qwac_cert = self._get_certificate(self._get_cert_data(self.cert[0])) ca_cert = self._get_certificate(self....
def create_student(self, usn='CS01', name='samarth'): cl = self.create_class() u = self.create_user() return Student.objects.create(user=u, class_id=cl, USN=usn, name=name) def create_course(self, id='CS510', name='Data Struct', shortname='DS'): dept = self.create_dept(id='CS2') ...
This test verifies the attendance view's functionality by creating a student, logging in, setting up an assignment with a course and teacher, requesting the attendance page for the student, and checking if the response is successful (200 status) and contains the expected AttendanceTotal object in the context.
def test_attendance_view(self): s = self.create_student() self.client.login(username='test_user', password='test_password') Assign.objects.create(class_id=s.class_id, course=self.create_course(), teacher=self.create_teacher()) response = self.client.get(reverse('attendance', args=(s.USN,...
def button_start(values: dict, cli: str) -> 'tuple[str, str]': ''' Run buttons starting with "Start" ''' cli.append("start") if values['starttime'] != '': cli.append(values['starttime']) result_display = "Started: " + values['taskdesc'] + " at " + values['starttime'] ...
This function maps GUI button events to TimeWarrior CLI commands, executes them, and returns output/results. It constructs CLI commands based on event types (e.g., Start/Track/Stop), calls handler methods to modify commands, executes them via execute_cli(), and returns (CLI output bytes, display message). It handles 12...
def button_logic(self, event: str, values: dict) -> 'tuple[bytes, str]': ''' Execute Button based events executing TimeWarrior CLI commands Command line is extended based on the button selection and outputs of the hander functions when used ''' cli = [config.CLI_BASE_COM...
def user_id_validation(intent_request): session_attributes = get_session_attributes(intent_request) slots = get_slots(intent_request) slot_values = get_slot_values(intent_request) email = slot_values['email'] if not email: return delegate(intent_request, session_attributes, slots, "UserIdInt...
The code handles intent requests by dispatching to appropriate validation or fulfillment functions based on the invocation source and intent name. If the source is 'DialogCodeHook', it validates user input (e.g., for 'UserIdIntent') or triggers validation logic. If 'FulfillmentCodeHook', it fulfills the intent (e.g., p...
def dispatch(intent_request): invocation_source = intent_request['invocationSource'] intent_name = intent_request['sessionState']['intent']['name'] # Dispatch to your bot's intent handlers print("###dispatching###") if invocation_source == 'DialogCodeHook': if intent_name == 'UserIdIntent': ...
def _hosts_file_is_valid(self) -> bool: """ Check if the hosts file exists and is readable and writable :return: bool """ return self._hosts_file_is_readable() and self._hosts_file_is_writable() def _validate_ip(ip_local: str) -> bool: """ Validate an IP address (...
The main task of the code is to add a valid IP-hostname entry to the hosts file, ensuring no duplicates exist. It validates inputs, checks for existing entries, and appends the new entry at a specific position marked by `start_markers_index`, updating file markers afterward. It returns `True` on success or `False` if v...
def _add_entry(self, _ip: str, hostname: str, print_note=True) -> bool: """ Add an entry to the hosts file :param _ip: str (IPv4 or IPv6) :param hostname: str (e.g. example.com, raspi, ...) :param print_note: bool (default: True) :return: bool """ if not s...
def _check_if_markers_exist(self) -> bool: """ Check if the markers exist in the hosts file :return: bool """ if not self._hosts_file_is_readable(): raise FileNotFoundError(f"Hosts file not found or not readable at {self.hosts_file_path}.") found_markers: lis...
The main task of the code is to initialize a HostsFile object by setting the hosts file path, checking if required markers exist and if the file is writable, setting up the hosts file if needed, and identifying the start and end marker indices for subsequent operations.
def __init__(self, hosts_file_path: str = HOST_FILE): """ Initialize the HostsFile object :param hosts_file_path: str """ self.hosts_file_path = hosts_file_path if not self._check_if_markers_exist() and self._hosts_file_is_writable(): self._setup_hosts_file()...
def _save_backup_of_hosts_file(self) -> None: """ Save a backup of the hosts file :return: None """ if not self._hosts_file_is_readable(): raise FileNotFoundError(f"Hosts file not found or not readable at {self.hosts_file_path}.") if not os.path.exists(self.B...
This function updates entries in a hosts file by replacing an existing IP or hostname with new values, ensuring validation of inputs, checking for matching identifiers, and handling errors. It creates a backup, updates matched lines, and removes duplicates post-modification.
def update_entry(self, identifier: str, new_ip: str = None, new_hostname: str = None) -> None: """ Update an entry in the hosts file :param identifier: str :param new_ip: str :param new_hostname: str :return: None """ self._save_backup_of_hosts_file() ...
def clear_entries(self, with_backup: bool = True) -> bool: """ Remove all entries between the markers :return: bool """ if with_backup: self._save_backup_of_hosts_file() if not self._hosts_file_is_valid(): print(f"Hosts file not found or not reada...
This function manages hosts file backups by listing, restoring, or removing backups based on parameters. It lists recent backups, restores specific versions (latest or named), removes backups (all, last, oldest, or specific), or saves a new backup if no action is specified.
def backup(self, hostsfile: str = None, backup_dir: str = None, list_backups: int = None, restore: str = None, remove: str = None) -> None: """ Backup the hosts file :param hostsfile: str (default: None) :param backup_dir: str (default: None) :param list_backups: i...
def install_extra_requirements(): run('pip install awscli') def setup_django(): django.management('migrate') django.management('collectstatic --noinput') def setup_logs(): """ Create log directories. """ sudo('mkdir %(SERVER_LOG_PATH)s' % server_config.__dict__) sudo('touch %(SERVER_LOG_...
The code defines a `setup()` function that prepares a server environment for deployment by installing additional requirements, configuring Django, setting up logging, installing SSL certificates, and deploying configuration files. Its main task is to automate server preparation steps necessary for deploying a Django ap...
def setup(): """ Setup servers for deployment. """ install_extra_requirements() setup_django() setup_logs() setup_cert() deploy_confs()
def is_inside_bbox(self, left, right, top, bottom, area): area_details = area test_point_left = (left,bottom) test_point_right = (right,bottom) area_left = self.is_inside_rectangle(area_details, test_point_left) area_right = self.is_inside_rectangle(area_details, test_po...
The main task of the code is to track customer movements, detect behaviors (e.g., walking, viewing, reaching), match motion patterns to predefined primitives, apply prioritization rules to resolve conflicting behaviors, and visualize detected behaviors on a frame. It updates customer behavior states in real-time using ...
def update_actions(self, tracking, tl_area,frame_aux, y_coor=120): # threshold_1 is used to not take movements with a distance shorter than it for consideration # threshold_2 is used to take movements with a distance shorter than it as a stop state # timeout is the amount of primitives to be use...
def init_config(self, args): try: print('Getting parameters') self.videos = args.get('videos', []) self.cameras = args.get('cameras', []) self.division_area = args.get('division_area') self.refresh_threshold = args.get('refresh_threshold', self.refresh...
The code processes local video files by initializing configurations, tracking objects within specified camera areas, generating processed videos with tracking visualizations, uploading results to the cloud, and returning a JSON summary of processed videos, cloud upload responses, and errors. It handles frame-by-frame t...
def process_videos(self, data): print(data) self.init_config(data) if self.local_videos == []: print('There are no videos to process') json_response = json.dumps({'videos_processed': len(self.local_videos), 'errors': self.errors}) return json_response ...
def update_height_and_balance(node): node.height = 1 + max(get_height(node.left), get_height(node.right)) balance = get_balance(node) return node, balance def restore_balance(node, balance): if balance > 1: if get_balance(node.left) >= 0: return right_rotation(node) else: ...
The function inserts a value with a specified priority into a binary tree, recursively placing it in the left or right subtree based on priority comparison. It updates the tree's height and balance factor, and if imbalance exceeds a threshold, it restores balance through rotations, ensuring the tree remains balanced fo...
def insert_into_queue(root_node, value, priority): if not root_node: return Node(value, priority) elif priority <= root_node.priority: root_node.left = insert_into_queue(root_node.left, value, priority) else: root_node.right = insert_into_queue(root_node.right, value, priority) r...
def update_height_and_balance(node): node.height = 1 + max(get_height(node.left), get_height(node.right)) balance = get_balance(node) return node, balance def restore_balance(node, balance): if balance > 1: if get_balance(node.left) >= 0: return right_rotation(node) else: ...
This function deletes the node with the highest priority from a tree-like data structure, recursively handles right subtree deletion, updates node balance, rebalances if necessary, and finally returns the new highest-priority node. It maintains tree balance during deletion operations for efficient priority queue manage...
def delete_from_queue(root_node): if not root_node: return root_node if not root_node.right: return root_node.left root_node.right = delete_from_queue(root_node.right) root_node, balance = update_height_and_balance(root_node) if abs(balance) > 1: return restore_balance(root_n...
def make_neighbors_zero(grid): mines_positions = [] for y in range(len(grid)): for x in range(len(grid[0])): if grid[y][x] == 0: mines_positions.append([y, x]) for position in mines_positions: position_neighbors = get_neighbors(grid, position[1], position[0]) ...
The code finds the shortest safe path in a grid by first converting hidden mines to zeros, identifying valid start points, and then computing the shortest route from these points, returning -1 if no valid path exists.
def the_shortest_safe_route(grid): if not grid or not grid[0]: return -1 grid_without_hidden_mines = make_neighbors_zero(grid) start_points = find_start_points(grid_without_hidden_mines) if not start_points: return -1 return find_shortest_route(start_points, grid_without_hidden_mines...
def read_input(file_name): input_matrix = [] with open(file_name, 'r') as file: for line in file: row = list(map(int, line.split())) input_matrix.append(row) file.close() return input_matrix def the_shortest_safe_route(grid): if not grid or not grid[0]: return...
The main task of the code is to find the shortest safe route in a grid. It reads the grid data from the input file, computes the shortest safe path using the `the_shortest_safe_route` function, and writes the result to the specified output file.
def find_shortest_safe_route(file_input,file_output): grid = read_input(file_input) result = the_shortest_safe_route(grid) write_output(file_output, result)
def cdc_bd(self, flavor, i, j, k, stateA): # hopping operator: anihilation operator followed by creation operator # - returns sign and new state # - first we check that no boson is hopping if self.reducedDOF[j]*self.reducedDOF[j]<15: return 0, stateA found, stateB =...
The main task of the code is to construct a quantum Hamiltonian for a system with fermions, spins, and bosons. It initializes interaction parameters, processes boson couplings, and builds sparse Hamiltonian matrices for each quantum number subspace. The Hamiltonian incorporates terms like Hubbard-U, hopping, spin-spin ...
def getH(self, parameters, **kwargs): # Input: # L1: is the number of bonds, # L2: sets the interaction range # Qztot: total particle number # Sztot: total magnetic quantum number # # First we collect all the states in the right subspace. #...
def createDirectories(self): self.models_dir = os.path.join(os.path.dirname( os.path.realpath(__file__)), "models/") self.models_tmp_dir = os.path.join(os.path.dirname( os.path.realpath(__file__)), "models_tmp/") self.log_dir = os.path.join(os.path.dirname(os.path.realpa...
The code initializes a class for a multi-stage training process, setting up environment parameters, model locations, and directories. It prepares to iterate through input parameters, changing stages and executing training for each entry. Attributes store results across stages, suggesting a framework for iterative model...
def __init__(self, envParameters, initModelLoc=None) : self.step_stage = 0 self.step_total = 800000 self.env = None self.n_cpu = 8 self.modelLoc = initModelLoc self.model = None self.stage = -1 self.envParameters = envParameters self.createDirecto...
def bookend_instructions(instructions): """Check instructions type and wrap with isready and quit commands""" assert(isinstance(instructions, list)) assert(len(instructions) > 1) if instructions[-1] == 'quit': if instructions[-2] != 'isready': instructions[-1] = 'isready' ...
The main task of the code is to execute the Leela Chess Zero (Lc0) engine as a subprocess, process a set of chess-related instructions (either provided or read from 'inputs.txt'), capture and parse the engine's output, and return parsed position information, moves, and process logs. The function handles input preparati...
def main(instructions=None, verbose=0): """Call Lc0 directly as a subprocess with a fixed set of instructions.""" if instructions is None: with open('inputs.txt') as f: instructions = f.read().splitlines() instructions = bookend_instructions(instructions) proc = start_leela() en...
def least_squares_GD(y, tx, initial_w, max_iters, gamma, log=False, store=False): """Compute the Gradiant Descent with least squares loss function. Parameters: y (numpy.ndarray): An array with shape (n,1) tx (numpy.ndarray): An array with shape (n,m) ...
The function `get_w_loss` applies a specified algorithm (e.g., least squares, ridge regression, logistic regression) to compute weights (`w`) and loss based on input data `y` and `x`. It supports iterative descent methods (like GD/SGD) with parameters for iterations, learning rate, and regularization. The method determ...
def get_w_loss(y, x, method, initial_w=0, max_iters=10, gamma=0.00000005, threshold=1e-08, logs=False, batch_size=1, lambda_=0.005, store=False): """applies the algorithm described by <method>. by default as the awaited behaviour for the project, but offers some possible enhancements (batch_size,threshold, logs, st...
def yy3(tx, ld): N, n = tx.shape tx3 = [] for i in range(N): l2 = tx[i] tx3 += [np.delete(l2, ld)] return np.array(tx3) def yy2(tx, k, ld): N, n = tx.shape tx2 = [] y = [] for i in range(N): z = tx[i, k] if z != -999: l = tx[i] tx2...
The function completes missing values (-999) in specific columns of a matrix using multiple regression. It trains separate regression models for each column with missing data, predicts missing entries using non-missing data, and replaces -999 values with predicted values while retaining existing data. The result is a c...
def Datas_completion_lacking_values_predicted(tx): """complete tx using a regression Args: tx (numpy.ndarray): with shape(n,m) Returns: numpy?ndarray: with shape (n,m) """ N, n = tx.shape # columns with lacking values (-999) l = [0, 4, 5, 6, 12, 23, 24, 25, 26, 27, 28] t...
def read_table_pair_data_from_config_file(): try: input_csv = "config/tables_to_compare.csv" table_pairs = pd.read_csv(input_csv) return table_pairs except FileNotFoundError as e: log_error(f"Input file not found: {e.filename}") sys.exit(1) def load_database_configuration...
The main task of the code is to validate data integrity between source and target databases by comparing table structures and relationships. It reads configuration files to establish database connections, iterates through table pairs to check primary/foreign key constraints, logs errors during validation, and generates...
def main(): # Get the table info on which validation needs to be performed table_pairs = read_table_pair_data_from_config_file() # Load the source and target config source_config, target_config = load_database_configurations() # Get the source and target connections source_connection, source_cur...
def load_prompt(prompt_cfg): log.debug("Loading prompt %s", prompt_cfg) prompt = prompt_cfg.get("prompt") if not prompt: log.error("Prompt not defined in %s", prompt_cfg) return env = prompt_cfg.get("env", []) match env: case list(): load_env_list(prompt, env) def...
The function `load_prompts` processes a list of prompt configurations by loading prompts, volumes, and ports for each. It identifies plugin names from prompt metadata and conditionally applies default volume or port settings from the global `settings` object into `settings_maps`, based on configuration flags. This inte...
def load_prompts(prompts, settings): for prompt_cfg in prompts: load_prompt(prompt_cfg) load_volumes(prompt_cfg) load_ports(prompt_cfg) plugin_name = prompt_cfg.get('prompt').split()[0] log.debug("use default volumes? %s", prompt_cfg.get("default_volumes")) if prompt_...
def stop_clock(self): if not self.is_clock_ticking: return time_now = datetime.datetime.now() if self.white_to_move: elapsed_time = time_now - self.start_time_white elapsed_milliseconds = np.floor(elapsed_time.total_seconds()*1000) self.time_left_w...
The main task of the code is to manage a game clock by stopping it, checking for a win condition, and restarting it if the game is not yet ended. This function ensures the clock is properly reset and reactivated based on game state, likely part of a turn-based or timed game mechanism.
def tick_clock(self): self.stop_clock() self.check_for_clock_win() if not self.is_game_ended(): self.start_clock()
def _best_criteria(self, X, y, feat_idxs): """ Find the best split criteria for the decision tree. Parameters: - X: Input features (numpy array). - y: Target values (numpy array). - feat_idxs: Indices of the features to consider for splitting. Returns: -...
This function recursively builds a decision tree by selecting the best feature and threshold to split the data, creating left and right subtrees, and returning a node. It stops when max depth is reached or samples are insufficient, creating a leaf node with the average target value. Random feature selection and recursi...
def _grow_tree(self, X, y, depth=0): """ Recursively grow the decision tree. Parameters: - X: Input features (numpy array). - y: Target values (numpy array). - depth: Current depth of the tree (default is 0). Returns: - node: The root node of the decisio...
def _most_common_label(self, y): """ Find the most common label in a set of labels. Parameters: - y: Target labels (numpy array). Returns: - most_common: Most common label. """ counter = Counter(y) most_common = counter.most_common(1)[0][0] ...
The main task of the code is to recursively construct a decision tree by selecting the best feature and threshold to split the data, creating left and right child nodes, and stopping when maximum depth is reached, all labels are the same, or minimum samples per split are met. It returns a tree node structure with split...
def _grow_tree(self, X, y, depth=0): """ Recursively grow the decision tree. Parameters: - X: Input features (numpy array). - y: Target labels (numpy array). - depth: Current depth of the tree (default is 0). Returns: - node: The root node of the decisio...
def partitions(self, mode="id", distributed=True): """return a list of available partitions (the first is highest). *Parameters* - **mode** : str (default 'id') - AnaDfield representation ('field', 'id', 'index') - **distributed** : boolean (default True) - Include only distri...
The function categorizes fields into primary, secondary, unique, mixte, and variable groups based on the specified mode (e.g., 'id', 'field') and distribution settings. It processes input partitions to determine hierarchical relationships, filters unique fields, identifies mixte dimensions, and classifies remaining fie...
def field_partition(self, mode="id", partition=None, distributed=True): """return a partition dict with the list of primary, secondary, unique and variable fields. *Parameters* - **mode** : str (default 'id') - AnaDfield representation ('field', 'id', 'index') - **parti...
def partitions(self, mode="id", distributed=True): """return a list of available partitions (the first is highest). *Parameters* - **mode** : str (default 'id') - AnaDfield representation ('field', 'id', 'index') - **distributed** : boolean (default True) - Include only distri...
This function generates a dictionary mapping each field's ID to a list of related field IDs based on their categorization (primary, unique, etc.) within a specified partition. It adjusts relationships according to parameters like 'primary' (filtering to primary fields) and 'noroot' (replacing 'root' with primary fields...
def relation_partition(self, partition=None, primary=False, noroot=False): """return a dict with the list of relationships for fields in a partition. *Parameters* - **partition** : list (default None) - if None, partition is the first - **primary** : boolean (default False) - if True, ...
def openFile(self,form ): """ Opening file browser to import the txt file. :param form: The current layout to display the message box error . """ if self.checkEnvironment(2): self.initSettings() options = QFileDialog.Options() options |= QFileD...
This code initializes a user interface for a Twitter Bot Detector application. It loads a stylesheet, sets window properties, creates a main frame with a vertical layout, adds buttons (return, help), a file browser, model settings, and a predict button. It organizes UI elements using QFormLayout and QGridLayout, integr...
def initUI(self): file = QFile(':css/StyleSheet.css') file.open(QFile.ReadOnly) stream = QTextStream(file) text = stream.readAll() self.setStyleSheet(text) self.setObjectName("Windowimg") self.setWindowTitle(self.title) self.setWindowIcon(QIcon(':Pictures/...
def Create_Tokenizer(self,text_for_tokenizer): global tokenizer tokenizer.fit_on_texts(text_for_tokenizer) def Build_Train_Set(self,X_train, y_train): global bots_list global max_input_lenght global tokenizer # built two lists with tweets and labels tweets_train = [x for x in X_train] labels_train = ...
This code creates a text classification model to distinguish between bot and human tweets. It loads and processes tweet data, splits it into training/test sets, tokenizes text, builds a model using the processed data, trains it with specified parameters, and saves the model and tokenizer for future use.
def create_model(self,model_name = 'arcii_first_version_with_two_inputs', bots_file_path = 'bots_tweets.txt' , human_file_path = 'human_tweets.txt', test_size_input = 0.3, batch_size=50, epochs=10): global bots_list global tokenizer global max_input_lenght tokenizer = Tokenizer() bots_list =[] max_inp...
def convert_string_to_array(string): """ convert_string_to_array converts an input hex string into a 4x4 matrix Parameters --------------- string : string the string that you want to convert into a square matrix Returns --------------- list a list of lists filled ...
This function encrypts a 16-byte hex string using AES-128 encryption. It converts the plaintext to an array, applies the initial round key, then performs 9 rounds of substitution, row shifting, column mixing, and key addition. The final round omits column mixing. The result is converted back to a string and returned as...
def encrypt_one_block(self,plaintext): """ encrypt_one_block should encrypt 16 byte input via aes 128 Parameters --------------- plaintext: string 16 byte hex string (32 chars) Returns --------------- string the ciphertex...
def convert_string_to_array(string): """ convert_string_to_array converts an input hex string into a 4x4 matrix Parameters --------------- string : string the string that you want to convert into a square matrix Returns --------------- list a list of lists filled ...
This code decrypts a single AES block of ciphertext by applying the inverse AES encryption steps. It starts with the last round key, then iteratively applies inverse operations (shift rows, substitution bytes, mix columns) with corresponding round keys for rounds 1-9, omitting mix columns in the final round. The proces...
def decrypt_one_block(self, ciphertext): state = convert_string_to_array(ciphertext) # start by adding the last round key state = add_round_key(state, self.round_keys[10]) # For rounds 1 - 9 we do the full inverse process for x in range(1,10): state = i_matrix_shift_...
def get_outlier_fit(x, x_spiked, name, pcutoff, spike_vals, prefix): x_body = get_body(x) n_bins = np.max([int(len(x_body)/200), 50]) out = test_monotonicity(x_body, x, 100*pcutoff, n_bins, not_sensitive = True) is_monotonic, mirrored_data, status = out num_unique = len(np.unique(x_body)) is_low...
The function `compute_outliers` processes a spiked dataset by removing outliers and spikes, computes key statistical metrics (e.g., min, max, median), and returns cleaned data, overlap area, and a summary of outlier-related statistics. It filters NaN values, applies spike removal, fits a model using a percentile cutoff...
def compute_outliers(x_spiked, name, prefix, pcutoff): x_spiked = x_spiked.astype(float) x_spiked_old = COPY(x_spiked) x = COPY(x_spiked)[np.isnan(x_spiked)==False] x, spike_vals, decreases = remove_spikes(x, x_spiked, name, prefix, 0, [], []) outlier_info = [name] old_count = np.sum(np.isnan(...
def check_audio_files(self, entry, name): # * Checks all Audio Files for audio_extension in file_extensions.audio_extensions: if name.endswith(audio_extension) or name.endswith(audio_extension.upper()): dest = folder_path.AUDIO_DIR_PATH move_file(dest, entry, name) ...
The code defines a method `on_modified` that monitors directory changes. It scans the source directory for entries, extracts filenames, and checks each file against audio, video, image, and document type handlers to process or validate them based on their type.
def on_modified(self, event): with scandir(folder_path.SOURCE_DIR_PATH) as entries: for entry in entries: name = entry.name self.check_audio_files(entry, name) self.check_video_files(entry, name) self.check_image_files(entry, name) ...
def wait_response(con): while True: resp = con.recv(1024).decode() if(resp.split(":")[0] == "OK"): break def broadcast_send(msg): for conn in connection_list: conn.send(msg) total_resp = 0 while total_resp < len(connection_list): for conn in connection_list: ...
This function manages a multiplayer game by broadcasting player counts, initiating battles when two players are connected, collecting action choices (ATTACK), coordinating attack selections, and triggering a battle process with collected player actions.
def threaded_clients(con,total): con.send(("ID:" + str(total)).encode()) wait_response(con) #print(total) broadcast_send(("MSG:Number of players " + str(total)).encode()) if(total == 2): broadcast_send("MSG:The battle will start!".encode()) print("The battle will start!") ...
def get_device_names(devices): return [d['hostname'] for d in devices] def parse_cdp_output(cdp_data, dev): """ Find local interface, remote name, remote interface, remote platform, remote capabilities return tuple [0] links, e.g. [{ "router1": "Ten1/2, "rout...
The code processes devices' CDP data to generate a network topology and interface mappings in CML format. It parses device links, validates interfaces, constructs a topology using templates, adds links, and optionally external connectors. The result is returned as JSON with 'topology' and 'mappings' for automation work...
def main(): arguments = dict( devices=dict(required=True, type='list', elements='dict'), device_template=dict(required=True, type='dict'), default_mappings=dict(required=True, type='dict'), ext_conn=dict(required=False, type='bool', default=True), start_from=dict(required=Fal...
def intf_truncate(data, intf_dict=None): if not data: return {} if intf_dict is None: return data regex_list = intf_dict.keys() temp_interface_list = [] temp_stp_interface_list = [] data_out = data.copy() if "mdd:openconfig" in data: oc_data = data["mdd:openconfig"...
The main task of the code is to process input data through a sequence of transformations: truncating and translating interface configurations, truncating general configuration data, and truncating VLAN-related data. The function applies these operations sequentially using provided dictionaries and lists to modify netwo...
def config_xform(data, intf_dict=None, truncate_list=None, vlan_list=None): data = intf_truncate(data, intf_dict) data = intf_xlate(data, intf_dict) data = config_truncate(data, truncate_list) data = vlan_truncate(data, vlan_list) return data
def __aStarAlgo(self): #EXPERIMENTAL self.aStar = [AStar((self.snakeLinks[0].getLinkX(),self.snakeLinks[0].getLinkY()),(self.foodX, self.foodY),self.snakeLinks)] self.aStar = self.aStar[0].algo() def __eatFood(self): if (self.snakeLinks[0].getLinkX() == self.foodX and self.snakeLinks[0]....
This method handles snake head movement using A* pathfinding, processes user input for directional changes, checks boundary collisions to trigger game over, and updates snake segments. It alternates between A* path execution and manual movement, adjusts velocity vectors based on key presses, and triggers food consumpti...
def __headMove(self): #self.snakeLinks[0].moveLink(self.snakeX,self.snakeY) self.ticksPast = pygame.time.get_ticks() #Directional Maniplulation self.keyPressed = pygame.key.get_pressed() if(self.ticksPast % 10 == 0): if(self.aStar): self.snakeLinks[0]...
def update_cluster(self, train_type, input_embeddings): print("start train %s cluster" % train_type) if train_type == "aspect": for i in range(self.epoch): self.aspect_model.fit(input_embeddings) if opt.cluster == "KMeans": cluster_centers = self.a...
The code trains a model to disentangle aspect and sentiment embeddings from input data, clustering them into topics and sentiments. It initializes or updates clusters, merges embeddings, identifies top sentences, and saves results. The main task involves disentangling representations, clustering, and generating structu...
def train(self, model, input_embeddings, sentences, initialise=False, save_embedding=opt.save_embedding, evaluate=True): if initialise: aspect_labels, aspect_centers = self.update_cluster("aspect", input_embeddings) aspect_labels, aspect_centers = self.merge(input_embeddings, aspect_labe...
def fitness(self): if self._fitness is None: self.calculate_fitness() return self._fitness def get_column(level, column): """returns a string representation of a column of level""" string = "" for j in range(height): string += level[j][column] return string def mutate...
The code generates offspring by performing crossover between two parent genomes, using their fitness values to probabilistically select blocks from each parent. It ensures valid block placements through sanity checks (e.g., no floating pipes, enemy limits), mutates the genome, and enforces essential elements like groun...
def generate_children(self, other): new_genome = copy.deepcopy(self.genome) # Leaving first and last columns alone... # do crossover with other # Basic idea is to loop through 1 block at a time and randomly choose a block from one of the two parents, but # have the odds of a spe...
def fitness(self): if self._fitness is None: self.calculate_fitness() return self._fitness def get_column(level, column): """returns a string representation of a column of level""" string = "" for j in range(height): string += level[j][column] return string def mutate...
The main task of the code is to generate a child genome through weighted crossover between two parent genomes (self and other), where each tile is selected from either parent based on their fitness. It ensures valid block placements by sanity-checking rules (e.g., no floating pipes, enemy limits), applies mutations, an...
def generate_children(self, other): new_genome = copy.deepcopy(self.genome) # Leaving first and last columns alone... # do crossover with other # Basic idea is to loop through 1 block at a time and randomly choose a block from one of the two parents, but # have the odds of a spe...
def forward(self): """ student feature = encoder -> projection mlp -> prediction mlp | teacher feature = encoder -> projection mlp <-| """ # student net: forward source images self.feat_stu_S, self.seg_stu_S = self.net_student(self.img_S_aug) self....
This method optimizes model parameters by performing a forward pass, computing gradients via backward pass, updating weights with the optimizer, applying exponential moving average (EMA), and adjusting clustering centroids/pixel assignments. It increments the iteration counter after each training step to track progress...
def optimize_parameters(self): self.forward() self.optimizer.zero_grad() self.backward() self.optimizer.step() self.ema() self.update_centroid() self.update_pixel() self.iters += 1
def init_move_cmd_vel_pose(self): upperlegM1_angle = -1.55 upperlegM2_angle = -1.55 upperlegM3_angle = -1.55 lowerlegM1_angle = -0.7 lowerlegM2_angle = -1.55 lowerlegM3_angle = -1.55 headarm_angle = 0.0 headforearm_angle = 0.0 ...
The main task of the code is to initialize and control Gurdy's movement via the cmd_vel topic. It initializes movement parameters, waits for 5 seconds, then enters a loop to continuously determine movement direction and magnitude using `decide_movement()`, and executes jumps via the `jump()` method with calculated valu...
def movement_cmd_vel(self): """ We use the cmd_vel topic to move Gurdy """ print("START Init Move CMD vel...") self.init_move_cmd_vel_pose() time.sleep(5) print("Init Move CMD vel finished") while not rospy.is_shutdown(): # print("Loop...
def gurdy_flip(self): """ UPPER limits lower="-1.55" upper="0.0" LOWER limits lower="-2.9" upper="1.5708" :return: """ upperlegM1_angle = -0.7 upperlegM2_angle = -0.7 upperlegM3_angle = 0.0 lowerlegM1_angle = 0.0 lowerlegM2_angle = 0.0 ...
This function executes predefined movements for a robotic system by dispatching the input movement command to corresponding methods. It handles actions like flipping, stance adjustments, and jumps by calling specific functions like gurdy_flip() or gurdy_init_pos_sequence(). Unsupported movements trigger an error log.
def execute_movement_gurdy(self, movement): """ Executes a movement given """ if movement == "flip": self.gurdy_flip() elif movement == "basic_stance": self.gurdy_basic_stance() elif movement == "movement_stance": self.init_move_cmd_vel...
def create_net(self): net_dict = OrderedDict() net_dict["linear_layer_0"] = nn.Linear(self.num_inputs, self.hidden_size[0]) if self.layer_norm: net_dict["layer_norm_0"] = nn.LayerNorm(self.hidden_size[0]) net_dict["activation_0"] = self.get_activation(self.activation) ...
The main task of the code is to add a new layer to a neural network. If the hidden layer size has fewer than three elements, it extends the size, creates a new network, preserves existing parameters, and updates the network. Otherwise, it directly adds a node. This ensures proper layer configuration while maintaining m...
def add_layer(self): if len(self.hidden_size) < 3: self.hidden_size += [self.hidden_size[-1]] new_net = self.create_net() new_net = self.preserve_parameters(old_net=self.net, new_net=new_net) self.net = new_net else: self.add_node()
def create_net(self): net_dict = OrderedDict() net_dict["linear_layer_0"] = nn.Linear(self.num_inputs, self.hidden_size[0]) if self.layer_norm: net_dict["layer_norm_0"] = nn.LayerNorm(self.hidden_size[0]) net_dict["activation_0"] = self.get_activation(self.activation) ...
This method reduces the hidden layer size by truncating self.hidden_size to one element, creates a new network, preserves parameters from the original network, and replaces the old network with the new one. If hidden_size has only one element, it adds a new node instead.
def remove_layer(self): if len(self.hidden_size) > 1: self.hidden_size = self.hidden_size[:1] new_net = self.create_net() new_net = self.shrink_preserve_parameters(old_net=self.net, new_net=new_net) self.net = new_net else: self.add_node()
def winnerId(): #make sure input is integer while True: try: winner = input("which seat won? 0=draw,1=east,2=south,3=west,4=north: ") winner = int(winner) break except ValueError: print ("stop fucking around") #make sure input is in t...
The code simulates a four-player game with rounds and a rotating banker. It tracks scores, determines winners, handles draws by advancing the banker, and updates scores accordingly. The loop continues until both circle and banker reach 4, with player positions and scores printed each round.
def fourCircle(): #position of the round circle = 1 banker = 1 #players' current score score = [0,0,0,0] #seat seat = ["east","south","west","north"] while circle < 4 or banker < 4: #print info of current round print("circle = " + str(circle) + ", banker = ...
def cost_function(self, edge_corresp, plane_corresp, T): err = 0 for corresp in edge_corresp: r, _ = self.r(corresp, T, corresp_type='edge') err += self.e(r) for corresp in plane_corresp: r, _ = self.r(corresp, T, corresp_type='plane') err += sel...
This function estimates a 3D transformation (SE3) by iteratively minimizing a cost function using edge and plane correspondences. It updates the transformation matrix via Jacobian and Hessian derivatives, tracks inlier/outlier errors, and applies robust estimation with sigma scaling. The process repeats until convergen...
def fit(self, edge_corresp, plane_corresp, initial_T=None): T = mrob.geometry.SE3(np.zeros(6)) if not initial_T else initial_T iter_cnt = 0 initial_err = self.cost_function(edge_corresp, plane_corresp, T) errors = [initial_err + 1, initial_err] inlier_errors = [initial_err + 1...
def playing_draw(self): self.screen.fill(Black) self.screen.blit(self.maze, (Gap // 2, Gap // 2)) self.draw_coins() self.player.draw() draw_text('CURRENT SCORE: {}'.format(self.player.current_score), self.screen, [130, 15], 18, White, Start_Font) draw_te...
This code manages a game loop that runs while the game is active. It checks the current game state: if 'playing', it updates, draws, and handles events; if 'game over', it resets and displays the menu. The loop maintains a consistent frame rate and exits Pygame when the game ends.
def play(self): while self.running: if self.state == 'playing': self.playing_draw() self.playing_events() self.playing_update() elif self.state == 'game over': self.reset() self.game_over_menu() e...
def update_height(node): node.height = max(height(node.left), height(node.right)) + 1 def update_gamma(node): node.gamma = 1 + gamma(node.left) + gamma(node.right) def height(node): if node is None: return -1 else: return node.height def right_rotate(self, x): y = x.left ...
This function rebalances a binary tree by checking height differences between subtrees. It updates node heights and gamma values, then applies left/right rotations to correct imbalances, ensuring the tree remains height-balanced during insertions or deletions.
def rebalance(self, node): while node is not None: update_height(node) update_gamma(node) if height(node.left) >= 2 + height(node.right): if height(node.left.left) >= height(node.left.right): self.right_rotate(node) else: ...
def print_menu(options,selection): display_height = 4 current_menu = options s = selection -1 if selection - display_height < 0: down_vote = 0 elif selection - display_height > len(current_menu) - display_height: down_vote = 0 else: down_vote = selection - display_he...
This function handles menu navigation in an application by updating the current menu and option based on user selections. It transitions between main, info, settings, config, and about menus, triggers actions like time/date/drop settings, and displays the updated menu. The core task is to manage state changes and execu...
def onSelect(currentMenu,currentOption): #Main if currentMenu == Main_Menu: if currentOption == 1: currentMenu = Info_Menu currentOption = 1 print_menu(Info_Menu,currentOption) replaceInfoTime() elif currentOption == 2: currentMenu = Setting...
def e_step(self, xs): batch_size = len(xs) # E step log_gammas_batch = [] log_etas_batch = [] for batch_idx in range(batch_size): _, _, _, log_gammas, log_etas = self.forward_backward(xs[batch_idx]) log_gammas_batch.append(log_gammas) log_e...
This code performs one iteration of the EM algorithm for a probabilistic model. It calculates log-likelihood components during the E-step, updates model parameters in the M-step, and computes the total log-likelihood by combining initial state probabilities, transition probabilities, and observation probabilities weigh...
def learn_em(self, xs): # E step log_N1, log_Nj, log_Njk, log_gammas_batch, _ = self.e_step(xs) # M step self.m_step(xs, log_N1, log_Nj, log_Njk, log_gammas_batch) # log likelihood log_px = self.condition(xs) log_px = np.transpose(log_px, axes=[1, 2, 0]) ...
def setup_variables(self): self.init_v = tf.Variable(np.random.normal(0, 1, size=self.num_hidden_states), trainable=True, dtype=tf.float32) self.init = tf.nn.softmax(self.init_v, axis=0) self.A_v = tf.Variable(np.random.normal( 0, 1, size=(self.num_actions, self.num_hidden_states, s...
This method initializes a model by setting up variables, placeholders for input sequences, actions, and masks, computes the log-likelihood of the model's output, and defines an optimization step using Adam to minimize the negative log-likelihood, enabling training of probabilistic or reinforcement learning models.
def setup(self, seq=None, actions=None, mask=None): self.setup_variables() self.setup_placeholders(seq=seq, actions=actions, mask=mask) self.log_likelihood = self.likelihood() self.opt_step = tf.train.AdamOptimizer(self.learning_rate).minimize(- self.log_likelihood)
def LOAD_DATA(params_data): """function to load train/valid data""" # Read data filenames = params_data['filenames_train'] signalData = readSeismicData(filenames) # Train/Valid data split numSignal = signalData['time'].shape[0] numTrain = int(numSignal*params_data['train_data_split']) numValid = numTra...
This function generates training and validation datasets focused on "major slips" by selecting specific indices around slip locations from loaded data. It slices input/output data, adjusts indices with offsets, saves dataset sizes, and writes processed data into TFRecord files for machine learning model training and va...
def write_tfrecord_train_valid_data_major_slips(params_data, train_fail_index, valid_fail_index): """function to write train/valid tfrecord major slips data""" # Read Train/Valid data print('\nLoad Train/Valid major slips Data') train_data, valid_data, input_scaler_train, output_scaler_train = LOAD_DATA(params_...
def readSeismicData(filenames): """read acoustic emission and friction data""" filename_seismic_data = filenames[0] filename_shear_data = filenames[1] # acoustic emission data with h5py.File(filename_seismic_data, 'r') as f: wf_ae_data = f.get('wf_ae')[:] wf_ae_data = np.abs(wf_ae_data) # friction...
This function processes test seismic data by loading, scaling input/output signals, transforming data into windowed format, writing it to a TFRecord file, and saving scalers for later use in model inference.
def write_tfrecord_test_data(params_data, filenames_test): """function to write test tfrecord data""" # Read Test data start_time = time.time() print('\nLoad Test Data') signalData = readSeismicData(filenames_test) numSignal = signalData['time'].shape[0] # Input/output scalers numDataScaler = int(numSi...
def start_data_processing(wordstring): sns.set(font_scale=1.5) sns.set_style("whitegrid") all_tweets_no_urls = [remove_url(tweet) for tweet in wordstring['text']] all_tweets_no_urls[:500000000] lower_case = [word.lower() for word in all_tweets_no_urls] set(lower_case) words_in_tweet = [tweet.lower().split() for ...
The function performs data analysis by aggregating historical JSON/CSV files (excluding 'asset_classes') into a DataFrame for processing, or fetching live data via a unique ID. If live data lacks 'asset_word', it defaults to historical analysis, returning aggregated data or live results for further processing.
def start_data_analysis(unique_id): if unique_id == 'historical': print("Going for historical analysis") files_list = os.listdir() main_df = pd.DataFrame() for filename in files_list: if (filename.endswith(".json") or filename.endswith(".csv")) and ('asset_classes' not in filename): if filename.endswith...
def move_stepper(is_forward): GPIO.output(direction_pin, GPIO.HIGH if is_forward else GPIO.LOW) # Set direction GPIO.output(step_pin, GPIO.HIGH) time.sleep(delay) GPIO.output(step_pin, GPIO.LOW) time.sleep(delay) def move_stepper2(is_forward): GPIO.output(direction_pin2, GPIO.HIGH if is_forward...
This code initializes a system for tracking physical repetitions using accelerometer data, controlling stepper motors via slider inputs, and managing sessions through a Flask web app. It continuously processes sensor data to count repetitions, updates LEDs for feedback, and saves session data when tracking is disabled....
def main(): global prev_reps global tracking_enabled global folder_id global switch global prev_switch_state global slider_value rep_counter = RepCounter(threshold_multiplier=0.65) accel_manager = AccelerometerManager(bus_number=1, device_address=0x68) accel_manager.initialize()...
def isRoyalFlush(self, fplyrCard, collect=False): final_player_hand = fplyrCard hist = self.histogram(final_player_hand) for count in hist.values(): if count >= 5: key = list(hist.keys())[0] royal_flush = ['A'+ key, 'K'+ key, 'Q'+ key,'J'+ key, '0'+ k...
The main task of the code is to determine and collect the best 5 cards for each player based on their poker hand type (e.g., RoyalFlush, StraightFlush, etc.), using specific methods to extract and store these cards in a dictionary (`self.playerTop5Cards`). The function iterates through a list of players with tied hands...
def collectCards(self, sort_list, player_dict): ''' :param: sort_list, player_dict: [(key, name, indexOfKey)], {name: [7 cards]} only of players with tie :return: top5: {name: [best 5 cards of player]} ''' for key, name, i in sort_list: fplyrCard = player_dict[name] ...
def collectCards(self, sort_list, player_dict): ''' :param: sort_list, player_dict: [(key, name, indexOfKey)], {name: [7 cards]} only of players with tie :return: top5: {name: [best 5 cards of player]} ''' for key, name, i in sort_list: fplyrCard = player_dict[name] ...
The code resolves ties among players with identical poker hand ranks by comparing specific card attributes. It checks hand types (e.g., RoyalFlush, StraightFlush) and applies tie-breaking rules, such as evaluating suits, card values, and pairs. Helper methods like `isDuplicate` and `pairTieBreaker` identify winners or ...
def tieBreaker(self, sort_list): ''' fires when rank draw comes up and implements tie breaker acc to rank :param sort_list: [(key, name, indexOfKey)] only of players with tie :return: isDraw, list of draw OR winner(key, name, indexOfKey) ''' playernames = [name for k, nam...
def process_input(): with open("2021/day5/input.txt") as f: input = f.read() # input = """0,9 -> 5,9 # 8,0 -> 0,8 # 9,4 -> 3,4 # 2,2 -> 2,1 # 7,0 -> 7,4 # 6,4 -> 2,0 # 0,9 -> 2,9 # 3,4 -> 1,4 # 0,0 -> 8,8 # 5,5 -> 8,2 # """ # input = """0,2 -> 2,0 # """ ...
The main task of the code is to process input lines, construct a matrix grid, draw lines on the matrix to track coordinates, and calculate the total number of unique points marked (`num_points`) and overlapping intersections (`num_overlaps`). The result is printed as two values: the count of distinct points and the cou...
def main(): lines = process_input() matrix = form_matrix(lines) num_points, num_overlaps = draw_lines_on_matrix(lines, matrix) # for row in matrix: # print(row) print(num_points) print(num_overlaps)
def read_input(file): with open(file) as f: input = f.read() return input def clean_input(input): return [int(x) for x in input.split(",")] def simulate_fishes(fishes, num_days): num_fishes = 0 while fishes: fish = fishes.pop(0) breeding_days = simulate_one_fish(fish, num_day...
The code simulates the growth of lanternfish over a specified number of days (default 80). It reads input data, initializes fish with their initial values, and uses a simulation function to calculate the total number of fish after the given days, returning this count.
def solve_day_6(file=None, input=None, num_days=80): if not input: input = read_input(file) fish_values = clean_input(input) fishes = [{"value": value, "starting_day": 0} for value in fish_values] num_fishes = simulate_fishes(fishes, num_days) return num_fishes
def get(post_id): ''' Get post by id :returns: Post entity ''' if not post_id: return post = Post.query.get(post_id) return post def check_if_user_exists(user_id:int) -> bool: if not User.query.get(user_id): return False return True def get_total_posts_today(us...
This function creates a new post entity with validation rules: checks for allowed repost/quote sources, text length limits, user existence, and daily post limits. It raises exceptions for invalid inputs and commits the post to the database if valid.
def post(body, repost_from_id=None, quote_from_id=None): ''' Create entity with body :param body: request body :returns: the created entity ''' post = Post(**body) #Add Reference Id if its a Repost or Quote if repost_from_id: post.repost_from_id = repost_from_id if quote_fro...
def separate_xml(infile: str, outfile_path: str = "clean_data") -> None: """ Copies individual XML chunks that each contain valid, parsable XML trees and writes to new files. """ clean_dir = Path.cwd() / "clean_data" clean_dir.mkdir(exist_ok=True, parents=True) # os.makedirs(outfile_path, ex...
The main task of the code is to process a raw XML file by splitting it into valid XML chunks, saving them as individual files in a specified directory, and then converting these XML files into JSON format for structured data output.
def main(raw_xml_file: str) -> None: # path to output clean XML data clean_data_path = "clean_data" # separate into valid XML chunks and write to individual files separate_xml(raw_xml_file, clean_data_path) # Read in XML files and write to JSON xml_files = get_xml_file_list(clean_data_path) ...
def process_interests(interests, levels): groups = split(interests, levels) groups = calc_weights(groups, len(interests)) groups = calc_percentages(groups) groups = [calc_x_value(group) for group in groups] return clac_interests_score(groups) def process_components(mapping, interests): output = ...
The code processes user interests and product components to score products, then recommends the top ones based on the scores.
def alg(interests, products, levels, mapping): interests = process_interests(interests, levels) comps = process_components(mapping, interests) products = [product_score(p, comps) for p in products] recommended = get_recommended(products) return recommended
def _calculate_space(size_image: tuple[int, int], factor=0.8): """ function to calculate the space inside where have to position the information image :param size_image: size image main :param factor: define the space proportional, with 0.8, we say the 80% to use :return: tuple w...
The main task of the code is to merge two images by inserting one into another, calculate the layout space, position the second image centrally, and save the combined result as a PNG file with optional optimization. It returns the absolute path of the generated image.
def generate(self, path_image_base: str, path_image_inside: str, name_image_result="result.png", optimize=True) -> str: """ Create the merge of images :param path_image_base: path from image base, where to insert the second one :param path_image_inside: path from image t...
def add_nodes(conn, vom_df, vxmd_df): traded_products = distinct_values_of('TRAD_COMM', vxmd_df) products = distinct_values_of('NSAV_COMM', vom_df) product_nodes = [(v, {'code': v, 'is_tradable_commodity': v in traded_products}) for v in products] upsert_nodes(conn, PRODUCT_VERTEX, product_nodes) c...
The main task of the code is to write data from multiple pickle files into a graph database. It initializes a database connection, clears old data, reads input DataFrames, adds nodes and importer relationships, creates product input edges using combined data, and executes a post-processing query to denormalize statisti...
def write_data(config, paths): conn = initDbWithToken(config, GRAPHNAME) clear_old_data(conn) vom_df = pd.read_pickle(paths['VOM']) vxmd_df = pd.read_pickle(paths['VXMD']) add_nodes(conn, vom_df, vxmd_df) add_importers(conn, vxmd_df, vom_df) vdfm_df = pd.read_pickle(paths['VDFM']) vifm_d...
def write_standard_data(config): base_path = 'resources/gtap_extracted/fully-disagg' paths = { 'VOM': f'{base_path}-BaseView-VOM.pkl.bz2', 'VXMD': f'{base_path}-BaseData-VXMD.pkl.bz2', 'VDFM': f'{base_path}-BaseData-VDFM.pkl.bz2', 'VIFM': f'{base_path}-BaseData-VIFM.pkl.bz2', ...
The main task of the code is to process economic/production data by either writing standardized data or querying a graph database. It initializes a database connection, defines producer codes for oil (Mexico/USA), adjusts graph proportions, and runs shock queries to analyze production impacts. Conditional logic handles...
def main(args): cfg = make_config() if args['write-data']: write_standard_data(cfg) else: conn = initDbWithToken(cfg, GRAPHNAME) mex_oil = producer_code(product_code='oil', country_code='mex') usa_oil = producer_code(product_code='oil', country_code='usa') # LAOtian ...
def moves(state: str, room_size: int): for room, final in zip(range(0, 4 * room_size, room_size), "ABCD"): door = get_door(room, room_size) for pos, cell in enumerate(state[room : room + room_size]): if cell != ".": if cell != final or any( state[roo...
The code solves a puzzle by finding the minimum energy required to rearrange a given state into a target configuration. It uses Dijkstra's algorithm with a priority queue to explore possible moves, calculating energy costs for each step. The target state has each of the letters "A", "B", "C", "D" fully contained in the...
def solve(state: str, room_size): to_do = [(0, state)] done = {state: 0} final = "".join(x * room_size for x in "ABCD") + "." * 11 while to_do: energy, state = heapq.heappop(to_do) if final == state: return energy for distance, src, dest in moves(state, room_size):...
def parse_snailnumber(content: list): snailnumbers = map(reduce_number, parse_pairs(content)) return snailnumbers def get_magnitude(snail_number: tuple): if isinstance(snail_number, int): return snail_number left, right = snail_number return 3 * get_magnitude(left) + 2 * get_magnitude(right)...
The code calculates the maximum magnitude achievable by adding any two distinct pairs from a list of reduced snail numbers. It first parses and reduces the input snail numbers, then iterates through all unique pair combinations, computes their sum's magnitude, and tracks the highest value found. The result is printed a...
def solve2(content: list): snail_number = parse_snailnumber(content) snail_number = list(map(reduce_number, snail_number)) max_number = float("-inf") for i, pair1 in enumerate(snail_number): for j, pair2 in enumerate(snail_number): if i == j: continue ne...
def construct_msg_packet(msg): # ack field = 3 (not sending ack or nak) ack = 3 sequence_num = get_sequence_number() # formatting of message string msg = f"{USER_NAME}: {msg}" # Encode message msg_encoded = msg.encode() # Size of encoded message size_msg_encoded = len(msg_encoded) ...
The code sends a message packet over a network, constructs the packet, transmits it, and waits for an acknowledgment (ACK). If no ACK is received, it retransmits the packet. It uses a sequence number to track packets, flips the sequence number after sending, and relies on global variables for socket, host, port, and st...
def send_msg(msg): global out, loop, CLIENT_SOCK global PORT, HOST # construct packet outgoing_packet = construct_msg_packet(msg) out = outgoing_packet print("\n\n###############sending pack") print(f"seq:{get_sequence_number()}") flip_sequence_number() print(f"flipped seq:{get_seq...
def __comment(observation): """ Args: observation: Single observation from CSV file Returns: Disregards comment lines """ return observation['date'].startswith('#') def __duplicate_obs(self, observation): """ Args: ob...
The main task of the code is to link observations in `obs_df` to a candidate ID (`canid`) by inserting records into the `TNOLINK` database table. It retrieves the existing `ORBID` from the candidate's entry, filters valid observations in `obs_df` (excluding comments/duplicates), writes them, and inserts new `TNOLINK` e...
def addObstoCan(self, canid, obs_df): cursor = self.dessci.cursor() cmd = "SELECT * FROM KFRANSON.TNOLINK WHERE ID= '" + str(canid) + "'" existing_df = pd.query_to_pandas(cmd) for i, row in existing_df.iterrows(): orbid = i['ORBID'] #Writes the observations ...