dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def yesno(userinput): '''Demands a yes/no response from user and stops at nothing to get it.''' while True: #while function called try: return strtobool(input(userinput).lower()) except ValueError: print('Please answer with ''yes'' or ''no''.') def simp_inputting(): '...
The code provides a menu-driven interface to compare the results of Euler and RK4 numerical methods for simulating orbital mechanics scenarios (circular, elliptical, and moon slingshot orbits). It allows users to select a scenario, computes trajectories using both methods, and generates visual comparisons via plots. Th...
def compare_menu(): '''Menu function for comparing results of pre-coded scenarios for Euler and RK4 methods.''' Comp_Input = '0' model = yesno(' [y/n] Take moon into account? ') while Comp_Input != 'q': comp_question = ''' R-K4 vs Euler comparison menu: Enter a ...
def yesno(userinput): '''Demands a yes/no response from user and stops at nothing to get it.''' while True: #while function called try: return strtobool(input(userinput).lower()) except ValueError: print('Please answer with ''yes'' or ''no''.') def default_euler_menu(mode...
The code provides a menu-driven interface for simulating orbital motion using the Euler method. Users can choose between pre-coded scenarios (default values) or input custom parameters (runtime, initial conditions). It calculates orbits, generates plots (trajectory, energy), and produces a mission report, with options ...
def euler_menu(): '''Menu function for Euler orbit method.''' Euler_Input = '0' model = yesno(' [y/n] Take moon into account? ') while Euler_Input != 'q': euler_question = ''' Euler menu: Enter a choice - "1" (default values), "2" (user input val...
def yesno(userinput): '''Demands a yes/no response from user and stops at nothing to get it.''' while True: #while function called try: return strtobool(input(userinput).lower()) except ValueError: print('Please answer with ''yes'' or ''no''.') def default_menu(model): ...
The code provides a menu-driven interface for simulating orbits using the RK4 method, allowing users to choose between pre-defined scenarios (default values) or custom inputs. It handles user input for parameters like runtime, initial conditions, and moon inclusion, then executes the RK4 orbit calculation, generates vi...
def RK4_menu(): '''Menu function for RK4 orbit method.''' RK4_Input = '0' model = yesno(' [y/n] Take moon into account? ') while RK4_Input != 'q': rk4_question = ''' RK4 menu: Enter a choice - "1" (default values), "2" (user input values) ...
def pars_main_page(self,link): if (input("Re-parse main page: ") == "1"): self.__update_user_agent() # self.proxy = self.update_poxi() time_to_load = time.time(); print('@Log ::proxy :{} '.format(self.proxy)) print('@Log ...
This code initializes a web scraper to extract anime-related data from a given main link. It updates the main page, parses all anime pages, collects their URLs, retrieves media links, and stores the data in a Data object. The scraper uses proxies, iterates through pages, and dumps collected information, including anime...
def __init__(self,main_link): self.http_proxy = 'https://free-proxy-list.net/' self.proxy = {} self.link = main_link self.data_dump = Data() self.header = {} self.max_number = 0 self.name_of_anime_pages = [] self.urls_of_anime_pages = [] self.urls_...
def predict(self, data, coefficient=1): matrix = self.calculate_matrix(data, coefficient) pred = np.dot(matrix, self.weights) return pred def _radial_function(self, center, data_point, sigma, coefficient): if sigma == 0: sigma = 0.7 beta = coefficient / (2 * (sigma **...
This function trains a two-stage radial basis function (RBF) network. It initializes RBF centers via k-means, computes spread parameters, and performs either backpropagation with momentum (if enabled) or direct matrix inversion to calculate weights. The goal is to minimize prediction error by iteratively adjusting weig...
def fit_two_stages(self, X, Y, backward_propagation, coefficient=1, epochs=1000, l_rate=0.2, b_rate=0.2): self.centers = k_means(X, self.hidden_neurons) d_max = np.max([get_distance([c1], [c2]) for c1 in self.centers for c2 in self.centers]) self.s = np.repeat(d_max / np.sqrt(2 * self.hidden_neu...
def _create_cells(self): for row in range(self.num_rows): self.cells.append([]) for col in range(self.num_cols): top_left_point = Point(self.x1 + col * self.cell_size_x, self.y1 + row * self.cell_size_y) top_right_point = Point(self.x1 + (col + 1) * self.c...
This code initializes a maze structure with specified dimensions and parameters. It sets up a grid of cells, configures randomization via a seed, and prepares the maze by creating cells, breaking walls recursively for path generation, and setting entrance/exit points. The main task is to construct a maze object ready f...
def __init__ ( self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None ): self.x1 = x1 self.y1 = y1 self.num_rows = num_rows self.num_cols = num_cols ...
def increase_age(self): for i in self.population: self.population[i].age += 1 def breed(self): pop_size = len(self.population) children = [] for i in range(pop_size): parent = self.tournament_selection() child = copy.deepcopy(self.population[parent]) ...
This method performs one generation of an evolutionary algorithm by aging the population, breeding offspring, inserting randomness, evaluating fitness, and extending the population. It records population statistics, tracks best individuals, and saves data if configured.
def perform_one_generation(self): self.increase_age() children = self.breed() children = self.insert_random(children) children = self.evaluate(children) self.extend(children) pf = self.reduce_pop() self.print_best() # record stats self.pf_...
def initialize_grids(self, init_grid, init_signal): if constants.CONTINUOUS_SIGNALING: # both grids are continuous x=np.zeros((constants.GRID_SIZE+2,constants.GRID_SIZE+2,self.n_channels), dtype=float) # +2 for padding else: # both grids are discrete x=np....
The code simulates a grid-based system over multiple iterations, tracking grid states, sensor data, and actions. It initializes grids if starting fresh or continues from prior states. Each iteration updates the grid, records sensor/action data, and appends grid snapshots (excluding borders) to history. Diffusion is app...
def run(self, iterations=constants.ITERATIONS, continue_run=False, additional_iterations=1): if not continue_run: self.grids = self.initialize_grids(self.init_grid, self.init_signal) ca_iter = iterations elif continue_run: ca_iter = additional_iterations hist...
def perform_first_generation(self): self.population = self.evaluate(self.population) self.print_best() # record stats self.pf_sizes_per_gen[0] = len(self.find_pareto_front()) best = self.find_best() self.fits_per_gen[0] = best.get_objective('error') self.best_ind...
The code runs an evolutionary algorithm, either starting fresh or resuming from a checkpoint. It performs generations, saves checkpoints periodically, extends data arrays for continued runs, and collects statistics like fitness, Pareto front sizes, and best solutions. Finally, it returns the best individual and aggrega...
def run(self, continue_from_checkpoint=False, additional_gens=1): if not continue_from_checkpoint: self.perform_first_generation() while self.gen < self.gens + 1: self.perform_one_generation() if self.gen % self.checkpoint_every == 0 and self.checkpoint: ...
def checkQ(self): if len(self.readyQ) == 0: return 'empty' else: ret = '' for i in self.readyQ: ret += i.getName() return ret def checkIO(self, count, time, cs): #print(self.current) #print('checkIO', self.current) #...
The code simulates a First-Come-First-Served (FCFS) process scheduling algorithm, managing process execution, I/O operations, and resource metrics. It tracks CPU utilization, wait time, turnaround time, and processes events like arrivals, CPU bursts, and I/O blocking. The loop processes ready queue tasks, updates time,...
def run(self): print('time {}ms: Simulator started for FCFS [Q {}]'.format(self.time, self.checkQ())) self.time = self.processes[0].getArrival() self.readyQ.append(self.processes[0]) self.current = self.readyQ[0] print('time {}ms: Process {} arrived; added to ready queue [Q {}]'....
def fit(self, xtrain, ytrain, lr=0.01, iter=100000, eps=0.1, normal = True): if normal: xtrain = self.normalization(xtrain, flag = True) ytrain = ytrain[np.newaxis] numiter = 1 cost = 0 cost1 =list() const = 1e-5 #To prevent zero for i in range(iter): cost = -1*(ytrain.dot(np.log(self.sigmoida...
This code performs k-fold cross-validation by splitting the training data into k subsets, iteratively using each subset as a validation set while training on the remaining data. It calculates the model's accuracy for each fold, averages these accuracies, and returns the mean cross-validation accuracy. The parameters in...
def crossvalidation(self, xtrain, ytain, k, alpha = 0.01, iter = 50000, eps = 0.01): size = int(len(xtrain)/k) cv_accuracy = 0 for i in range(k): valstart = i*size valend = valstart + size if i!=(k-1): valend = size xval = xtrain[:valend,:] yval = ytrain[:valend] kxtrain = xtrain[va...
def fit(self,x_train,y_train): self.x_train=x_train self.y_train=y_train self.datadict[0]=np.array([[]]) self.datadict[1]=np.array([[]]) self.datadict=self.gendata(self.datadict,self.x_train,self.y_train) self.datadict[0]=np.transpose(self.datadict[0]) self.datadict[1]=np.transpose(self.datadict[1])...
This function performs k-fold cross-validation on the training data. It splits the dataset into k folds, iterates through each fold as a validation set while training on the remaining data, computes prediction accuracy for each fold, and returns the average accuracy across all folds. The parameters include training dat...
def crossvalidation(self, xtrain, ytain, k, alpha = 0.01, iter = 50000, eps = 0.01): size = int(len(xtrain)/k) cv_accuracy = 0 z=0 for i in range(k): valstart = i*size valend = valstart + size if i!=(k-1): valend = size xval = xtrain[:valend,:] yval = ytrain[:valend] kxtrain = xtr...
def get_dataLoader(args, processor, tokenizer, phase=None): dataset_dict = {"train": args.train_set, "dev": args.dev_set, "std_test": args.std_test_set, "complex_test": args.complex_test_set, "small_test": args.small_test_set, "simple_test": args.simple_test_set} label_li...
The code evaluates a model's performance on a dataset, calculating losses (task and guide) and accuracy metrics. It processes batches, computes predictions using softmax, accumulates results, and logs metrics like accuracy for different model components (experts) and overall loss. Results are stored, visualized via Ten...
def run_eval(device, processor, tokenizer, model, writer, global_step, tensorboard=False, phase=None): sys.stdout.flush() logger.info("\n************ Start {} *************".format(phase)) model.eval() loss_fct = torch.nn.KLDivLoss(reduction='batchmean') cross_entropy = nn.CrossEntrop...
def get_dataLoader(args, processor, tokenizer, phase=None): dataset_dict = {"train": args.train_set, "dev": args.dev_set, "std_test": args.std_test_set, "complex_test": args.complex_test_set, "small_test": args.small_test_set, "simple_test": args.simple_test_set} label_li...
This code trains a model using a custom optimizer and loss function, with gradient accumulation and evaluation during training. It initializes parameters, computes loss with KLDivLoss, and updates the model. It also evaluates performance periodically, saves the best model based on validation accuracy, and logs metrics ...
def run_train(device, processor, tokenizer, model, writer, phase="train"): logger.info("\n************ Start Training *************") tr_dataloader, tr_num_steps, tr_examples = get_dataLoader(args, processor, tokenizer, phase="train") model.train() loss_fct = torch.nn.KLDivLoss(reduction='batchmean')...
def get_dataLoader(args, processor, tokenizer, phase=None): dataset_dict = {"train": args.train_set, "dev": args.dev_set, "std_test": args.std_test_set, "complex_test": args.complex_test_set, "small_test": args.small_test_set, "simple_test": args.simple_test_set} label_li...
The code trains a model using adaptive loss with KL divergence, focusing on parameters in specific layers (shift_layer, shift_classifier). It employs BertAdam optimizer with weight decay, handles multi-GPU setups, gradient accumulation, and early stopping. Training involves iterating over epochs, computing loss from sh...
def run_train(device, processor, tokenizer, model, writer, phase="train"): logger.info("\n************ Start Training *************") tr_dataloader, tr_num_steps, tr_examples = get_dataLoader(args, processor, tokenizer, phase="train") model.train() loss_fct = torch.nn.KLDivLoss(reduction='batchmean')...
def mkdir(path): if not os.path.exists(path): os.makedirs(path) def run_train(device, processor, tokenizer, model, writer, phase="train"): logger.info("\n************ Start Training *************") tr_dataloader, tr_num_steps, tr_examples = get_dataLoader(args, processor, tokenizer, phase="train") ...
The code's main task is to train and evaluate a RoBERTa-based Mixture of Experts (MoE) model for sequence classification. It initializes the model, loads data, sets up training parameters, and executes training or evaluation phases based on command-line arguments. The script handles logging, device configuration, and m...
def main(): mkdir(args.output_dir) args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps writer = SummaryWriter(os.path.join(args.output_dir, 'events')) cache_dir = args.cache_dir device = torch.device("cuda") n_gpu = torch.cuda.device_count() random.seed(args....
def mkdir(path): if not os.path.exists(path): os.makedirs(path) def run_train(device, processor, tokenizer, model, writer, phase="train"): logger.info("\n************ Start Training *************") tr_dataloader, tr_num_steps, tr_examples = get_dataLoader(args, processor, tokenizer, phase="train") ...
The main task of the code is to train and evaluate a RoBERTa-based Mixture of Experts (MoE) model for sequence classification. It sets up GPU configurations, loads data and pre-trained models, and executes training or evaluation phases based on command-line arguments. The model is adapted for binary classification, wit...
def main(): mkdir(args.output_dir) args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps writer = SummaryWriter(os.path.join(args.output_dir, 'events')) # device = torch.device("cuda") device = torch.device("cuda") n_gpu = torch.cuda.device_count() random.seed(...
def reset_instance(): # fails with HTTP 422 because `can't delete a team with contents!` # Teams, Folders are likely to exhibit this behavior # Thus, first delete_all(resource_type_1, resource_type_2, etc), then delete these containers delete_all_items('admin/users') delete_all_items('global_resources') de...
The main task of the code is to initialize and execute a multi-step upload process. It resets the instance, generates team and folder structures, iterates through teams and content types to upload items, and finally uploads user data, ensuring systematic organization and distribution of content across designated folder...
def main(): reset_instance() teams_list = make_teams() pprint({'TEAMS_LIST': teams_list}) folders_list = make_folders(teams_list) pprint({'FOLDERS_LIST': folders_list}) for team in teams_list: for content_name in CONTENT_MAP.values(): print(f'initiate upload_all_items for team:{team}, content_na...
def prepare_url(self, search_word): """Get the Amazon search URL, based on the keywords passed Args: search_word (str): word passed by the user to search amazon.com for (eg. smart phones) Returns: search url: Url where the get request will be passed (it will look someth...
The main task of the code is to search for a product using a given search term, handle pagination by either processing a single page or multiple pages in parallel via threading, and generate a JSON output file containing the collected product data.
def search(self, search_word): """Initializies that search and puts together the whole class Args: search_word (str): user given word to be searched """ search_url = self.prepare_url(search_word) page_content = self.get_page_content(search_url) if (not page_...
def load_jsonl(data_path, use_max=False, max_lines=1000): data = [] with open(data_path) as f: #for loop: Here is the canonical code to open a file, # read all the lines out of it, handling one line at a time. for idx, line in enumerate(f): #json.loads() method can be use...
The function `get_candidates_mp` processes text data using specified tokenizers (BERT, RoBERTa, or DistilBERT) to generate candidate summaries via multiprocessing. It loads JSONL files, validates data consistency, creates temporary directories, and distributes tasks across processes. Results are written to output paths...
def get_candidates_mp(args): # choose tokenizer #Specified when the Arg parseris used to run the file if args.tokenizer == 'bert': tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') cls, sep = '[CLS]', '[SEP]' elif args.tokenizer == 'roberta': tokenizer = Roberta...
def read_documents(input_dir, file_extractor) -> List[Document]: document_reader = SimpleDirectoryReader(input_dir, file_extractor=file_extractor) return document_reader.load_data() def load_llm_model(model: str, timeout: float = 360.0) -> Ollama: check_model_name(model) return Ollama(model=model, requ...
The code's main task is to process documents using AI models for query handling and code generation. It reads documents via a parser, loads language and embedding models, builds a query engine and code generator, creates an agent for code tasks, and runs an interactive prompt loop for user queries. The system integrate...
def main() -> None: # Read documents # TODO: find a way to develop your own parser using notion API file_parser = LlamaParse(result_type="markdown") file_extractor = {".pdf": file_parser} document_path = os.environ.get("document_path") or "./data" documents = read_documents(document_path, file_e...
def prepare(self, seed: int, size: Tuple[int, int]) -> None: self._rnd.seed(seed) octaves = sorted( [self._rnd.randint(1, 7) for _ in range(self._rnd.randint(1, 5))] ) self._noises = [PerlinNoise(seed=seed, octaves=octave) for octave in octaves] self._noise_depth = se...
The code generates an image by creating a grid of noisy pixels, applying a path-walking algorithm to modify pixel values, and coloring the path. It initializes a seed for randomness, constructs an RGB image from the processed pixels, and returns the resulting image.
def generate(self, size: Tuple[int, int], seed: int) -> Image: self._size = size width, height = self._size self.prepare(seed, size) self._pixels = [self.put_noise(i) for i in range(width * height)] self.walk() self.color_path() img = Image.new("RGB", self._size...
def printScreen(self): #BUFFER CHECK if self.screen.displayBuffer < time.time(): #WIPE SCREEN self.screen.wipe() #block self.screen.screenArray = self.block.display(self.screen.screenArray) #landedBlockes for i in self.landedBloc...
The code defines a game loop that continuously updates the game state by printing the screen, handling key presses, moving elements, generating new blocks, and checking for completed rows, ensuring real-time gameplay and interaction.
def game(self): while True: self.printScreen() self.keyPresses() self.moveMent() self.genBlock() self.checkRows()
def push(stack, val): print("Pushing", val) stack.append(val) def pop(stack): if isEmpty(stack): print("Stack underflow") return else: print("Popping element", stack.pop()) return def empty(stack): print("Emptying stack") while not isEmpty(stack): pop(stac...
This code implements a stack-based interactive program where users can push values ('s'), pop elements ('p'), empty the stack ('e'), or quit ('q'). It handles invalid inputs with error messages and displays a farewell message upon exit.
def main(): # Initialize an empty stack. stack = [] # Enter an infinite loop for user interaction. while True: # Prompt the user for an operation ('s', 'p', 'e', 'q'). ch = input() # If 's' is entered, push a value onto the stack. if ch == 's': n = int(input...
def get_all_jobs() -> list[Job]: page = requests.get(BASE_URL).content first_page_soup = BeautifulSoup(page, "html.parser") pages_num = get_num_pages(first_page_soup) all_jobs = get_single_page_jobs(first_page_soup) for page_num in range(2, pages_num + 1): page = requests.get(BASE_URL, {"...
The main task of the code is to retrieve all job data, calculate associated technologies, and save the processed results into a CSV file at the specified output path.
def main(output_csv_path: str) -> None: all_jobs = get_all_jobs() calculate_technologies(all_jobs) write_to_csv(Result_dict, output_csv_path)
def get_default_answer(skill, question): # Retrieve the level from session state or other means level = st.session_state.get("level").value if "level" in st.session_state else None print(level, skill.value, question) if level and skill.value in default_questions and level in default_questions[skill.valu...
The function evaluates a given answer against a question, using either a predefined default answer or an LLM-based assessment depending on the topic (math/English). It first checks for a default answer; if absent, it routes evaluation to math or English-specific methods based on the topic.
def evaluate(llm, topic, skill, question, answer): print("Evaluating. Question:", question, "Answer:", answer) if not answer: return # Check if the question is from the default set default_answer = get_default_answer(skill, question) if default_answer is not None: evaluate_default(s...
def getAddedImped(tarLoc): addedImped = 0 if ('a' in avaiDists(tarLoc)): addedImped += getMinWeight(dt.destruction_wind_rainfall_analysis(), aHos, tarLoc) if ('b' in avaiDists(tarLoc)): # print (tarLoc.x, tarLoc.y) # print (getMinWeight(dt.destruction_wind_rainfall_analysis(), bHos, ...
The function processes tiles to maintain a set of up to 50 tiles with the lowest impedance values. It iterates through shuffled tiles, updating a dictionary (`lastFifty`) by replacing the highest impedance entry with a lower one if applicable. Adjustments to impedance parameters (`adjPar`) are made dynamically, removin...
def downToFifty(tiles): adjPar = {} #initialize adjust parameters lastFifty = {} counter = 1 for i in tiles: adjPar[i] = 1 keys = list(tiles.keys()) random.shuffle(keys) for i in keys: print (counter) ''' if(counter == 135): print ('1/4 DONE!!'...
def _message(message): if message is END_MSG: messageQueue.put_nowait(message) elif isinstance(message, dict): messageQueue.put_nowait(_withRaw(message)) else: for m in message: messageQueue.put_nowait(_withRaw(m)) def _withHost(message, serverName): if 'host' not in ...
This function processes a line of text (JSON or arbitrary) by parsing it, associating it with a server name, and outputting it as an event if non-empty. It uses helper functions to handle parsing, server attribution, and message formatting.
def outputLine(line, serverName): """ Output a single line of text as an event :param line: Either JSON, or else arbitrary text :param serverName: :return: """ if line != '': _message(_withHost(_parseRaw(line), serverName))
def filterRollProviders(vixes, providers): rollProviders = {} for k,indexMap in vixes.items(): p = indexMap['provider'] if p not in rollProviders and p in providers: rollProviders[p] = providers[p] return rollProviders def genSearchString(vixes, providers): m = {'vixes' : vix...
The main task of the code is to execute a Splunk search using a dynamically generated query string, ensuring proper session validation, scheduler compliance, and error handling. It retrieves configuration settings, filters providers/vixes, prepares execution parameters, and dispatches the search with retry logic. Excep...
def execute(): try: keywords, argvals = isp.getKeywordsAndOptions() results,dummyresults,settings = isp.getOrganizedResults() sessionKey = settings.get('sessionKey') if sessionKey == None: return vixutils.generateErrorResults('sessionKey not passed to the search command,...
def _getVixCommand(providerMap): commands = {} for k,v in providerMap.items(): if k.startswith('command'): if k == 'command': commands['command.arg.0'] = v else: commands[k] = v commandsByArgOrder = collections.OrderedDict(sorted(commands.item...
This function executes Java processes for each provider in the given providers dictionary, validating commands, preparing configuration JSON, setting environment variables, and handling execution with logging and error management. It ensures only authorized commands run, constructs necessary arguments, and manages proc...
def _executeJavaProcesses(action, logFileName, indexFilterFunc, providers, vixes, indexes, serverId, serverName, sessionKey): # should be: for providerName in providers.iteritems(): for providerName, providerMap in providers.items(): # Create the command string that will be run in the shell comm...
def _replaceAllSplunkHomeBinJars(m): return _mapValues(_replaceSplunkHomeBinJars, m) def _entityToDict(entity): m = {} for k, v in entity.items(): if isinstance(v, (en.Entity, dict)): m[k] = _entityToDict(v) else: m[k] = v m.pop('eai:acl', None) return m def _...
This function executes a specified action on Splunk providers using the SplunkMR protocol, launching processes for each provider associated with virtual indexes. It filters non-virtual indexes using a provided function, respects provider configurations, and handles authentication/session keys. Output is logged to a spe...
def launchSplunkMRForIndexes(sessionKey, action, logFileName, providers, vixes, indexFilterFunc): """ Will execute an action on each of a set of providers. Here "action" is meant in the sense of the ERP protocol contract, and must have a handler registerd with the SplunkMR java class. This function expects ...
def define_all_signals_without_descriptions(self): config_file_path = "config/config.csv" with open(config_file_path, "r", encoding="utf-8-sig") as file: fileReader = csv.reader(file, delimiter=";") return [[signal, ""] for signal, _ in fileReader] def interface(self): ...
The code initializes a class by setting up signals and their descriptions, establishing an interface, creating a database connection via SignalDataBase, and verifying the database connection state.
def __init__(self): super().__init__() self.signals_and_descriptions = self.define_all_signals_without_descriptions() self.interface() self.SignalDataBase = SignalDataBase() self.successful_database_connection = self.SignalDataBase.connect_with_database() self.check_da...
def get_value_from_coordinate(result, coordinate): """ This helper function obtains the value at the coordinate of an array. >>> result = [[[3, '.'], [3, 3], [1, 1], [0, 0]], [['.', 3], [3, '.'], [1, 1], [0, 0]]] >>> get_value_from_coordinate(result, (0, 0, 1)) '.' """ #run recursive --...
The function `dig_nd` recursively reveals squares on a game board starting at given coordinates, revealing the square and its neighbors if they are safe (no bombs). It updates the game's mask to show revealed squares, checks for bombs to end the game in defeat, and determines victory if all safe squares are revealed. T...
def dig_nd(game, coordinates): """ Recursively dig up square at coords and neighboring squares. Update the mask to reveal square at coords; then recursively reveal its neighbors, as long as coords does not contain and is not adjacent to a bomb. Return a number indicating how many squares were reve...
def _play_audio(self, title): self._logger.info('play entered') if self._player and self._player.is_playing(): self._stop_audio() url = self._get_url(title) playing_thread = Thread(target=self._play_audio_from_url, args=[url]) playing_thread.start() def _pause_audio...
This code processes voice commands to control audio playback. It identifies keywords like 'play', 'pause', 'resume', 'stop', 'raise', or 'lower' in the input command and triggers corresponding actions: playing audio with extracted titles, pausing/resuming/stopping playback, and adjusting volume. The function returns an...
def process(self, command): if 'play' in command: # TODO: Use more elaborate nlp title = command.split("play")[-1] self._play_audio(title) elif 'pause' in command: self._pause_audio() elif 'resume' in command: self._resume_audio() ...
def divide(data, attr_idx): rtn = collections.defaultdict(list) # print(f'{attr_idx}') for line in data: rtn[line[attr_idx]].append(line) return rtn def calc(divided): rtn = 0 for _, value in divided.items(): rtn += calc_entropy(value) * len(value) return rtn
The code recursively builds a decision tree by selecting the optimal attribute index to split the dataset, maximizing a delta metric. It partitions data, evaluates splits, and constructs child nodes until no further splits are possible. Returns the tree structure with node indices, divided subsets, and classification r...
def build_tree(data, possible_index=None): if possible_index is None: possible_index = [i for i in range(len(data[0]) - 1)] count = [line[-1] for line in data].count('yes') if count == len(data) or count == 0 or not possible_index: return -1, data, count / len(data) record = -1e9 # a nu...
def priority(queue): #find the path with shortest distance that will be selected from the priority queue min = math.inf index = 0 for check in range(len(queue)): _,value,_,_ = queue[check] if value<min: min = value index = check #index of the shortest path return ...
This function implements the A* algorithm to find a path for an agent and trailer from a start position to a goal. It uses a priority queue (open_set) to explore states, calculates combined costs (gcost + hurestic), and checks if the current state meets the goal condition. If so, it returns the path; otherwise, it gene...
def A_star(): open_set = [] visited = [] start = [agent_start[0],agent_start[1],agent_start[2],agent_trailer_start[0],agent_trailer_start[1],agent_trailer_start[2]] tcost = 0 gcost = 0 path = [start] open_set.append((start,tcost,gcost,path)) itr =0 while len(open_set)>0: itr+...
def priority(queue): #find the path with shortest distance that will be selected from the priority queue min = math.inf index = 0 for check in range(len(queue)): _,value,_,_ = queue[check] if value<min: min = value index = check #index of the shortest path return ...
The code implements the A* algorithm to find a path from a starting point to a goal. It uses a priority queue (open_set) to explore nodes, calculating total cost (temp_tcost) as a weighted sum of path cost (gcost) and heuristic (hurestic_function). Neighbors are generated via kinematic equations, and the goal is reache...
def A_star(): open_set = [] visited = [] start = agent_start tcost = 0 gcost = 0 path = [start] open_set.append((start,tcost,gcost,path)) while len(open_set)>0: index = priority(open_set) (shortest,_,gvalue,path) = open_set[index] #select the node with lowest distance ...
def log(self, s): """ Log string :param s: string to log """ if self.DEBUG == True: sys.stdout.write("%s\n" % s) def checkoutJob(self): return self.get("jobs/checkout_one", {"workerid" : self.workerId}) def stopProcessing(self): """ signals that proces...
The main task of the code is to manage a worker thread that continuously checks for jobs in a loop. It handles job checkout, processes exceptions by sleeping, terminates or pauses based on job availability and flags, and invokes `userWorker` to process valid jobs. The thread stops when no jobs are pending or when a "PA...
def worker(self): """ Internal worker thread entry point """ self.log("Worker thread active") while True: # keep looping until signaled to stop if self.processing == False: break job = None try: ...
def getFamilies(self): return self.get(f"jobs/families") def getCount(self, family): self.log(f"getcount(family={family})") return self.get(f"jobs/count", { "family" : f"{family}" }) def log(self, s): """ Log string :param s: string to log """ if self.DEBU...
The main task of the code is to retrieve and aggregate counts for each family from a list of families, excluding empty family IDs. It initializes an empty dictionary, iterates through each family, retrieves their count using `getCount`, logs the result, and stores it in the dictionary. Finally, it returns the dictionar...
def getCounts(self): counts = {} families = self.getFamilies() for item in families: family = item["_id"] if family == "": continue c = self.getCount(family) self.log(f"c={c}, family={family}") counts[family] = c...
def resolve_backend(b) -> Backend: if b == "colorThief": return ColorThiefBackend() return ColorZ() def extract_input(arg): colors = extraction.extract(arg) show(trim(colors), "Colors from arguments") def extract_file(arg): path = arg if not is_path_exists(path): ...
The code processes command-line arguments to extract and display colors from input arguments, files, or palettes using a backend. It handles color extraction, sorting, and visualization, with optional GUI output based on flags. Different actions (e.g., extracting from arguments, files, or generating palettes) are trigg...
def handle_input(parser: argparse.ArgumentParser) -> None: args = parser.parse_args() gui_enabled: bool = args.n is False backend: Backend = resolve_backend(args.b) target_colors = args.c or 8 target_template = args.t or "all" if args.g else None execute_arg = (lambda arg, func: func(arg) if arg...
def advance(self, ): self.tok_idx += 1 if self.tok_idx < len(self.tokens): self.current_tok = self.tokens[self.tok_idx] return self.current_tok def power(self): return self.bin_op(self.atom, (TT_POW, ), self.factor)
This function parses unary expressions (handling '+' and '-') by checking the current token. If a unary operator is found, it advances the token, recursively parses the operand via `factor()`, and returns a `UnaryOpNode`. If no unary operator is present, it delegates to `power()` to handle other expression types. The r...
def factor(self): res = ParseResult() tok = self.current_tok if tok.type in (TT_PLUS, TT_MINUS): res.register_advancement() self.advance() factor = res.register(self.factor()) if res.error: return res return res.success(UnaryOpNode(tok, factor)) return self.power()
def advance(self, ): self.tok_idx += 1 if self.tok_idx < len(self.tokens): self.current_tok = self.tokens[self.tok_idx] return self.current_tok def expr(self): res = ParseResult() if self.current_tok.matches(TT_KEYWORD, 'VAR'): res.register_advancement() self.advance() if self.current_tok.type !...
This function parses atomic expressions, handling numbers, variables, parenthesized expressions, and 'if' statements. It returns a parse result with the corresponding node (NumberNode, VarAccessNode, or if_expr) or an error if invalid syntax is encountered, ensuring proper token advancement and validation.
def atom(self): res = ParseResult() tok = self.current_tok if tok.type in (TT_INT, TT_FLOAT): res.register_advancement() self.advance() return res.success(NumberNode(tok)) elif tok.type == TT_IDENTIFIER: res.register_advancement() self.advance() return res.success(VarAccessNode(tok)) elif...
def add_book(): book_title = input("\nPlease enter the book's title: ").title().strip() author = input("Now enter the author's name: ").title().strip() pub_year = int(input("And finally, please enter the year it was published: ")) book = { "title": book_title, "author": author, "...
The code provides a menu-driven interface for managing a reading list, allowing users to add, display, or delete books. It continuously prompts for input, executes corresponding functions based on choices (1-3), and exits on 'q' or 'Q'. Invalid inputs trigger error messages, ensuring user interaction remains within def...
def main(): while True: print("Hello there, what would you like to do?") print("1. Add book to your reading list.") print("2. Display all books in your reading list.") print("3. Delete a book from your reading list.") choice = input("Enter the number of your desired option (o...
def neuralNet(x_train,t_train,lengths,func,eta,lamda,batchsize,itr): np.random.seed(0) biases = [np.random.randn(y, 1) for y in lengths[1:]] weights = [np.random.randn(y, x) for x, y in zip(lengths[:-1], lengths[1:])] # temp=update(x_train,t_train,40000,weights,biases,lengths,func,eta,lamda) te...
The function performs k-fold cross-validation to compute the average accuracy of a neural network. It splits data into 'folds' subsets, iteratively uses one subset as a test set while combining the rest for training, trains the network, and evaluates accuracy. The process repeats for each fold, aggregating results to r...
def crossAccuracy(folds,lengths,func,eta,lamda,batchsize,itr): b=n//folds ac=0 y=[] y1=[] f=0 for i in range(folds): temp=np.array(x[f:f+b,0:m]) temp1=np.array(t[f:f+b]) f=f+b y.append(temp) y1.append(temp1) for i in range(folds): x_test=y...
def generate_optima(d1, d2): optimum1 = np.array([(-(1/d1)*np.log(r))**(1/Q)]) optimum2 = np.array([-(-(1/d2)*np.log(r))**(1/Q)]) return optimum1, optimum2 def standard_adaptation(position, optimum, samp): counter = 0 distance_to_optimum = dist.euclidean(position, optimum) while counter < m: mutation_size, vect...
The code runs a simulation by generating two optima, then iteratively applying adaptation and conflict modeling processes for a specified number of samples. It processes each sample by evaluating standard adaptation to the first optimum and conflict dynamics between both optima, storing results in output files. The mai...
def run_simulation(position, num_samples): optimum1, optimum2 = generate_optima(d1,d2) for sample in range(num_samples): standard_adaptation(position, optimum1, sample) conflict_model(position, optimum1, optimum2, sample) output.close() mut_out.close()
def corr_ss(self, t): return self.kappa / self.lamda * np.exp(-np.abs(t) * self.lamda) def corr_xx(self, t): c1 = np.exp(-self.mu * np.abs(t)) - np.exp(-self.lamda * np.abs(t)) c2 = np.exp(-self.mu * np.abs(t)) d1 = self.rho ** 2 / (self.lamda ** 2 - self.mu ** ...
The code calculates mutual information using log determinants of correlation matrices. It computes the log determinants of three symmetric matrices (c_ss, c_xx, z), then returns half the sum of det_c_ss and det_c_xx minus det_z, representing a measure of statistical dependence between variables.
def mutual_information(self, t): c_ss = np.atleast_2d(self.corr_ss(t)) c_xx = np.atleast_2d(self.corr_xx(t)) z = np.atleast_2d(self.corr_z(t)) det_c_ss = logdet_symmetric(c_ss) det_c_xx = logdet_symmetric(c_xx) det_z = logdet_symmetric(z) return 0.5 * (det_c_ss ...
def corr_ss(self, t): return self.kappa / self.lamda * np.exp(-np.abs(t) * self.lamda) def corr_z(self, t): c_ss = self.corr_ss(t) c_sx = self.corr_sx(t) c_xs = self.corr_xs(t) c_xx = self.corr_xx(t) return np.block([[c_ss, c_xs], [c_sx, c_xx]]) def logdet_symmetric(matri...
This code calculates the conditional entropy of a multivariate Gaussian distribution. It computes the difference between the log determinants of two correlation matrices (from `corr_z` and `corr_ss`) and combines it with a term involving the dimension `n`, returning a scalar value representing the entropy. The formula ...
def conditional_entropy(self, t): c_ss = self.corr_ss(t) z = self.corr_z(t) det_c_ss = logdet_symmetric(c_ss) n = c_ss.shape[0] det_z = logdet_symmetric(z) return 0.5 * (det_z - det_c_ss + n * np.log(2 * np.pi * np.e))
def target_extract(train_set, basic=True): basic_train = {} for sample in tqdm(train_set): target = sample[0] sentence = sample[1] index = sample[2] label = str(sample[3]) if label == '1' and basic: continue if target in basic_train.keys(): ...
The code evaluates model performance on known vs. unknown targets by splitting test data into两类: targets present in training data (known) and those not (unknown). It separates predictions/labels for each group, calculates metrics, and prints results. The main task is to assess how well the model handles known entities ...
def find_unknown(data, pred, label): basic = target_extract(data['train']) basicer = DefaultBasic() know_target = [] uk_target = [] lk_pred = [] lk_label = [] wn_pred = [] wn_label = [] uk_pred = [] uk_label = [] for i, sample in enumerate(data['test']): target = sa...
def target_extract(train_set, basic=True): basic_train = {} for sample in tqdm(train_set): target = sample[0] sentence = sample[1] index = sample[2] label = str(sample[3]) if label == '1' and basic: continue if target in basic_train.keys(): ...
The code evaluates a model's performance on different categories of test samples based on target word characteristics. It categorizes samples into groups (e.g., known with meta, known literal-only, unknown with WordNet mappings) by checking if target words exist in training-derived dictionaries. It collects predictions...
def find_unknown(data, pred, label): basic = target_extract(data['train']) meta_basic = meta_extract(data['train']) all_basic = target_extract(data['train'], False) basicer = DefaultBasic() lk_lo_pred = [] lk_lo_label = [] lk_m_pred = [] lk_m_label = [] om_pred = [] om_label = [...
def load_tsv(path): data=[] with open(path) as f: lines = csv.reader(f, delimiter='\t') next(lines) for line in lines: data.append(list(line)) return data def vua_reform(data, new=False): r_data=[] for s in tqdm(data): sentence = s[2].lower() if ne...
The code's main task is to load and process VUA dataset splits (train/val/test), load precomputed model predictions and labels, evaluate model performance using metrics, identify unknown/misclassified samples, and save processed metadata. It focuses on evaluating sequence prediction models (melodic/basic embeddings) on...
def main(): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) data = {} os.environ["CUDA_VISIBLE_DEVICES"] = '1' path = '../data/VUA20' val_path = '../data/VUA18/val.tsv' test_path = '../data/VUA20/test.tsv' ...
def load_tsv(path): data=[] with open(path) as f: lines = csv.reader(f, delimiter='\t') next(lines) for line in lines: data.append(list(line)) return data def vua_reform(data, new=False): r_data=[] for s in tqdm(data): sentence = s[2].lower() if ne...
The main task of the code is to evaluate model performance on the VUA dataset by loading training/validation/test data, comparing predicted (mel/basic) outputs against labels using metrics, and identifying unknown/failed cases through specialized functions. It configures logging, loads data, processes predictions/label...
def main(): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) data = {} os.environ["CUDA_VISIBLE_DEVICES"] = '1' path = '../data/VUA20' val_path = '../data/VUA18/val.tsv' test_path = '../data/VUA20/test.tsv' ...
def Open_pdf(): global filename cwd = os.getcwd() filename = fd.askopenfilename() global temp temp=0 show(filename) def clear_pdf(): frame.pack_forget() def onrotation(): rotation1.place(x=20,y=335) rotation2.place(x=325,y=335) rotation3.place(x=360,y=335) rotation4.place(x=...
This code handles UI interactions based on the `msg_title` parameter. It hides a frame (`msgframe`) and performs actions like opening/closing files, printing, exiting, or updating UI elements for operations like rotating PDFs, exporting audio, extracting text/images, merging/splitting PDFs, adding watermarks, and encry...
def msg(msg_title): if msg_title=="Open File" or msg_title=="Print" or msg_title=="Close" or msg_title=="Exit": if msg_title=="Open File": msgframe.place_forget() Open_pdf() #print("open File") elif msg_title=="Print": msgframe.place_forget() ...
def parseTXTBoM(self, bomDir): bomData = [] with open(bomDir, 'r') as bom: # skipping cadence logging info for _ in range(7): next(bom) # reading first line which is header data in the following convention # 0 1 2 3 4 ...
The code initializes a comparator for two Bill of Materials (BoMs) by parsing input data (strings or pre-parsed structures), converting them into linked lists, and comparing material attributes (e.g., part numbers under 'PRT_NUMBER'). It stores parsed BoMs, creates linked lists, and triggers a comparison process, outpu...
def __init__(self, oldBoM, newBoM, bomName): if isinstance(oldBoM, str) and isinstance(newBoM, str): oldBoM = self.parseTXTBoM(oldBoM) newBoM = self.parseTXTBoM(newBoM) self.oldBoM = oldBoM self.newBoM = newBoM self.bomName = bomName self.oldBoMdll = sel...
def generate_user_submissions(handle): submissions = get_cf( 'user.status', {'handle': handle, 'count': 10000, 'from': 1}) submission_data = [] for submission in submissions: formatted = format_submission(submission) if formatted is not None: submission_data.append(format...
The function `gen_user_data_files` generates and saves a user's submission and rating history data into CSV files if they do not already exist. It retrieves submission data via `generate_user_submissions`, processes it, and writes it to `submission_fname`. Similarly, it fetches rating history via `generate_user_rating_...
def gen_user_data_files(handle, submission_fname, rating_fname): try: if not os.path.isfile(submission_fname): submissions = generate_user_submissions(handle) submissions = postprocess_submissions(submissions) submissions.to_csv(submission_fname, index=False) ...
def get_data(subset_size=0): filenames = os.listdir(data_folder / 'contests') if subset_size != 0: filenames = filenames[:subset_size] ratings = {} submissions = {} for handlecsv in tqdm(filenames, "reading data"): handle = handlecsv[:-4] contest_results = getPerf(pd.read_csv...
The main task of the code is to retrieve contest and submission data, compute rating change correlations, and generate overall statistics. It logs results to a file, with parameters like subset_size and analysis paths defined. Functions like `compute_rating_change_correlation` and `get_overall_stats` process data into ...
def main(): # count_problem_tags(explode_problem_tags()) subset_size = 0 logging.basicConfig( filename=f'read_data_{subset_size}.log', filemode='w', level=logging.INFO) contests, submissions = get_data(subset_size) df = compute_rating_change_correlation(contests, submissions, analysis_folde...
def generate_problem_data(): formated = [] for problem_data in itertools.chain([get_cf('problemset.problems', {})], [get_cf('problemset.problems', {'problemsetName': 'acmsguru'})]): for problemInfo, statistics in zip(problem_data['problems'], problem_data['problem...
The main task of the code is to generate problem and user data for a programming contest platform, organize data into 'contests' and 'submissions' directories, count the number of contest and submission files, and deduplicate user handles. It logs timestamps, data counts, and outputs results for monitoring and verifica...
def main(): logging.info(f"Script begins running at {datetime.datetime.now()}") generate_problem_data() os.makedirs(data_folder / 'contests', exist_ok=True) os.makedirs(data_folder / 'submissions', exist_ok=True) rated_handles = get_rated_handles() logging.info(f"There are {len(rated_handles)}...
def __perform_temporary_prediction(self): blank_start = -1 blank_end = -1 for i in range(0, len(self.object_list)-1): self.object_list[i].predict_page_printed_number(self.object_list) if not self.object_list[i].predicted_page_temp: if blank_start == -1: ...
The code parses an XML file to extract objects, processes text and page numbers, and fills gaps in document content using temporary predictions and specific numeral systems like Arabic and Roman numerals.
def __init__(self, xml_filename): tree = ET.parse(xml_filename) root = tree.getroot() self.object_list = [] self.blank_gap_dictionary = {} self.last_blank_start = 0 for object_element in root.iter('OBJECT'): object_ = Object(object_element) object_...
def __extract_text_UL(self): result = "" min_x1 = 0 if self.min_word_y2 > 0: for word in self.word_list: if word.y1 <= self.min_word_y2 and (min_x1 == 0 or min_x1 < word.x1) \ and not word.has_inteterferring_text_upwards(self.word_list): ...
The main task of the code is to extract text from six specific document regions (upper left, upper middle, upper right, lower left, lower middle, lower right) by calling private methods, likely to identify potential page numbers or relevant content from structured layouts like multi-column documents or forms.
def extract_possible_page_numbers(self): self.text_UL = self.__extract_text_UL() self.text_UM = self.__extract_text_UM() self.text_UR = self.__extract_text_UR() self.text_LL = self.__extract_text_LL() self.text_LM = self.__extract_text_LM() self.text_LR = self.__extract_t...
def add_event_nodes(schema_graph, args): for event in schema_graph['steps']: # this is to remove 'Transaction.ExchangeBuySell.Unspecified:2' and 'Movement.Transportation.Unspecified:2' # from Car-IED schema, since they are almost equivalent to 'Transaction.ExchangeBuySell.Unspecified:1' # an...
This function processes a dataset schema by loading the appropriate JSON schema based on the dataset name, then constructs graph structures by adding event nodes, edges between events, coreferential nodes, and entity relationships, ultimately returning node relationships, node types, and the number of events.
def read_schema(args): print('processing schema') if args.dataset == 'car_bombings': schema_obj = json.load(open('../data/schema_IED.json'))['schemas'][6] elif args.dataset == 'ied_bombings' or args.dataset == 'suicide_ied': schema_obj = json.load(open('../data/schema_IED.json'))['schemas'][...
def identify_word_category(word): doc = nlp(word) for entity in doc.ents: if entity.label_ == 'ORG': return 'company' # elif entity.label_ == 'PERSON': # return 'person' return 'other' def remove_d(text): start, end = "", "" try: start = text.index('...
The main task of the code is to scrape Wikipedia for information about a given word, determine its category (e.g., company, person), extract relevant details, store them in Neo4j via specific upload functions, and return a formatted summary with a Wikipedia link. It handles both pre-existing Neo4j data and direct web s...
def scrap(word, type_of_word=None): if not type_of_word: type_of_word = identify_word_category(word) print(type_of_word) global context word = word.title() context = word result = get_from_neo(context) print(result) if len(result) > 0: final = result[0]['kb.definition'] ...
def coagulation_propensity(self, group_1, group_2): if len(group_1) > 0 and len(group_2) > 0: opinion_matrix = self.get_opinion_matrix_for_cartesian_prod_of_groups(group_1, group_2) return 2*self.M_links/self.N_agents**2*len(group_1)*len(group_2)*opinion_matrix.sum() else: ...
The function calculates and returns an array of propensities for group interactions, including coagulation between distinct groups, densification, and dissolution. It initializes a zero array, computes coagulation propensities for all group pairs, then adds densification and dissolution values for each group, combining...
def get_propensities(self): propensities = np.zeros((self.N_agents*(self.N_agents + 2), 1)) for i, group_i in enumerate(self.groups): for j, group_j in enumerate(self.groups): if i != j: propensities[i*self.N_agents + j] = self.coagulation_propensity(grou...
def coagulate_groups(self, group_1, group_2): opinion_matrix = self.get_opinion_matrix_for_cartesian_prod_of_groups(group_1, group_2) possible_links = opinion_matrix.nonzero() link_to_add = self.rng.integers(0, len(possible_links[0])) agent_1_to_link = group_1[possible_links[0][link_to...
This function processes an index to determine which group reaction to execute. If the index corresponds to coagulation, it merges two groups by their calculated indices. For densification, it enhances a specific group's density. For dissolution, it splits a group. The index dictates the action type and target groups, e...
def exec_reaction_by_index(self, index): if index < self.N_agents * self.N_agents: group_1_index = index // self.N_agents group_2_index = index % self.N_agents group_1 = self.groups[group_1_index] group_2 = self.groups[group_2_index] self.coagulate_g...
def parse_algo(l): split = l.split('_') ts = split[1] run = split[-2] algo = '_'.join(split[4:-2]).split('.')[0] return (algo, ts, run) def parse_inst(instfile, algo, ts, run): log = open(instfile,'r') bench = [] time = [] for line in log.readlines(): if line.startswith('Benc...
The function parses log files from a directory, processing '_inst.log' and '.cap' files within a specified range. It extracts algorithm data, timestamps, and run details, then aggregates benchmark results, timing data, and capture data into structured lists. Finally, it returns the formatted data using the 'beautify' f...
def _parse(_min=0, _max=None): bench = [] time = [] cap = [] dirlist = os.listdir(LOG_DIR) if _max is None: _max=len(dirlist) for i, l in enumerate(dirlist): if i < _min or i > _max: continue print(f'Parsing log {i}/{len(dirlist)}: {l}') algo, ts, run ...
def sample_hidden(self, visible_vector): hidden_probs = self.calc_prob_hidden(visible_vector) return np.random.binomial(1, hidden_probs) def sample_visible(self, hidden_vector): visible_probs = self.calc_prob_visible(hidden_vector) return np.random.binomial(1, visible_probs) def calc_pro...
The code trains a model using contrastive divergence by iteratively sampling hidden and visible layers, updating weights and biases via gradient descent, tracking mean squared error per epoch, and returning the average error across all epochs.
def train(self, training_data, num_reads=1): self.errors = [] for epoch in range(self.epochs): # Shuffle the training data for each epoch np.random.shuffle(training_data) total_error = 0 for sample in training_data: # Sample the hidden la...
def generate_prior(self, n_samples=None, n_batches=None, n_lists=None): if n_samples is None: if n_batches is None: total_samples = self.batch_size else: total_samples = self.batch_size * n_batches else: total_samples = n_samples ...
This code trains a hybrid GAN-RBM model by alternating between critic (discriminator) and generator updates, using MMD loss and Wasserstein distance. It trains the critic on real/generated data, optimizes the generator to fool the critic, and periodically trains an RBM on feature-layer outputs. Gradient clipping and lo...
def train(self): real_labels = np.ones((self.batch_size, 1)) fake_labels = np.zeros((self.batch_size, 1)) d_loss_real_total = 0 d_loss_fake_total = 0 g_loss_total = 0 rbm_loss_total = 0 rbm_loss = 0 average_critic_loss = 0 wasserstein_dist = 0 ...
def generate_prior(self, n_samples=None, n_batches=None, n_lists=None): if n_samples is None: if n_batches is None: total_samples = self.batch_size else: total_samples = self.batch_size * n_batches else: total_samples = n_samples ...
The main task of the code is to generate synthetic data using a generator model, compute the Wasserstein distance to evaluate data distribution, and visualize results (loss curves, Wasserstein metrics) while saving outputs (plots, parameters) to a folder. It orchestrates data generation, evaluation, and result persiste...
def plot_and_save(self): folder_path = self.create_result_folder() rbm_prior = self.generate_prior(n_samples=1000) generated_data = self.generator.predict(rbm_prior, verbose=0).flatten() self.wasserstein_dist = self.wasserstein_distance(gen_samples=generated_data) self.plot_resu...
def get_metadata_from_video(self, video_filepath, start_or_end): return_time = None success = False if start_or_end == "start": try: # Get the creation date from metadata parser = createParser(video_filepath) metadata = extractMetadata(...
The function extracts start and end times from a video file by first attempting to retrieve metadata, then using OCR on frames if metadata fails. It constructs timestamps by combining filename components and manually extracted seconds, adding a 15-minute duration for end time. Finally, it returns start and end times as...
def get_video_start_end_times(self): # Define logger self.logger.debug(f"Running function get_video_start_end_times({self.filepath})") video_filename = os.path.basename(self.filepath) self.logger.debug(' '.join(["Processing video file -", self.filepath])) # Get start time from ...
def get_data_from_recording_name(self): filename = os.path.basename(self.filepath) # Prepare name elements locality, transect, plant_id, date, hour, minutes = filename[:-4].split("_") file_extension = filename[-4:] # Define compound info recording_identifier = "_".join...
This code initializes a video processing class by setting up logging, extracting metadata (filename, timestamp, format), determining video origin (VT/MS) from file extension, initializing video capture, retrieving FPS and frame count, and validating file type. It also sets start/end times if specified, logging errors f...
def __init__(self, filepath, root = None, ocr_roi: tuple = (0, 0, 500, 60), initiate_start_and_end_times: bool = True): # Define logger self.logger = utils.log_define() # Define variables self.filepath = filepath self.filename = os.path.basename(self.filepath) ...
def digest_data(data: bytes): """Compute the digest of a given input byte string, which are the first 8 bytes of its sha256 hash.""" m = hashlib.sha256() m.update(data) return m.digest()[:8] def get_content(): return extract_file_from_zip_archive( archive, ...
The function checks if a file already exists at the specified path with a matching hash. If not, it downloads the file using the provided get_content function and installs it, returning True on success or False if the file is already up-to-date.
def _get_and_install_file( install_path: str, hex_digest: Optional[str], force_download: bool, get_content: Callable[[], bytes], ) -> bool: if not force_download and hex_digest is not None \ and os.path.exists(install_path): with open(install_path, "rb") as f: content: byte...
def _navigate_permit_heading(self): """ _navigate_permit_heading - finds the permit link on the main page :return: None """ super(PermitRecGov, self).navigate_main_page("Permits") def _load_permit_link(self): """ _get_permit_link - grabs the necessary link from th...
The code automates browser operations to navigate a website, log in, access permit sections, and attempt permit booking. It returns True if successful, False otherwise, handling exceptions by printing errors and returning False.
def execute(self): """ execute - starts the execution of the browser :return: bool: True if successfully in checkout, False otherwise """ try: super(PermitRecGov, self).navigate_site() super(PermitRecGov, self).log_into_account() self._navigate...
def _navigate_camping_heading(self): """ _navigate_camping_heading - finds the camping link on the main page :return: None """ super(CampRecGov, self).navigate_main_page("Camping & Lodging") def _load_camping_link(self): """ _get_camping_link - grabs the necessary...
The code automates booking a campsite by logging into a site, navigating to camping sections, selecting a campsite, handling scheduling details, and polling for availability. It returns True if successful, False otherwise, or catches exceptions to print errors and return False.
def execute(self): """ execute - starts the execution of the browser :return: bool: True if successfully in checkout, False otherwise """ try: super(CampRecGov, self).navigate_site() super(CampRecGov, self).log_into_account() self._navigate_cam...
def is_single_resp(document): if isinstance(document, dict): return True else: assert isinstance(document, list), 'Response object should be a list of documents at this time.' return False def get_master_info(__uid: str | int) -> tuple[str, str, str] | None: """ Returns master to...
The function `query_vault_entry` retrieves user vault entries based on criteria, primary keys, or multiple keys. It authenticates using a user ID and password, sends a POST request to a database API, processes the response, and decrypts protected fields if needed. It returns either a single entry or a list of entries w...
def query_vault_entry(__uid, pw, *, crit=None, pk=None, pks=None): """ Fetch vault entries based on conditions given. Fetches single document if `pk` is passed, and multiple otherwise. Parameters: __uid (int | str): user identification pw (str): raw user password crit (dict): qu...
def encrypt_secret(secret, pw, salt=None): if salt is None: if isinstance(secret, bytes) and isinstance(pw, bytes): return encrypt_secret_bytes(secret, pw) if isinstance(secret, str) and isinstance(pw, str): return encrypt_secret_str(secret, pw) else: rais...
The code demonstrates encryption/decryption of a secret message using a password and salt, generates a master token, hashes a password, and verifies password matches. It illustrates cryptographic operations for secure data handling and authentication.
def _main(): secret, salt = encrypt_secret('secret message', 'your-strong-password') message = decrypt_secret(secret, 'your-strong-password', salt) print(f'Secret : {secret}') print(f'Message : {message}') print(f'Salt : {salt}') token, salt = gen_master_token_and_salt('yo...
def get_charging_time(network=None, q_learning=None, state=None, alpha=0): # request_id = [request["id"] for request in network.mc.list_request] time_move = distance.euclidean(network.mc.current, q_learning.action_list[state]) / network.mc.velocity energy_min = network.node[0].energy_thresh + alpha * networ...
This function calculates three key metrics for a network's performance in a reinforcement learning context: (1) a weighted energy efficiency score (`first`), (2) the ratio of alive nodes to total nodes (`second`), and (3) charging time. These values likely serve as reward components to guide Q-learning decisions, balan...
def reward_function(network, q_learning, state, alpha=0.2, receive_func=find_receiver): charging_time = get_charging_time(network, q_learning, state, alpha) w, nb_node_alive = get_weight(network, network.mc, q_learning, state, charging_time, receive_func) p = get_charge_per_sec(network, q_learning, state) ...
def get_database(db_file): if os.path.exists(db_file): print('Opening ' + db_file) db = open_database(db_file) else: print('No database found. Creating one.') db = create_database() return db def get_energy_estimates_from_folder(energy_estimates_folder): files = os.listdir(energy_estimates_fold...
The main task of the code is to compile energy estimates from a specified folder into a database, update the database with these estimates, format the updated data, and save the revised database back to the original file.
def compile_energy_estimates(): db = get_database(db_file) energy_estimates = get_energy_estimates_from_folder(energy_estimates_folder) updated_db = add_energy_estimates_to_db(db, energy_estimates) formatted_db = format_database(updated_db) save_database(formatted_db, db_file)
def probSet(grid): gridlen = len(grid) init_prob = float(1 / (gridlen ** 2)) probs = list() for i in range(gridlen): temp = list() for j in range(gridlen): temp.append(probability(init_prob, (i, j), grid[i][j].chance)) probs.append(temp) return probs def fool1(gri...
The code compares three agent search strategies (fool1, fool2, smart) across 10 terrain types by generating 10 maps of 50x50 grids, running each agent 10 times per map, and averaging their search counts and traversal distances to evaluate efficiency.
def agentComparator(): terrains = {0.1: "flat", 0.3: "hilly", 0.7: "forested", 0.9: "grid of caverns"} gridlen = 50 num_maps = 10 map_repeats = 10 avg_fool1_search, avg_fool2_search, avg_smart_search = 0, 0, 0 avg_fool1_dist, avg_fool2_dist, avg_smart_dist = 0, 0, 0 # Generating maps fo...
def chem(student2courses, row, term): id_num = row['id_num'] if id_num in student2courses: course_list = student2courses[row['id_num']] if has_taken(course_list, 'CHEM', '110'): if term == 1: return 1 elif has_taken(course_list, 'CHEM', '120'): ...
The function calculates scores for students in a specified cohort and term using multiple scoring criteria, aggregates them, and optionally filters out non-persisted students. It returns a list of ScoredStudent objects with computed scores.
def get_scores_for(cohort: str, term: int, data: DataDictionary, exclusion=True) -> List[ScoredStudent]: score_func_list = [summer_checklist, gpa_score, explorations, tec, lambda row, term: chem(data.student2courses, row, term), local_trajectory, global_trajectory, spor...
def hierarchical_search(reference_frame, current_frame, block_size=64, search_radius=32, max_levels=3): predicted_frames = [reference_frame] error_frames = [] for level in range(1, max_levels+1): scaled_ref = cv2.resize(predicted_frames[-1], (predicted_frames[-1].shape[1] // 2, predicted_frames[-1]...
The code encodes a video sequence using hierarchical motion estimation and compensation. It initializes with the first frame as a reference, then iteratively predicts subsequent frames via motion vectors, computes residual errors, and stores encoded motion vectors and error frames. This reduces data by leveraging tempo...
def encode_video(frames, block_size=64, search_radius=32, max_levels=3): encoded_data = [] reference_frame = frames[0] encoded_data.append(reference_frame) for frame in frames[1:]: predicted_frames, error_frames = hierarchical_search(reference_frame, frame, block_size, search_radius, max_levels...
def compile(): ret = shell(f"""cd ./sandbox && g++ \ -O0 -g -w \ -fprofile-arcs -ftest-coverage \ -fdump-tree-all-graph \ ./sol{EXTENSION} \ -o ./sol && cd .. """) assert ret == 0 def execute_all_Tests(sol, problem_id): ...
The main task of the code is to test a programming problem's solution by setting up a sandbox environment. It copies input/output data and the solution file, compiles the code, runs all tests, logs failed cases into a file, saves coverage data, and cleans up the sandbox directory afterward.
def main(problem_id): try: rmtree("./sandbox") except FileNotFoundError: pass makedirs("./sandbox/") shutil.copytree(f"./result/{problem_id}/in", "./sandbox/in") shutil.copytree(f"./result/{problem_id}/out", "./sandbox/out") shutil.copy(f"./result/{problem_id}/sol{EXTENSION}", "....
def apply_jitter(data_err, jitter, jitter_type): """Apply jitter to the data error bar :param array_float data_err: data error array :param float jitter: jitter value :param str jitter_type: jitter_type ("multi" or "add") """ # Adapt the data_err to the jitter value is needed. if jitter_typ...
The function `overplot_one_data_model` plots observed dataset data and a model prediction (with residuals) on shared axes, optionally phase-folded using ephemeris parameters. It supports zooming into specific time or phase ranges, applies jitter corrections, and handles multi-planet scenarios by isolating a target plan...
def overplot_one_data_model(param, l_param_name, datasim, dataset, datasim_kwargs={}, model_instance=None, oversamp=10, supersamp_model=1, exptime=exptime_Kepler, phasefold=False, phasefold_kwargs=None, datasim_dbf_instmod=None, zoom=No...
def add_twoaxeswithsharex_perplanet(subplotspec, nplanet, fig, gs_from_sps_kw=None): """Add two axes per planet to a subplotspec (created with gridspec) for data and residual plot. """ # Create the nplanet axes gs = gridspec.GridSpecFromSubplotSpec(1, nplanet, subplot_spec=subplotspec) # Create the...
This function overplots observed datasets and a model for each dataset, generating residual plots. It handles phase-folded data for multiple planets if specified, using oversampling and supersampling to refine model accuracy. The function creates subplots for each dataset, displaying data/model comparisons and residual...
def overplot_data_model(param, l_param_name, datasim_dbf, dataset_db, datasim_kwargs={}, model_instance=None, oversamp=10, supersamp_model=1, exptime=exptime_Kepler, phasefold=False, phasefold_kwargs=None, plot_height=2, plot_width=8, kwargs_tl={})...
def center(self): return self.pos + Vector2D(self.radius, self.radius) def reflect(self, reflection_axis): self.velocity = self.velocity - 2 * self.velocity.proj(reflection_axis) def lose(self): self.reset_pos()
The code handles collision detection and response for a game object (likely a ball). It checks collisions with a paddle, adjusting velocity and playing a sound upon impact, and with bricks, reflecting the ball and removing bricks upon collision. It also manages boundary interactions, reversing velocity when hitting scr...
def check_collisions(self, paddle, bricks, paddle_sound, brick_sound): vibrate = False if self.rect.colliderect(paddle.rect): paddle_reflection_axis = utils.collide_detect_polygon_circle(paddle.lines(), self.center(), self.radius) if paddle_reflection_axis: self....
def __motion( self, v_left: float, v_right: float, x: float, y: float, theta: float, dt: float ): """Calculate the forward kinematics of the robot""" aveVel = (1 / 2) * (v_right + v_left) x_Dot = -aveVel * math.sin(theta - math.pi / 2) y_Dot = aveVel * math.cos(theta - math.p...
The code simulates a robot's movement using left/right velocities, updates its trajectory and position, checks obstacles, and returns observations including path, goal direction, obstacles, and reward/status for reinforcement learning.
def step(self, action): vLeft, vRight = action[0], action[1] dt = 0.1 x, y, theta = self.__motion( vLeft, vRight, self.tx[-1], self.ty[-1], self.theta[-1], dt ) ##replaced by finding the actual new point and going there self.tx.append(x) self.ty.appen...
def bad_request(error=None): message = { 'status': 400, 'message': 'Bad Request: ' + request.url + '--> Please check your data payload...' + error, } resp = jsonify(message) resp.status_code = 400 return resp def score(filename): app.logger.debug(filename) # based on curren...
The code processes CSV input data for a machine learning model by accepting a file, saving it to a specified directory, and defaulting to 'sample.csv' if none is provided. It executes a Python scoring script (default: 'score.py' or '_score.py') within an Anaconda environment, using the input CSV to generate a timestamp...
def batch(): """ * Accept input data in csv file and store it to subdirectory <model repo dir>/<job definition id> * Try sample.csv if there's no input data file; * execute the python program (under the anaconda environment) * extract score filename from fileMetadata.json if any, otherwise assume the first pyth...
def _add_replica_id_to_graph(self, num_replicas, result_tensor): """Adds nodes for computing the replica ID to the graph.""" if not num_replicas: self._replica_id = 'unknown' return result_tensor self._num_replicas = num_replicas with ops.control_dependencies(None): # Uses None as d...
The function `trace_tpu` traces tensors from TPU operations in a TensorFlow graph, generating a copy of the result tensor and collecting tracing operations. It processes the graph by adding replica IDs, pre-tracing operations, and handling checkpoints. It iterates through operations, skips unnecessary ones, and creates...
def trace_tpu(self, graph, result_tensor, num_replicas=None): """Traces the tensors generated by TPU Ops in a TF graph. Args: graph: the graph of Ops executed on the TPU. result_tensor: a result tensor of evaluating the graph. num_replicas: number of replicas used on the TPU. Returns: ...
def _pre_tracing(self, graph): """Work needs to be done prior to TPU or CPU tracing.""" operations = graph.get_operations() (opname_idx_map, tensor_list, tensorname_idx_map) = ( TensorTracer._make_op_and_tensor_maps(operations)) self._write_config_section() self._write_op_list_section(opera...
The code traces tensors from CPU operations in a TensorFlow graph, generating a map of trace calls. Each trace call pairs a function (to process a tensor) with the tensor itself, keyed by operation name and output index. It skips excluded ops/tensors, checks user inclusions, and constructs tracing functions for valid o...
def trace_cpu(self, graph): """Traces the tensors generated by CPU Ops in a TF graph. Args: graph: the graph of Ops executed on the CPU. Returns: tracing_calls: a map from keys to trace calls. A key is constructed from an Op's name. A trace call consis...
def get_wordlist(file): f = open(file) wordlist = f.readlines() wordlist = [word.upper().strip() for word in wordlist] return wordlist def get_answer(wordlist): answer = random.choice(wordlist) # print(answer) return answer def refresh_page(headline): console.clear() console.rule(f"[...
The code implements a word guessing game where the player has a limited number of attempts to guess a selected word. It initializes guesses, retrieves a wordlist, selects an answer, and iterates through trials, displaying progress and accepting guesses. If a guess matches the answer, the game ends early; otherwise, it ...
def main(): guesses = ['_' * NUM_LETTERS] * NUM_GUESSES wordlist = get_wordlist(FILE) answer = get_answer(wordlist) with contextlib.suppress(KeyboardInterrupt): # when we forcibly interrupt, game over will appear before program ends for trial in range(1, NUM_GUESSES + 1): r...
def _set_categorical_and_ordinal_features(self, X, to_train): if to_train: self.input_columns = X.columns self.cat_ix = X.select_dtypes(include=["object", "bool"]).columns self.num_ix = X.select_dtypes(include=["int64", "float64"]).columns else: if np.any(...
The main task of the code is to preprocess input data to extract and prepare categorical and ordinal feature descriptions required for initializing a CRF (Conditional Random Field) object. It categorizes features, preprocesses their categories and numerical ranges, and returns the structured predictor descriptions for ...
def preprocess_predictor_descriptions(self, X: pd.DataFrame): """Get the predictor descriptions to be used to intialized a Crf object. Args: X (pd.DataFrame): A set of samples. """ self._set_categorical_and_ordinal_features(X, True) self._categories_preprocessing(X, ...
def _set_categorical_and_ordinal_features(self, X, to_train): if to_train: self.input_columns = X.columns self.cat_ix = X.select_dtypes(include=["object", "bool"]).columns self.num_ix = X.select_dtypes(include=["int64", "float64"]).columns else: if np.any(...
The function preprocesses input features by categorizing and encoding categorical/ordinal variables, handling new categories, and processing numerical features. It returns the unified preprocessed data and identifies rows with new categorical entries for further handling.
def _preprocess_X(self, X, to_train): self._set_categorical_and_ordinal_features(X, to_train) dfs = [] rows_with_new_categories = self._categorical_features_preprocessing(X, to_train, dfs) self._numerical_features_preprocessing(X, to_train, dfs) X_full = self._unite_preprocessed...
def _reset_state(self): self.cat_encoders = [] self.label_encoder = LabelEncoder() self.discretizers = [] self.columns_to_merge = [] self.columns_list = [] self.output_columns = [] self.trained = False self.batch_ind = 0 def _preprocess_X(self, X, to_trai...
The main task of the code is to preprocess input features (X) and labels (y) by applying one-hot encoding, while distinguishing between categorical and ordinal predictors. It handles training data initialization, tracks new categories during inference, and returns preprocessed data as NumPy arrays along with lists iden...
def _preprocess(self, X: pd.DataFrame, y: pd.DataFrame, is_train_set: bool=False): """apply preprocessing on input data, the first call to this method should be done with is_train_set=True Args: X (pd.DataFrame): input features y (pd.DataFrame): input labels is_trai...
def generate_dates(calendar, last_date, days, json=True): if json: return (calendar.valid_days(last_date, end_date=last_date + pd.Timedelta(days, "d"), tz="America/New_York")[1:] + pd.Timedelta(5, "h")).tz_localize(None) return (calendar.valid_days(last_date, end_date=last_date + pd.Timedelta(days, "d"...
The function `runSims` performs Monte Carlo simulations of stock price forecasts using a trained model. It generates multiple simulated price paths over specified days, computes returns and profits for each simulation, and aggregates results like average returns, profit, and precision. The simulations use historical da...
def runSims(hist, model, full_predictors, n_days, n_sims, sig_scal=1, v_scal=1): sims = [] preds = [] all_rets = np.zeros(n_sims) # profits = np.zeros(n_sims) calendar = mcal.get_calendar('NYSE') last_date = hist.iloc[[-1]].index[0] # print(hist) dates = generate_dates(calendar, last_da...
def check_clean(clause): if (clause.__class__.__name__ == "Literal"): return True elif (clause.__class__.__name__ == "Negation"): if (clause.sentence_f.__class__.__name__ != "Literal"): return False else: return True elif (clause.__class__.__name__ == "Disjunction"): return check_clean(clause.sent...
The code converts a knowledge base (KB) into Conjunctive Normal Form (CNF) by recursively decomposing logical expressions. It processes each clause in the KB, breaking down complex operators (e.g., negation, conjunction, implication) into simpler components until they are in CNF. The result is a list of clauses (`cnf`)...
def to_cnf(KB): cnf = [] #clauses for clause in KB: result = [] result.append(clause) while(len(result) != 0): # print(str(result) + "result") # print(str(cnf) + "cnf") temp = result.pop(0) if (check_clean(temp)): cnf.append(temp) else: if (temp.__class__.__name__ == "Negation"): ...
def get_key_chunks_counts(self, key): l = len(bin(key)[2:]) l &= (1 << 256) - 1 if 256 >= l > 192: return 8 elif 192 >= l > 128: return 6 elif l <= 128: return 4 def G(self, r, word): mask = (1 << 8) - 1 final = 0 for i ...
The code encrypts a 128-bit block using a custom cryptographic algorithm with 8 rounds of transformations. It splits the input into four 32-bit components, applies XOR, arithmetic operations (square_plus/square_minus), and key-dependent functions (G) iteratively. The process involves dynamic variable swapping, key chun...
def encrypt_block(self, X): if self.get_key_chunks_counts(X) != 4: raise ValueError() d = X & 0xFFFFFFFF X >>= 32 c = X & 0xFFFFFFFF X >>= 32 b = X & 0xFFFFFFFF X >>= 32 a = X for i in range(1, 9): b = b ^ self.G(5, self.sq...
def get_key_chunks_counts(self, key): l = len(bin(key)[2:]) l &= (1 << 256) - 1 if 256 >= l > 192: return 8 elif 192 >= l > 128: return 6 elif l <= 128: return 4 def G(self, r, word): mask = (1 << 8) - 1 final = 0 for i ...
This function decrypts a 128-bit block using a custom cryptographic algorithm. It splits the input into four 32-bit components, applies iterative rounds of modular arithmetic operations (square additions/subtractions), XORs with key-dependent values via function G, and swaps variables. The 8-round process reverses encr...
def decrypt_block(self, X): if self.get_key_chunks_counts(X) != 4: raise ValueError() d = X & 0xFFFFFFFF X >>= 32 c = X & 0xFFFFFFFF X >>= 32 b = X & 0xFFFFFFFF X >>= 32 a = X for i in range(8, 0, -1): b = b ^ self.G(5, sel...
def encrypt_block(self, X): if self.get_key_chunks_counts(X) != 4: raise ValueError() d = X & 0xFFFFFFFF X >>= 32 c = X & 0xFFFFFFFF X >>= 32 b = X & 0xFFFFFFFF X >>= 32 a = X for i in range(1, 9): b = b ^ self.G(5, self.sq...
The code encrypts data chunks using a counter-based method. It initializes a state `s` by encrypting `S`, then iterates over each chunk `X`. For each chunk, `s` is updated with a square-plus operation, and `X` is encrypted via XOR with a transformed version of `s`. The result is a list of encrypted chunks, leveraging d...
def encrypt_counter(self, chunks, S): results = [] s = self.encrypt_block(S) for X in chunks: s = self.square_plus(s, 1) Y = X ^ self.L(X, self.encrypt_block(s)) results.append(Y) return results
def split_message(self, message): chunks = [] chunk = 0 while message: chunk = message & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF chunks.append(chunk) message >>= 128 return chunks def encrypt_block_coupled(self, chunks, S): results = [] for...
The code encrypts a message by converting it into an integer, splitting it into chunks, applying mode-specific encryption (BLOCK, PLAIN, GAMMING, or COUNTER) with synchronization parameters, reassembling the encrypted chunks, and converting the result back to bytes for output.
def encrypt(self, message: str, **kwargs): plain_msg = int.from_bytes(message.encode(), 'big') chunks = self.split_message(plain_msg) synchro = kwargs['S'] if self.mode == BLOCK: results = self.encrypt_block_coupled(chunks, synchro) elif self.mode == PLAIN: ...
def split_message(self, message): chunks = [] chunk = 0 while message: chunk = message & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF chunks.append(chunk) message >>= 128 return chunks def decrypt_block_coupled(self, chunks, S): results = [] for...
The code decrypts a byte-encoded message using a mode-specific algorithm (BLOCK, PLAIN, GAMMING, or COUNTER), splitting the message into chunks, processing them with the corresponding decryption method, and reassembling the result into a decoded string. It uses a synchronization parameter for certain modes and converts...
def decrypt(self, message: bytes, **kwargs): plain_msg = int.from_bytes(message, 'big') chunks = reversed(self.split_message(plain_msg)) synchro = kwargs['S'] if self.mode == BLOCK: results = self.decrypt_block_coupled(chunks, synchro) elif self.mode == PLAIN: ...
def subaction_indentify(): subjects = [1,5,6,7,8,9,11] for i in subjects: db_subaction[i] = {} for i in subjects: for act_name in action_name_dict: db_subaction[i][act_name] = [] for i in subjects: video_path = op.join(H36M_videos,'S'+str(i),'Videos') ...
The code preprocesses Human3.6M dataset for training/testing, integrating GraphCMR and Pose2Mesh annotations. It loads 3D joints, camera parameters, and SMPL parameters, aligns them by matching frames, and filters SMPL parameters based on fitting errors. It encodes images as base64, extracts 2D/3D keypoints, and genera...
def preproc(mode, output_set): if mode=='train': protocol = 1 else: protocol = 2 # init SMPL smpl_mesh_model = SMPL() # tsv structs we need rows, rows_label, rows_hw = [], [], [] # bbox expansion factor scaleFactor = 1.2 # load datasets provided by GraphCMR data...
def FORWARD_to_SERVERNODE(instr, id_,key,value,cli_ip,cli_port,num_k,time,version,where): global IsThereConn,Socket2,host_S,port_S if instr == "INSERT": Send_to_Serv = {"req":str(instr), "key":key, "value":str(value),"cli_port":int(cli_port), "cli_ip":str(cli_ip),"num_k":int(num_k),"time":time,"whe...
The main task of the code is to manage a distributed node system where nodes join, communicate, and handle data operations (insert, delete, query) using threads and sockets. It coordinates node connections, data replication, and consistency by processing messages like "Joined," "ChangeConnection," and "ToUpDate," while...
def Main(): global NodeInfo,ThereISconnection, SUCC,listeningPort, SERV_Count, IsThereConn,QUERY_DONE,CLI_THREAD,host_S,port_S,Name_of_file global DataList, Replicas,ThereIs,SEARCH_DONE,DELETE_DONE,THREADS,filename,t0,ToUpDate,Instr_Socket,listeningPort_ip,listeningPort socks = [] #asks for t...
def passenger_update(pickup_position): global PASSENGER_PICKED if(PASSENGER_PICKED == False): # get the passenger states passenger_states = PASSENGER_POS[pickup_position] # display the sprite passenger_sprite(passenger_states) def dropoff_update(dropoff_position): gl...
The main task of the code is to reset a game state by assigning new passenger pickup and dropoff positions, updating global variables, and re-evaluating game logic. It randomly selects a new pickup location, ensures the dropoff is different, resets flags, updates positions, and calls game logic to return updated state ...
def restart(I, J, p_I, p_J): global PASSENGER_PICKED global PASSENGER_DROPPED global pickup_position global dropoff_position global NEW_GAME # pickup location of the passenger, a new location pickup_position = random.randint(0, 3) # new p_I and p_J p_I = PASSEN...