dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def run_baselines() -> None: """ Runs the baseline experiments. """ run_command(["python", "scripts/training/baselines.py"]) def run_dataframe_statistics() -> None: """ Runs the dataframe statistics script. """ run_command(["python", "scripts/analysis/dataset_statistics.py"]) run_com...
The main task of the code is to execute a reproducibility script for experiments by parsing hyperparameter tuning evaluations (`--max_evals`), then sequentially running baseline models, data statistics, single/multi-target experiments, visualizing results, and generating an accuracy table to analyze experimental outcom...
def main(): parser = argparse.ArgumentParser( description="Run reproducibility script for all experiments." ) parser.add_argument( "--max_evals", "-me", type=int, default=1, help="Max evaluations for hyperparameter tuning.", ) args = parser.parse_args(...
def init_window(self): #sets up the main window self.setGeometry(300, 300, 800, 800) self.show() # Add scenes for drawing 2d objects self.scene_top = QtWidgets.QGraphicsScene() self.scene_bot = QtWidgets.QGraphicsScene() #adds views for the 2 scenes in the main window ...
The code initializes a GUI window by setting up a central widget with a vertical layout, creating horizontal layouts for top and bottom sections, and configuring the interface with text elements, file prompts, and buttons. It establishes the structural framework for a Qt application, preparing components for further UI...
def __init__(self): super().__init__() self.setCentralWidget(QtWidgets.QWidget()) # QMainWindown must have a centralWidget to be able to add layouts self.layout = QtWidgets.QVBoxLayout() # Vertical main layout(s) self.centralWidget().setLayout(self.layout) #set the main layout as the c...
def train_epoch(cur_epoch, print_every): epoch_loss = 0 batch_num = len(train_iter) NMTmodel.train() with tqdm(total=print_every) as pbar: for i, batch in enumerate(train_iter): # src: (max_src, b) src = batch.src # trg: (max_trg, b) trg = batch.t...
The code trains a neural machine translation (NMT) model by loading pre-trained checkpoints if specified, iteratively training over multiple epochs, calculating training and validation losses, and saving the best model based on validation performance. It tracks the lowest validation loss, updates the model's state, and...
def train(): if args.checkpoint != '': path = args.checkpoint print(f'Loading checkpoint from {path} ...') checkpoint = torch.load(path) NMTmodel.load_state_dict(checkpoint['model_state']) print(f'Checkpoint loading complete!\n') best_score = float('inf') for epoch i...
def verify_audio(audio_files, checksum_file, expected_duration, n_jobs=1, verbose=0): success = True success &= check_md5(audio_files, checksum_file, n_jobs, verbose) success &= check_durations(audio_files, expected_duration, n_jobs=n_jobs, verbose=verbose, to...
The main task of the code is to verify the integrity of the OpenMIC dataset by checking audio files, VGGish features, and labels against checksum files. It performs three verification steps: validating audio durations, confirming VGGish feature shapes, and matching label hashes, combining results into a single boolean ...
def main(openmic_dir, checksum_dir, n_jobs, verbose): success = True print("[{}] Verifying Audio...".format(datetime.datetime.now())) success &= verify_audio( glob.glob(os.path.join(openmic_dir, 'audio/*/*.ogg')), os.path.join(checksum_dir, 'openmic-2018-audio.csv'), expected_duratio...
def compute_phrase_weight(possible_paper_dict, query_phrases, pos, phrase_pos: list): assert pos >= 0 if pos >= len(query_phrases): return possible_paper_dict, phrase_pos phrases = query_phrases[pos] phrases_index = {} doc_keys = set() is_first_loop = True for phrase in phrases: ...
The main task of the code is to retrieve top-k relevant documents/phrases based on a query and additional input phrases. It processes queries and phrases by parsing, computing term/phrase weights (e.g., TF-IDF), and ranking results. The function returns the top `top_number` results after generating weighted scores and ...
def retrive(query, phrases, top_number): # handle phrase and words texts, querys = parse_query(query) text_phrases, query_phrases = [], [] for phrase in phrases: parse_querys = parse_query(phrase) query_phrases.append(parse_querys[0]) text_phrases.append(parse_querys[1]) tf_p...
def animate(self): plt.clf() # Extract datapoints from node list: get x, y, etc of each node keys_nodes = self.vertices.keys() x_values = [self.vertices[key_node][0][0] for key_node in keys_nodes] y_values = [self.vertices[key_node][0][1] for key_node in keys_nodes] #q1_...
The code implements the RRT* (Rapidly-exploring Random Tree Star) algorithm to find a collision-free path from an initial configuration to a goal position in a 3D space. It iteratively samples random configurations, connects them to the nearest nodes in the tree, checks for collisions, and optimizes the path by rewirin...
def run(self, initial_config, goal_xyz, sample_radius=3, neighbor_radius=3, n_expansions=1000, stop_when_goal_reached=True, also_run_normal_RRT = False, animate_plot=False, file_directory=None, verbose=False): # Initialize variables self.goal_xyz = goal_xyz self.initial_config = initial_config ...
def sanitize_context(self, context): """Pass-through to be overloaded by subclasses""" return context def set_context(self, context): self._context = context def serialize_values(self, fields): """ Collects requested field value as serializable value. If fields are not va...
The main task of the code is to serialize an object's data into values while temporarily managing the context. It saves the current context, applies a sanitized context, serializes specified fields into values, restores the original context, and returns the serialized values, ensuring context isolation between requests...
def serialize(self, fields=None, context=None): # set the context to the requesting user old_context = self._context context = self.sanitize_context(context) self.set_context(context) values = self.serialize_values(fields) # set the context back so context doesn't chan...
def angles_to_df(self,lst): self.get_landmark() one = lst[0] two = lst[1] three = lst[2] once = self.angle_2p_3d((self.x[one],self.y[one],self.z[one]),(self.x[two],self.y[two],self.z[two]),(self.x[three],self.y[three],self.z[three])) return(once) def angles_to_image(self...
This code classifies an image using a pre-trained model, displays predicted labels, and visualizes pose landmarks or angles based on the input type (tp). It saves the image if a name is provided and shows the result using OpenCV.
def class_image(self,tp,name): filename = 'finalized_model.sav' clf = pickle.load(open(filename, 'rb')) finall = np.reshape([self.angles_to_df(t) for t in self.right_side],(1,5)) cv2.putText(img=self.image, text=self.trans[int(clf.predict(finall))], org...
def adjust_learning_rate(self): base_lr = self.cfg['optimizer']['args']['lr'] for param_group in self.optimizer.param_groups: param_group['lr'] = base_lr self.log_temp_scalar('lr', self.optimizer.param_groups[0]['lr']) def train_epoch(self): self.model_ddp.train() ave...
The code trains a model for a specified number of epochs, performing training, evaluation, visualization, and checkpoint saving. It initializes an optimizer, adjusts the learning rate, and iterates through epochs, logging progress, timing operations, and handling distributed training. Checkpoints are saved at intervals...
def train(self): """ For epochs perform training, evaluation, and visualization. Note that ave_scalars update ignores the actual current batch_size. """ cfg = self.cfg self.optimizer = utils.make_optimizer(self.model_ddp.parameters(), cfg['optimizer']) m...
def make_datasets(self): """ By default, train dataset performs shuffle and drop_last. Distributed sampler will extend the dataset with a prefix to make the length divisible by tot_gpus, samplers should be stored in .dist_samplers. Cfg example: train/test_datase...
The code's main task is to either evaluate a pre-trained model or train a new one based on configuration. It loads datasets, initializes the model (either from a saved file or fresh), and executes evaluation or training workflows. If evaluation is enabled, it runs metrics and visualization; otherwise, it trains the mod...
def run(self): self.make_datasets() if self.cfg.get('eval_model') is not None: model_spec = torch.load(self.cfg['eval_model'])['model'] self.make_model(model_spec, load_sd=True) self.epoch = 0 self.log_buffer = [] self.t_data, self.t_model = 0...
def find_repeated_node_indices(edge_names): """ Determines which metanodes are visited more than once in a metapath froms the edge names. Returns these values as a dictionary with key as metanode and values a list of indices that tell the step number along the metapath where that metaedge is visited. ...
The function `count_paths` computes path counts in a metapath by multiplying matrices, while handling repeated metanodes. It removes exact repeats using `count_removing_repeats` if one metanode type is repeated, or estimates counts via `uncountable_estimate_func` for multiple repeats or complex cases. It returns a spar...
def count_paths(path, edges, matrices, verbose=False, uncountable_estimate_func=estimate_count_from_repeats, uncountable_params=None): """ Counts paths removing repeats due to only one repeated metanode in the metapath. A String or List can be passed as the repeat type. A String will only ...
def getPlayerData(self, player): logger.debug('Getting player data') try: response = self._api.getPlayer(player) pId = response.get('membershipId') pType = response.get('membershipType') displayName = response.get('displayName') logger.info('G...
The main task of the code is to optimize a player's data by processing their items, characters, and bounties. It retrieves player and item data, constructs an automaton for pattern recognition, identifies key words in bounties, and generates optimized "buckets" for strategic decision-making. The process logs errors and...
def performOptimisation(self, player): t1 = process_time_ns() try: profile = self.getPlayerData(player) assert profile is not None, "Unable to get profile data" playerId = profile[1] playerType = profile[0] items = self.getAllItems(playerTy...
def cmd_address_set(self): logging.debug("cmd_address_set()") data = bytes([0x88, 0x30, 0x01, 0xff]) self.send_bytes(data) def cmd_if_clear(self): logging.debug("cmd_if_clear()") self.send_bytes( bytearray.fromhex('88 01 00 01 FF') ) def cmd_pt_reset(self): logging.debug("cmd_pt_reset()") hex_str = '...
The code initializes a camera system by configuring address settings, clearing interfaces, resetting parameters, setting auto exposure, and initiating auto-focus. It retrieves and logs firmware details (vendor ID, model ID, ROM version) from the camera. Finally, it commands the camera to return to its home position, en...
def init(self): self.cmd_address_set() self.cmd_if_clear() self.cmd_pt_reset() self.cmd_set_exposure_mode(ExposureMode.AUTO) self.cmd_focus_auto() info = self.inquiry_camera_version() logging.debug(f'Firmware Info:') logging.debug(f"vendor id: {info['vendor_id_str']}") logging.debug(f"model id: {inf...
def parse_args() -> None: for i, cur_ in enumerate(sys.argv[1:]): cur = cur_.lower().strip() is_last = i + 2 >= len(sys.argv) if cur == '-h' or cur == '--help': print_help() sys.exit(0) if (cur == '-f' or cur == '--filename') and not is_last: setti...
The main task of the code is to parse and validate command-line arguments, create necessary directories, and split data or files, likely for preprocessing or workflow setup in a script.
def main() -> None: parse_args() check_args() split(make_dir())
def _check_order(n): """ Description: Checks the order of the proposition is withing range (0=<n<=1) Input: n <int>: order of the proposition Returns: raise Exception to handle out of bounds for the order """ if not((0 <= n) and (n <= 1)): raise Exception('The ord...
This function revises a belief base by integrating a new belief while maintaining consistency. It converts the new proposition to CNF, checks for contradictions, and applies logical operations like contraction (removing conflicting beliefs) and expansion (adding the new belief). If the new belief is a tautology, it adj...
def revise(self, other): """ Revises the belief base with the new belief. In case of inconsistency the belief base is modified to remain consistent with the new belief. The new belief system should contain as much information as possible """ try: prop_cnf = to...
def close(self): if self._connection: if self._cursor: self._cursor.close() self._connection.close() print("PostgreSQL connection is closed") self._connection = None self._cursor = None def connect(self,retry_counter=0): if not self._co...
The main task of the code is to reset a database connection by closing the existing connection, reconnecting to the database, and obtaining a new cursor for subsequent operations. This ensures a fresh connection state and prepares the object for executing new queries or commands.
def reset(self): self.close() self.connect() self.cursor()
def getWord(address): return z.memory[address] | (z.memory[(address+1) & 0xFFFF] << 8) def updateState(msg): global state, computerHistory s = msg.decode("ascii", "ignore") if 'CARE FOR' in s: state = STATE_ASK_PLAY elif 'IS THIS RIGHT' in s: state = STATE_ANALYZE_ASK_FINISH elif...
This code processes specific function calls by interpreting memory values, handling message data with state updates, and managing screen output. It checks function1/function2 pairs to trigger actions like message parsing, state transitions, character output, or screen clearing, while updating program counters and stack...
def handle38(): global state addr = getWord(z.sp) function1 = z.memory[addr] addr = (addr+1) & 0xFFFF function2 = z.memory[addr] addr = (addr+1) & 0xFFFF if (function1 == 0xb2 or function1 == 0xb3) and function2 == 0x1a: msg = getWord(addr) addr = (addr+2) & 0xFFFF le...
def handle_page_from_file(self, pagename): try: with open("client/"+pagename) as f: self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.send_str(f.read()) except IOError: se...
This code handles HTTP GET requests by routing URLs to specific functions. It splits the URL path, checks its structure, and calls methods like `handle_page_from_file` for static files, `handle_pokemon_search` for Pokémon-related queries, or `handle_error_page` for invalid paths. The logic determines the appropriate re...
def do_GET(self): path = self.path.split("/")[1:] if (len(path)==1 and path[0] == ""): self.handle_page_from_file("index.html") elif (len(path)==1): self.handle_page_from_file(path[0]) elif (len(path)==2 and path[0] == "pokemon"): self.handle_pokemon_...
def read_data(path): # we connect the path to read the data of the given csv file. fun=open(path) # the varible fun is decalre to open the path for the file to read tidee=[] # tidee is the empty set for the program. for margines in fun.readlines(): # for the margines of the fun with the readlines. ...
The code reads and preprocesses data from a text file, standardizes features, and trains a model (likely linear regression) with varying iterations. It evaluates accuracy for each iteration count, prints results, and generates 3D plots to visualize model performance. The main task involves data preprocessing, model tra...
def main(): print('START Q3_AB\n') # start the program and print the value . path=r'datasets/Q3_data.txt' #we read the path for the data.txt which we given info=read_data(path) # we fecth the data amd move it to info. info=np.array(info) # we make the info with the array #Changing dataypes ...
def lookup_typevar(self, node: NodeNG, name: str) -> TypeResult: """Given a variable name, return the equivalent TypeVar in the closest scope relative to given node.""" cur_node = node while cur_node is not None: # Get first parent node with scope cur_scope = cur_node.sc...
The function `_assign_type` updates the type environment by binding the target of an assignment to the given expression type. It handles various assignment forms: single variables (AssignName), attributes (AssignAttr), tuples (unpacking), and subscripts. For tuples, it unifies element types with the expression's tuple ...
def _assign_type(self, target: NodeNG, expr_type: type, node: astroid.Assign) -> TypeResult: """Update the type environment so that the target is bound to the given type.""" if isinstance(target, astroid.AssignName): # A single identifier, e.g. x = ... target_type_var = self.look...
def _handle_call(self, node: NodeNG, function_name: str, *arg_types: type) -> TypeResult: """Helper to lookup a function and unify it with given arguments. Return the return type of unified function call. """ arg_inf_types = [self.type_constraints.resolve(arg) for arg in arg_types] ...
(This function processes augmented assignment operations in an AST node, inferring types by determining the appropriate method (e.g., `__setitem__` or arithmetic operators) based on the target type (e.g., subscript, variable, attribute). It handles type conversions, fallbacks for failures, and assigns the resulting typ...
def visit_augassign(self, node: astroid.AugAssign) -> None: node.inf_type = NoType() # lookup method for augmented arithmetic assignment method_name = BINOP_TO_METHOD[node.op] if isinstance(node.target, astroid.Subscript): target_type = node.target.value.inf_type ...
def charging(): """ get charge state: is battery charging or discharging """ power_dir = "/sys/class/power_supply/" computer_type = getoutput("dmidecode --string chassis-type") if computer_type in ["Notebook", "Laptop", "Convertible", "Portable"]: # AC adapter states: 0, 1, unknown ...
The main task of the code is to provide CPU frequency scaling recommendations based on battery status. It checks if the device is charging or discharging, suggests an appropriate governor (performance for charging, powersave for discharging), and executes corresponding monitoring functions to optimize power management.
def mon_autofreq(): """ make cpufreq suggestions :return: """ print("\n" + "-" * 28 + " CPU frequency scaling " + "-" * 28 + "\n") # determine which governor should be used if charging(): print("Battery is: charging\n") get_current_gov() print(f'Suggesting use of "{g...
def charging(): """ get charge state: is battery charging or discharging """ power_dir = "/sys/class/power_supply/" computer_type = getoutput("dmidecode --string chassis-type") if computer_type in ["Notebook", "Laptop", "Convertible", "Portable"]: # AC adapter states: 0, 1, unknown ...
The main task of the code is to adjust the CPU frequency scaling governor based on the device's charging status. It checks if the battery is charging or discharging, then sets the governor to "performance" when charging (for higher performance) or "powersave" when discharging (to conserve energy). The function prints s...
def set_autofreq(): """ set cpufreq governor based if device is charging """ print("\n" + "-" * 28 + " CPU frequency scaling " + "-" * 28 + "\n") # determine which governor should be used if charging(): print("Battery is: charging\n") set_performance() else: print("B...
def getCaptureDate(img): captureDate = img.get("datetime_original") captureDate = captureDate.split(' ')[0].replace(':', '-') return captureDate def generateMdx(filename, title, tags, summary, captureDate): file = getPhotoFolder(tags) + filename tagsString = "['" + ('\',\'').join(tags.split(':')) + "']" md...
The code processes an image file by removing unnecessary EXIF data, generates an MDX file containing metadata (title, tags, summary, capture date), and saves the modified image. It extracts the capture date, filters EXIF tags, creates a structured MDX file, and stores both the processed image and metadata in designated...
def processFile(filename, title, tags, summary, folder): imageFile = folder + filename with open(imageFile, 'rb') as imageF: img = Image(imageF) captureDate = getCaptureDate(img) exifList = ['x_resolution', 'y_resolution', 'resolution_unit', '_exif_ifd_pointer', 'exif_version', 'color_space'] for x...
def forward(self): """Run forward pass; called by both functions <optimize_parameters> and <test>.""" ## Your Implementation Here ## # fanchen: "Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)" self.fake_B = self.netG_A(self.real_A) # fanchen: x -> G(x) self.rec_A = sel...
This function optimizes neural network parameters in a GAN framework by alternating between generator and discriminator training. It first computes forward passes, disables discriminator gradients, updates the generator via backpropagation, then re-enables discriminator gradients and updates them separately, following ...
def optimize_parameters(self): """Calculate losses, gradients, and update network weights; called in every training iteration""" ## Your Implementation Here ## # fanchen: fake_A/B, rec_A/B computation self.forward() # ref: https://blog.csdn.net/special_hang/article/details/896764...
def punc_remover_lower(self, line): cleaned = [] punc_rem = str.maketrans("", "", string.punctuation) line = line.split() line = [word.translate(punc_rem) for word in line] line = [word.lower() for word in line] cleaned.append(' '.join(line)) return cleaned def en...
The code translates a German sentence into English using a pre-trained neural machine translation model. It loads tokenizers and a model from a saved file, preprocesses the input German text (removing punctuation, lowercasing), encodes it into sequences, and generates the English translation via the model.
def execute(self): eng_tok, ger_tok, dict_vars = np.load(open(self.prefix+".pkl", "rb")) model = load_model(dict_vars["model_path"]) ger_sent = self.src_sent ger_sent = self.punc_remover_lower(ger_sent) ger_sent = self.encode_sequences(ger_tok, ...
def get_assignments(node: AssignType) -> Set[str]: ''' Given a cst.CSTNode, if it is any assignment type like `a = b` or `a = b = c` it will return all the assigned-to variables as str. Skip control flow body Potential modifications count too so self.xxx() modifies self, and function args ...
The code performs **Reaching Definitions Analysis (RDA)** on a control flow graph (CFG) to compute `IN`/`OUT` sets for each instruction, tracking which variable assignments (definitions) reach each program point. It identifies definitions (`gens`), kills (conflicting definitions), and propagates these through the CFG u...
def run_rda(cfg: DirectedGraph, ast: cst.Module, cfgs): ''' Given a CFG (generated by cfg.py) and the original cst, this will compute IN/OUT sets per instruction https://en.wikipedia.org/wiki/Reaching_definition Note that nothing is returned, rather, the IN/OUT sets are added to the cfg. You...
def exclude_paths(args): """Returns the absolute paths for excluded path.""" results = [] if args.exclude: for excl_path in args.exclude: results.append(os.path.abspath(os.path.join(args.root, excl_path))) return results def filter_dirs(root, dirs, excl_paths): """Filter director...
The code collects coverage reports by processing .gcov files, mapping them to source files, and compiling a structured report with coverage data, git information, and excluded paths. It filters directories, resolves file paths relative to the project root, reads source code, parses coverage metrics, and includes unrepo...
def collect(args): """Collect coverage reports.""" excl_paths = exclude_paths(args) report = {} if args.repo_token: report['repo_token'] = args.repo_token report['service_name'] = args.service_name report['service_job_id'] = args.service_job_id discovered_files = set() report['...
def get_record_type(operator): base_name = "" if "type" in operator and operator["type"] in ["Combiner", "FinalAggregate"]: base_name = get_request_name_from_name(operator["in_operator"]) else: base_name = get_request_name(operator) return base_name.lower()+"_record" def gen_output_recor...
This function processes a join operator in a distributed system by generating C++ code snippets for handling record joins. It determines input operators, extracts metadata, and selects templates based on join conditions (e.g., EXISTS/NOT EXISTS). The generated code performs hash map lookups, applies filters, creates ou...
def partition_join_probe_phase_process_record(operator, operator_mapping, left_rec_name="left_rec.", right_rec_name="right_rec."): left_operator = "" right_operator = "" if isinstance(operator["left_input"], str): left_operator = operator_mapping[operator["left_input"]] if left_operator["typ...
def get_record_type(operator): base_name = "" if "type" in operator and operator["type"] in ["Combiner", "FinalAggregate"]: base_name = get_request_name_from_name(operator["in_operator"]) else: base_name = get_request_name(operator) return base_name.lower()+"_record" def get_record_size(...
The function generates C++ code for remapping operations based on input operator configurations. It checks if any output column in the input operator is a dictionary-type string. If found, it constructs a loop to process records, declare input record structs, and append remapping logic using generated dictionary functi...
def gen_remap_combiner(operator, operator_mapping): out_text = "" in_operator = operator_mapping[operator["in_operator"]] found_dict = False for column in in_operator["out_columns"]: if column[1] == "STRING" and len(column) >=4 and column[3] == "DICT": found_dict = True if not fo...
def get_request_name(operator): return get_request_name_from_name(operator["stage_name"]) def gen_selected_columns(operator): output = "" alias_len = 0 if "alias" in operator: alias_len = len(operator["alias"]) + 1 for col in operator["in_columns"]:#each selected column: if col[1] ==...
This function generates C++ code for a base table scan and aggregation operation by combining templates with dynamic parameters. It processes input operators to create task definitions, launch configurations, and output structures, handling data partitioning, aggregation logic, and S3 bucket references. The generated c...
def gen_base_table_scan_aggregate_cpp(root, operator, operator_idx): template_text = "" task_template = "" launcher_template = "" with open("base_table_scan_aggregate.template", "r") as template: template_text = template.read() with open("read_base_table_task.template", "r") as template: ...
def gen_selected_columns(operator): output = "" alias_len = 0 if "alias" in operator: alias_len = len(operator["alias"]) + 1 for col in operator["in_columns"]:#each selected column: if col[1] == "CUSTOM": continue output += " selectedColumns.push_back(std::string(\"{...
This function generates C++ code for a base table scan partition by combining templates with dynamic data. It processes column aliases, reads template files, constructs task definitions with parameters like stage names, output partitions, and data processing logic, then formats these into a final C++ code string using ...
def gen_base_table_scan_partition_cpp(root, operator, operator_idx): template_text = "" task_template = "" if "alias" in operator: for column in operator["in_columns"]: column[0] = operator["alias"] + "_" + column[0] launcher_template = "" with open("base_table_scan_partition.tem...
def get_record_type(operator): base_name = "" if "type" in operator and operator["type"] in ["Combiner", "FinalAggregate"]: base_name = get_request_name_from_name(operator["in_operator"]) else: base_name = get_request_name(operator) return base_name.lower()+"_record" def gen_selected_col...
This function generates C++ code for joining two base tables using partitioning. It processes input operators, modifies column names with aliases, reads templates, constructs task parameters for build/probe phases, and combines them into a formatted output. The code creates hash map building and probing tasks with spec...
def gen_two_base_table_join_partition_cpp(root, operator, operator_idx, operator_mapping, operator_idx_mapping): left_operator = operator["left_input"] right_operator = operator["right_input"] if "alias" in left_operator: for column in left_operator["in_columns"]: column[0] = left_o...
def get_max_encoding_size(operator, operator_mapping): if operator["type"] in ["Combiner", "FinalAggregate"]: operator = operator_mapping[operator["in_operator"]] max_size = "" for column in operator["out_columns"]: if len(column) >=4 and column[3] == "DICT": max_size += " 1+{}_D...
This function generates a combiner configuration by reading template files, populating dynamic parameters from operator/root data, and formatting them into a structured output. It constructs task definitions, launcher configurations, and combines them into a final template for a combiner stage in a data processing pipe...
def gen_combiner(root, operator, operator_idx, operator_mapping, operator_idx_mapping): in_operator = operator_mapping[operator["in_operator"]] in_operator_idx = operator_idx_mapping[operator["in_operator"]] template_text = "" task_template = "" launcher_template = "" with open("combiner.templa...
def get_record_type(operator): base_name = "" if "type" in operator and operator["type"] in ["Combiner", "FinalAggregate"]: base_name = get_request_name_from_name(operator["in_operator"]) else: base_name = get_request_name(operator) return base_name.lower()+"_record" def create_bcast_pro...
This function generates C++ code templates for broadcast hash join operations, handling inner/outer joins and existence checks. It constructs code snippets to process record matches based on operator configurations, including join keys, filter conditions, and aggregate record creation logic, with conditional formatting...
def agg_join_probe_bcast_process_record(operator, operator_mapping, exists =""): left_operator = operator_mapping[operator["left_input"]] right_operator = operator_mapping[operator["right_input"]] if left_operator["type"] == "Combiner": left_operator = operator_mapping[left_operator["in_operator"]]...
def get_record_type(operator): base_name = "" if "type" in operator and operator["type"] in ["Combiner", "FinalAggregate"]: base_name = get_request_name_from_name(operator["in_operator"]) else: base_name = get_request_name(operator) return base_name.lower()+"_record" def create_agg_recor...
This function generates C++ code templates for aggregate join operations in a probe phase. It constructs conditionals based on operator types, join keys, and existence checks, handling inner/outer joins by combining filter conditions with record creation logic. The output uses hash_map lookups, iteration over matches, ...
def aggregate_join_probe_phase_process_record(operator, operator_mapping, exists=""): left_operator = operator_mapping[operator["left_input"]] right_operator = operator_mapping[operator["right_input"]] if left_operator["type"] == "Combiner": left_operator = operator_mapping[left_operator["in_operat...
def init_default_puzzle(): """ Hardcoded the various usecases of problem statement for evaluating the performance of the algorithms """ puzzle_list = [ ("trivial", [[1, 2, 3], [4, 5, 6], [7, 8, 0]]), ("very easy", [[1, 2, 3], [4, 5, 6], [7, 0, 8]]), ("easy", [[1, 2, 0], [4...
The code's main task is to allow users to select a 3x3 puzzle or customize a puzzle's dimensions, then execute a search algorithm on the chosen configuration while measuring execution time. It handles user input validation, initializes puzzle states, selects an algorithm, runs the search, and outputs the time taken in ...
def main(): print("Select an option:\n") print("[1] Default 3x3 puzzle" + "\n" + "[2] Custom puzzle" + "\n" + "(Press enter to default to [1])" ) initial_state = [] goal_state = [] problem = {} while True: user_choice = input() or "1" if user_choice == ...
def get_topic_class_model(): jobs_df, model, vec, topic_list = process_data() model_1 = predictive_modeling(jobs_df) return model, model_1, vec def tokenize_stem(series): tokenizer = TreebankWordTokenizer() stemmer = PorterStemmer() series = series.apply(lambda x: x.replace("\n", ' ')) series = series.app...
The main task of the code is to process a resume by tokenizing and stemming its text, transforming it using a vectorizer, predicting topic classes and probabilities with a pre-trained model, then returning the results as a JSON object with class labels and confidence percentages (prob*100). This implements resume topic...
def main_(resume): topic_model, model, vec = get_topic_class_model() doc = tokenize_stem(resume) doc = vec.transform(doc) prob, classes = resume_pred(topic_model, model, doc) return turn_json(classes, prob[0]*100)
def open_map(map_file) : '''Open the map file Args: map_file (str): The file location where the map is located Returns: map (dict): A dictionary containing the map ''' f = open(map_file, 'r') map = json.load(f) f.close() return map def get_closest_value(arr, val): ...
The function `lift_u_to_c` converts coordinates from an uncompressed DNA sequence to a compressed representation using a provided mapping file. It maps an input range `[uncompressed_start, uncompressed_end)` to the corresponding compressed range by leveraging run-length encoding (RLE) and a compression map. The helper ...
def lift_u_to_c(uncompressed_start, uncompressed_end, uncompressed_seq, id, map_file): '''A helper function for lifting a coordinate from uncompressed to compressed space Args: uncompressed_start (int): The 0-based, inclusive uncompressed start coordinate being lifted uncompressed_end (int): Th...
def start_playerctld(): playerctld = shutil.which("playerctld") if not playerctld: print("playerctld is not available") exit(1) subprocess.check_call( ["playerctld", "daemon"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) def signal_handler(sig, frame, loop): if sig...
The main task of the code is to initialize a service manager, set up a GLib main loop for event handling, register shutdown signal handlers, track active players via "name-appeared" and "name-vanished" callbacks, populate initial player data, print system state, and run the event loop to maintain continuous operation.
def main(): start_playerctld() loop = GLib.MainLoop() for sig in SHUTDOWN_SIGNALS: signal.signal(sig, lambda sig, frame: signal_handler(sig, frame, loop)) connect_playerctld() # Keep track of all active players manager.connect("name-appeared", on_name_appeared) manager.connect("na...
def readNasari(): nasariData = [] with open("dd-small-nasari-15.txt") as nasariFile: for line in nasariFile: if len(line) > 0: split = line.strip().split(";") wordnetCorrelations = [] for s in split[2:]: wn = s.split("_") if len(wn) > 1: wordnetCorre...
The main task of the code is to summarize a text file by compressing it according to a specified percentage. It reads input arguments for compression rate and file path, processes the text to remove stopwords, generates context from a Nasari dataset, calculates scores for lines, and removes lines based on the compressi...
def main(): global nasari parser = argparse.ArgumentParser() parser.add_argument("compression", help="compression rate in [0-100]%", type=int) parser.add_argument("path", help="path to file to summarize") args = parser.parse_args() if args.compression < 0 or args.compression > 100: print("invalid compre...
def parse_xml(xml_text, wordPress_website_link): root = ET.fromstring(xml_text) data = { 'about': root.find('.//span[@itemprop="about"]').text, 'comment': root.find('.//span[@itemprop="comment"]').text, 'encoding': root.find('.//span[@itemprop="encoding"]').text, 'publisher': roo...
The main task of the code is to create a chatbot by ingesting data from provided URLs and corresponding WordPress links. It downloads and parses XML data, processes it into structured documents, splits them into text chunks, and stores them in a Chroma database for the chatbot to use. The function returns True on succe...
def create_chatbot(user_id, knowledge_Store_id,urls, wordpressUrls ): Urls_for_chatbot=[urls] urls_corresponding_wordPress_website_links=[wordpressUrls] try: parsed_data_against_urls = [] for url, wordpress_link in zip(Urls_for_chatbot, urls_corresponding_wordPress_website_links): ...
def parse_xml(xml_text, wordPress_website_link): root = ET.fromstring(xml_text) data = { 'about': root.find('.//span[@itemprop="about"]').text, 'comment': root.find('.//span[@itemprop="comment"]').text, 'encoding': root.find('.//span[@itemprop="encoding"]').text, 'publisher': roo...
The code updates a knowledge store in a Chroma DB by processing XML data from URLs, filtering existing documents by user and store ID, comparing dates to retain the latest content, generating new documents, removing outdated entries, and adding updated texts. It ensures the database reflects the most recent curated con...
def update_store(knowledgeStoreid,user_id,urls,wordpressUrls): Urls_for_chatbot = [urls] urls_corresponding_wordPress_website_links = [wordpressUrls] try: parsed_data_against_urls = [] for url, wordpress_link in zip(Urls_for_chatbot, urls_corresponding_wordPress_website_links): p...
def showTCP(self): self.FrameParameters["IP"]['Protocol'] = "TCP" self.frameTCP.show() self.frameUDP.hide() self.frame.hide() self.frameIP.hide() self.frameICMP.hide() def showUDP(self): self.FrameParameters["IP"]['Protocol'] = "UDP" self.frameTCP.hide() ...
The `showNext` method determines the network protocol type from `self.FrameParameters` and executes corresponding actions: calling `showTCP`, `showUDP`, or `showICMP` for respective protocols, invoking `SendPacket` if the protocol is "Empty", or returning silently for unrecognized protocols. Its primary task is to rout...
def showNext(self): if self.FrameParameters["IP"]['Protocol'] == "TCP": self.showTCP() elif self.FrameParameters["IP"]['Protocol'] == "UDP": self.showUDP() elif self.FrameParameters["IP"]['Protocol'] == "ICMP": self.showICMP() elif self.FrameParameters...
def NewQueue(self, _, load): dialog_app = QtWidgets.QDialog() QWindow = QD.QueueDialog() QWindow.setupUi(dialog_app, state = False, load = load) dialog_app.exec() def setupIP(self): self.frameIP = QtWidgets.QFrame(self.centralwidget) self.frameIP.setGeometry(QtCore.QRect(...
The code sets up a GUI interface for a packet generator application, initializing UI components like buttons for creating/loading packets/queues, configuring network protocols (IP/TCP/UDP/ICMP), and connecting actions to methods. It prepares the main window with layouts, menus, and status bars, enabling user interactio...
def setupMain(self, PacketGenerator): self.Sender = PS.PacketSender() self.FrameParameters = { "IP" : {}, "TCP" : {}, "UDP" : {}, "ICMP" : {} } font = QtGui.QFont() font.setPointSize(12) self.CurrentPacket = "" ...
def _initialize_with_zero(self, dim): # w = np.zeros((1,dim)) w = np.random.randn(1, dim) * 0.01 b = 0 assert (w.shape == (1, dim)) assert (isinstance(b, float) or isinstance(b, int)) return w, b def _optimize(self, w, b, X, Y, num_iterations, learning_rate): co...
This code trains a model using gradient descent by initializing parameters, optimizing them with given iterations and learning rate, predicting on train/test data, calculating accuracy, and returning results including costs, predictions, and parameters.
def _model(self, train_x, train_y, test_x, test_y, num_iterations, learning_rate): # initialize parameters with zeros (≈ 1 line of code) w, b = self._initialize_with_zero(train_x.shape[0]) # Gradient descent (≈ 1 line of code) parameters, grads, costs = self._optimize(w, b, train_x, tra...
def crt_disp_frme(self): frme = Frame(self.root,height=300,bg=CLR) frme.pack(expand=True, fill="both") return frme def crt_disp_labei(self): tot_lab = Label(self.frame_disp, text=self.tot_exp, anchor=E, bg=CLR, fg= CLR2, font=SFONT) tot_lab.pack(expand=Tru...
This code initializes a Tkinter-based calculator application by setting up the main window, display frames, digit/operator buttons, and keyboard bindings. It configures the GUI layout, defines button positions, and prepares interactive elements for arithmetic operations and user input handling.
def __init__(self): ##### Root Properties ###### self.root = Tk() self.root.geometry("350x660") self.root.resizable(1,0) self.root.title("calculator_App") self.tot_exp = "" self.inp_exp = "" self.frame_disp = self.crt_disp_frme() ...
def generate_quasi_combinations(self, r=None): self.combinations_list = [] quasiIden = self.quasi_iden if r is None: r = len(quasiIden) self.combination( quasiIden, [None] * len(quasiIden), 0, len(quasiIden) - 1, 0, r) def create_graphs_for_r_attributes(self): ...
The main task of the code is to achieve k-anonymity by iteratively generalizing quasi-identifiers through graph-based processing. It generates combinations of quasi-identifiers, constructs attribute graphs, and checks nodes for k-anonymity. If a node fails, it generalizes data and extends the queue with further general...
def main_algorithm(self, kAnon): self.generate_quasi_combinations(1) self.create_graphs_for_r_attributes() queue = [] total_comb = 0 for i in range(1, len(self.quasi_iden) + 1): for x in range(len(self.combinations_list)): total_comb += len(self.combi...
def count_tuple_and_triple(msb_pos: int): ''' return (n_tuple, n_triple) ''' n_tuple, n_triple = 0, msb_pos l_bound = msb_pos - 1 while l_bound > 0: flag = (l_bound + 1) % 3 if flag == 2: n_triple += 2 n_pair = (l_bound + 1) // 3 n_tuple += n_pair ...
(SecureBiNN performs secure neural network inference using a 3-party computation framework. It processes model layers (dense/conv2d) with secret sharing, adding random masks and Beaver triples for privacy. Roles (data/model/ttp) collaboratively compute outputs via oblivious transfer and tuple/triple sharing, ensuring d...
def SecureBiNN(role, random_handler, listener, sender, data_share, model_share): # role 0: data owner (share_0, share_1) # role 1: model owner (share_1, share_2) # role 2: trusted third party (share_2, share_0) data_owner = 0 model_owner = 1 ttp = 2 role_last = (role - 1) % 3...
def count_tuple_and_triple(msb_pos: int): ''' return (n_tuple, n_triple) ''' n_tuple, n_triple = 0, msb_pos l_bound = msb_pos - 1 while l_bound > 0: flag = (l_bound + 1) % 3 if flag == 2: n_triple += 2 n_pair = (l_bound + 1) // 3 n_tuple += n_pair ...
The function implements a secure activation computation in a multi-party setting (data owner, model owner, and trusted third party) using secret sharing and oblivious transfer. It generates random tuples/triples, exchanges shares, computes the most significant bit (MSB) via 3-input gates, and performs 3-party oblivious...
def test_secure_activation(n_bit: int, n_batch: int, role: int, listener: list, sender: list, config): data_owner = 0 model_owner = 1 ttp = 2 role_last = (role - 1) % 3 role_next = (role + 1) % 3 ret = np.zeros(n_batch, dtype='int32') cur_layer = { 'dtype': 'int32', 'output...
def create_folders(self): folders = "shots", "files", "logs", "buffer" for folder in folders: try: create_folder(self.storagepath, folder=folder) except CuckooOperationalError: log.error("Unable to create folder %s" % folder) retur...
This code handles a client connection by storing connection details, creating necessary directories, initializing a protocol handler, processing events (specifically opening process logs for BSON data), and gracefully managing exceptions. It logs connection closure upon completion.
def handle(self): ip, port = self.client_address self.connect_time = datetime.datetime.now() self.storagepath = self.server.build_storage_path(ip) if not self.storagepath: return # Create all missing folders for this analysis. self.create_folders() ...
def normalize(ytil, T): yres=copy.deepcopy(ytil) total = 0 for yi in ytil: for yij in yi: total+=yij for i in range(len(ytil)): for j in range(len(ytil[i])): yres[i][j]=ytil[i][j]/(2*total) return yres def ytilde(ycur, Eb, T, m): yres=copy.deepcopy(ycur) ...
This function performs a recursive binary search to find a temperature value (Tavg) that satisfies convergence criteria. It iteratively calculates a normalized value (y) using ytilde, checks for convergence, and adjusts the search range based on the difference between Xe and Xo. If the difference is within tolerance, i...
def tsearch(Eb, m, Trang, guess): #recursive binary search Tavg = (Trang[1]+Trang[0])/2 #base case if (Trang[1]-Trang[0])<T_PRECISION: return Tavg #Find whether to update top or bottom of range y=normalize(guess,Tavg) yold=[[0,0,0],[0,0,0],[0,0,0]] counter = MAX_ITER ...
def normalize(ytil, T): yres=copy.deepcopy(ytil) total = 0 for yi in ytil: for yij in yi: total+=yij for i in range(len(ytil)): for j in range(len(ytil[i])): yres[i][j]=ytil[i][j]/(2*total) return yres def ytilde(ycur, Eb, T, m): yres=copy.deepcopy(ycur) ...
The code calculates equilibrium compositions and free energy of a ternary system using iterative methods over a temperature range. It computes phase diagrams, free energy curves, and thermodynamic quantities (E, C) by iterating through temperature steps, updating compositions via ytilde(), and plotting results for anal...
def min(Eb=[[0,-1,-1], [-1,0,0], [-1,0,0]], Trang=[0,5], samp=200, guess=[[25,212.5,212.5], [12.5,12.5,0], [12.5,0,12.5]], m=[1.,0.6,0.5]): delta = (Trang[1]-Trang[0])/samp temp = np.linspace(Trang[0]+delta, Trang[1], samp) ...
def F(J,h,z,T): if T == 0: return H(J,h,z) #might as well skip entropy calc if possible return H(J,h,z)-T*S(z) def X(z): y=Y(z) return [y[0]+y[1], y[1]+y[2]] def Y(z): return [z[0]+2*z[1]+z[2], z[1]+z[2]+z[3]+z[4], z[2]+2*z[4]+z[5]]
This code calculates the minimum free energy of a 2D square lattice model across temperature ranges using optimization with constraints. It computes thermodynamic quantities (energy, specific heat) via finite differences, plots results, and saves composition vs. temperature data. The function optimizes compositions (z)...
def min(J=-1, hpj=0, samp=249, Trang=[0,5]): h = hpj*abs(J) delta = (Trang[1]-Trang[0])/(samp) Temp = np.linspace(Trang[0]+delta,Trang[1],samp-1) #starting guess #guess=[0.0625,0.0625,0.0625,0.0625,0.0625,0.0625] guess=[1,0,0,0,0,0] #ensure reasonable compositions con = opt.Linear...
def get_baseline(label_training, label_testing): """Calculate the baseline MSE by using the mean of label in training set as the prediction.""" mean_training_label = np.mean(label_training) MSE = np.sum(np.power((mean_training_label - label_testing), 2)) / len(label_testing) return MSE def sgd_stepwise(...
The code performs logistic regression with stepwise feature selection using stochastic gradient descent (SGD). It splits data into training, validation, and test sets, trains a model with feature selection on the training set, validates it, and evaluates accuracy on the test set using selected features. The process inc...
def logistic_regression(data): data_train = data.get_data_train(True, "chd") data_validation = data.get_data_validation(True, "chd") data_test = data.get_data_test(True, "chd") learning_rate = 0.06 n_epoch = 1500 get_baseline(data_train, data_test) # theta = sgd_training(data_train, learning...
def divide_image(img, image_path, section_size): img = Image.open(image_path) img_width, img_height = img.size sections = [] for y in range(0, img_height, section_size): for x in range(0, img_width, section_size): box = (x, y, x + section_size, y + section_size) section ...
The main task of the code is to split an input image into sections, generate QR codes for each section, merge them into a montage image, and save the result. The function opens an image, divides it into smaller parts, creates QR codes for each part, combines them into a new image layout, and exports the final montage t...
def main(image_path, output_path): section_size = 60 img = Image.open(image_path) sections = divide_image(img, image_path, section_size) qr_images = create_qr_codes(sections) montage_img = montage_with_qr(sections, qr_images, section_size) montage_img.save(output_path)
def calculateBitrate(prefix, bitrates): [timestamps, qualities, qualityChange, bufferings, endtime] = getEvents(prefix) timestamps.append(endtime) periods = [x / 1000 for x in timestamps] periods = np.diff(periods) periods = np.round(periods) periods = [int(i) for i in periods] usedBitrates = [] #qualities ...
The code's main task is to generate a CSV-formatted string combining calculated bitrate, buffer, and stall values from input data, then delete associated files. It concatenates results from three functions, removes temporary files, and returns the output string.
def getOutput(prefix, bitrates): bitrate = calculateBitrate(prefix, bitrates) buffer = calculateBuffer(prefix) stalled = calculateStallings(prefix) #print("buffer", buffer) out = bitrate + "," + buffer + "," + stalled os.remove("results/" + prefix + "_events.txt") os.remove('results/' + prefix + '_buffer.txt') ...
def getScans(self,directoryPath=None): """ Get new scan from directory. """ # Unless otherwise states, will search same directory for files. directoryPath = self.directoryPath if directoryPath is None else directoryPath files, _ = getFiles(directoryPath) # For any new files in t...
This function live-updates a scatter plot displaying intensity vs. time for a specified wavelength, dynamically retrieving and processing scan data from a directory. It applies optional dark or buffer subtraction to counts, formats axis labels, and updates plot titles. The function ensures at least one scan exists befo...
def _watchExpt(self, i, directoryPath, wavelength, timeInterval, subtractDark, subtractBuffer): """ Automatically updating figure for watching data live. """ # First get any new files. self.getScans(directoryPath) # Must have at least one scan. try: ...
def Elitist(self): for key in gen: arrUse = [val for val in gen[key]] arrUse.sort(key=lambda x: float(x.percent)) for i in range(int(NN.PopulationSize/2)): del arrUse[i] gen[key] = arrUse def Crossover(self): for key in gen: arr...
The code's main task is to execute a genetic algorithm loop for a specified number of generations. It performs elitism, crossover, optional mutation (based on the 'Mutation' parameter), mutation adjustment, and fitness data collection in each iteration to evolve a population toward an optimal solution.
def GenerationLoop(self,NumGens, dict, Mutation): for i in range(NumGens): self.Elitist() self.Crossover() if Mutation: self.Mutate() self.AdjustMutation() self.GetFitnessData()
def get_projection_weights_fisher(inputs, targets): """ Takes input and target data for classification and projects this down onto 1 dimension using the Fisher method. :param inputs: a 2d input matrix (array-like), each row is a data-point :param targets: 1d target vector (array-like) -- can be at most...
The function performs cross-validation to train Fisher's Linear Discriminant Analysis (LDA) models, optimizing projection weights and classification thresholds by maximizing a weighted metric (0.5 recall + 0.25 accuracy + 0.25 precision). It then applies the best parameters to predict test data labels, projects inputs ...
def fit_and_predict_fisher(x_crossval, y_crossval, inputs_test, targets_test, classes): """ Using cross-validation, fits a Fisher's Linear Discriminant model and uses it to make predictions on test data. :param x_crossval: an array of training inputs data, split for cross validation :param y_crossval: ...
def updateP(self): active_agents_near = self.active_near_agents() cops_near = self.near_cops() self.P = 1 - np.exp(-k * (1+cops_near) / (1.0+C3*active_agents_near)) def updateN(self): self.N = C2*self.R * self.P def updateG(self): self.G = self.Il*self.H def move(self): p...
The code's main task is to conditionally update object properties (P, N, G, position, and Il) if the status is not 2, then update the status and return the object instance.
def time_step(self): if self.status != 2: self.updateP() self.updateN() self.updateG() self.move() self.updateIl() self.update_status() return self
def penUp(self): self.down = False def wait(self, frames): for i in range(frames): self.bufferInstruction(0, 0) def penDown(self): self.down = True
The main task of the code is to control a drawing mechanism by lifting the pen, waiting for specific durations, and repositioning the pen with timed intervals, likely to create pauses or manage drawing states in a graphical or robotic context.
def click(self): self.penUp() self.wait(1) self.penDown() self.wait(7) self.penUp() self.wait(1)
def rightUp(self): self.rightdown = False def wait(self, frames): for i in range(frames): self.bufferInstruction(0, 0) def rightDown(self): self.rightdown = True
The code simulates a right-click action with specific timing intervals: lifting the right mouse button, waiting 1 second, pressing it again, waiting 7 seconds, then lifting it once more with a 1-second pause. This sequence may mimic a delayed or multi-stage right-click interaction for automation or testing purposes.
def rightclick(self): self.rightUp() self.wait(1) self.rightDown() self.wait(7) self.rightUp() self.wait(1)
def penUp(self): self.down = False def wait(self, frames): for i in range(frames): self.bufferInstruction(0, 0) def plotAbsolute(self, tarX, tarY): # clamp our targets targetX = self.clamp(tarX, mp.SCREEN_MIN_X, mp.SCREEN_MAX_X) targetY = self.clamp(tarY, mp.SCREEN_MI...
The main task of this code is to trace the black pixels in an image using a plotter's pen. It converts the image to RGB, identifies black pixels, and navigates the plotter to draw lines by moving between adjacent black pixels. The code manages pen states (up/down), ensures smooth transitions between points, and adjusts...
def mask(self, path): # open image using PILLOW im = Image.open(path) # make sure it's RGB im = im.convert("RGB") # define black as the value of its RGB triple for comparison later black = (0, 0, 0) # prep pen if (self.down): ...
def getClippingWindowSize(): print("Enter the clipping window size : ") xWin0 = float(input("Enter the minimum window value of x : ")) xWinMax = float(input("Enter the maximum window value of x : ")) yWin0 = float(input("Enter the minimum window value of y : ")) yWinMax = float(input("Enter the maxi...
The main task of the code is to set up an OpenGL environment using GLUT to clip a line against a defined window. It retrieves clipping window coordinates, line endpoints, initializes GLUT functions, and uses a lambda to pass these parameters to a `clipLine` function for rendering the clipped line within the specified w...
def main(): xWin0, xWinMax, yWin0, yWinMax = getClippingWindowSize() x1, x2, y1, y2 = getLine() glutFunct() glutDisplayFunc(lambda: clipLine(x1, x2, y1, y2, xWin0, xWinMax, yWin0, yWinMax)) glutMainLoop()
def infer_nodes(flows): ''' Given a list of flows, automatically infers the nodes and returns them in a nested list which can be directly input into sankey(). The flows must not have loops or backwards flows. @param flows : See Sankey.sankey() ''' from collections import...
The code generates a Sankey diagram by processing input flows and nodes, scaling values to fit the widest level, creating nodes with automatic coloring, validating flows, determining flow colors based on specified modes, and applying layout adjustments for proper alignment.
def sankey(self, flows, nodes=None): ''' @param flows : A list of flows as (source_name, dest_name, value) or (source_name, dest_name, value, opts), where opts is a dictionary containing arguments to SankeyFlow(). opts may also contain key flow_color_mode with ...
def compute_tmax(self, spike_times): """ Compute the maximum mebrane potential of the tempotron as a result of the input spikes. The maxima of the function can be computed analytically, but as there are as many maxima and minima as their are number of spikes, we still nee...
The function adjusts synaptic efficacies to correct classification errors in a tempotron. It computes weight updates based on the difference between the neuron's output and the target, increasing weights when the neuron fails to fire (target=True) and decreasing them when it erroneously fires (target=False). The update...
def adapt_weights(self, spike_times, target, learning_rate): """ Modify the synaptic efficacies such that the learns to classify the input pattern correctly. Whenever an error occurs, the following update is computed: dw = lambda sum_{ti} K(t_max, ti) The synapt...
def new_food(self): import random x = random.randint(0, 49) y = random.randint(0, 29) return (x,y) def read(self, f=sys.stdin, old_attr=tcgetattr(sys.stdin.fileno()), time=1, chars=1): ''' cooperative io read from stdin/terminal without pressing enter ''' ...
The main task of the code is to run a snake game loop. It handles user input for movement, updates the game state (e.g., food generation), renders the game canvas, checks for collisions, and controls game logic like eating food and exiting. The loop continuously processes input, updates the display, and manages game me...
def run(self): f = sys.stdin old_attr = tcgetattr(f.fileno()) previous_time = time.time() food = self.new_food() while True: current_time = time.time() delta_time = current_time - previous_time buff = self.read(f, old_attr, time=1) ...
def insert_filer_information(self) -> None: self.cik = self.filing.filer["cik"] business = self.filing.filer["business_address"] mail = self.filing.filer["mail_address"] lei = self.filing.general_information["filer_lei"] if self.filing.filer["former_names"] is None: ...
The main task of the code is to insert multiple related data entries into a system, including filer information, series class details, fund data, portfolio information, and explanatory notes. The function conditionally skips fund-related inserts if `series_id` is missing, ensuring dependent data is only processed when ...
def insert_all(self) -> None: self.insert_filer_information() self.insert_series_class_information() if self.series_id is None: return self.insert_fund_information() self.insert_portfolio_data() self.insert_explanatory_notes()
def print_usage(): print("usage: python3 main.py <training-set-path> <dev-set-path> <predictions-path>") def feature_vectors_for_context(key, context, examples): global vectorizer global tfidf_matrix sentences = nlptools.split_to_sentences(context) sentences_indexed = [] start_index = 0 for...
The main task of the code is to process training and development datasets for a machine learning model. It reads input files, extracts text features (noun phrases) from context paragraphs using TF-IDF vectorization, generates feature vectors for training examples, trains a logistic regression model, and outputs predict...
def main(): 'Program entry point' global vectorizer, tfidf_matrix if len(sys.argv) != 4: print_usage(); return -1 train_set_path = sys.argv[1] dev_set_path = sys.argv[2] prediction_path = sys.argv[3] train = ioutil.read_examples_from_file(train_set_path) dev = ioutil.r...
def print_usage(): print("usage: python3 dirt.py <corpus_file> <test_file> <minfreq>") def parse_corpus_file(path): corpus_entries = [] with open(path) as input_file: for line in input_file: line = line.split() if len(line) >= 3: syntactic_type = line[0] ...
The code processes legal text data by parsing a corpus and test file, filtering triples by minimum frequency, and identifying the most similar rules for each test phrase based on distinct paths in the filtered database.
def main(): 'Program entry point' if len(sys.argv) != 4: print_usage() corpus_file_path = sys.argv[1] test_file_path = sys.argv[2] min_freq = int(sys.argv[3]) corpus_entries = parse_corpus_file(corpus_file_path) triple_database = get_triple_database(corpus_entries) legal_triple...
def geo_contourf(m, lon, lat, values, levels=None, cmap='RdBu_r', title=None, put_colorbar=True, colorbar_label=None, draw_coastlines=True, draw_gridlines=True, draw_labels=True, greenwich=False, **kwargs): ''' Contourf plot together with coast...
This function generates a frame of a plot visualizing temperature and geopotential data on a map. It clears the axes, draws coastlines/gridlines, plots temperature contours if available, overlays geopotential contours with labels and max/min values, sets a title, and applies a mask over a region of interest. It also ac...
def _plot_frame(i): m.cla() m.coastlines() m.gridlines(draw_labels=draw_grid_labels) # plot significant temperature if temp_sign is not None: geo_contourf(m, lon, lat, temp_sign[i], levels=temp_levels, put_colorbar=False, draw_coastlines=False...
def get_files(files, path): try: for filename in files: FileSystemStorage(location="tmp").save( f"{path}/{filename}", ContentFile(files[filename].read()) ) except Exception as e: print(e) def create_background_image(height, width, path, color): try: ...
This function generates a video reel by combining layered media elements (images, videos, titles, subtitles) onto a canvas. It creates a background, processes input files, composites layers using FFmpeg, generates a thumbnail, and outputs the final video with metadata tracking progress/status. The task involves media c...
def generate_reel_v2(id, body, files): id = str(uuid.uuid4()) print("id") path = f"{settings.BASE_DIR}/tmp/{id}" out_path = f"{settings.BASE_DIR}/media/reels/{id}" os.makedirs(path, exist_ok=True) os.makedirs(out_path, exist_ok=True) name = body['name'] meta = {} meta["name"] = nam...
def find_that(self, obj): p = path(0,0,0) self.get_look() p = self._find_that(obj) return p def walk(self): i = rd.randrange(8) if i == 0: self.Left() elif i == 1: self.Right() else: self.Forward() def go_to(self, path):...
The code's main task is to navigate to and retrieve a specified object. It first locates the object using `find_that(obj)`, checks if forward movement is required (`p.forward == -1`), and either walks forward or directly moves to the object's position (`p`). Once positioned, it executes a `Take(obj)` action to collect ...
def get_object(self, obj): p = self.find_that(obj) if p.forward == -1: self.walk() else: self.go_to(p) self.Take(obj)
def fetch_train_data(): bucket_name = "teeeeeeeeeeeeeeeeeeeeest" source_file = "train_data.csv" train_data_path = "train_data.csv" download_blob(bucket_name, source_file, train_data_path) df = pd.read_csv(train_data_path) return df def feature_data(df): extract_title(df) extract_deck(df)...
The main task of the code is to fetch and process Titanic training data, save the processed data as a CSV file, upload it to a blob storage, trigger a training process via an HTTP request, and return "OK" upon completion.
def feature(): df = fetch_train_data() df = feature_data(df) featured_data_path = "titanic_featured_data.csv" df.to_csv(featured_data_path) upload_blob( "feature-titanic-data", featured_data_path, "titanic_featured_data.csv" ) requests.get("http://training:5001/train") return "OK...
def rollout(self): # Batch Data batch_obs = [] batch_actions = [] batch_log_probs = [] batch_rewards = [] batch_rtgs = [] batch_lens = [] t = 0 train_scores = [] # Start rollout pbar = tqdm(total = self.timesteps_per_batch) ...
The code implements Proximal Policy Optimization (PPO) for training an actor-critic reinforcement learning agent. It collects experience through rollouts, processes data in mini-batches, computes advantages, and performs multiple gradient updates per iteration. The actor and critic networks are optimized using clipped ...
def learn(self, total_time_steps): curr_t = 0 epoch = 0 while curr_t < total_time_steps: self.actor.eval() self.critic.eval() full_batch_obs, full_batch_acts, full_batch_log_probs, full_batch_rtgs, full_batch_lens = self.rollout() # Calculate how m...
def vpn_initialise(): settings = initialize_VPN() rotate_VPN(settings) return settings def get_suburbs_with_streets(filename): return json.loads(open(filename, FILE_READ_MODE).read()) def fetchone_statement(statement): try: execute_statement(statement) return cursor.fetchone() ex...
The main task of the code is to synchronize street data from a file into a database, checking for existing entries and inserting new ones. It uses a VPN switcher to manage connections, updates a status flag based on the latest database entry, extracts postcodes, formats street names, and inserts listings. The process i...
def main(): settings = vpn_initialise() suburb_switch_counter = 3 print('HERE') up_to_date = False suburb_and_street_mappings = get_suburbs_with_streets(SUBURB_AND_STREETS_FILE_NAME) last_updated_street_statement = 'SELECT TOP 1 * FROM dbo.street ORDER BY suburb_name DESC, name DESC;' fetch...
def word2vec_metric(word1, word2): similarity_ = word_vectors.similarity(word1, word2) return word1, word2, similarity_ def Wu_Palmer_metric(word1, word2): y1 = lexicon_dict[word1]['lf_parent'] y2 = lexicon_dict[word2]['lf_parent'] parents1 = [] parents2 = [] for i in range(len(y1)): ...
The code computes four similarity scores (word2vec, Wu-Palmer, brown-vector, 4th technique) for each word pair in the input list `y`, appending results to a DataFrame with columns for triple IDs, word pairs, and corresponding similarity metrics. It returns a structured DataFrame containing all computed scores for analy...
def predict(y): score = pd.DataFrame() tripleid = [] words1 = [] words2 = [] sim1 = [] sim2 = [] sim3 = [] sim4 = [] for i in range(len(y)): for j in range(len(y[i])): word1, word2, similarity1 = word2vec_metric(y[i][j][0], y[i][j][1]) word1, word2, similarity2 ...
def file2list(file): story = [] for line in file: line = line.replace(' (THE-SET', ')\n(THE-SET') # input6 casse lines = line.split('\n') new_line = [] for l in lines: if l.startswith('('): l = shlex.split(l) for i in range(len(l)): ...
The code processes input text from a file, splits it into sections, generates candidate outputs using helper functions, and writes the formatted results to another file, removing unwanted characters before writing each line.
def main(): import sys with open(sys.argv[1]) as f1: inputs = f1.read() inputs = inputs.split('\n\n') with open(sys.argv[2], 'r+', ) as f2: story = file2list(inputs) candidates = get_candidate(story) outputs = final_outputs(candidates) print(outputs) ...
def read_csv(filename, id_column, fieldnames): dict_reader = csv.DictReader(open(filename, 'rb'), fieldnames=fieldnames, delimiter=',', quotechar='"') return parse_dict_reader(dict_reader, id_column) def parse_int_field(values, field_name): result = [] for value in values: value[field_name] = in...
The main task of the code is to read a CSV file containing technology data, convert the 'id' field to integers, and construct a dictionary where each key is an integer ID from the CSV file. This structured dictionary maps each technology ID to its corresponding data, enabling efficient lookups and data management.
def parse_technologies(): technologies = read_csv('technologies.csv', 'id', ['n', 'id']) technologies = parse_int_field(technologies, 'id') return build_dict(technologies, 'id')
def read_csv(filename, id_column, fieldnames): dict_reader = csv.DictReader(open(filename, 'rb'), fieldnames=fieldnames, delimiter=',', quotechar='"') return parse_dict_reader(dict_reader, id_column) def parse_int_field(values, field_name): result = [] for value in values: value[field_name] = in...
The main task of the code is to read a CSV file containing objectives data, convert specific fields (id and t) into integer and list formats respectively, and return a dictionary structured with 'id' as the key. This processed data is likely used for further analysis or manipulation in a program.
def parse_objectives(): objectives = read_csv('objectives.csv', 'id', ['id', 'n', 'uc', 'd', 't']) objectives = parse_int_field(objectives, 'id') objectives = parse_list_field(objectives, 't', integer=True) return build_dict(objectives, 'id')
def read_csv(filename, id_column, fieldnames): dict_reader = csv.DictReader(open(filename, 'rb'), fieldnames=fieldnames, delimiter=',', quotechar='"') return parse_dict_reader(dict_reader, id_column) def parse_int_field(values, field_name): result = [] for value in values: value[field_name] = in...
The main task of the code is to read a CSV file containing personas data, convert the 'id' field to an integer, parse the 'o' field as a list of integers, and return a dictionary keyed by 'id'. This processes structured data for efficient lookup and use in further computations.
def parse_personas(): personas = read_csv('personas.csv', 'id', ['id', 'n', 'o']) personas = parse_int_field(personas, 'id') personas = parse_list_field(personas, 'o', integer=True) return build_dict(personas, 'id')
def read_csv(filename, id_column, fieldnames): dict_reader = csv.DictReader(open(filename, 'rb'), fieldnames=fieldnames, delimiter=',', quotechar='"') return parse_dict_reader(dict_reader, id_column) def parse_int_field(values, field_name): result = [] for value in values: value[field_name] = in...
The code reads a CSV file containing vendor data, converts specified fields to integers and lists, and returns a flattened version of the processed data.
def parse_vendors(): vendors = read_csv('vendors.csv', 'id', ['o', 't', 'n', 'id', 'fo', 'u', 'g', 'l', 'tl', 'd', 'c', 'lu']) parse_int_field(vendors, 'id') parse_int_field(vendors, 'o') parse_int_field(vendors, 't') parse_list_field(vendors, 'g') return flat_vendors(vendors, 'id')
def _get_intent_ids(project_id, display_name): intents_client = dialogflow.IntentsClient() parent = intents_client.project_agent_path(project_id) intents = intents_client.list_intents(parent) intent_names = [ intent.name for intent in intents if intent.display_name == display_name] ...
This function creates or updates an intent in a project. It checks if the intent exists: if not, it creates it; if it does and a parent follow-up intent exists, it deletes the existing intent and creates a new one; otherwise, it updates the existing intent. A 15-second delay is added after the operation.
def create_or_update_intent(project_id, intent): logger.info("Creating or updating intent {}...".format(intent['name'])) if not _get_intent_ids(project_id, intent['name']): create_intent(project_id, intent) elif (_get_intent_ids(project_id, intent['name']) and _get_parent_followup_intent...
def parse_technologies(): technologies = read_csv('technologies.csv', 'id', ['n', 'id']) technologies = parse_int_field(technologies, 'id') return build_dict(technologies, 'id') def parse_objectives(): objectives = read_csv('objectives.csv', 'id', ['id', 'n', 'uc', 'd', 't']) objectives = parse_int_...
The main task of the code is to gather data from four parsing functions—technologies, objectives, personas, and vendors—into a dictionary and save it as a JSON file named 'result.json'. This involves executing each parsing function, compiling their outputs into structured data, and writing the combined result to a file...
def main(): data = { 'technologies': parse_technologies(), 'objectives': parse_objectives(), 'personas': parse_personas(), 'vendors': parse_vendors(), } with open('result.json', 'w') as json_file: json.dump(data, json_file)
def check_firefox_installed(self): firefox_version = self.get_firefox_version() if not firefox_version: self.install_firefox() def download_geckodriver(self): url = self.get_downlaod_url() filenme = os.path.join(self.directory, 'geckodriver-'+self.version+'.' ...
The main task of the code is to install the GeckoDriver by checking if Firefox is installed, downloading the appropriate GeckoDriver version for the platform if it's not already present, extracting it, and returning the path to the extracted GeckoDriver executable file.
def install_geckodriver(self): self.check_firefox_installed() zipfilename = os.path.join(self.directory, 'geckodriver-'+self.version+'.' +DEFAULT_FILE_EXTENSIONS[self.platform]) if not os.path.isfile(zipfilename): self.download_geckodriver() se...
def render_intro(): st.title("KGE QA System") s = "**Factoid-Question Answering System Based on Knowledge Graph Embeddings**" st.markdown(s) help_ = st.checkbox("Show help") if help_: st.write( "This system answers simple factual questions such as `who acted in titanic movie?` " ...
This code defines a Streamlit app for a Knowledge Graph Embedding (KGE) QA system. It logs readiness, renders an intro, takes user questions, generates answers using the `answer()` function, and displays results. Additional sidebar components allow model interaction, new KGE model building, evaluation forms, and a sign...
def run(): logging.info("KGE_QA APP is READY!") render_intro() question = st.text_input("Enter your question: ") if question: results = answer(question) # return: str, str, List[str] st_render_answer(results) _sb_supplementals_play_with_models() _sb_build_new_kge_models() _s...
def embed(self, gs, hs): o_hs = [] o_rs = [] o_ds = [] o_mus = [] o_logvars = [] for g, h in zip(gs, hs): h,r,d,mu,logvar = self.embed_one(g, h) o_hs.append(h) o_rs.append(r) o_ds.append(d) o_mus.append(mu) ...
The code's main task is to process input graphs (gs) and hidden states (hs) through an embedding layer, generate logits via a classifier, and compute a metric using logits, labels, and embedded variables (rs, ds, mus, logvars) for evaluation or loss calculation.
def forward(self, gs, hs, labels): hs,rs,ds,mus,logvars = self.embed(gs, hs) logits = self.classify(hs) return self.metric(logits, labels, rs, ds, mus, logvars)
def data_extraction(self, row_index=0): """ Take the whole dataframe of defect: 1. select the defect through row_index 2. return the lifetime data for this defect under different temperature as a list of array lifetime_diff_T: is a list of array for lifetime data under differ...
The code calculates the parameter $ k $ for varying $ E_t $ values using the slope and intercept from a linear fitted SHR equation at different temperatures. It iterates over $ E_t $, computes $ k $ and $ \tau $ values assuming constant doping and thermal velocities, and plots $ E_t $ vs $ k $ and $ E_t $ vs $ \tau $ a...
def DPSSplot(self): """ return the k value given the Et and slope and intercept of the linear fitted SHR equation each Et will have a k corresponding to it this function assumes that doping is unchanged this function was assuming vp=vn=1, which is wrong, will figure out later ...
def run_example1(): chars = ['a', 'b', 'c', 'd', 'e', 'f'] # frequency of charecters freq = [ 5, 9, 12, 13, 16, 45] # list containing unused nodes nodes = [] for x in range(len(chars)): nodes.append(Huffmantree(freq[x], chars[x])) while len(nodes) > 1: # sort all the nodes ...
The main task of the code is to sequentially execute four example functions (run_example1 to run_example4) and separate their outputs with blank lines, likely for demonstration or testing purposes.
def main(): run_example1() print("\n\n") run_example2() print("\n\n") run_example3() print("\n\n") run_example4()
def checkEndGame(playersChoiceList): for i in range(3): if playersChoiceList[i] == playersChoiceList[i + 3] and playersChoiceList[i] == playersChoiceList[i + 6]: if playersChoiceList[i] != 0: x = (166 * i) + 85 pygame.draw.line(screen, White, (x, 60), (x, 540), 10...
This code implements a single-player Tic Tac Toe game using Pygame, allowing users to select victory points (3/4/5). It handles game initialization, score tracking, AI opponent logic via a minimax algorithm, and displays results with a play-again prompt. The double-player mode is commented out, focusing on AI vs. playe...
def game(): # initializing all variables global running global gameCount #print(gameCount) Init_message = True multiplayerMssg = True pointsMssg = True singlePlayerGame = False doublePlayerGame = False playAgainMssg = True playersChoiceList = [0] * 9 player1Score = 0 ...
def read_data(): keepRecieving = True sock.setblocking(False) # clear buffer of data to get most recent data while(keepRecieving): try: d, a = sock.recvfrom(1024) except: keepRecieving = False sock.setblocking(True) data, addr = sock.recvfrom(1024) # l...
The code continuously reads data to visualize real-time room layouts, UWB anchors, and a tag's position using Turtle graphics. It updates the display by redrawing rooms, anchor positions, and the tag's location based on incoming coordinates, with error handling for connection issues.
def draw_room(): while 1: list, recv_data = read_data() if (recv_data): x = list[0] y = list[1] r = list[2] anchor_range = [list[3],list[4],list[5]] clean(t_rooms) for i in range(len(rooms)): color = "black" ...
def ppdb_matches(ppdb_dict, sent, parser, sent_parsed=None, sent_words=None, single_words=False, max_cand=100, ppdb_dict_key_len=3): pars = defaultdict(set) sent = sent.lower() if not sent_parsed: sent_parsed = parser(sent.lower()) if not sent_words: sent_words = [t.orth_ for t in sent_p...
The main task of the code is to generate all non-overlapping paraphrased versions of a given sentence using a PPDB dictionary. It parses the input sentence, identifies candidate paraphrases, filters non-overlapping combinations, and systematically replaces original phrases with alternatives while fixing grammatical art...
def ppdb_paraphrases(ppdb_dict, sent, parser, single_words=True, ppdb_dict_key_len=3, max_cand=1000): if type(sent)==str: sent_parsed = parser(sent) else: sent_parsed = sent sent_words = [t.orth_.lower() for t in sent_parsed] sent = ' '.join(sent_words).strip() pars = ppdb_matches(pp...
def flatten(ls): return [item for l in ls for item in l] def simple_paraphrases(sent, parser, incl_modal=True, incl_contractions=True, incl_comma=True, incl_indef_pron=True): pars = [] if incl_modal: modals = modal_comb(sent, parser=parser) else: modals = [' '.join([w for w in word_token...
The function `paraphrase_candidates` generates diverse paraphrased versions of input sentences using multiple strategies (PPDB, WordNet, and simple transformations). It iteratively expands paraphrases by randomly selecting existing candidates, applies transformations, removes duplicates, and limits the output to a spec...
def paraphrase_candidates(sents, parser, ppdb_dict, infl_dict, use_ppdb=True, use_wn=True, max_cand=1000, print_time=False): time1 = time.time() if type(sents)==str: sents = [sents] sents = flatten([simple_paraphrases(s, parser=parser, incl_modal=True) for s in sents]) if use_ppdb: ...
def define_wall(self): ''' Wall definition: Every cell has 4 flags (0:free, 1:bocked by wall) 0: Left 1: Up 2: Right 3: Down For eg, self.walls = (0,0) = [0,1,1,0], this means that or cell 0,0: Up and Right sides are blocked by walls ...
The code initializes a grid-based reinforcement learning environment for a player and minotaur. It defines grid dimensions, player/minotaur positions, terminal states (win/dead), and action sets. It generates killing/winning states, calculates total states, and sets up transition probabilities, discount factors, and RL...
def __init__(self): #Origin at Top left self.GRID_SIZE_COL = 6 self.GRID_SIZE_ROW = 5 self.reward = 0 '''State''' # position of player self.p = (0,0) # position of minotaur self.m = (4,4) # dead state self.dead = ((-100, -100), (...
def dump_json_to_file(file, data): with open(file, 'w') as f: json.dump(data, f) def activities_file_for_date(self, date): return self._get_record_from_date(date) + "activities.json" def get_activity_data(self, date): date = convert_date_to_str(With.DASHES, date) subcategorie...
The main task of the code is to update a JSON file with activity data for a specified date. It generates the appropriate file path using `activities_file_for_date(date)`, retrieves the activity data via `get_activity_data(date)`, and writes this data to the file using `dump_json_to_file`. This ensures the activity reco...
def update_activities_file(self, date): self.dump_json_to_file(file=self.activities_file_for_date(date), data=self.get_activity_data(date))
def dump_json_to_file(file, data): with open(file, 'w') as f: json.dump(data, f) def productivity_file_for_date(self, date): return self._get_record_from_date(date) + "productivity.json" def get_productivity_data(self, date): date = convert_date_to_str(With.DASHES, date) prod...
The main task of the code is to update a productivity file with data specific to a given date by generating the appropriate file path and dumping the retrieved productivity data into the JSON file.
def update_productivity_file(self, date): self.dump_json_to_file(file=self.productivity_file_for_date(date), data=self.get_productivity_data(date))
def date_range(start_date, end_date, *, inclusive=True): inclusive_day = 1 if inclusive else 0 days_between_dates = (end_date - start_date).days + inclusive_day for days in range(days_between_dates): yield start_date + datetime.timedelta(days=days) def activities_file_is_up_to_date(self, date): ...
The main task of the code is to iterate through a date range from a specified start date to the current date, checking if the activities and productivity files are up-to-date for each date. If not, it updates the respective files to ensure data consistency and completeness.
def update_data(self): for date in date_range(self.start_date, datetime.datetime.today()): if not self.activities_file_is_up_to_date(date): self.update_activities_file(date) if not self.productivity_file_is_up_to_date(date): self.update_productivity_file(d...
def lecnumber_to_filename(lecnumber: int): """ Converts lecture number to corresponding tex file name. """ return f'lec_{lecnumber:02}.tex' def _init_lectures(self): """ Read in lectures under course path. """ l_paths = self.c_path.glob('lec_*.tex') return sorted(...
This method creates a new lecture file with auto-incremented numbering, sets its date, and updates the master file to include recent lectures. It generates a LaTeX-formatted entry, creates the file, and adjusts the lecture list. If it's the first lecture, it adds it directly; otherwise, it includes the last two lecture...
def add_lecture(self) -> Lecture: """ Creates a new lecture """ if len(self.lectures) != 0: new_l_number = self.lectures[-1].number + 1 else: new_l_number = 1 new_l_path = self.c_path / \ lecnumber_to_filename(new_l_number) to...
def create_player(): global v ,player,instance instance = vlc.Instance() player = instance.media_player_new() player.set_hwnd(videoframe.winfo_id()) def display_info(): global player global duration if player is not None: meta = player.get_media().get_meta(vlc.Meta.Title) tit...
The code defines a `play()` function that loads a video file via a file dialog, initializes a media player, plays the video, updates UI elements (frame border), retrieves the video's duration using `moviepy`, prints the duration, and triggers UI updates. The main tasks are: video playback, UI customization, duration ex...
def play(): global player,instance if player is None: create_player() v=filedialog.askopenfilename() player.set_media(instance.media_new(v)) player.play() videoframe['bd'] = 6;videoframe['relief']='ridge' print(f".player {player}") #=======get length===========...