dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def parse_arguments(self, argv): try: args = argv opts, args = getopt.getopt(args,"hm:s:p:i:o:",["mail=", "iterations=", "saved=", "past=", "input=", "output="]) except getopt.GetoptError: self.print_help() sys.exit(2) for opt, arg in opts: ...
This code parses command-line arguments to configure and execute a Secret Santa gift-drawing process. It either loads a pre-saved gift assignment or generates a new random draw, writes results to a specified file, and optionally sends the assignments via email. The function handles argument validation, configuration, r...
def run(self, argv): """ Parse arguments, and run a roll and write emails and files depending on command arguments. """ self.parse_arguments(argv) if self.is_command_ok(): self.secretdraw = secretdraw() if self.saved_roll_provided: ...
def get_csv_filepath() -> Path: """ Asks the user for the path to the csv file Raises ------ KeyboardInterrupt If the user enters "q" or "Q" Returns ------- pathlib.Path Path to csv file """ while True: readline.set_completer_delims("\t") readline...
The main task of the code is to label a CSV file by reading configuration settings, processing each row with a labeling function, and saving the updated data. It handles test mode configurations, existing labels, and user interruptions, offering confirmation to save changes before exiting. The tool reads the CSV, appli...
def main(): """ CSV Labeler A simple tool for labeling your csv files """ config = configparser.ConfigParser() config.read("config.ini") if bool(util.strtobool(config["development"]["testmode"])): # Development behavior, set values inside of config.ini csv_filepath = config[...
def mst(self): """Builds the maximum spanning tree for the given data and alpha. The results is kept in the undirected attribute. """ complete_graph = nx.Graph() lexicographic_edges = list(combinations(list(range(self.num_vars)), 2)) weight_list = self.get_weight_list(lex...
The code implements a greedy hill-climbing algorithm to learn chordal k-Directed Graphs (kDGs) by iteratively adding edges to an initial Minimum Spanning Tree (MST). It maintains chordality and enforces a maximum clique size (k_max) while improving the Bayesian Network (BN) score using the BDEU metric. The algorithm ch...
def greedy_learn(self, k_max=np.inf, time_limit=np.inf): """An algorithm for learning kDGs using a greedy hill-climbing approach. The code is influenced by the design of the hill climbing approach used in the pgmpy package (https://pgmpy.org/_modules/pgmpy/estimators/HillClimbSearch.html). Howev...
def passTableToJava(fileName): start6 = time.perf_counter() print("Running NewMatrix Jar!") subprocess.run(["java", "-jar", "RunNewMatrix.jar", str(mu), fileName,str(beta),str(sigma)], text=True) inputClusterInput = open('BlockNumbers.txt', 'r') newSingleBlockNbr = inputClusterInput.readline() ...
The code processes input data from a file, either passing it to a Java tool or building blocks for iterative clustering. It runs transitive closure, adjusts parameters (mu, epsilon) if reprocessing is needed, and recursively restarts the process with updated values. The main task involves clustering/refinement iteratio...
def main(fileName): if runKrisJavaJar: passTableToJava(fileName) else: table = buildBlocks(fileName) iterateBlocks(ERtype, table) runTransitiveClosure() reprocess = iterateClusters() global mu global epsilon #mu = 1 if reprocess and (mu + muIterate < 1....
def main(fileName): if runKrisJavaJar: passTableToJava(fileName) else: table = buildBlocks(fileName) iterateBlocks(ERtype, table) runTransitiveClosure() reprocess = iterateClusters() global mu global epsilon #mu = 1 if reprocess and (mu + muIterate < 1....
The code processes a text file to cluster records based on token frequency statistics, computes clustering metrics (entropy, F-measure, precision, recall), and generates reports. It reads input data, calculates token frequencies, initializes cluster profiles, runs clustering iterations with parameters (mu, epsilon), ev...
def driver(fn, bt, sg, m, mi, eps, epsin, rCM, rFM, cFJ,rpf, jar): global sourceFileName global hasHeader hasHeader = rpf global clusterProfile sourceFileName = fn global runKrisJavaJar runKrisJavaJar = jar #start time start = time.perf_counter() #set paramters programVer...
def prepare(args): args.reader = FileRD args.writer = FileStat if args.dry_run else FileRDWR args.hasher = llehash.Hash.instance(args.digest_algo, args.digest_key) args.executor = futures.ThreadPoolExecutor(max_workers=args.threads) if args.verbose > 1: loglevel = logging.DEBUG elif arg...
The code defines a `main()` function that processes files using configurable hash algorithms and options. It parses command-line arguments for verbosity, dry-run mode, file inclusion/exclusion patterns, encoding settings, concurrency, and hash key. After preparation, it executes tasks in parallel with error handling, u...
def main(): digs = sorted(llehash.Hash.algorithm().keys()) argp = argparse.ArgumentParser() argp.add_argument('-v', '--verbose', action='count', default=0) argp.add_argument('-n', '--dry-run', action='store_true', default=False) argp.add_argument('-S', '--sync', action='store_true', default=False) ...
def get_auto_record_instrums(): conn = sqlite3.connect('sigicom2.db', timeout=30) cur = conn.cursor() ret = cur.execute('SELECT serial from instruments where auto_record is true').fetchall() conn.close() return [x[0] for x in ret] def update_sensor_parameters(): token=get_token() conn = sqli...
The function `auto_acq` automatically acquires data from a list of instruments. It retrieves the instrument serial numbers if not provided, updates sensor parameters, checks each instrument for pending data updates, and fetches the data using `get_data` if updates exist. The task involves managing instrument records, q...
def auto_acq(sn_list=None): if sn_list is None: sn_list = get_auto_record_instrums() update_sensor_parameters() for sn in sn_list: query_dts = check_for_update(sn) if query_dts is not None: get_data(sn, *query_dts)
def load_spec(file, module_name): with open(file, 'r') as fin: lines = fin.read().split('\n') for line in lines: i0 = line.find('#') if i0 != -1: line = line[:i0] i1 = line.find(';') if i1 != -1: line = line[:i1] line = line.replace('-stub ', '') i2 = line.find('stdcall') if i2 == -1: ...
The main task of the code is to load Windows API specification files (user32, IMM32, win32k), parse input data from a file specified by argv[1], process it through three stages of transformation, and finally print the structured output. The code likely analyzes or converts binary/ABI data using these specifications.
def main(argv): load_spec("user32.spec", "user32") load_spec("imm32.spec", "IMM32") load_spec("win32k.spec", "win32k") #print(spec) data = load_and_parse(argv[1]) data = stage1(data) data = stage2(data) data = stage3(data) print('---') print_data(data)
def is_32bit_reg(text): text = text.strip() if text in 'eax,ebx,ecx,edx,esi,edi,ebp,esp,eip,EFLAGS'.split(','): return True return False def is_16bit_reg(text): text = text.strip() if text in 'ax,bx,cx,dx,si,di,bp,sp,cs,ss,ds,es,fs,gs,ip,FLAGS'.split(','): return True return False def is_8bit_reg(text): text...
The main task of the code is to determine the byte size of a given operand (register or memory reference) by checking its type. It returns 4 for 32-bit registers, 2 for 16-bit registers, 1 for 8-bit registers, delegates memory size calculation to `get_mem_size()`, and returns -1 for unknown cases.
def get_size(text): if is_32bit_reg(text): return 4 if is_16bit_reg(text): return 2 if is_8bit_reg(text): return 1 if is_mem(text): return get_mem_size(text) return -1
def is_unknown(op): if is_unknown_mem(op) or is_unknown_reg(op) or is_unknown_var(op): return True return False def is_reg(text, unknown_ok = False): if is_8bit_reg(text) or is_16bit_reg(text) or is_32bit_reg(text): return True if unknown_ok and is_unknown_reg(text): return True return False def is_mem(text,...
This function checks if two operands (op0, op1) can be matched based on their type (register or memory) or equality. If they match, it updates the replace_dict with a mapping between them and returns True. It handles cases where one operand is unknown, ensuring both are of the same type before creating the mapping. Ret...
def operand_match(replace_dict, op0, op1): if op0 == op1: return True if is_unknown(op0) and not(is_unknown(op1)): if is_reg(op0, True) and is_reg(op1, True): replace_dict[op0] = op1 return True if is_mem(op0, True) and is_mem(op1, True): replace_dict[op0] = op1 return True if not(is_unknown(op0)) ...
def text_to_code(text): code = [] lines = text.split('\n') for line in lines: line = line.strip() if line == '' or line == '---': continue if line[:3] == 'kd>': continue if line[:11] == 'Breakpoint ': continue while True: new_line = line.replace(' ', ' ') if line == new_line: break l...
The main task of the code is to verify the correctness of functions `text_to_code` and `data_to_text` for converting text to data structures and back, ensuring semicolon appending, and testing `code_match` for pattern replacement logic. It validates that replacements work as expected and that mismatches are correctly i...
def unittest(): data = text_to_code('A = 1') assert data_to_text(data) == 'A = 1;' data = text_to_code('push eax') assert data_to_text(data) == 'push eax;' data = text_to_code('pop eax') assert data_to_text(data) == 'pop eax;' data = text_to_code('push eax\npop ebx') assert data_to_text(data) == 'push eax;\npop...
def Lg_i(self, x, i, po): return self.grad_h(x, i, po)@self.g(x,i) def Lf_i(self, x, i, po): return self.grad_h(x, i, po)@self.f(x,i) def h(self, x, i, po): px, py, vx, vy = x[i].flatten() pox, poy = po.flatten() return 2*(vx*(px - pox) + vy*(py - poy)) + self.alpha*((pox - px)...
This function constructs a matrix by combining vectors from lists A and b. For each observation in 'obs', it computes 'Lg_i' values into A and 'Lf_i + eta*h' values into b. It then stacks these vertically and horizontally to form a concatenated matrix, likely for optimization or constraint formulation in a system of eq...
def psi_1_eq(self, x, obs, i, eta): A, b = [], [] for po in obs: A.append(self.Lg_i(x, i, po)) b.append(np.atleast_2d(self.Lf_i(x, i, po) + eta*self.h(x, i, po)).T) return np.hstack([np.vstack(A), np.vstack(b)])
def Lf_iLg_i(self, x, i): return self.gradi_Lg()@self.f(x, i) def Lg_iLf_i(self, x, i, po): return self.gradi_Lf(x, i, po)@self.g(x, i) def Lg_i(self, x, i, po): return self.grad_h(x, i, po)@self.g(x,i)
The function computes a matrix by iterating over observations, combining Lie derivative terms (Lf_iLg_i, Lg_iLf_i) and scaled Lg_i terms weighted by (eta + kappa), then stacking results vertically.
def q(self, x, obs, i, eta, kappa): # Returns a matrix of shape O x M_i q = [] for po in obs: q.append(self.Lf_iLg_i(x, i).T + self.Lg_iLf_i(x, i, po) + (eta+kappa)*self.Lg_i(x, i, po)) return np.vstack(q)
def Lf_jLf_i(self, x, i, j, po): return self.gradj_Lf(x,i,j,po)@self.f(x, j) def L2f_i(self, x, i, po): return self.gradi_Lf(x, i, po)@self.f(x, i) def Lf_i(self, x, i, po): return self.grad_h(x, i, po)@self.f(x,i) def h(self, x, i, po): px, py, vx, vy = x[i].flatten() pox, poy =...
The function computes a stacked array of scalar values derived from combining multiple terms involving functions Lf_jLf_i, L2f_i, Lf_i, and h, scaled by parameters η and κ. It iterates over observations in 'obs', calculates a sub-total for each, adds weighted function evaluations, flattens the result, and concatenates ...
def b(self, x, obs, i, eta, kappa, N_in): # Returns a scalar b = [] for po in obs: sub_tot = sum([self.Lf_jLf_i(x, i, j, po) for j in N_in]) b.append([(sub_tot + self.L2f_i(x, i, po) + (eta+kappa)*self.Lf_i(x, i, po) + eta*kappa*self.h(x, i, po)).flatten()]) retu...
def readint() -> int: """ Reads an integer from :code:`stdin`. This function expects a single line of input with only an integer present. If the input value is not an integer, the program exits. :rtype: int :return: The integer held in the :code:`stdin` buffer. """ # Initialize storage. ...
The main task of the code is to implement Freivalds' algorithm for probabilistically verifying whether the matrix product of A and B equals matrix C. It reads input matrices A, B, C, then uses a randomized vector-based check to determine if AB ≈ C with high probability, outputting the result.
def main() -> None: """ A simple test harness for *Freivalds' test*. """ n: int = readint() A: list[list[int]] = readmatrix(n) B: list[list[int]] = readmatrix(n) C: list[list[int]] = readmatrix(n) print(freivalds(A, B, C))
def copy_tools(self): if not self.tools_copied: print("Pushing updated scripts") self.execute_command('mkdir -p ' + self.basedir) self.copy_file(os.path.join(script_path, 'tools'), self.basedir, recursive=True, keep=True) self.tools_copied = True def execute_comma...
The code retrieves configuration data by executing a shell script, validates the command's success, processes the output by decoding and splitting it into lines, and returns the cleaned configuration list.
def get_config(self): self.copy_tools() status, stdout, stderr = \ self.execute_command(self.toolsdir + '/get_configuration.sh') assert status == 0, "Failed to get config" config = stdout.decode().split('\n') return clean(config)
def copy_tools(self): if not self.tools_copied: print("Pushing updated scripts") self.execute_command('mkdir -p ' + self.basedir) self.copy_file(os.path.join(script_path, 'tools'), self.basedir, recursive=True, keep=True) self.tools_copied = True def formatstring(...
The main task of the code is to generate and deploy a Vyatta configuration script to a router. It validates input parameters, constructs a Vbash script with specified actions (compare/commit/commit-confirm), writes it to a temporary file, copies it to the target router, and returns the filename. The script applies conf...
def push_config(self, config, action='compare'): assert type(config) is str assert action in ['compare', 'commit', 'commit-confirm'] self.copy_tools() if action == 'commit-confirm': action = "echo 'y' | commit-confirm 5" script = f""" #!/bin/vbash ...
def initialize_box_score(self): return {pos: [0] * 11 for pos in ['PG', 'SG', 'SF', 'PF', 'C', 'Team']} def possession(off_team, def_team): ''' Simulates a possession and returns the players' stats. ''' # initialize who will have the ball on the next possession next_team = def_team # ini...
The code simulates a basketball game by initializing team box scores, calculating possessions based on team pace, and iterating through possessions where offensive and defensive teams alternate. It updates box scores with results from each possession, switches team roles, and aggregates final stats before returning bot...
def play_game(self): team1_box_score = self.initialize_box_score() team2_box_score = self.initialize_box_score() num_possessions = int(np.ceil(sum([self.team1.pace, self.team2.pace]) / 2.0)) off_team, def_team = self.team1, self.team2 for _ in range(num_possessions * 2): ...
def generate_field_types(t_data): # print (t_data[0]) data_labels = {"str": 0, "num": 0, "dt": 0} field_name_types = {} field_name_types_array = [] for field_name in t_data[0]: current_label = non_null_label(t_data, field_name) # t_data[0][field_name] ...
The function generates training data pairs by processing JSON files from a directory, normalizing field names, and creating source-target pairs. It samples data, tracks sequence lengths, shuffles pairs, and splits them into output files according to specified parameters for model training.
def generate_data_pairs(examples_directory, train_data_output_directory, data_split_params): all_sources_hold = [] all_target_hold = [] max_source_seq_length = 0 max_target_seq_length = 0 print("Generating source and target pairs ======") for subdir, dirs, files in os.w...
def findid(id): cur=db.all() for row in cur: if str(id)==str(row[0]): return True return False def creatable(item): path=findpath("-p",item,False) if path!=None: print(relpath(path)+" is already exist.") return None if not os.path.exists(item): print("...
The function generates unique identifiers for items by combining a type (from idtype) with an incrementing number, ensuring each ID is unique in the database. It processes each item in the 'items' list, creates a path using 'creatable()', and stores the item in the database with the generated ID if the path is valid. I...
def create(idtype,items): selected=False idtype=str(idtype).upper() if len(idtype)>1: idnum=int(idtype[1:]) idtype=idtype[0] selected=True else: idnum=1 id=idtype+str(idnum) i=0 for item in items: i+=1 j=0 while findid(id): ...
def retrieve(option,items,show=False): wholetext="" for item in items: path=findpath(option,item) if path==None or path==0: return None text=file.read(path) wholetext+=text if show: print(text) return wholetext def relpath(path): try: ...
The code compares word frequencies between two texts (questioned and known) by retrieving, cleaning, and counting words. It outputs top words in descending order, paginating results in chunks of 20, allowing user interaction to view more or quit.
def compare(option,questioned,known): qtext=retrieve(option,questioned) ktext=retrieve(option,known) if qtext==None or ktext==None: return qtext="".join(c for c in qtext if c.isprintable()) qtext=qtext.split() qdict={} for word in qtext: if word in qdict: qdict[wo...
def im2dots(filename, n_points): # Make a points cloud from an image's filename # Load the picture and make it a greyscale array im = picture_treatment(filename) # Convert to a dotted picture probabilities = convert_to_black_probabilities(im) x, y = convert_pic_to_scatter_plot(probabilities, i...
The code processes a sequence of images by converting each into a set of points, computes transport plans between consecutive images to form a cycle, and ensures the cycle is closed by connecting the last image back to the first if more than two images are provided. The results are saved for further use.
def main(): if len(conf.picture_list) < 2: raise ValueError("Multiple pictures must be provided") else: print(f"{len(conf.picture_list)} pictures were found") dotted_pictures = [] # Will store scatter plots in the order of the cycle plans = [] # Will store any transport plan between a p...
def new_cases(self, country, startDate, endDate=None): if endDate==None: date_obj=self.str_to_obj(startDate) prev_date_obj=date_obj-dt.timedelta(days=1) prev_date=self.obj_to_str(prev_date_obj) if prev_date in self.fields: return self.dict[country][startDate]-self.dict[country][prev_date] else: r...
This code calculates the case rate (as a percentage) for a specified country on a given date or date range. If endDate is provided, it iterates through each date, computes the rate using new_cases and stored data, and returns a list of results. If endDate is omitted, it returns a single percentage value for the start d...
def rate(self, country, startDate, endDate=None): if endDate==None: c=self.new_cases(country,startDate) n=self.dict[country][startDate] if c!= None and n!=0: # n=self.dict[country][startDate] return (c/n)*100 else: return 0 else: retlist=[] endDate=self.__increment_date(endDate) whi...
def new_cases(self, country, startDate, endDate=None): if endDate==None: date_obj=self.str_to_obj(startDate) prev_date_obj=date_obj-dt.timedelta(days=1) prev_date=self.obj_to_str(prev_date_obj) if prev_date in self.fields: return self.dict[country][startDate]-self.dict[country][prev_date] else: r...
The main task of the code is to calculate a global rate (as a percentage) of new cases relative to total cases for a specified date range. If no end date is provided, it computes the rate for a single date by summing values across all entries. If an end date is provided, it iteratively calculates and returns the rate f...
def global_rate(self, startDate, endDate=None): if endDate==None: sum_cases=0 sum_new_cases=0 for x in self.dict.keys(): sum_cases+=self.dict[x][startDate] sum_new_cases+=self.new_cases(x,startDate) rate=(sum_new_cases/sum_cases)*100 return rate else: retlist=[] endDate=self.__increment...
def new_cases(self, country, startDate, endDate=None): if endDate==None: date_obj=self.str_to_obj(startDate) prev_date_obj=date_obj-dt.timedelta(days=1) prev_date=self.obj_to_str(prev_date_obj) if prev_date in self.fields: return self.dict[country][startDate]-self.dict[country][prev_date] else: r...
This function calculates total new cases across all regions for a given date (startDate) or returns a list of daily totals between startDate and endDate by recursively aggregating data. If endDate is provided, it iterates through each day, incrementing the date until reaching endDate, collecting daily global new cases ...
def global_new_cases(self, startDate, endDate=None): if endDate==None: sum=0 for x in self.dict.keys(): sum+=self.new_cases(x,startDate) return sum else: retlist=[] endDate=self.__increment_date(endDate) while startDate!=endDate: retlist.append(self.global_new_cases(startDate)) startDa...
def _get_process_name(path: Path) -> str: return path.absolute().parent.name def run_triggers(self) -> int: if isinstance(self._rootfile_path, pd.DataFrame): c = self._rootfile_path["efficiency"] assert np.std(c) < 1e-10, f"{np.std(c)}\n{c}" trigger_efficiency = np.mean(c...
The code initializes an object to process either a ROOT file or a pandas DataFrame, extracting process information and preparing data structures for event selection. It determines the process name from the input, loads data, applies triggers and preselections, and tracks unselected events for analysis.
def __init__( self, rootfile_path: Union[Path, pd.DataFrame], config: Config, ) -> None: self._rootfile_path = rootfile_path self._config = config if isinstance(self._rootfile_path, Path): self._rootfile = uproot.open(self._rootfile_path) self...
def train_step_lester(self, batch, task=None, progressive=True): prefix_len = self.prefix_len model = self.model embed_prompt = self.prefix_MLPs!=None if embed_prompt: assert task!=None ...
The code implements multi-task learning training by iterating over multiple tasks' data, handling imbalanced dataset sizes through cycling, combining losses from all tasks during training, and evaluating model performance on each task after each epoch. It supports prompt tuning and saves validation/test results.
def multi_task_training(self, num_epochs=5, progressive=False, save_path=''): tasks_data_dict = self.tasks_data_dict val_scores = {x: [] for x in list(tasks_data_dict)} # getting index of the largest dataset (other datasets will be cycled) task_lengths = [len(tasks_data_dict[t]['train'])...
def _determinist_matrix(self): """Generate the 12x12 pre-defined matrix from the subject.""" matrix = np.array( [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0], [0, 0, 3, 3, 3, 0, 0, 3, 3, 3, 0, 0], ...
This code initializes a grid-based reinforcement learning environment with a 12x12 matrix. It defines observation (flattened 144D) and action spaces (4 directions), sets up agent/guard positions, pillars, and hiding spots. The environment supports deterministic or random configurations, validates positions against obst...
def __init__(self, render_mode=None, determinist=False): # Flatten observation space 12x12 -> 144 self.observation_space = spaces.flatten_space( spaces.Box(low=0, high=4, shape=(MATRIX_SIZE, MATRIX_SIZE), dtype=np.uint8) ) # 4 possible actions self.action_space = gym....
def _determinist_matrix(self): """Generate the 12x12 pre-defined matrix from the subject.""" matrix = np.array( [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0], [0, 0, 3, 3, 3, 0, 0, 3, 3, 3, 0, 0], ...
The main task of the code is to reset the environment by initializing a 12x12 matrix with random or predefined positions for the agent, guard, pillars, and hiding spots, ensuring no overlaps with pillars. It validates positions, updates the matrix with entities, and returns the observation and info. The reset supports ...
def reset(self, seed=None, options=None): """Reset the environment. Random position for AI, agent and pillars.""" super().reset(seed=seed) # 12x12 matrix with posiiton of Agent, player, pillars and good hiding spots if self.determinist: self.matrix, self.pillars = self._dete...
def _get_predetermined_pillars(self): """Get the pre-defined coordinates of the obstacles from the subject to generate a pre-determined 12x12 map.""" matrix = np.array( [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
The code generates a grid environment for a "Hide and Seek" game, creating walls, placing pillars (deterministically or randomly), positioning a lava guard, hiding spots with goals, and initializing the agent. It sets up the environment's layout and mission for the game.
def _gen_grid(self, width, height): """Generate the grid and place all elements. This method is called by gym's reset()""" # Create an empty grid self.grid = Grid(width, height) # Generate the surrounding walls self.grid.wall_rect(0, 0, width, height) if self.dete...
def strip_margin(text: str) -> str: return re.sub("(^|\n)[ \t]*\|", "\\1", text) def create_config(par, component_type, pretty_name, script_path) -> str: info_str = generate_info(par, component_type, pretty_name) resources_str = generate_resources(par, script_path) docker_platform = generate_docker_platform(par...
The main task of the code is to validate input parameters, determine script type based on language, check and parse an API file for component type, generate a configuration file, create a corresponding script (Python/R) using API data, and write these outputs to a specified directory. It ensures proper formatting, enfo...
def main(par): ####### CHECK INPUTS ####### print("Check inputs", flush=True) assert re.match("[a-z][a-z0-9_]*", par["name"]), "Name should match the regular expression '[a-z][a-z0-9_]*'. Example: 'my_component'." assert len(par['name']) <= 50, "Method name should be at most 50 characters." pretty_name = re....
def _solve_svd(self, X, y): n_samples, n_features = X.shape n_classes = len(self.classes_) self.means_ = _class_means(X, y) if self.store_covariance: self.covariance_ = _class_cov(X, y, self.priors_) Xc = [] for idx, group in enumerate(self.classes_...
The main task of the code is to fit a linear model (likely a discriminative classifier like LDA or logistic regression) by validating input data, estimating class priors, determining the maximum number of components, selecting a solver (SVD, LSQR, or eigen), and applying the corresponding algorithm to compute model coe...
def fit(self, X, y): X, y = self._validate_data( X, y, ensure_min_samples=2, dtype=[np.float64, np.float32] ) self.classes_ = unique_labels(y) n_samples, _ = X.shape n_classes = len(self.classes_) if n_samples == n_classes: raise ValueErr...
def how_file_obtained(url, filename, bloburl, directory): """ Log how we obtained file and set meta accordingly """ if url==None and filename==None and bloburl==None and directory==None: print("URL, Filename, BlobURL and Directory were not supplied. Must exit") raise ValueError("Must supply one...
The main task of the code is to ingest data into a system by determining the source of the file (single file or blob) via the `how_file_obtained` function. If the source is a blob, it processes it iteratively using `loop_blob`; otherwise, it directly sends the file to Google Cloud Storage via `to_gcs_flow`. The functio...
def ingest_flow(category: str, url: str = None, filename: str = None, bloburl: str = None, directory: str = None): globals()['CATEGORY'] = category meta = how_file_obtained(url, filename, bloburl, directory) if meta > 1: # Bl...
def decision_tree_Build(train,maxdepth,min_size): root=get_best_split(train) split_func(root,maxdepth,min_size,1) return root def predict(node ,row): if row[node['index']]<node['value']: if isinstance(node['left'],dict): return predict(node['left'],row) else: retu...
The function trains a decision tree classifier on the training data, predicts outcomes for test samples, compares predictions with actual labels to calculate accuracy, and returns the list of predicted labels.
def Decision_Tree_classifier_func(train,test,max_depth,min_size): tree=decision_tree_Build(train,5,1) predictions_list=[] actual=[] for row in test: actual.append(row[1]) predictions_list.append(predict(tree,row)) score=accuracy_metric_func(actual,predictions_list) #print(score)...
def adjacent(size_list, l, w, h): ''' Given a list of the 3 Dimensional size of the cube of cubes, and the location of cubes and faces adjacent to it, return a dict containing THIS cube's face number, and the LHW coordinates of the adjacent Cube and the face number. ''' adj = {} ...
The main task of this code is to generate a 3D toroidal structure of interconnected cubes (NxNxN) where each cube's faces align with adjacent cubes. It initializes a "oneself" anchor cube, propagates its faces along axes, and fills remaining faces by resolving conflicts between neighboring cubes. The message sequence i...
def create_NxNxN_seq_old(stan, size_list, message_seq): ''' ------------- WARNING ------------- THIS DOES NOT WORK! What happens is that when we fill in blanks, the blanks propogate to neighbors and the neighbors down the line may already have a block that doens't match... ...
def initialize_torus(size_list, stan): #Create a reference cube. fcs = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$!' fc = cube(fcs, 0, stan[0], stan[1], stan[2]) #Iterate over all and build the info object for each lmax = size_list[0] wmax = size_list[1] hmax = size_li...
The main task of the code is to construct a 3D torus-like structure of cubes where each cube's faces are matched with their opposite faces, ensuring no conflicts through propagation. It initializes a network of cubes, applies a message sequence by replacing '.' characters in each cube's sequence, and propagates changes...
def create_3torus(stan, size_list, message_seq): ''' Create one cube where all faces match the face opposite of it one base at a time. Then propogate the changes through the entire cube network to ensure no conflicts. The center 4 on each face are fair game that aren't at 0,0,0, or extendi...
def smooth(x,windowlenth=11,window='hanning'): "windowlenth need to be an odd number" s = np.r_[x[windowlenth-1:0:-1],x,x[-2:-windowlenth-1:-1]] w = getattr(np,window)(windowlenth) return np.convolve(w/w.sum(),s,mode='valid')[windowlenth//2:-(windowlenth//2)] def pickpeaks(peaks,props,totalpoints): ...
The function `myfitpeak` processes voltage-current data to detect and analyze peaks. It smooths the current data, filters out edge regions, and identifies significant peaks using thresholds based on noise statistics. It calculates peak characteristics (current, voltage) via tangent lines, returning filtered data, peak ...
def myfitpeak(xydataIn): x = xydataIn[0,:] #voltage y = xydataIn[1,:] #current sy = smooth(y) prange_flag = ((x.min() + 0.025) < x)*((x.max() - 0.025) > x) sy_for_fit = sy[prange_flag] x_for_fit = x[prange_flag] noise = np.absolute(y - sy) # limit peak width to 1/50 of the totoal scan ...
def should_discard_this_execution(self): if abs(time.time() - self.__prev_successful_exec_timestamp - Constants.TICKER_TIME) > 2: log.info("Discard execution as most likely we skipped some tracking or we've just launched this tool") return True else: return False def ...
The code monitors applications and URLs based on configurations. It checks if applications need timer updates or closure due to limits, then evaluates whitelisted/blacklisted URLs. If blacklist matches are detected, it adjusts timers (full or half TIMERTICKER) based on interval timing and prior states, closing apps whe...
def monitor(self, configs_file: str): if not self.should_discard_this_execution(): self.setup_date_monitor() configs = ConfigsManager(configs_file) #1. check applications. If application is in the list we need to update timer. If timer limit is reached close app ...
def __create_presentation(slideInfo): template = slideInfo.get('template') if (template is not None): if (not isinstance(template, str)): template = None else: if (not path.isfile(template)): template = None return Presentation(template) def __create_...
The main task of the code is to generate a PowerPoint presentation from structured input data, handling slide creation, chart insertion, and font configuration. It initializes a presentation, iterates through slides and charts, applies default fonts where missing, creates slides and placeholders, inserts charts, and re...
def toPPT(presentation): ppt = __create_presentation(presentation) if ppt is None or isinstance(ppt, str): return 'Could\'t create PPT' slide_count = 0 body_font = presentation.get('body_font') if body_font is None: body_font = dict( name='Verdana', size=10 ...
def reset_combo(self, keyboard, combo): combo.reset() if combo._timeout is not None: keyboard.cancel_timeout(combo._timeout) combo._timeout = None self._reset.add(combo) def activate(self, keyboard, combo): combo.result.on_press(keyboard) self._active.appe...
The main task of the code is to handle key press events for combo inputs with timeout management. It filters potential combos, manages active matches, updates key buffers, triggers combo activation or reset based on timeout states, and ensures proper key handling by either sending buffers or re-evaluating keys when no ...
def on_press(self, keyboard, key: Optional[Key], int_coord): # refill potential matches from timed-out matches if not self._matching: self._matching = list(self._reset) self._reset = set() # filter potential matches for combo in self._matching.copy(): ...
def h1_GreedySearch(candidate_units): rate = 0 motions = [] # print(candidate_units) # Iterating through the paths to find one with the highest success rate for unit in candidate_units: motion = foon_functional_units[unit].motion_node motions.append(motion) ...
The main task of the code is to generate a task tree of functional units (FUs) required to achieve a goal node in a kitchen environment, using a specified search strategy (e.g., greedy or IDDFS). It explores input nodes of selected FUs, ensuring all necessary ingredients and containers are included, and constructs a re...
def search_Main(kitchen_items=[], goal_node=None, search=None): # list of indices of functional units reference_task_tree = [] # list of object indices that need to be searched items_to_search = [] # find the index of the goal node in object node list items_to_search.append(goal_node.id) ...
def get_piece_from_action(self, action): return (action // 9) + 1 def get_index_from_action(self, action): pos = self.get_pos_from_action(action) # [0-8] piece_size = self.get_piece_size_from_action(action) # [1-3] return pos + 9 * (piece_size - 1) def is_legal(self, action, agent_inde...
The main task of the code is to execute a player's turn in a board game by validating a move, updating the game state by placing or repositioning a piece, and ensuring no duplicate pieces exist on the board. It checks move legality, removes a piece from its previous position if it already exists, and places it at the n...
def play_turn(self, agent_index, action): piece = self.get_piece_from_action(action) if agent_index == 1: piece = piece * -1 index = self.get_index_from_action(action) # First: check if a move is legal or not if not self.is_legal(action, agent_index): ret...
def add_point(self, x, y): self.points.append(Point(x, y)) crt_len = len(self.points) self.points_list_box.insert(END, f"Point no.{crt_len}: " + "({:.3f}, {:.3f})".format(x, y)) self.update_points_label() def set_alpha(self, alpha): self.alpha = alpha self.update_alpha_la...
The main task of the code is to update an object's data by adding a new point (x, y) and setting parameters alpha and beta. It calls `add_point(x, y)` to record coordinates, `set_alpha(alpha)` to adjust the alpha value, and `set_beta(beta)` to modify the beta value, enabling dynamic data and parameter updates for furth...
def update_data(self, x, y, alpha, beta): self.add_point(x, y) self.set_alpha(alpha) self.set_beta(beta)
def update_points_label(self): label_singular = "There is 1 point in this plot:" label_plural = f"There are {len(self.points)} points in this plot:" self.points_label["text"] = label_singular if len(self.points) == 1 else label_plural def set_alpha(self, alpha): self.alpha = alpha ...
The `reset` method clears the points list box, resets the points data structure, updates the points label, and sets alpha and beta parameters to `None`, effectively initializing or restarting the application's state related to point tracking and parameter values.
def reset(self): self.points_list_box.delete(0, END) self.points = [] self.update_points_label() self.set_alpha(None) self.set_beta(None)
def get_parent_idxs(node): parent_vals = [] for v in node.args: if isinstance(v, Value): parent_vals.append(v) for v in node.kwargs.values(): if isinstance(v, Value): parent_vals.append(v) ans = [] for v in parent_vals: if v.src_node: ans....
The code visualizes a Directed Acyclic Graph (DAG) by organizing nodes into columns based on dependencies, ensuring parents are printed before children. It iteratively identifies nodes with all parents already processed, sorts them vertically, assigns output positions, and prepares formatted node representations. Final...
def pretty_print_dag(dag): nodes_to_print = {i: n for i, n in enumerate(dag.nodes)} # organize nodes into columns and rows node_columns = [] # columns of prepared nodes prev_output_pos = {} while len(nodes_to_print) > 0: # while have some nodes to print current_column_nodes = [] # nodes ...
def login(): br.open("https://rtpc.ucfprogrammingteam.org/index.php") br.select_form(nr=0) br.form['username'] = "" br.form['password'] = "" br.submit() def scrape_range(start, end): practices = { "2022-2023": f"{RTPC_BASE_URL}/index.php/downloads/category/42-2022-2023/", "2021-2...
The main task of the code is to scrape data between specified years using command-line arguments, with options to export results as CSV files, generate individual problem PDFs, and create ZIP archives. The script processes flags like --start, --end, --export, --pdfs, and --zips to determine scraping range and output fo...
def main(): parser = argparse.ArgumentParser(description="example: python3 scraper.py --start 2022 --end 2023 --export --pdfs --zips which would scrape the year 2022-2023 and export .csvs as well as pdfs and zips") # parser.add_argument("--username", help="RTPC username", required=True) # parser.add_argumen...
def create_table(name): create_users_table = f""" CREATE TABLE IF NOT EXISTS {name} ( id INTEGER PRIMARY KEY AUTOINCREMENT, english VARCHAR(100), russian VARCHAR(100) ); """ execute_query(create_users_table) def get_id(message): """ Returns id of use...
This function processes user responses to a word, updating data structures and database tables. It checks if the user's answer matches the correct translation, updates the day_dict and first_day_dict accordingly, and either saves progress to a database table or continues the learning process. The task involves conditio...
def learn_1st_2(message, day_dict, temp, word, num, first_day_dict): if message.text == word[1]: a = day_dict.pop(num) first_day_dict.append(a) bot.reply_to(message, 'Correct') else: bot.reply_to(message, 'Wrong') bot.send_message(message.chat.id, f'<b>{word[1]}</b> is co...
def create_table(name): create_users_table = f""" CREATE TABLE IF NOT EXISTS {name} ( id INTEGER PRIMARY KEY AUTOINCREMENT, english VARCHAR(100), russian VARCHAR(100) ); """ execute_query(create_users_table) def get_id(message): """ Returns id of use...
This function checks if a user's message matches a target word. If correct, it transfers the word from `first_day_dict` to `second_day_dict` and replies affirmatively. If incorrect, it informs the user of the correct word. When `first_day_dict` is empty, it saves `second_day_dict` entries into database tables (`second`...
def learn_2nd_2(message, second_day_dict, first_day_dict, temp, word, num): if message.text == word[0]: a = first_day_dict.pop(num) second_day_dict.append(a) bot.reply_to(message, 'Correct') else: bot.reply_to(message, 'Wrong') bot.send_message(message.chat.id, f'<b>{word...
def create_table(name): create_users_table = f""" CREATE TABLE IF NOT EXISTS {name} ( id INTEGER PRIMARY KEY AUTOINCREMENT, english VARCHAR(100), russian VARCHAR(100) ); """ execute_query(create_users_table) def get_id(message): """ Returns id of use...
This function checks if a user's message matches a target word. If correct, it transfers data from `second_day_dict` to `third_day_dict` and replies affirmatively; if wrong, it corrects the user. When `second_day_dict` is empty, it creates database tables, inserts `third_day_dict` entries into the appropriate table bas...
def learn_3rd_2(message, second_day_dict, third_day_dict, word, num): if message.text == word: a = second_day_dict.pop(num) third_day_dict.append(a) bot.reply_to(message, 'Correct') else: bot.reply_to(message, 'Wrong') bot.send_message(message.chat.id, f'<b>{word}</b> is ...
def translate_it(message): """ User can write a word or a phrase to translate """ msg = bot.send_message(message.chat.id, 'Enter English word') bot.register_next_step_handler(msg, translate_it2) def start(message): menu(message) def save_translated(message, eng, rus): """ Saving a pair o...
The function `translate_it4` handles user commands in a bot by checking the message text and executing corresponding actions: translating another word, returning to the main menu, saving a translated word, or sending an error message and restarting. It routes user input to specific handler functions based on the comman...
def translate_it4(message, eng, rus): if message.text == 'Translate another word': translate_it(message) elif message.text == 'To main menu': start(message) elif message.text == 'Save this word': save_translated(message, eng, rus) else: bot.send_message(message.chat.id(me...
def checkBlanks(board): blank = [] for x, row in enumerate(board): for y, col in enumerate(row): if board[x][y] == 0: blank.append([x, y]) return blank def minimax(state, depth, player): global minmax_count minmax_count += 1 if player == -1: best = [-...
The code implements a computer player's move in a game (likely Tic-Tac-Toe) using minimax or alpha-beta pruning algorithms. It checks if the board is empty to use minimax directly, otherwise applies alpha-beta pruning to determine the optimal move for the computer player, updates the board with the selected move, and d...
def o_comp(board): if len(checkBlanks(board)) == 9: move = minimax(board, len(checkBlanks(board)), -1) x, y = move[0], move[1] set_Move(board, x, y, -1) displayGameBoard(board) else: result = abminimax(board, len(checkBlanks(board)), -inf, inf, -1) set_Move(board...
def checkBlanks(board): blank = [] for x, row in enumerate(board): for y, col in enumerate(row): if board[x][y] == 0: blank.append([x, y]) return blank def minimax(state, depth, player): global minmax_count minmax_count += 1 if player == -1: best = [-...
The function `x_comp` determines the optimal move for the AI player ('X') in a game (likely Tic-Tac-Toe) using either the minimax or alpha-beta pruning algorithm based on the number of empty cells. If the board is empty (9 blanks), it uses minimax with depth 9; otherwise, it uses alpha-beta pruning with the remaining b...
def x_comp(board): if len(checkBlanks(board)) == 9: move = minimax(board, len(checkBlanks(board)), +1) x, y = move[0], move[1] set_Move(board, x, y, 1) displayGameBoard(board) else: result = abminimax(board, len(checkBlanks(board)), -inf, inf, 1) set_Move(board, ...
def blanks(board): blank = [] for x, row in enumerate(board): for y, col in enumerate(row): if board[x][y] == 0: blank.append([x, y]) return blank def minimax(state, depth, player): if player == -1: best = [-1, -1, -10000000] else: best = [-1, -1,...
The function `o_comp` determines the computer's move in a game (likely Tic-Tac-Toe) by using the minimax algorithm for an empty board or alpha-beta pruning for non-empty boards, selecting the optimal move for the computer player (-1) and updating the game board accordingly.
def o_comp(board): if len(blanks(board)) == 9: #x = choice([0, 1, 2]) #y = choice([0, 1, 2]) move = minimax(board, len(blanks(board)), +1) x, y = move[0], move[1] setMove(board, x, y, -1) createGameBoard(board) else: result = abminimax(board, len(blanks(b...
def blanks(board): blank = [] for x, row in enumerate(board): for y, col in enumerate(row): if board[x][y] == 0: blank.append([x, y]) return blank def minimax(state, depth, player): if player == -1: best = [-1, -1, -10000000] else: best = [-1, -1,...
The function `x_comp` determines the optimal move for a player (represented by 1) in a game like Tic-Tac-Toe. If the board is empty, it uses the `minimax` algorithm to choose a move; otherwise, it employs `abminimax` (alpha-beta pruning) for efficiency. The selected move is applied to the board, updating the game state...
def x_comp(board): # If the board is empty (i.e., the game just started), make a random move if len(blanks(board)) == 9: #x = choice([0, 1, 2]) #y = choice([0, 1, 2]) move = minimax(board, len(blanks(board)), +1) x, y = move[0], move[1] setMove(board, x, y, 1) cre...
def minimax(state, depth, player): if player == -1: best = [-1, -1, -10000000] else: best = [-1, -1, +10000000] if depth == 0 or isGameWon(state): score = getScore(state) return [-1, -1, score] for cell in blanks(state): x, y = cell[0], cell[1] state[x][...
The main task of the code is to determine which move-generation function to call based on the current player and mode. If in mode 1, player 1 uses minimax with blank count, while other players use o_comp. In other modes, player 1 uses o_comp and player 2 uses x_comp, facilitating different strategies for AI or human mo...
def makeMove(board, player, mode): if mode == 1: if player == 1: minimax(board,len(blanks(board)),player) else: o_comp(board) else: if player == 1: o_comp(board) else: x_comp(board)
def checkBoardFullStatus(board): if len(checkBlanks(board)) == 0: return True return False def checkGameStatus(board): return checkWinningPlayer(board, 1) or checkWinningPlayer(board, -1) def make_Move(board, player, mode): if mode == 1: if player == 1: x_comp(board) ...
The main task of the code is to simulate a two-player game on a board, alternating turns between players (starting with player -1) by placing moves until the board is full or a win condition is met. It repeatedly calls `make_Move` to update the board, switches players after each move, and finally displays the game's ou...
def adver_search(): current_Player = -1 while not (checkBoardFullStatus(board) or checkGameStatus(board)): make_Move(board, current_Player, 1) current_Player *= -1 displayGameStatus(board)
def boardFull(board): if len(blanks(board)) == 0: return True return False def isGameWon(board): return checkWinningPlayer(board, 1) or checkWinningPlayer(board, -1) def makeMove(board, player, mode): if mode == 1: if player == 1: minimax(board,len(blanks(board)),player) ...
The code implements a Player vs Computer (PVC) game loop where players take turns making moves on a board until the game is won or the board is full. It alternates between the player (1) and computer (-1), using `makeMove` for each turn, and displays the game result. However, the player switch logic contains an error: ...
def pvc(): currentPlayer = 1 while not (boardFull(board) or isGameWon(board)): makeMove(board, currentPlayer, 1) currentPlayer *= -1 makeMove(board, currentPlayer, -1) currentPlayer *= 1 showGameResult(board)
def spawn_ship(me): #Only shipyards not currently occupied are valid for conversion valid_shipyards = [shipyard for shipyard in me.shipyards if shipyard.position not in [ship.position for ship in me.ships]] if len(valid_shipyards) > 0: constructing_shipyard = random.choice(valid_shipyards) c...
The code manages a player's ships and shipyards in a strategic game. It spawns new ships if conditions are met, assigns goals to ships, determines their movement, converts ships to shipyards when appropriate, and prepares for the next turn by clearing tracked positions. The main task is to optimize the player's strateg...
def agent(obs, config): global turn global next_points global num_ships global num_shipyards turn += 1 size = config.size board = Board(obs, config) me = board.current_player num_ships = len(me.ships) num_shipyards = len(me.shipyards) #Create a list of ships shi...
def get_trip_probabilities_per_day_type(parameters): vehicle = parameters['vehicle']['name'] if vehicle == 'car': trip_probabilities_per_day_type = ( get_car_trip_probabilities_per_day_type(parameters) ) else: print('Vehicle does not have a model') exit() ret...
The code generates mobility data by aggregating trip probabilities, mobility matrices, location splits, and distance calculations to model movement patterns, likely for simulation or analysis of human mobility behavior.
def make_mobility_data(parameters): trip_probabilities_per_day_type = get_trip_probabilities_per_day_type( parameters ) run_mobility_matrix = get_mobility_matrix(parameters) location_split = get_location_split(parameters) kilometers_for_next_leg = get_kilometers_for_next_leg(parameters)
def is_ready_to_trade(self) -> bool: """ Example of a function that checks that API received all data necessary to trade. Returns ------- True if all data received and algo ready to trade, False otherwise """ fn = self.is_ready_to_trade.__name__ i...
This function executes a trading strategy loop by repeatedly checking if trading conditions are met, executing trades when ready, and managing the API's operational status. It sleeps for a set interval, monitors if the API should stop, and handles exceptions to ensure the loop terminates gracefully when the API finishe...
def strategy_loop(self): fn = self.strategy_loop.__name__ api_finished = False try: while not api_finished: if not self.phx_api.to_stop: if self.is_ready_to_trade(): self.trade() time_is_out = self.check_...
def _compute_ref_images(self): # Compute Ref Image default_color = (255, 255, 0) # Yellow default_alpha = 0.5 self.roi_images = [] self.roi_pos = [] for ii, active_roi in enumerate(self.rois_in_ref): if self.rois_in_ref[active_roi]['type'] == 'freehand': ...
This function initializes new data by clearing old ROI text and UI elements, updating the ROI listbox with available data, computing reference images, initializing stimulus/recording plots, and configuring the reference image display with ROI labels. It ensures UI states (like buttons and plots) are updated based on av...
def _initialize_new_data(self): # Remove text of old rois for kk in self.ref_img_text: Artist.remove(kk) # Remove old lms and reg self.lm_scoring_available = False self.show_reg_button.config(state='disabled') self.reg_plot.set_visible(False) self.can...
def _compute_ref_images(self): # Compute Ref Image default_color = (255, 255, 0) # Yellow default_alpha = 0.5 self.roi_images = [] self.roi_pos = [] for ii, active_roi in enumerate(self.rois_in_ref): if self.rois_in_ref[active_roi]['type'] == 'freehand': ...
This method initializes the GUI by hiding initial text, configuring plot axes, populating a listbox with ROI numbers, initializing stimulus/recording plots, displaying reference images with labels, adding navigation toolbars, and setting up a "Show Reg" button for toggling registration visibility. It handles data files...
def _initialize_first_data(self): # Remove the text on the Canvas self.import_data_text.set_visible(False) self.axs.axis('on') # Hide the right and top spines self.axs.spines.right.set_visible(False) self.axs.spines.top.set_visible(False) # Fill List with rois ...
def pop_up_error(self, tlt, msg): tk.messagebox.showerror(title=tlt, message=msg) self.window_dummy.lift() def convert_to_delimiter(d): if d == 'Comma': d_str = ',' elif d == 'Tab': d_str = '\t' elif d == 'Semicolon': d_str = ';' elif d...
This function reconstructs a stimulus signal from protocol data by validating user inputs, reading CSV files with specified delimiters and headers, extracting onset/offset intervals, generating a time series, and creating a binary stimulus array where intervals are marked as '1'. It ensures data consistency and stores ...
def _get_reconstruct_stimulus(self): try: col_01 = int(self.reconstruct_column_01.get()) col_02 = int(self.reconstruct_column_02.get()) except ValueError: self.pop_up_error('ERROR', 'Column Number must be Integer') return "break" delimiter = self.c...
def pop_up_error(self, tlt, msg): tk.messagebox.showerror(title=tlt, message=msg) self.window_dummy.lift() def convert_to_delimiter(d): if d == 'Comma': d_str = ',' elif d == 'Tab': d_str = '\t' elif d == 'Semicolon': d_str = ';' elif d...
The function collects and validates user-selected import settings, processes stimulus/recording data files, checks file existence, imports data into structured formats, handles time-axis generation, and ensures consistency between imported data (e.g., duration, ROI count) before initializing new data setup.
def _collect_import_data(self): # When user clicks on "DONE" Button in the Import Menu this function is called # It will collect all the info from the Import Menu Settings # All inputs are strings! # Data Info print('IMPORTING ...') stimulus_selected = self.import_stimulu...
def encode(df, this_instance_data): df2 = df.loc[df.resource_type == "machine"].sort_values(['start', 'resource'], ascending=[True, True]) ov = df2.job.values df3 = df.loc[df.resource_type == "machine"].sort_values(['job', 'operation'], ascending=[True, True]) mv = df3.resource.values order = [(row....
The code implements a Tabu Search algorithm to optimize a scheduling problem, aiming to minimize total completion time. It starts with an initial solution, iteratively explores neighbors via swaps, avoids revisiting solutions using a tabu list, and tracks performance metrics. The algorithm stops early if no improvement...
def tabu_search(df_schedule, instance_data, instance, max_steps=param["tabu_search"]["max_steps"], ls_steps=param["tabu_search"]["ls_steps"], tabu_list_size=param["tabu_search"]["tabu_list_size"]): start_time = datetime.datetime.now() random.seed(datetime.datetime...
def check_size_divergence(df_schedule): if len(df_schedule.loc[df_schedule.resource_type == "machine"].job) != len(df_schedule.loc[df_schedule.resource_type == "analyst"].job): print("#machines: {}, #analysts: {}".format(len(df_schedule.loc[df_schedule.resource_type == "machine"].job), len(df_schedule.loc[d...
The code runs heuristic and Tabu Search algorithms on scheduling problems defined by varying parameters (jobs, machines, workers, etc.). It evaluates solution quality (e.g., completion time), saves results, and generates visualizations. The process iterates through problem instances, applying heuristics like M-LQ/SPT/L...
def run(): ex_parameters = settings['experiments'] path_instances = os.path.join(path_project, settings['paths']['instances']) path_results = os.path.join(path_project, settings['paths']['results']) saved_schedules = {} past_data = read_past_results(path_results) force_run = True force_run_...
def say_voice(self, voice_msg, t_sec): self.add_task_srv_proxy(task_name="say", task_priority=11, task_permanence=False, task_impact="None", task_args=[voice_msg]) rospy.sleep(t_sec) def navigate_to_node(self, node_data, record_path): # Creates a goal to be send to the Navigation action server. ...
The main task of the code is to initialize a ROS node for autonomous patrolling, retrieving environmental nodes, navigating to each location for measurement, waiting for user confirmation, and returning to dock. It subscribes to buttons, pose data, and navigation topics, uses service clients for task management, and lo...
def __init__(self): rospy.init_node("patrol_with_confirmation") # Read params self.verbose = rospy.get_param("~verbose",True) self.topic_buttons = rospy.get_param('~topic_buttons',"/giraff_node/buttons") self.topic_start_navigation = rospy.get_param('~topic_start_navigat...
def list_image_tags(): images_tags = [] images,_ = get_image_infos() images = images.get('results',[]) for image in images: last_updater_username = image['last_updater_username'] image_name = image['name'] # print("%s/%s"%(last_updater_username,image_name)) images_tags.ap...
The main task of the code is to handle different actions based on the `args.action` parameter. It lists image tags, creates containers, creates volumes, or updates images. For 'update', it checks if 'all' is present in `unknow` to determine if all images should be updated, then calls `update_images(update_all)`.)
def main(): if(args.action == 'list'): image_tags = list_image_tags() for tag in image_tags: print(tag) elif(args.action == 'create'): create_container() elif(args.action == 'create_volume'): create_volume() elif(args.action == 'update'): ...
def receive_msg(self, conn): msg_length = conn.recv(self.HEADER).decode(self.FORMAT) if not msg_length: return msg_length = int(msg_length) msg = conn.recv(msg_length).decode(self.FORMAT) return msg def handle_set(self, conn, key, value): if self.set_k...
This code handles client requests for 'set' and 'get' commands by receiving and parsing messages, executing corresponding operations (storing/retrieving data), and closing the connection after processing. It processes incoming data, splits commands, validates inputs, and manages exceptions by closing the connection and...
def handle_client(self, conn, addr): # print(f"[NEW CONNECTION] {addr} connected.") try: connected = True while connected: # msg = conn.recv(4096).decode(self.FORMAT) msg = self.receive_msg(conn) split_msg = msg.split("\r\n") ...
def download_model_weight(local_file_path, s3_file_path): # Check if the file exists if not os.path.exists(local_file_path): BUCKET_NAME="ds-kas-bucket" download_file(BUCKET_NAME, s3_file_path, local_file_path) else: print(f"File {local_file_path} already exists.") def defin...
The function generates a white background image by removing the background from an input image using a pre-trained model. It downloads a model weight file, loads the model, processes the input image to create a mask, and saves the resulting mask as an output image.
def white_bg_generate(input_path,output_path): script_dir = os.path.dirname(os.path.abspath(__file__)) local_path = os.path.join(script_dir, "saved_models/DIS_model.pth") s3_model_path = "finetune_models/background_removal/finetune_model_v1.pth" download_model_weight(local_path,s3_model_path) device = 'cuda'...
def RunTuningReport(self, valsDataReport): self.set(valsDataReport, True) self.get_report() valsDataReport.CapScore = self.ScoreTuningValue() def ScoreTuningValue(self): if(len(self._reports) > 0): data = self._reports[0] else: raise Exception("'cannot get...
This function searches for the optimal global capacitance value (GCBCCap) by iteratively adjusting it through a binary search-like approach. It evaluates the tuning score, updates the best capacitance value when a lower score is found, and adjusts the search step size halving each iteration until convergence. The proce...
def SearchBestGlobalCBC(self, valsData): progressMax = 50 currProgress = 0 interval = 5 valsScore = HybridAnalogParamValues(valsData) valsScore.setGCBCCap(self._nGlobalCapacitanceMaxCBC) valsScore.CapStep = (self._nGlobalCapacitanceMaxCBC + 1) / 2 valsScore.CapBe...
def SetGlobalCBC(self, arrDataGains, bWrite): if bWrite: p = self.paraName self._sc = update_static_config(self.handle, self._sc, {p.CBCCapGain01916: arrDataGains[0]}) self._sc = update_static_config(self.handle, self._sc, {p.CBCCapGain1: arrDataGains[1]}) self._s...
The main task of the code is to validate and configure global CBC (Capacitance Balance Control) parameters by checking capacity limits, running tuning reports, and adjusting gains/channels iteratively until successful validation. It uses a loop to attempt configuration, verify results, and apply corrections if initial ...
def CheckGlobalCBC(self, valsData): bDataValid = False bDataSuccess = (valsData.getGCBCCap() <= self._nGlobalCapacitanceMaxCBC) arrDataGains = self._arrGlobalCapGainsInitial while not bDataValid and bDataSuccess: bDataSuccess = self.SetGlobalCBC(arrDataGains, True) ...
def update_static_config(handle, config, config_to_set, bWrite=False): try: for key in config_to_set: config_value = config_to_set[key] if isinstance(config_value, list): for idx, x in enumerate(config_value): config[key][idx] = int(x) ...
The code's main task is to execute global tuning of CBC (Current Balance Control) parameters by disabling relevant configurations, searching for optimal CBC settings using provided initial values, restoring, validating, and confirming the tuned parameters, ultimately returning the adjusted parameter values for system o...
def RunGlobalTuning(self, valsInitTuning): p = self.paraName valsTuning = HybridAnalogParamValues(valsInitTuning) #self.ValidateGlobalCBC(valsTuning) #PrepareGlobalCBC array = self._sc[p.CBCs] array = [0 for element in range(len(array))] self._sc = update_static_...
def InitializeGlobalCBC(self, valsData): valsData.gcbcIdx = self.paraName.gcbcIdx valsData.setGCBCCap(self._nGlobalCapacitanceMaxCBC) valsData.GCBCInScale = self._nGlobalCapacitanceInScaleInit valsData.GCBCOutScale = self._nGlobalCapacitanceOutScaleInit #check parameter...
The main task of the code is to perform global parameter tuning by initializing parameters, executing a global tuning process, and calculating the final result using optimized parameter values. It initializes tuning parameters, runs the tuning algorithm, and returns the computed global CBC value based on the best tunin...
def DoGlobalTuning(self): valsBestTuning = HybridAnalogParamValues() valsInitTuning = HybridAnalogParamValues() self.InitializeGlobalCBC(valsInitTuning) valsBestTuning = self.RunGlobalTuning(valsInitTuning) return self.CalculateGlobalCBC(valsBestTuning)
def plot_fig_3b(fig=None, axis=None): ax, _ = create_panel_if_needed(fig, axis) n_flees, total_n_trials, p_val = fig_3b_data() colors = [default_colors["ih_ivc_7day"], default_colors["lse"]] plot_fig_3_bars(ax, n_flees, total_n_trials, p_val, colors, bars_empty=True) plt.ylabel("Auditory Threat...
This code generates a multi-panel figure with specific subplots, applying formatting and plotting data visualizations (tracks, events, histograms) using predefined layouts, then saves and displays the figure.
def main(): mpl.rcParams["pdf.fonttype"] = 42 mpl.rcParams["font.sans-serif"] = "Arial" mpl.rcParams["font.family"] = "sans-serif" h_fig = a4figure() labels = { "a": [37, 297 - 73, 0, 0], "b": [37, 297 - 140, 0, 0], "c": [73, 297 - 140, 0, 0], "d": [73, 297 - 164, ...
def plot_fig_2b(fig=None, axis=None): ax, _ = create_panel_if_needed(fig, axis) t, tracks, linestyle = track_plot_data(data.dataframe["lse"]) plot_tracks_general(t, tracks, linestyle, fig=fig, axis=ax) ax.text( 2.25, 55, "Post LSE test trials", fontsize=10, ho...
The code generates a multi-panel scientific figure (Figure 2) with customized layouts. It sets Matplotlib font parameters, creates an A4-sized figure, positions labels and subplots using predefined coordinates, formats axes, and plots specific data panels (2b, 2c, 2d, 2e, 2f). Finally, it saves the figure as a PDF and ...
def main(): mpl.rcParams["pdf.fonttype"] = 42 mpl.rcParams["font.sans-serif"] = "Arial" mpl.rcParams["font.family"] = "sans-serif" h_fig = a4figure() # position of legend labels labels = { "a": [23, 297 - 65, 0, 0], "b": [103, 297 - 65, 0, 0], "c": [23, 297 - 65 - 55, ...
def get_payoff_matrix(agent_classes): # get pairs without repetitions payoff_matrix = [[0 for _ in range(len(agent_classes))] for _ in range(len(agent_classes))] for i in range(len(agent_classes)): for j in range(i, len(agent_classes)): agent1 = agent_classes[i]() agent2 = ag...
The main task of the code is to generate and simplify a set of inequalities representing payoff comparisons between agent classes in a game-theoretic context. It constructs payoff equations, avoids duplicates, adds zero-based conditions, and reduces inequalities using symbolic math to determine dominance rules for each...
def compute_formula(agent_classes, is_zero_possible=True): win_rules = dict() payoff_matrix = get_payoff_matrix(agent_classes) vector_tp = get_total_payoff_vector(agent_classes, payoff_matrix) for i in range(len(agent_classes)): win_rules[agent_classes[i].__name__] = [] for j in range(l...
def getContact( self, id, type, priority ): """ Return a contact record from MbrContact. Input: id = CAPID type = contact type: HOME PHONE, CELL PHONE, EMAIL... priority = PRIMARY, SECONDARY, EMERGENCY Returns: a string containing the contact. Receiver is re...
The main task of the code is to create a new Google account for an eServices member by generating a GAM command with their details, including email, name, organization unit, and password. It checks for a primary email; if absent, it returns None. A placeholder is inserted into Google's database to prevent duplicate acc...
def mkNewAccount( self, m ): """ Make a new member account Input m: eServices Member record. Output GAM member creation command to job file. Returns Gmail address, adds placeholder record to Google to prevent duplication of new email addresses. NOTE: if the member...
def mkNewAccount( self, m ): """ Make a new member account Input m: eServices Member record. Output GAM member creation command to job file. Returns Gmail address, adds placeholder record to Google to prevent duplication of new email addresses. NOTE: if the member...
The main task of the code is to search for new members using a specified query, create Google accounts for members without existing accounts, add them to designated groups and calendars, and log the process. It skips members in invalid units and ensures only new accounts are created, tracking the number of accounts gen...
def run(self): """ Search for new members, create account, notify and add member to group and appropriate mailing list. The subclass must specify the query to find members. Note: by construction members in unit 000 or no unit are not considered for new accounts. ...
def createSense(self): ''' DESCRIPTION Creates peripheral and audible areas for AI sensing INPUT self: class instance OUTPUT None ''' # peripheral area dimensions if self.state['PATROL']: dim = 150 else: d...
The code's main task is to update and draw enemy behavior each frame, including combat state management, movement logic, detection of player presence, health tracking, and state transitions (e.g., patrol, combat, alert). It checks for enemy death, updates combat timers, triggers state changes in other enemies, and hand...
def tick(self): ''' DESCRIPTION Called every frame to update and draw enemy INPUT self: class instance OUTPUT None ''' # Character tick function Character.tick(self) # create sense perimeters self.createSense() ...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def print_board(board): s = "*" for i in range(len(board[0]) - 1): s += str(i % 10) + "|" s += str((len(board[0]) - 1) % 10) s += "*\n" for i in range(len(board)): s +=...
The code implements a Gomoku game where the computer (playing as "Black") and a human player (playing as "White") take turns placing stones on a board. The computer uses a search algorithm to determine its moves, while the human inputs their moves. The game checks after each move for a win or draw and returns the resul...
def play_gomoku(board_size): board = make_empty_board(board_size) board_height = len(board) board_width = len(board[0]) while True: print_board(board) if is_empty(board): move_y = board_height // 2 move_x = board_width // 2 else: move_y, move_...
def random_data(num_images, num_classes): random = [] for _ in range(num_images * num_classes): random_vector = np.random.uniform(-1, 1, 512) random.append(random_vector / np.linalg.norm(random_vector)) return random def spectral_clustering(values, n_clusters, entities, affinity): if (a...
This code computes and compares clustering metrics using different methods (cosine similarity and RBF kernel) with and without PCA on embeddings from multiple entities. It aggregates results into a table, visualizes them, and saves the output as an image.
def compute_clustering_metrics_different_flavors(entities, num_classes, num_images): all_embeddings = entities[0].embeddings for i in range(1, len(entities)): all_embeddings = np.concatenate((all_embeddings, entities[i].embeddings), axis = 0) random_vectors = random_data(num_images, num_classes) ...
def csv_to_dict(csv_file): labels_dict = {} with open(csv_file, 'r') as file: csv_data = file.read() rows = csv_data.split('\n') for row in rows: split = row.split(" ", 1) if len(split) < 2: continue labels_dict[split[0]] = split[1].spl...
The main task of the code is to process image and text data from specified directories and CSV labels, generating embeddings using CLIP for either ImageNet or LAION datasets. It creates entities with associated embeddings and counts, handling preprocessing, caption generation, and sampling based on parameters like data...
def main(images_dir, labels_csv, dataset_name, classes, preprocess_image_data, num_images, generate_texts): #perfectly_clustered_data(50, 100, 0.1,"zij-gaussian-0.1sigma-100classes-50perclass.pk1" ) labels_mapping_dict = csv_to_dict(labels_csv) if preprocess_image_data: if dataset_name == "Ima...
def init_all_optimizers(self): self.optimizers = {} for key, oparams in self.optim_params.items(): self.optimizers[key] = None if oparams != None: self.optimizers[key] = self.init_optimizer( self.networks[key], oparams, key) def run_train_w...
The code trains a model using prototype-based learning, computing class prototypes from features and updating them iteratively. It incorporates soft labels for KNN, adjusts prototype weights, and performs training epochs with cosine annealing. The method evaluates the model on test datasets, including ImageNet, and sav...
def solve(self, data_loader_train, data_loader_eval, test_loader, imagenet_loader=None): # class frequency of training dataset self.img_num_list = np.array(data_loader_train.dataset.img_num_list) self.epsilons = ((self.img_num_list / self.img_num_list[-1]) ** 0.5) self.epsilons ...
def get_game_state(self): return self.board.fen() def get_ordered_moves(self,board): moves = self.get_valid_moves(board) ordered_moves = sorted( moves, key=lambda move: ( -self.get_captured_piece_value(move), self.get_attacker_piece_value(m...
This code determines the best chess move using a minimax algorithm with alpha-beta pruning. It evaluates all possible moves at the current depth, recursively assessing their outcomes to select the move with the highest value, optimizing performance through pruning.
def get_best_move(self,depth): try: board = chess.Board(self.get_game_state()) board.turn = True if self.turn == 'w' else False bestMove = None bestValue = -99999 alpha = -99999 beta = 99999 moves = self.get_ordered_moves(board)...
def print(self): if(self.root == None): return else: iter = self.root while(iter.next != self.root): print(iter.data) iter = iter.next print(iter.data) def fillWithRandom(): max_num_rows = 5 max_num_cols = 5 # generate ran...
The code implements a menu-driven program that allows users to select tasks related to algorithm problems. It handles three main tasks: finding the maximum path in a grid (Q1), calculating the median of a random array (Q2), and determining a survivor in a circular linked list using different time complexity approaches ...
def driver(): while(True): print("INPUTS ARE RANDOMLY GENERATED IN EACH TURN\n") print("1-) Q1\n2-) Q2\n3-) Q3\n0-) Exit\n") select = int(input("Choice : ")) if(select == 1): grid = fillWithRandom() print("Grid\n",grid,"\n") maxPathFinding...
def get_all_matches(season_key): matches, new_matches = [], [] start = 0 while True: r = get_data("match/all/"+season_key, {"start":start}) if r.status_code != 200: break new_matches = r.json() start+=len(new_matches) matches.extend(new_match...
This function retrieves all matches for a given season, filters them by a specified match type (if provided), and returns their score information. The 'type_' parameter allows filtering matches according to TOA guidelines (0-4 for specific formats, 5 for any elimination match).
def get_all_matches_score_info(season_key, type_=None): """type_ should follow the TOA match type guidelines (0-4) no distinction is made between semi/quarter final series a 5 will indicate any elimination match. """ matches = get_all_matches(season_key) if type_ is not None: matches =...
def get_all_combinations(self): ''' Combinatorially create sets of all states that can be reduced in self.all_reductions. In addition, returns the possible_reductions list after removing the sets that contain states involved in the outputs. ''' from itertools import combi...
This function generates reduced models by combining states from possible combinations, evaluates their error and robustness metrics using input data, and stores results in a dictionary. It skips invalid reductions and handles cases with no valid models by suggesting increased tolerance.
def reduce_with_input(self): if self.u is None: raise ValueError('For models with no inputs use reduce_simple') results_dict = {} possible_reductions = self.get_all_combinations() if not len(possible_reductions): print('No possible reduced models found. Try increa...
def get_all_combinations(self): ''' Combinatorially create sets of all states that can be reduced in self.all_reductions. In addition, returns the possible_reductions list after removing the sets that contain states involved in the outputs. ''' from itertools import combi...
This method reduces a model by generating possible state combinations, filtering them based on tolerance thresholds, creating reduced systems via timescale separation, calculating error and robustness metrics, and storing valid results. It skips invalid combinations and returns a dictionary of evaluated reduced systems...
def reduce_simple(self): if self.u is not None: raise ValueError('For models with inputs use reduce_with_input method.') results_dict = {} possible_reductions = self.get_all_combinations() if not len(possible_reductions): print('No possible reduced models found. T...
def make_delete(self, selection): """ Where actual logic happens. it deletes the selection provided based on the queryset :param selection: list of ids to delete """ self.get_queryset().filter(pk__in=selection).delete() messages.success(self.request, self.get_success_mess...
This code handles a POST request to process deletions. It retrieves a list of selected items from the request, deletes them if selected, or displays a message if no items are chosen. Finally, it redirects to a specified URL.
def post(self, *args, **kwargs): selection = self.request.POST.getlist("selection[]") if len(selection) > 0: self.make_delete(selection) else: messages.info(self.request, self.get_no_selection_message()) return redirect(self.get_redirect_url())
def is_week_results_filled(week): conn = psycopg2.connect(DB_URL) cur = conn.cursor() cur.execute(''' SELECT winner_id FROM matches WHERE week = %s ''', [week]) results = cur.fetchall() cur.close() conn.close() for result in res...
This code initializes an object to track user tips and week data by fetching user-specific and week-specific information, including completed games, correct tips, season tips, and match details for a given week.
def __init__(self, user_id, week): self.current_week = week #booleans self.is_week_completed = is_week_results_filled(week) #getters self.correct_tips = get_users_correct_tips_for_week(user_id, self.current_week) self.completed_games = get_total_completed_games_for_week(s...
def get_last_completed_week(): week = get_closest_week() conn = psycopg2.connect(DB_URL) cur = conn.cursor() cur.execute(''' SELECT winner_id FROM matches WHERE week = %s ''', [week]) results = cur.fetchall() cur.close() conn.cl...
The code initializes a class instance by retrieving the last completed week and setting up a leaderboard based on that week's data. It fetches the most recent completed week using `get_last_completed_week()` and then constructs the leaderboard by calling `get_leaderboard_for_leaderboard()` with the week's leaderboard d...
def __init__(self): self.last_completed_week = get_last_completed_week() self.leaderboard = get_leaderboard_for_leaderboard(get_leaderboard(self.last_completed_week), self.last_completed_week)
def get_rendered_sequence_number(file_path): if not path.exists(file_path): log.info('initializing rendering state file') with open(file_path, 'w') as rendered_file: rendered_file.write('lastRendered=1') return 1 return get_sequence_number_from_file(file_path, 'lastRendered')...
This function continuously monitors tile expiration by comparing sequence numbers from OSM2PGSQL and mod_tile states. It identifies tiles needing re-rendering, updates the expired tiles list, triggers re-rendering via mod_tile, logs progress, and updates the rendered state. The loop repeats at intervals to handle ongoi...
def expire_tiles(state_file_path, currently_expired_tiles_file_path, rendered_state_file_path): """ Call mod_tile's render_expired with tiles that need to be re-rendered Args: state_file_path (str): path to a state file that holds the current replication state defined by the sequence number ...
def configure_carto_project(): log.info('configuring the carto project') with open(CARTO_FILE, 'r') as file : carto_data = file.read() for placeholder, value in db_config.items(): carto_data = carto_data.replace(placeholder, value) with open(CARTO_FILE, 'w') as file: file.write(carto...
The main task of the code is to initialize and manage a tile server container by configuring a Carto project, starting Apache and Renderd services, and processing expired map tiles using specified state and file paths. It logs the container's startup and triggers tile expiration logic to maintain updated map data.
def main(): log.info('mod-tile container started') state_file_path = path.join(EXPIRED_DIRECTORY, 'state.txt') currently_expired_tiles_file_path = path.join(EXPIRED_DIRECTORY, 'currentlyExpired.list') rendered_state_file_path = path.join(EXPIRED_DIRECTORY, 'renderedState.txt') configure_carto_proj...
def gate_xor (A,B): return gate_and(gate_nand(A,B),gate_or(A,B)) def gate_or (A,B): if transistor(source,A): return high elif transistor(source,B): return high else: return low def gate_and (A,B): return transistor(transistor(source,A),B)
The main task of the code is to implement a full adder logic circuit, computing the binary sum (summ) of inputs A, B, and carry-in (c_in) using XOR gates, and determining the carry-out (c_out) via a combination of AND and OR gates. The sum is derived by cascading XOR operations, while the carry-out combines intermediat...
def full_adder (A,B,c_in): global summ, c_out summ = gate_xor(gate_xor(A,B),c_in) c_out = gate_or(gate_and(gate_xor(A,B),c_in),gate_and(A,B))
def gate_xor (A,B): return gate_and(gate_nand(A,B),gate_or(A,B)) def gate_or (A,B): if transistor(source,A): return high elif transistor(source,B): return high else: return low def gate_and (A,B): return transistor(transistor(source,A),B)
The code implements a full adder circuit that computes the sum (sum_out) and carry-out (c_out) of two binary inputs A and B along with an incoming carry (c_in). It uses XOR gates to calculate the sum and a combination of AND/OR gates to determine the carry-out, following the logic of a full adder in digital electronics...
def full_adder (A,B,c_in): global sum_out, c_out sum_out = gate_xor(gate_xor(A,B),c_in) c_out = gate_or(gate_and(gate_xor(A,B),c_in),gate_and(A,B))
def pred2boxes(pred, threshold=None): scores = pred['scores'] boxes = pred['boxes'] xmid = (boxes[:,0]+boxes[:,2])/2 ymid = (boxes[:,1]+boxes[:,3])/2 w = np.abs(boxes[:,0]-boxes[:,2]) h = np.abs(boxes[:,1]-boxes[:,3]) df_dict = {"Score": scores, "X": xmid, "Y": ymid, "Width": w, "...
This function evaluates object detection predictions against ground truths by converting tensors to numpy arrays, generating bounding boxes, matching predictions to ground truths using IoU, and calculating true positives (TP) and IoU values. It returns a dataframe with evaluation metrics and the total number of objects...
def evaluate_batch(y_pred, y_true): y_pred = [{k: v.detach().cpu().numpy() for k, v in t.items()} for t in y_pred] y_true = [{k: v.detach().cpu().numpy() for k, v in t.items()} for t in y_true] df_eval = pd.DataFrame() n_objects = 0 for i in range(len(y_pred)): df_gt_boxes = pred2boxes(y_tru...
def prepare(mat): """ Create a non-oriented adjacency matrix from oriented adjacency matrix representing an oriented graph Return the non-oriented adjacency matrix retaining only bidirectionnal connexions Note : the returned matrix is strictly triangular superior Keep only transitions if they are ...
The code identifies the longest chain of connected indices in an adjacency matrix, representing linked subgraphs. It processes the matrix to remove asymmetrical connections, extracts non-zero indices, computes connected chains, and merges overlapping chains. The function returns the size of the largest chain, providing...
def search(mat, debug=False): """ Search for the size of the longest chain of linked indices in the adjacency matrix Return an integer representing the size of the longest chain """ if debug: import pdb; pdb.set_trace() # prepare matrix (remove non-symmetrical connexion) mat = prepare(mat)...
def block_to_block_type(block): if block.startswith("#"): return block_type_heading if block.startswith("```") and block.endswith("```"): return block_type_code if all(line.startswith(">") for line in block.split("\n")): return block_type_quote if all(line.startswith(("* ", "- ")...
The function `block_to_html_node` converts a given block of text into an HTML node based on its type. It first identifies the block type using `block_to_block_type`, then delegates conversion to specialized functions like `paragraph_to_html_node` or `heading_to_html_node`. If the block type is unrecognized, it raises a...
def block_to_html_node(block): block_type = block_to_block_type(block) if block_type == block_type_paragraph: return paragraph_to_html_node(block) if block_type == block_type_heading: return heading_to_html_node(block) if block_type == block_type_code: return code_to_html_node(bl...
def _setGreenPhase(self, action_number, junction_id): if action_number == 0: traci.trafficlight.setPhase(junction_id, PHASE_N_GREEN) elif action_number == 1: traci.trafficlight.setPhase(junction_id, PHASE_E_GREEN) elif action_number == 2: traci.trafficlight.se...
The main task of the code is to simulate traffic light control using a neural network (net) to predict junction states and optimize traffic flow. It manages traffic light phases (green/yellow), prevents signal starvation by adjusting light durations, updates traffic metrics (queue length, waiting time), and iterates th...
def _run(self, net): starvation_counter = dict( (key, dict((small_key, 0) for small_key in range(4))) for key in self._junctions) traci.start(self._sumo_cmd) initial_state = np.zeros(shape=(4,)) initial_state[0] = 1 junction_record = dict((key, {'next_time': 0, 'nex...