dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def read_experiment_params(path, vals=None, flat=True): """ Reads the latest experiment parameter file in path, and returns a dictionary of the values. :param path: folder path, the experiment parameter file is in this folder and is named "experiment_params_<timestamp>.json" :param vals: li...
The main task of the code is to collect and aggregate experimental data from specified file paths into a unified dictionary. It reads parameters, pruning metrics, attack metrics, transfer attack metrics, and accuracy results, then combines them using dictionary unpacking to return a consolidated dataset for analysis or...
def collect_one_experiment_data(path): experiment_params = read_experiment_params(path) pruning_metrics = read_pruning_metrics(path) attack_metrics = read_attack_metrics(path, attack=experiment_params['attack_method']) transfer_attack_metrics = read_transfer_attack_metrics(path, attack=experiment_params...
def create_atoms(n_a, n_b, n_c): unitcell = bulk('Ar', 'fcc', np.power(2,(2./3)), cubic=True) #,orthorhombic=True) # ===> 1.122 sigma (from geometry) # unitcell = bulk('Ar', 'fcc', 5.4, orthorhombic=True) # visualize.view(unitcell) # print unitcell.get_cell() atoms_a = unitcell for i in range...
This function initializes a molecular dynamics simulation by creating a lattice of atoms, calculating box dimensions, initializing positions, velocities (with random generation and adjustments for center-of-mass velocity and thermostat scaling), and forces. It returns velocity, position, and force arrays for simulation...
def initialize_VXF(): global n_a,n_b,n_c global X0, Natoms global box_sizes,box_half_sizes atoms = create_atoms(n_a, n_b, n_c) Natoms = atoms.get_number_of_atoms() print('total number of atoms=', Natoms) box_sizes = np.array([atoms.get_cell()[0][0], atoms.get_cell()[1][1], atoms.get_cell(...
def highsymm_path(symm_points,l,K_step): """ Generates high symmetry path along the given points.""" gamma = np.array([0, 0, 0]) diff_symm_points = np.diff(symm_points, axis=0) path = np.array(symm_points[0],ndmin=2) pgp=np.array([0]) if (symm_points[0]==gamma).all() else np.array([],ndmin=1) for ii in range(d...
The code calculates phonon frequencies (eigenvalues) from atomic trajectories using a Green's function approach, applies the Acoustic Sum Rule (ASR), and plots the dispersion relation along a high-symmetry path in the Brillouin zone. It processes trajectory data, computes force constants, and saves frequencies for visu...
def main(): t_start = time.time() global Natoms global Natoms_root_rev global Nframes global nuq load_previous_calculation = False load_loaded_traj=False # load_previous_calculation = True # load_loaded_traj=True # set some initial values a = np.power(2,(2./3)) # cubic constant in sigma units skip_porti...
def initial_parameteres(): global Natoms,X0, n_a,n_b,n_c,box_sizes,box_half_sizes,Nsteps,cutoff,dump_step,log_step,velocity_zeroing_step,temp_ref,temp_step,Potential_formula,kB_true global trajectory_file,trajectory_file_unwrapped, log_file Natoms = 0 # will be set, also as global value in premain X0=0...
The main task of the code is to perform molecular dynamics simulations using the velocity Verlet integration algorithm. It initializes system parameters, applies forces, updates particle positions and velocities over a number of steps, and saves trajectory data and logs. The simulation includes velocity adjustments for...
def main(): global trajectory_file,trajectory_file_unwrapped,log_file global Nsteps,temp_step,velocity_zeroing_step global force global initial_parameteres initial_parameteres() V,X,F = initialize_VXF() #clean old files try: os.remove(trajectory_file) os.remove(trajecto...
def start_client(port, host=None, dgram=False): "Create a `socket` client on `port`, with optional `host`, of type `dgram`" # Source: https://github.com/fastai/fastcore/blob/da9ca219c86190d22f4dbf2c3cad619c477d64a4/fastcore/net.py#L242-L247 family,addr,typ = _socket_det(port,host,dgram) s = socket.socke...
The function `transfer` sends data over a network using the fastdaemon protocol via a socket, specified by `port` and `host` (optional), and returns the received reply. It uses `start_client` to establish a connection, writes the input `data` to the socket, reads the response, and returns it after processing with `recv...
def transfer(data, port, host=None, dgram=False): "Send a request and receive a reply in one socket using the fastdaemon protocol" with start_client(port, host, dgram) as client: with client.makefile('wb') as f: send_record(f.write, data) with client.makefile('rb') as f: return recv_record(f.rea...
def readFiles(): path = r'D:\Personal Project\Datacsv' #CHANGE THIS TO WHATEVER LOCATION THE FOLDER IS files = glob.glob(os.path.join(path,"*.csv")) dfs = list() name...
The main task of the code is to generate a fair shift schedule for workers based on priority levels and user-selected shift preferences (morning, afternoon, evening). It reads employee data and a template CSV, iteratively assigns shifts while checking fairness constraints, and adjusts fairness levels if needed. The pro...
def main(workers_list,fairness_level_gui,morning_combobox,afternoon_combobox,evening_combobox): try: data,name_list = readFiles() except Exception as e: print(f"\n{e}\nTo fix, add the employees shifts\ncsv files into 'Datacsv' folder.\n") sys.exit() try: output = pd.read_csv...
def __create_clue__(self, answr, guess): d = {} for k in set(guess): if (k not in answr): # d[k] = [self.__colour_vals__["b"]] d[k] = [-2] continue d[k] = [] idx_answr = [x.start() for x in re.finditer(k, answr)] ...
The code simulates evaluating possible guesses against a target answer by updating a simulation dictionary. It initializes or updates entries for each guess, generates clues, merges them with existing data, and refines possible word sets. The goal is to model how guesses narrow down solution possibilities, maintaining ...
def __simulate_answr__(self, answr): if (answr not in self.__solution_simulation__.keys()): self.__solution_simulation__[answr] = {} iter_words = self.__solution_simulation__[answr].keys() if (len(iter_words) == 0): iter_words = self.__words_possible__ for gue...
def previous_task(self): currentIndex = self.listView.currentIndex() row = currentIndex.row() column = currentIndex.column() previousIndex = self.listView.model().index(row - 1, column) self.listView.setCurrentIndex(previousIndex) self.fulfill_task_data(previousIndex) def...
The code sets up a graphical user interface (GUI) for an administrator's main window, creating components like a task list view, navigation buttons, text fields for task details, and action buttons (add, remove, edit). It configures layouts, styles, and connections to handle user interactions, enabling task management ...
def setupUi(self, AdministratorMainWindow): if not AdministratorMainWindow.objectName(): AdministratorMainWindow.setObjectName(u"AdministratorMainWindow") AdministratorMainWindow.resize(990, 711) AdministratorMainWindow.setStyleSheet(u"") self.centralwidget = QWidget(Administ...
def _creates_cells(self): for i in range(self._num_cols): col_cells = [] for j in range(self._num_rows): col_cells.append(Cell(self._win)) self._cells.append(col_cells) for i in range(self._num_cols): for j in range(self._num_rows): ...
This code initializes a maze structure by setting up grid dimensions, cell sizes, and a window. It creates cells, breaks walls to form paths, and sets entrance/exit points. The seed parameter ensures reproducible randomization for maze generation.
def __init__( self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None, ): self._cells = [] self._x1 = x1 self._y1 = y1 self._num_rows = num_rows self._num_cols = num_cols s...
def deconv_wiener(psf, reg_fact): r""" Create a Wiener filter using a PSF image The signal is $\ell_2$ penalized by a 2D Laplacian operator that serves as a high-pass filter for the regularization process. The key to the process is to use optical transfer functions (OTF) instead of simple Fouri...
The function computes a homogenization kernel to align two PSFs (point spread functions) by applying a Wiener filter with ℓ₂ regularization to deconvolve the source PSF. It then multiplies this filter with the Fourier transform of the target PSF, converts the result back to the image domain, and optionally clips values...
def homogenization_kernel(psf_target, psf_source, reg_fact=1e-4, clip=True): r""" Compute the homogenization kernel to match two PSFs The deconvolution step is done using a Wiener filter with $\ell_2$ penalization. The output is given both in Fourier and in the image domain to serve different p...
def update_client_names_display(name_list): tkDisplay.config(state=tk.NORMAL) tkDisplay.delete('1.0', tk.END) for c in name_list: tkDisplay.insert(tk.END, c+"\n") tkDisplay.config(state=tk.DISABLED) def get_name_client(client_list, curr_client): idx = get_client_index(client_list, curr_clie...
This code implements a multiplayer Blackjack game server. It handles client connections, manages game states, initializes new games, deals cards, processes player actions (hit/stay), checks for busts, and determines winners after all players stand. It broadcasts game updates to all clients and manages game flow includi...
def blackjack(client_connection, client_ip_addr): global server, clients_names, client_name, clients, stay, ready, new, player_hand, dealer_hand, points_name, points client_name = client_connection.recv(4096).decode() clients_names.append(client_name) print(client_name + " connected") update_clien...
def get_function_location(self, function): data = self.parsed["functionDefinitions"] location = {} for element in data: if re.match("c\+function:", element[0]) and function in element[0]: location["file"], location["position"] = re.split("\(", element[1]) ...
This code extracts function details from parsed data, including function names, return types, locations, and variables. It processes elements marked as "c+function:", strips formatting, and constructs a dictionary of functions with their attributes. The commented section suggests intent to handle parameters, though it'...
def get_functions(self): functions = {} data = self.parsed["declaredType"] for element in data: if re.match("c\+function:", element[0]): parameters = [] function = dict() function["functionName"] = re.split( "\(", re...
def get_method_location(self, className, method): data = self.parsed["functionDefinitions"] location = {} for element in data: if re.match("cpp\+method:\/+{}\/{}".format(className, method), element[0]): location["file"], location["position"] = re.split("\(", element[1...
This function extracts C++ method declarations from parsed data, parsing class names, method names, return types, parameters, and variables. It organizes these into a dictionary with keys combining class/method names, using regex and helper methods to process elements and their attributes.
def get_methods(self): data = self.parsed["declaredType"] methods = {} for element in data: parameters = [] if re.match("cpp\+method", element[0]): method = dict() method["class"] = re.split( "\/", re.sub("cpp\+method:\/...
def get_files(self): data = self.parsed["provides"] files = [] for f in data: files.append(f[0]) files = list(dict.fromkeys(files)) for f in files: files[files.index(f)] = re.sub("\/.+\/", "", f) return files def add_nodes(self, kind, content): ...
The code exports a graph structure by adding nodes for files, primitives, functions, variables, and edges representing relationships like 'returnType', 'contains', and 'invokes'. It then saves this graph as a JSON file at the specified path.
def export(self): for file in self.get_files(): self.add_nodes("file", file) for primitve in self.primitives: self.add_nodes("Primitive", primitve) functions = self.get_functions() for func in functions.items(): self.add_nodes("function", func) ...
def world_extract(x: np.ndarray, fs: int, f0min: int = 40, f0max: int = 800, n_fft: int = 512, n_shift: int = 256, mcep_dim: int = 25, mcep_alpha: float = 0.41,) -> np.ndarray: """Extract World-based acoustic features. Returns: ndarray: Mel-cepstrum with the size (N, n_fft). ndarray: F0 sequence...
The code computes evaluation metrics between predicted and reference audio signals, including log F0 RMSE, MCD (Mel-Cepstrum Distortion), and errors in pitch, voicing, and f0 tracking. It uses DTW alignment to synchronize features, extracts mel-cepstrum and f0 from both signals, and calculates discrepancies for compari...
def obtainMetrics(predFile, refFile): pred_x, pred_fs = sf.read(predFile,dtype="float32") ##int16") ref_x, ref_fs = sf.read(refFile,dtype="float32") ##int16") fs = pred_fs pred_mcep, pred_f0 = world_extract(x=pred_x, fs=fs, f0min=70, f0max=400, n_fft=512, n_shift=256, mcep_dim=34, mcep_alpha=0.45) #...
def get_text(self, text, add_blank=True): text_norm = text_to_sequence(text, dictionary=self.cmudict) if self.add_blank: text_norm = intersperse(text_norm, len(symbols)) # add a blank token, whose id number is len(symbols) text_norm = torch.LongTensor(text_norm) return text_...
The main task of the code is to process input data by extracting and preparing three components: text, mel spectrogram, and speaker information. It takes a line containing a file path, text, and speaker identifier, processes the text with `get_text`, retrieves the mel spectrogram using `get_mel`, and obtains the speake...
def get_triplet(self, line): filepath, text, speaker = line[0], line[1], line[2] text = self.get_text(text, add_blank=self.add_blank) mel = self.get_mel(filepath) speaker = self.get_speaker(speaker) return (text, mel, speaker)
def create_gems(self, cast): # create the initial gems and squares for n in range(DEFAULT_GEMS): text = '*' if random.randint(1,2) == 1 else 'O' gem = self.assign_gem_values(cast, 1 if text == '*' else -1, text) gem.set_score(1 if text == '*' else -1) cas...
The main task of the code is to initialize and run a game using the provided cast and player. It sets up display parameters, opens a window, generates game elements (gems), and executes a loop that processes inputs, updates game state, and renders outputs until the window is closed. The loop continuously handles intera...
def start_game(self, cast, player): """Starts the game using the given cast. Runs the main game loop. Args: cast (Cast): The cast of actors. """ self._CELL_SIZE = 15 self._FONT_SIZE = 15 self._video_service.open_window() self.create_gems(cast) ...
def build_romp(romp_root_path: str, branch: str) -> None: print("Build romp on branch ", branch); cwd = os.getcwd(); os.chdir(romp_root_path); try: os.system('git checkout ' + branch); os.system('./install.sh release'); finally: os.chdir(cwd); def create_output_directory(benchmark_root_path: str,...
The function runs benchmarks for a specified branch of a project by building the ROMP component, creating an output directory, executing benchmark tests with given iterations and timeout, and saving results to the output path.
def run_benchmarks_for_branch(romp_root_path: str, benchmark_root_path: str, branch: str, iteration: int, timeout: int) -> None: build_romp(romp_root_path, branch); output_path = create_output_directory(benchmark_root_path, branch); results = run(benchmark_root_path, output_path, branch, iteration, timeout); wr...
def calculate_performance(benchmark_root_path: str, baseline_branch: str, optimize_branch: str) -> None: baseline_output_path = get_output_directory_path(benchmark_root_path, baseline_branch); optimize_output_path = get_output_directory_path(benchmark_root_path, optimize_branch); baseline_output_files = os.listd...
The main task of the code is to parse command-line arguments for benchmarking and performance analysis, then execute tasks like calculating performance, validating results, or running benchmarks for specified branches. It uses flags (-c, -v, -r) to determine actions, handling baseline and optimized branches, and execut...
def main() -> int: parser = argparse.ArgumentParser(description='Argument parsing for performance profiler'); parser.add_argument('benchmark_root_path', type=str, help="root path to benchmark"); parser.add_argument('romp_root_path', type=str, help='root path to romp source'); parser.add_argument('baseline_branc...
def start(self, paramid): GPIO.output(self.SDA, 1) GPIO.output(self.SCL, 1) GPIO.output(self.SDA, 0) GPIO.output(self.SCL, 0) id = paramid self.write_one_byte(id) def ack(self): GPIO.setup(self.SDA, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(self.SCL, ...
This function writes a byte of data to a device, handling acknowledgment responses. It initiates communication, checks for acknowledgment, writes data if no acknowledgment is received, and prints error messages for failed acknowledgments. The process concludes by stopping communication, ensuring proper I2C/SPI protocol...
def write_item_to_pcf(self, id, databyte): self.start(id) status = self.ack() if(not status): self.write_one_byte(databyte) if(status): print("No acknowledge data") else: print("No acknowledge addresss") self.stop()
def createAllStates(): container = deque() container.append(np.array([0,0,0,0,0,0,0,0,0])) finalContainer = copy.deepcopy(container) # finalContainer.pop() storer = deque() t = 1 while container: temp = container.popleft() if checkWinCondition(temp) == 0: ...
The main task of the code is to generate a dictionary (`stateTable`) that maps unique hash codes (computed via `hashFcn`) to lists of states and their corresponding initial scores (calculated by `initScoreWithLossPenalty`). It iterates over all states from `createAllStates()`, groups them by their hash codes, and store...
def createStateTable(): finalContainer = createAllStates() # # create stateTable stateTable = dict() for state in finalContainer: hashCode = hashFcn(state) if hashCode in stateTable: stateTable[hashCode].append([state,initScoreWithLossPenalty(state)]) else: ...
def _compareBlocks(self, a, b): """ Returns whether two blocks have the same _accurateVisualization """ return self._accurateVisualization(a) == self._accurateVisualization(b) def _visualize(self, block): """ This method makes the visualization that the agent can use for the se...
This function navigates to the designated drop zone for a held goal block, executes the drop action, updates the agent's state, sends confirmation messages, and transitions to the next operational phase (either checking incorrect blocks or continuing to drop goal blocks) based on the number of blocks being carried.
def _dropGoalBlock(self, state: State): if not self._dropping: self._navigator.reset_full() # go to drop zone of the block that you're holding self._navigator.add_waypoints([[gb for gb in self._goalBlocks if self._compareBlocks(gb['visualization'], self._holdingBlocks[0]['vis...
def _processMessages(self, teamMembers): ''' Process incoming messages and create a dictionary with received messages from each team member. ''' receivedMessages = {} for member in teamMembers: receivedMessages[member] = [] for mssg in self.received_messages: for member in teamMembers: if mssg.fro...
The code implements a decision-making loop for an agent in a multi-agent system, handling phases like path planning, door opening, block delivery, and reordering. It processes team messages, updates trust beliefs, and returns actions based on the current phase, such as navigating to doors, manipulating blocks, or reord...
def decide_on_bw4t_action(self, state:State): self._agentName = state[self.agent_id]['obj_id'] # Add team members for member in state['World']['team_members']: if member!=self._agentName and member not in self._teamMembers: self._teamMembers.append(member) # Process messages from team members receive...
def _processMessages(self, teamMembers): ''' Process incoming messages and create a dictionary with received messages from each team member. ''' receivedMessages = {} for member in teamMembers: receivedMessages[member] = [] for mssg in self.received_messages: for member in teamMembers: if mssg.fro...
The function manages team collaboration and navigation in a multi-agent environment by tracking team members, processing messages, monitoring door states, and executing phase-based actions like path planning, door opening, room searching, and verifying goal block drops. It updates trust beliefs and handles dynamic stat...
def decide_on_bw4t_action(self, state:State): # Add team members for member in state['World']['team_members']: if member!=self._agentName and member not in self._teamMembers: self._teamMembers.append(member) # Process messages from team members receivedMessages = self._processMessages(self._teamMembers) ...
def _getRoom(self, room): # Non-Liars return the correct room if self._type is not 'liar' or random.random() > 0.8: return room # Lying agent returns a random door 80% of the time return random.choice(list(self._doors)) def _createPath(self, state: State): self._navi...
The code searches a room, detects blocks, and decides whether to pick up a block based on trust from other agents. It updates the agent's state, tracks progress, and returns an action (move or grab). Lazy agents may skip searching, while strong agents might seek multiple blocks. Trust thresholds and agent types influen...
def _searchRoom(self, state: State): # say that you are going to search the room self._sendMessage('Searching through ' + self._getRoom(self._door['room_name']), self._agentName) # add yourself to list of agents that have seached this room self._supposedlyGotBlock['rooms'][self._door['ro...
def load_values(): global w1, w2, w3, b1, b2, b3 with open('weights_and_biases_v0.2', 'r') as inpt: data = json.load(inpt) w1 = np.array(data[0]) w2 = np.array(data[1]) w3 = np.array(data[2]) b1 = np.array(data[3]) b2 = np.array(data[4]) b3 = n...
This code trains a neural network model using data from '60k_digits.json'. It iteratively selects random samples, normalizes input values, performs forward and backward passes to adjust model weights, and repeats this for specified iterations. The goal is to train the model to recognize digits by updating parameters th...
def learn(iterations=3): start = time.process_time() with open('60k_digits.json', 'r') as raw_data: data=json.load(raw_data) global x1 load_values() for m in range(iterations): g=np.random.randint(len(data)) h=np.random.randint(len(data[g])) ...
def find_lambda_new(X, u, w_2): """ vectorized version of finding lambda without precise search """ d = X.shape[1] Y = X.ravel("F") x = np.kron(np.eye(d), u.reshape(-1, 1))/w_2 Y_ols = x @ la.inv(x.T @ x) @ x.T @ Y var_ols = ((Y-Y_ols)**2).mean() lambdas = np.exp(np.linspace(3, ...
The code implements an iterative algorithm for computing the **sparse singular value decomposition (SVD)** of a matrix $ X $. It alternates between updating the left ($ u $) and right ($ v $) singular vectors using soft-thresholding operations with parameters $ \gamma_1 $ and $ \gamma_2 $, promoting sparsity. The algor...
def ssvd_new(X, gamma_1 = 2, gamma_2 = 2, tol=1e-10, iters=10000): """ vectorized version of sparse SVD algorithm """ # shapes of X n = X.shape[0] d = X.shape[1] # find starting vectors U, S, V = la.svd(X) u_old = U[:, 0] v_old = V[0, :] for i in range(iters): # updat...
def identify_data(data_name, cr_ratio=0): if data_name=='Cora': cora_dataset = Planetoid(root='data', name=data_name) c_params=[0.001, 0.01, 1, 0.001] data = cora_dataset[0] # print(data) elif data_name=='Citeseer': cora_dataset = Planetoid(root='data', name=data_name)...
This function loads and splits client data for federated learning tasks. It identifies input data, determines feature count and class labels, partitions data into target/shadow sets, and distributes them across clients using specified ratios. The output includes client-specific training/test datasets, shadow data, feat...
def load_clients_data(data_name, client_number, tr_ratio, cr=False, cr_ratio=0, sh_ratio=0): data, c_params=identify_data(data_name=data_name, cr_ratio=cr_ratio) num_features=data.x.shape[1] li=[] for i in data.y: if i not in li: li.append(i) num_classes=len(li) target_d...
def create_rec(self,x1,y1,x2,y2): colors = ["red", "orange", "yellow", "green", "blue", "violet"] color=random.choice(colors) rec = self.canvas.create_rectangle(x1,y1,x2,y2,fill=color) return rec def get_food(self): x1 = random.randint(0,49)*10 y1 = random.randint(0,49)*10 x2 = x1+10 y2 = y1+10 return...
This code initializes a graphical game interface with a black canvas for drawing game elements and a white score frame displaying "score" and a value. It sets up initial game variables for a snake's position, direction, and food, and triggers the movement method to start the game.
def __init__(self, master = None): self.master = master self.canvas = Canvas(master,bg = "black",width=500,height=500) scoref = Frame(master,bg="white") scoroetext = Label(scoref,bg="white",text="score") self.valtext = Label(scoref,bg="white",text="0") scoroetext.grid(row=0,column=0,sticky="n",padx=10,pady...
def process_input(s): sc = [tuple(tuple(int(k) for k in j.split(",")) for j in i.splitlines()[1:]) for i in s.split("\n\n")] return sc def solve1(sc): pts = set(sc[0]) r = deque(sc[1:]) sc = [(0, 0, 0)] while r: scn = r.popleft() ...
The code reads input from a file, processes it, solves two parts of a problem (likely a programming puzzle), and prints the results. First, it reads the file content, processes it with `process_input`, then computes `pts` and `ds` using `solve1`. It prints `pts` and passes `ds` to `solve2` to print its output. The main...
def main(fname): with open(fname) as f: s = f.read() sc = process_input(s) pts, ds = solve1(sc) print(pts) print(solve2(ds))
def total_height(self): return np.sum(self.col_height()) def get_biggest_dip(self): tops = self.col_height() dips = [0 for _ in range(NUM_COLUMNS)] dips[0] = max((tops[1] - tops[0]), 0) dips[NUM_COLUMNS - 1] = max((tops[NUM_COLUMNS - 2] - tops[NUM_COLUMNS - 1]), 0) for i ...
The code initializes a class to analyze a matrix (likely representing a game board) by calculating key metrics: total height, largest height dip between adjacent columns, total holes, height difference, empty columns, columns with holes, and a squared score based on these features. It processes the matrix to evaluate s...
def __init__(self, matrix): self.matrix = np.array(matrix) self.total_height = self.total_height() self.biggest_dip = self.get_biggest_dip() self.sum_holes = self.sum_holes() self.height_diff = self.height_diff() self.num_empty_col = self.num_empty_col() self.col_...
def find_and_parse_date(lines: List[str]) -> Tuple[Dict, Union[int, None]]: try: date_pattern = ( r"(?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2},\s+\d{4}|\d{1,2}/\d{1,2}/\d{2,4}" ) for index, line in enumerate(lines): ...
This function parses structured text data, extracts date, document, invoice, product, and freight information using helper functions, maps the parsed data into a dictionary, and returns a pandas DataFrame representing Excel-like columns. It handles errors by logging critical exceptions and returns an empty DataFrame on...
def map_text_to_excel_columns(text: str) -> pd.DataFrame: try: lines = text.strip().split('\n') mapped_data = {} date_data, date_index = find_and_parse_date(lines) mapped_data.update(date_data) document_data, document_end_index = parse_main_section( lines, date_...
def get_curve(self, p1, p2): control_points = self.get_control_points(p1, p2) flat_dist = 0 flat_dist += self.distance(p1, control_points[0]) flat_dist += self.distance(control_points[0], control_points[1]) flat_dist += self.distance(control_points[1], p2) curved_dist = f...
This function draws a curved edge between two points (p1, p2) with adjustable width, color, and glow effect. It generates a curve, iterates through points to draw segments with dynamic color adjustment for "glowy" style, and identifies the arrow tip near p2. Finally, it renders an arrowhead at the calculated position a...
def draw_edge_curved(self, p1, p2, w, color, ns): points = self.get_curve(p1, p2) steps = len(points) arrow_tip = None arrow_angle = None for index in range(steps-1): pp1 = points[index] pp2 = points[index+1] if self.graph_style == "glowy": ...
def get_curve(self, p1, p2): control_points = self.get_control_points(p1, p2) flat_dist = 0 flat_dist += self.distance(p1, control_points[0]) flat_dist += self.distance(control_points[0], control_points[1]) flat_dist += self.distance(control_points[1], p2) curved_dist = f...
This function draws a dashed, curved line between two points (p1, p2) with an arrowhead at the end. It generates a curve via `get_curve`, alternates between drawing dashed segments (`dash_len`) and spaces (`space_len`), and identifies the arrow tip near p2 using distance/angle checks. Finally, it renders the arrowhead ...
def draw_edge_curved_dashed(self, p1, p2, c, w, ns, dash_len, space_len): points = self.get_curve(p1, p2) arrow_tip = None arrow_angle = None dash_on = True i = 0 pp1 = points[0] while i < len(points): if dash_on == True: i = i + dash_l...
def inter_from_mapping(self, mapping): inter = {} edge_labels = {} edge_colors = {} edge_styles = {} for item in mapping: if len(item) == 3: source, target, weight = item elif len(item) == 4: source, target, weight, label = ...
This code initializes a graph visualization object by configuring layout parameters, visual styles, color palettes, and other rendering attributes. It accepts graph data from dictionaries, mappings, or NetworkX graphs, sets layout algorithms (e.g., FA2), adjusts node/edge sizing, defines color schemes (intense, gradien...
def __init__(self, from_dict=None, from_mapping=None, from_nx=None, initial_pos=None, extra_vars=None, info=None, custom_palette=None, layout="FA2", mag_factor=1.0, scaling=5.0, gravity=20.0, iterations=100, strong_gravity=False, dissuade_hubs=True, edge_weight_influen...
def add_edge(self, source, target, weight=1): # Register nodeids self.nodeids.add(source) self.nodeids.add(target) # Add item to interactions if source not in self.interactions: self.interactions[source] = Counter() self.interactions[source][target] += weight ...
This function constructs a graph based on a configuration, creating cores with nodes, connecting cores via specified links, and adding extra nodes/edges. It initializes core groups, links nodes within/ between cores, and appends additional elements like random/popularity-based nodes and secondary neighbor edges, using ...
def make_graph_from_config(self): cores = {} ci = 0 # Create initial cores for index, core_size in enumerate(self.config["cores"]): cores[index] = [] cores[index].append(ci) ci += 1 self.add_edge(ci, cores[index][0]) cores[index...
def add_edge(self, source, target, weight=1): # Register nodeids self.nodeids.add(source) self.nodeids.add(target) # Add item to interactions if source not in self.interactions: self.interactions[source] = Counter() self.interactions[source][target] += weight ...
The code generates a network graph by creating core subnetworks with intra-core connections, linking cores, adding nodes based on popularity/randomness, and introducing extra connections between nearby or random nodes to form a complex graph structure.
def make_new_graph_default(self): # Create a starting core network cores = {} ci = 0 for cn in range(self.num_cores): cores[cn] = [] subset = max(1, int(self.num_nodes/(20*self.num_cores))) sn = int(subset + random.randint(1, subset)) for s...
def get_incoming_weights(self, nodeid): ret = [] if nodeid not in self.reverse_interactions: return ret for source, weight in self.reverse_interactions[nodeid].items(): ret.append([source, weight]) return ret def oversample(self, data, num): sample = [] ...
The main task of the code is to decrease the weights of outgoing edges from specified nodes in a graph, ensuring no node becomes isolated. It filters targets with multiple incoming connections, reduces their weights by 1 (with oversampling if needed), and updates the graph structure while preserving non-zero weights. T...
def decrease_weights(self, nodeids, num=0.1): ret = {} for source, targets in self.interactions.items(): if source in nodeids: # Do not orphan a node in this process down_targets = [x for x, c in targets.items() if len(self.get_incoming_weights(x)) > 1] ...
def get_neighbours(self, nodeid): if nodeid in self.neighbours: return self.neighbours[nodeid] else: return [] def get_incoming_weights(self, nodeid): ret = [] if nodeid not in self.reverse_interactions: return ret for source, weight in self.re...
This code modifies a graph by breaking and creating connections around specified nodes to prevent orphaning. It identifies critical neighbors, oversamples connections to break and create, and rebuilds the graph with adjusted interactions, ensuring node connectivity while redistributing links based on the given ratio.
def move_nodes_sn(self, nodeids, num=0.1): to_break = {} to_make = {} for nodeid in nodeids: # Do not orphan a node in this process first_neighbours = [x for x in self.get_neighbours(nodeid) if len(self.get_incoming_weights(x)) > 1] if len(first_neighbours) > ...
def get_neighbours(self, nodeid): if nodeid in self.neighbours: return self.neighbours[nodeid] else: return [] def get_incoming_weights(self, nodeid): ret = [] if nodeid not in self.reverse_interactions: return ret for source, weight in self.re...
This function reconfigures a graph by randomly rewiring nodes while preserving connectivity. It identifies nodes with multiple incoming edges, breaks their connections, and creates new links to other nodes. The process avoids orphaning nodes by sampling neighbors proportionally to a given fraction (num), then reconstru...
def move_nodes_random(self, nodeids, num=0.1): to_break = {} to_make = {} for nodeid in nodeids: # Do not orphan a node in this process first_neighbours = [x for x in self.get_neighbours(nodeid) if len(self.get_incoming_weights(x)) > 1] if len(first_neighbours...
def draw_edge_curved(self, p1, p2, w, color, ns): points = self.get_curve(p1, p2) steps = len(points) arrow_tip = None arrow_angle = None for index in range(steps-1): pp1 = points[index] pp2 = points[index+1] if self.graph_style == "glowy": ...
This method determines whether to draw a curved or straight edge based on the 'edge_style' attribute. If curved, it selects between normal, dashed, or dotted styles, calling corresponding helper methods with parameters like coordinates, width, color, and style. If not curved, it uses a straight-line drawing method. The...
def draw_edge(self, p1, p2, w, c, style, ns): if self.edge_style == "curved": if style == "normal": self.draw_edge_curved(p1, p2, w, c, ns) elif style == "dashed": self.draw_edge_curved_dashed(p1, p2, c, w, ns, 8, 5) elif style == "dotted": ...
def make_graph_from_config(self): cores = {} ci = 0 # Create initial cores for index, core_size in enumerate(self.config["cores"]): cores[index] = [] cores[index].append(ci) ci += 1 self.add_edge(ci, cores[index][0]) cores[index...
This code initializes a graph generator with customizable parameters like node count, core connectivity, and interaction probabilities. It sets up data structures for nodes, edges, degrees, and communities, then constructs the graph and identifies communities based on the provided configuration or default settings.
def __init__(self, num_nodes=1000, num_cores=1, intra_core_connectivity=0.3, core_connectivity=0.7, add_nodes_random=0.4, add_nodes_popularity=1.4, popularity_cutoff=1.0, connect_core...
def pauseGame(): paused = True while paused: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: paused = False def drawStacks(): i = 0 for val in stack_a: draw_a(val, i) i += 1 i = 0 for ...
This code creates a Pygame visualization for sorting processes, allowing speed adjustment via arrow keys, pausing with spacebar, and displaying real-time metrics like speed, move count, and sorted status. It updates a window with stacks, a vertical line, and text indicators, checking if 'stack_a' is sorted and 'stack_b...
def vis(): clock = pygame.time.Clock() speed = 3 run = True i = 0 pygame.font.init() textfont = pygame.font.SysFont("monospace", 25) pausefont = pygame.font.SysFont("monospace", 45) while run: clock.tick(speed * FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if eve...
def update_batch(self, batch, eta, lmbda, n): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b...
The code implements Stochastic Gradient Descent (SGD) for training a neural network model using mini-batches, with optional L2 regularization. It trains over multiple epochs, shuffles data, updates weights via `update_batch`, and evaluates training/test accuracy/loss if test data is provided. Results are printed, plott...
def SGD(self, training_data, epochs, batch_size, eta, lmbda = 0.0, test_data=None, show_eval = True, show_graph = True, return_accuracies = False): n = len(training_data) train_losses = [] train_accuracies = [] test_accuracies = [] epoch = [] for i in range(epochs): ...
def update_batch(self, batch, eta, lmbda, n): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b...
This code implements mini-batch stochastic gradient descent (SGD) with cross-validation. It trains a model over multiple epochs, splitting data into batches and further dividing each batch into training and test subsets. For each batch, it updates model parameters, calculates training/test accuracy/loss, and aggregates...
def SGD(self, training_data, epochs, k, eta, lmbda = 0.0): n = len(training_data) train_losses = [] train_accuracies = [] test_accuracies = [] epoch = [] for i in range(epochs): random.shuffle(training_data) #Cross validation batch_size...
def get_frequent_itme_sets(self, min_support): self.large_item_sets[1] = self.support_count(1, min_support, False, None) k = 2 while self.large_item_sets[k-1]: self.apriori_gen(k) self.large_item_sets[k] = self.support_count(k, min_support, False, None) k += 1...
The code's main task is to initialize an object for mining association rules from transaction data. It first identifies frequent itemsets using a minimum support threshold, then generates association rules with a specified minimum confidence level, and finally prints the results. The methods `get_frequent_item_sets` an...
def __init__(self, min_support, min_confidence): self.get_frequent_itme_sets(min_support) self.get_arules(min_confidence) self.print_results()
def _prepare_data(self, x, y): x, y = self._get_x_y(x, y) x, y = self._get_x_y_in_correct_dims(x, y) return x.to(device), y.to(device) def _compute_loss(self, y_true, y_predicted): y_true = self.standard_scaler.inverse_transform(y_true) y_predicted = self.standard_scaler.inverse_...
The code trains a neural network model (PGDENet) using Adam optimizer and MultiStepLR scheduler, with validation loss monitoring, early stopping, and logging. It processes training data in batches, computes loss, performs backpropagation, and evaluates on validation/test sets. If enabled, it tracks ODE solver function ...
def _train(self, base_lr, steps, patience = 20, epochs=100, lr_decay_ratio=0.1, log_every=1, save_model=1, test_every_n_epochs=10, epsilon=1e-8, **kwargs): min_val_loss = float('inf') wait = 0 optimizer = torch.optim.Adam(self.pgdenet_model.parameters(), lr = base_lr, eps = epsil...
def ode_func_net_diff(self, inputs, _supports): c = inputs for i in range(self._gen_layers): c = self._gconv_dif(c, self._num_units,_supports) c = self._activation(c) c = self._gconv_dif(c, self._latent_dim,_supports) c = self._activation(c) return c def o...
This function computes the gradient for an ODE-based neural network, selecting between different filter types ("diff", "adv", "diff_adv", "unkP") to calculate the gradient. It applies a coefficient to "diff" gradients, uses separate networks for "adv" and "diff_adv" types, and combines gradients via a gated fusion for ...
def get_ode_gradient_nn(self, t_local, inputs): coeff = 0.1 if(self._filter_type == "diff"): grad = - coeff * self.ode_func_net_diff(inputs, self._supports) elif(self._filter_type == "adv"): grad = - self.ode_func_net_adv(inputs, self._supports_adv) elif(self._fil...
def Play(self): self.player.vel.x = 6 self.player_pos += self.player.vel.x #self.player_pos = [p.rect.x for p in self.player_sprite] self.player.update() self.CameraX = self.player.vel.x # for moving obstacles self.move_map() # apply CameraX to all elements se...
This code processes an action in a reinforcement learning environment, updates the player's state (e.g., jumping), simulates gameplay, evaluates win/loss conditions, calculates rewards (penalty for dying, bonus for passing spikes), and returns the observation, reward, and done status for the next step.
def step(self, action): reward = -0.02 actions = [action] + [0] * self.step_size for action in actions: if action == self.JUMP: self.player.isjump = True elif action == self.NO_JUMP: pass else: raise ValueError("...
def calculate_path_score(self): ''' returns a dict of dict of path scores and a list of scores ''' scores = {} scores_list = [] for receptor in self.paths: scores[receptor] = {} for target in self.paths[receptor]: curr_paths = self.paths[receptor][target] # more than one shortest path # score ...
The main task of the code is to iteratively refine a local optimal signaling network by adding random edges, evaluating path scores, and converging on a near-global optimal network. It uses parameters like edge sampling, path pruning, and convergence thresholds to maximize the score S(Q) while balancing network complex...
def optimal_graph(self, K, l, N, i_local, t, curve, seed, p, v): ''' K = # of intermediate nodes in shortest path l = # of paths to keep for each receptor-target pair in filter_paths2 N = # of top paths to keep i_local = # of iterations used to find the best local signaling network t = # of trys if no impro...
def showImg(img_array: np.ndarray, representation: int): if representation == 1: plt.imshow(img_array, cmap='gray') plt.show() # cv2.imshow("", img_array) # cv2.waitKey(0) else: if representation == 2: plt.imshow(img_array) plt.show() def cumulativ...
The function `hsitogramEqualize` performs histogram equalization on an input image (grayscale or RGB). It computes the cumulative histogram, generates a lookup table (LUT) to map pixel values, and applies it to enhance contrast. For RGB images, it converts to YIQ color space, processes the luminance channel, then recon...
def hsitogramEqualize(imgOrig: np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray): """ Equalizes the histogram of an image :param imgOrig: Original Histogram :ret """ showImg(imgOrig, imgOrig.ndim - 1) # Present image cumHist, grayOrRGB = cumulativeHistogram(imgOrig) # Returns...
def initialSections(nQuant: int, imOrig: np.ndarray) -> np.ndarray: """ Initialize the sections to values such that there are approximately the same number of pixels in each section :param nQuant: number of dividing lines on the histogram :param imOrig: Original image as numpy array :return: the sec...
The function quantizes an image into `nQuant` colors using iterative optimization. It initializes color sections, computes histograms, and iteratively adjusts color sections and optimal points to minimize error. Each iteration generates a quantized image and calculates the weighted mean squared error (WMSE). The proces...
def quantizeImage(imOrig: np.ndarray, nQuant: int, nIter: int) -> (List[np.ndarray], List[float]): """ Quantized an image in to **nQuant** colors :param imOrig: The original image (RGB or Gray scale) :param nQuant: Number of colors to quantize the image to :param nIter: Number of opt...
def superior_one(x): return 0.011 * x**2 + 0.63 * x + 20.751 def inferior_one(x): return 0.1442 * x - 13.073 def superior_two(x): return 0.0042 * x**2 + 0.1635 * x + 12.554 def inferior_two(x): return 0.1985 * x - 11.235 def superior_three(x): return 0.0041 * x**2 - 0.1619 * x + 12.696 def infe...
The code defines four x-range segments and calculates corresponding top/bottom y-boundaries using region-specific functions. It then generates a combined graph plotting 256 lines across these regions, visualizing bounded areas defined by the calculated y-values for each segment.
def main(): # Define the specific x range where both left and right are defined valid_x_one = np.arange(-59.29, -27.92, 0.1) # First region from LiDAR simulation valid_x_two = np.arange(-30.1478, 1.9507, 0.1) valid_x_three = np.arange(-1.9507, 30.5025, 0.1) valid_x_four = np.arange(27.0738916256157...
def get_rows_gen(board: list[list[int]]): yield from board def compress_to_left(board: list[list[int]], row_index: int) -> None: board[row_index] = get_compressed_to_left(board[row_index]) def can_add_right_cell(board, row, column): """ check if the column is not at last index, if it isn't. row and ...
The function `perform_left_command` processes a game board to move and merge tiles to the left. It iterates through each row, compresses non-zero values toward the left, checks for possible merges, and updates the board if movements occur. The process ensures tiles are shifted left, merged where applicable, and zeros a...
def perform_left_command(board: list[list[int]]): row_index = first_index for row in get_rows_gen(board): # for each row first compress to direction command # get the first cell from direction side to pars # if cell is zero means there is no more nonzero cell # because it has be...
def get_rows_gen(board: list[list[int]]): yield from board def get_compressed_to_right(row: list[int]) -> list[int]: """ compress all nonzero cells in queue to right by removing middle zeroes and append them to left :return compressed row """ global has_moved column_index = last...
This function processes each row of the board to compress non-zero values towards the right, merging adjacent equal values if possible. It iterates through rows, checks for mergeable pairs, updates the board by moving values left after merging, and tracks if any moves occurred. The process mimics a rightward slide and ...
def perform_right_command(board: list[list[int]]): # works like performing left command row_index = first_index for row in get_rows_gen(board): board[row_index] = get_compressed_to_right(row) cell = {"row": row_index, "column": last_index, "value": 0} value_of_cell = board[cell["ro...
def get_rotated_to_left(board: list[list[int]]) -> list[list[int]]: """ the result board should have the columns of the current board from last to first (reversely) """ board_to_rotate_left = [] for column_line in get_columns_gen(board): board_to_rotate_left = [column_line] + board_to_rotate_lef...
The function `perform_up_command` simulates an "up" movement on a board by rotating it left, applying a left command to merge tiles, rotating it back to the right, and updating the original board with the result. This technique effectively transforms the up movement into a left movement through rotation, then reverses ...
def perform_up_command(board: list[list[int]]): # it is enough to rotate board to left # then perform left command on it rotated_to_left = get_rotated_to_left(board) perform_left_command(rotated_to_left) performed_board = get_rotated_back_to_right(rotated_to_left) replace_to_main_board(performe...
def get_rotated_to_left(board: list[list[int]]) -> list[list[int]]: """ the result board should have the columns of the current board from last to first (reversely) """ board_to_rotate_left = [] for column_line in get_columns_gen(board): board_to_rotate_left = [column_line] + board_to_rotate_lef...
The main task of the code is to simulate a "down" command on a board by rotating it left, applying a "right" command, rotating it back to the original orientation, and updating the board with the transformed result. This approach leverages rotation transformations to indirectly achieve the downward movement effect.
def perform_down_command(board: list[list[int]]): # it is enough to rotate board to left # then perform right command on it rotated_to_left = get_rotated_to_left(board) perform_right_command(rotated_to_left) performed_board = get_rotated_back_to_right(rotated_to_left) replace_to_main_board(perf...
def perform_up_command(board: list[list[int]]): # it is enough to rotate board to left # then perform left command on it rotated_to_left = get_rotated_to_left(board) perform_left_command(rotated_to_left) performed_board = get_rotated_back_to_right(rotated_to_left) replace_to_main_board(performe...
This function executes a movement command on a board based on the given direction, updates the game state, and returns whether any movement occurred. It uses a global flag 'has_moved' to track if the board changed during the operation.
def perform_command(direction: Direction, board: list[list[int]]) -> bool: global has_moved has_moved = False # reinitialize has moved match direction: case Direction.UP: perform_up_command(board) pass case Direction.DOWN: perform_down_command(board) ...
def package_version_timestamps(package_name): resp = requests.request("GET", f"https://registry.npmjs.org/{package_name}") IGNORE_EVENTS = {"created", "modified"} if resp.status_code == 200: return { key: datetime.strptime(val[:-5], "%Y-%m-%dT%H:%M:%S").timestamp() for key, v...
The main task of the code is to process a package's version and issue timestamps, generating a plot if enabled. It parses the start date, retrieves version and issue timestamps for the package and its dependencies, then visualizes them using `do_make_plot` when `make_plot` is True.
def main(package_name, start_date="2019-01-01", make_plot=True): try: start_timestamp = datetime.strptime(start_date, "%Y-%m-%d").timestamp() except Exception as e: print(type(e)) version_timestamps = package_version_timestamps(package_name) self_issues_timestamps = get_issues_timestamps...
def Find_Or_Add_Unique_table(x,weigs=[],succ_nodes=[]): """To return a node if it already exist, creates a new node otherwise""" global global_node_idx,unique_table,node_find_time,node_hit_time if x==-1: if unique_table.__contains__(x): return unique_table[x] else: ...
The function converts a numpy array into a Tensor Decision Diagram (TDD) by recursively splitting the array along specified dimensions. It handles scalar cases, processes the array based on the given order, splits the array into subparts, and constructs TDD nodes for each segment. If key_width is enabled, it records th...
def np_2_tdd(U,order=[],key_width=True): U_dim=U.ndim U_shape=U.shape if sum(U_shape)==U_dim: node=Find_Or_Add_Unique_table(-1) res=TDD(node) for k in range(U_dim): U=U[0] res.weight=U return res if not order: order=list(range(U_dim)) ...
def get_int_key(weight): """To transform a complex number to a tuple with int values""" global epi return (int(round(weight.real/epi)) ,int(round(weight.imag/epi))) def Find_Or_Add_Unique_table(x,weigs=[],succ_nodes=[]): """To return a node if it already exist, creates a new node otherwise""" globa...
This function performs addition of two TDD (Tree Decision Diagram) nodes, handling cases where either node has zero weight, combining weights when nodes match, and recursively processing successors when nodes differ. It uses memoization via a computed table to avoid redundant calculations, normalizes results, and retur...
def add(tdd1,tdd2): """The apply function of two TDDs. Mostly, it is used to do addition here.""" global global_index_order k1=tdd1.node.key k2=tdd2.node.key if tdd1.weight==0: return tdd2.self_copy() if tdd2.weight==0: return tdd1.self_copy() if tdd1.node==...
def find_computed_table(item): """To return the results that already exist""" global computed_table,add_find_time,add_hit_time,cont_find_time,cont_hit_time if item[0]=='s': temp_key=item[1].index_2_key[item[2]] the_key=('s',get_int_key(item[1].weight),item[1].node,temp_key,item[3]) i...
This function contracts two Terminal Decision Diagrams (TDDs) by combining their nodes based on key mappings, contraction order, and contraction count. It handles terminal nodes, recursively processes successors, adjusts weights multiplicatively, and stores results in a computed table for efficiency. The output is a no...
def contract(tdd1,tdd2,key_2_new_key,cont_order,cont_num): """The contraction of two TDDs, var_cont is in the form [[4,1],[3,2]]""" k1=tdd1.node.key k2=tdd2.node.key w1=tdd1.weight w2=tdd2.weight if k1==-1 and k2==-1: if w1==0: tdd=TDD(tdd1.node) tdd.weight=...
def get_chunks_in_range(chunk_x, chunk_y): chunks_in_range = [] for x in range(chunk_x - CHUNK_RANGE, chunk_x + CHUNK_RANGE + 1): for y in range(chunk_y - CHUNK_RANGE, chunk_y + CHUNK_RANGE + 1): chunks_in_range.append((x, y)) return chunks_in_range def unload_chunk(entities, tile_enti...
This code manages dynamic chunk loading/unloading based on camera position. It calculates current chunk coordinates, compares them to the last known chunk, and unloads chunks no longer in view while loading new ones. This optimizes performance by maintaining only relevant map sections in memory.
def run_chunk_system(entities): camera_filtered_entities = get_entities_with( entities, Component.POSITION, Component.CAMERA ) if len(camera_filtered_entities) == 0: return camera_entity = camera_filtered_entities[0] camera_position = camera_entity.get_component(Component.POSITION)...
def ui_default(self): if self.is_expression_node: self.frame_expression.hide() self.frame_expression_node.show() self.fill_expression_widget() else: self.frame_expression_node.hide() self.frame_expression.show() self.frame_right.hide(...
This code initializes a GUI component by loading a UI file, configuring database and menu settings, and setting up signal connections and expression node parameters for interactive data handling and user interface operations.
def __init__(self, db_file, menu_file, is_expression_node=False, parent=None): QWidget.__init__(self, parent) # self.setupUi(self) ui.load_ui(os.path.join(os.path.dirname(__file__), 'ui/expression.ui').replace('\\', '/'), self) reload(db) self.is_expression_node = is_expression_...
def pid_exists(pid): conn = get_db_connection() statement = "SELECT pid from objects WHERE pid = ?" with conn: c = conn.cursor() c.execute(statement, (pid.strip(),)) pid = c.fetchone() c.close() return pid is not None def write_obj_to_db(obj): values = obj.get_data() ...
The code writes an object and its datastreams to a database if the object's process ID does not already exist. It first checks for the process ID's existence, writes the main object if it's new, then iterates through and stores each associated datastream.
def write_to_db(obj): if not pid_exists(obj.get_pid()): write_obj_to_db(obj) for ds in obj.get_datastreams(): write_ds_to_db(ds)
def setup(): global db_file db_file = args.db_file if args.wipe_db and os.path.exists(db_file): if args.object_dir is None: print("You do not want this. You can't wipe the database without rebuilding it. Manually " "delete the file if you just want it removed.") ...
The code defines a `main()` function that initializes setup, processes an object directory if specified, prints yearly data if requested, and concludes with a "Done" message.
def main(): setup() if args.object_dir is not None: parse_dir() if args.print_yearly: print_yearly() print("Done")
def list_nexus(repo_alias): # Patterns is as follows: http://nexus-url/repository/<nx-reponame>/(extract-filepath-here) rgx_extract = r'.*\/repository\/[^\/]*\/(.*)' object_list = api_nexus.list_nx(repo_alias) output = extract_substring_from_list(object_list, rgx_extract) # [ print("> " + o) for o ...
The code synchronizes objects between a Nexus (nx) and AWS S3 (s3) repository by comparing their file lists, excluding locked files, and generating a policy to align the repositories. It identifies files to add/delete in each system, applies thresholds for deletions, and executes the policy (first adding, then deleting...
def perform_sweep(nx_repo_alias, s3_repo_alias, file_deletion_threshold=300, detailed_report=True): # Initialize nx_objects nx_objects = [] s3_objects = [] policy = { "nx": { "del": set(), "add": set() }, "s3": { "del": set(), "add...
def check_max(listener): """ - Checks if max attempts have been reached. - Max attempts is defined by number of valid grasps genereated by the model. - Returns False if max attempts have been reached. - Returns True if max attempts have not been reached. """ # if listener.pred_grasps_cam is None: # #...
This callback processes grasp poses from a neural network, filters valid ones based on gripper width, selects top 4 poses, applies coordinate transformations, and interacts with a user to attempt grasping using a robotic arm. It handles pose validation, user input for execution, and limits attempts while maintaining gr...
def sub_contact_graspnet_callback(self, Float32MultiArray, *args, **kwargs): """ Subscriber Callback function for /contact_graspnet_pose topic. uppacks the Float32MultiArray message, self.pose (PoseStamped) Prompts the User to attempt grasp. """ rospy.loginfo('service: /contact_graspnet/request...
def get_coupon() -> str: csrf = get_csrf_token() body = { 'csrf': csrf, 'email': f'{random.randint(0, 99)}@gmail.com' } res = s.post(f'{url}/sign-up', data=body, proxies=proxy, verify=False, ...
The code's main task is to repeatedly redeem a gift card using a coupon until the user's balance reaches at least 1337, then attempt to purchase a specific item (L33T_LEATHER_JACKET_ID). If the purchase fails with a non-200 status code, it logs an error and exits; otherwise, it logs a success message.
def exploit(): coupon = get_coupon() while get_current_money() < 1337: redeem_gift_card(coupon) res = buy_item(L33T_LEATHER_JACKET_ID, coupon) if res.status_code != 200: log.error('failed l33t') exit(1) log.success('y33t')
def check_for_game_over(): global game_over if game_over == True: end_game() else: pass def take_input(): # As a fail safe we always want to check for game over because this could be called # in the multiple matches function check_for_game_over() # Take input and return it i = input("\n> ") return i def i...
The main task of the code is to manage a game loop where it checks for game over status, displays current game data, takes user input for names, extracts possible initial combinations, finds matching entries in the game session, and handles single/multiple matches by updating the session or prompting retries, repeating...
def main_gameplay_loop(): # First we check if the game is over check_for_game_over() # Then if not we display initials & answers as a list game_session.display() # Then we take input for a new name print("Input a name:") i = take_input() # Then we send that input to extraction. # Initial extraction returns tu...
def user_id_loop(self): # First we need to get user input for our possible user id: print("Welcome to the initials game! What is your USER ID?") print("If you want to check your answers against past answers you need to use the same USER ID.") user_id_to_check = input("USER ID: ").strip() # Next we check that...
The code initializes an HTTP connection to a local server, retrieves a user ID via a loop, prompts for a game mode, and fetches game-specific data (initials and duration) from a database through server-side functions.
def __init__(self,): http_server = "127.0.0.1" self.conn = http.client.HTTPConnection(http_server, port=5000) self.user_id = self.user_id_loop() self.game_id = self.game_mode_prompt() #self.game_initials = self.db.get_initials_from_game_id(self.game_id) self.game_initials = self.server_to_db_func(server_f...
def show_image(image, title="", logLevel=logging.DEBUG, scale=1.0): if title=="": title = random.randint(0, 1000).__str__() title = title + " scale: " + scale.__str__() logger = logging.getLogger("main") if logger.getEffectiveLevel() <= logLevel: if scale != 1.0: image = cv2.resize(image, (0,0), fx=scale,...
The main task of the code is to process a cropped license plate image by converting it to grayscale, applying thresholding for segmentation, correcting perspective distortion, adjusting rotation, and flipping the image horizontally to prepare for character recognition. The function returns the processed plate and a cop...
def process_cropped_plate(plate): overview = plate.copy() plate = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY) plate = cv2.threshold(plate, PLATE_THRESH_LOW, PLATE_THRESH_HIGH, cv2.THRESH_BINARY)[1];show_image(plate, "Plate threshold", logging.DEBUG) #plate, overview = fix_plate_rotation(plate, overview);show_image(plat...
def close(self): logging.info("ENTERING close") if self._connection: if self._cursor: self._cursor.close() self._connection.close() logging.info("PostgreSQL connection is closed") self._connection = None self._cursor = None logg...
The code's main task is to reset a connection by closing it, reconnecting, and initializing a cursor, with logging to track entry and exit points.
def reset(self): logging.info("ENTERING reset") self.close() self.connect() self.cursor() logging.info("EXITING reset")
def save_workbook(self, filename, workbook): success_flag = True try: workbook.save(filename) except PermissionError: print("Failed to save the workbook. The file is currently open.") success_flag = False except exceptions.ReadOnlyWorkbookException: ...
This code creates or updates an Excel workbook with sheets named after dates, ensuring seven future days are present. It formats new sheets, populates match data from league structures, updates timelines, and maps matches to rows, saving changes to the file.
def create_file_sheet(self, filename): create_flag = False if not os.path.exists(filename): workbook = Workbook() self.save_workbook(filename, workbook) create_flag = True workbook = load_workbook(filename) # Generate the name with today's date ...
def search_jcr(key, page): with requests.get("https://academic.oup.com/jcr/search-results?page=" + page + "&q=" + key +"&fl_SiteID=5397&SearchSourceType=1&allJournals=1",headers=headers) as html: soup = BeautifulSoup(html.text, "html.parser") for link in soup.find_all("div", "sr-list al-article-box ...
The main task of the code is to search for academic journals or articles using multiple search functions (e.g., JCR, JCP, JM, etc.) with adjusted page numbers, and download the results into a specified output folder. The function iterates three times, varying page numbers to cover multiple result pages, ensuring compre...
def search_journals(keyword, page, output_folder): for i in range(3): search_jcr(keyword, str(int(page) + i)) search_jcp_w(keyword, str(int(page) + i - 1)) search_jm(keyword, str(int(page) + i - 1)) search_jmr(keyword, str(int(page) + i - 1)) search_jppm(keyword, str(int(page...
def count_blocks(subtitle_string): if not subtitle_string.endswith('\n'): subtitle_string += '\n' return len(re.findall(r'(\d+\n(?:.+\n)+)', subtitle_string)) def send_to_openai(self, subtitles, prev_subtitle, next_subtitle, prev_translated_subtitle, subtitles_length, warning_message=None, prev_response...
The code translates subtitles using OpenAI, verifies the output's structure (block count, no extra content, no errors), and retries up to a limit if mismatches occur, logging warnings and tracking costs, retries, and wasted funds during each attempt.
def translate_subtitles(self, subtitles, prev_subtitle, next_subtitle, prev_translated_subtitle): subtitles_length = count_blocks(subtitles) translated_subtitles, used_dollars = self.send_to_openai(subtitles, prev_subtitle, next_subtitle, prev_translated_subtitle, subtitles_length) count = 0 ...
def get_conversation(self, msg_info=None, msg_idx=None): if not msg_info: msg_info = self.get_msg_by_idx(msg_idx) conv_id = msg_info[self.MSG_CONV_ID] if conv_id: return ([self.get_msg_by_idx(int(conv_id, 36))] + self.get_replies(msg_idx=int(conv_id, 36))) else: return [m...
This function adds a specified tag to messages in a session. It handles both individual messages and entire conversations, updating their metadata, the main index, and a posting list for the tag. It also manages caching and ensures tags are uniquely applied, with progress tracking during the operation.
def add_tag(self, session, tag_id, msg_info=None, msg_idxs=None, conversation=False): pls = PostingList(session, '%s:tag' % tag_id) if not msg_idxs: msg_idxs = set([int(msg_info[self.MSG_IDX], 36)]) session.ui.mark('Tagging %d messages (%s)' % (len(msg_idxs), tag_id)) for msg_idx in ...
def get_conversation(self, msg_info=None, msg_idx=None): if not msg_info: msg_info = self.get_msg_by_idx(msg_idx) conv_id = msg_info[self.MSG_CONV_ID] if conv_id: return ([self.get_msg_by_idx(int(conv_id, 36))] + self.get_replies(msg_idx=int(conv_id, 36))) else: return [m...
This function removes a specified tag from messages and their conversations. It updates message tags, modifies the index, and maintains a posting list. If 'conversation' is True, it recursively processes all replies. It handles batch operations, clears cache periodically, and updates UI progress.
def remove_tag(self, session, tag_id, msg_info=None, msg_idxs=None, conversation=False): pls = PostingList(session, '%s:tag' % tag_id) if not msg_idxs: msg_idxs = set([int(msg_info[self.MSG_IDX], 36)]) session.ui.mark('Untagging conversations (%s)' % (tag_id, )) for msg_idx in lis...
def update_ptrs_and_msgids(self, session): session.ui.mark('Updating high level indexes') for offset in range(0, len(self.INDEX)): message = self.l2m(self.INDEX[offset]) if len(message) > self.MSG_CONV_ID: self.MSGIDS[message[self.MSG_ID]] = offset for msg_ptr in message[self.MSG_PTR...
The code scans a mailbox, parses each message, indexes them with unique identifiers, handles date validation, manages message conversations, and updates the database with new/modified messages, returning the count of added messages.
def scan_mailbox(self, session, idx, mailbox_fn, mailbox_opener): try: mbox = mailbox_opener(session, idx) session.ui.mark('%s: Checking: %s' % (idx, mailbox_fn)) except (IOError, OSError, NoSuchMailboxError): session.ui.mark('%s: Error opening: %s' % (idx, mailbox_fn)) return 0 if ...
def elem(ns, tag): return ET.Element(f"{{{ns}}}{tag}") def subelem(parent, ns, tag, text = None, **kwargs): elem = ET.SubElement(parent, f"{{{ns}}}{tag}", **kwargs) if text: elem.text = text return elem def create_representation(root_elem, name, parent_id, item_id, is_pres): rep = subelem(root_elem, xip, 'Repr...
The code generates an XML structure for a XIP file, creating information objects, representations (preservation/access), content entries, and bitstreams based on input asset ID and entries. It organizes data into preservation/access groups, assigns unique IDs, and constructs a properly indented XML tree for archival us...
def create_xip(asset_id, entries): """Create a xip file to go in the pax file""" root_elem = elem(xip, "XIP") info_obj = subelem(root_elem, xip, 'InformationObject') ref_id = str(uuid.uuid4()) subelem(info_obj, xip, 'Ref', ref_id) subelem(info_obj, xip, 'Title', asset_id) subelem(info_obj, xip, 'SecurityTag...
def get_menu_option(the_list): """pass in a list, and this function gets the user's choice of menu item (returns a list index, counting from zero, not the user's actual choice)""" # show the user their list of options print("") # just give ourselves a little space view_list(the...
The code manages a to-do list application by reading from/writing to files ('todo_app_todo.txt' and 'todo_app_done.txt'), allowing users to view, add, or mark tasks as completed via a menu. It loads saved lists, processes user inputs, and persists changes to files upon exiting.
def main(): '''control logic for the program''' # will be True if the file is there, False if not if os.path.isfile('todo_app_todo.txt'): my_file_object = open("todo_app_todo.txt", "r") # converts the text into a list todo_list_saved = my_file_object.readlines() ...
def GetSelectedAlgorithm(): """ Returns the Selected Algorithm """ return AlgorithmSelected.get() def Bubble_Sort(iterable,ms,callback): global SORTING n = len(iterable) SORTING = True for i in range(n-1): for j in range(-1+n-i): if iterable[j]> iterable[j+1]: ...
The main task of the code is to execute the selected sorting algorithm (Bubble, Selection, Insertion, Quick, or Merge Sort) on a dataset with a user-defined speed, and visualize the sorting process using the `draw_data` function. It routes the request to the corresponding algorithm's implementation, passing the data, s...
def Visualize(): # Referencing global variables algo = GetSelectedAlgorithm() if algo=='Bubble Sort': Bubble_Sort(data,float(Speed.get()),draw_data) elif algo=='Selection Sort': Selection_Sort(data,float(Speed.get()),draw_data) elif algo=="Insertion Sort": Insertion_S...
def __finddir(self, path, permpath): self.__log('Finding files in {}...'.format(path)) for i in os.listdir(path): if os.path.isfile(os.path.join(path, i)): self.__log('Found file {}, adding...'.format(i)) if path.replace(permpath, '') == '': self.addfile(os.path.join(path, i), pa...
The main task of the code is to add files from a specified directory path to `self.directory`, either recursively (default) or non-recursively. If recursive, it calls `__finddir()` to process subdirectories; otherwise, it iterates through files in the given path, logs each file, and adds them using `addfile()` with adj...
def adddir(self, path, recursive=True): self.directory = {} ROOT_DIR = os.path.join(self.ROOT_DIR, os.pardir) ROOT_DIR = self.ROOT_DIR PATH_DIR = os.path.join(ROOT_DIR, path) if recursive: self.__finddir(PATH_DIR, ROOT_DIR) else: self.__log('Finding files...') for i in os.listd...
def get_data(data,num_classes): if data == 'MNIST': return get_mnist_datasets() elif data == 'CIFAR': return get_cifar_datasets(num_classes) def get_train_set(dataset,data): if data=='MNIST': x_train = dataset.train.images y_train = np.asarray(dataset.train.labels, dtype=np.int32) # x_train = ...
This code trains and evaluates CNNs using various optimization methods (e.g., SANC, SCR) on MNIST/CIFAR datasets. It runs multiple trials, tracks loss values and oracle calls (gradient computations), and returns averaged loss curves across repetitions to compare method performance.
def _main_cnn(method, data, opt): dtype = opt['dtype'] batch_size = opt['batch_size'] # num_input = 784 # MNIST data input (img shape: 28*28) num_classes = 10 # MNIST total classes (0-9 digits), CIFAR: 10 f_vals_avg = None g_norms_avg = None repetition = opt['repetition'] oracles_max = [] for i i...
def getNewBoard(): # Creates a brand new, blank board data structure board = [] for i in range(8): board.append([0] * 8) return board def resetBoard(board): # Blanks out the board it is passed, except for the original starting posit for x in range(8): for y in range(8): ...
The code simulates a two-player game between two agents, alternating turns to make moves on a board until the game ends. It returns 1 if the first agent wins (higher score) or 0 otherwise.
def play(agent1, agent2): game = getNewBoard() resetBoard(game) turn = 1 cur_player = agent1 while not gameOver(game): move = cur_player.getComputerMove(game) if move is not None: makeMove(game, turn, move[0], move[1]) if turn == 1: turn = 2 ...
def dot_write(rna, fold): dot = ["." for i in range(len(rna))] for s in fold: dot[min(s)] = "(" dot[max(s)] = ")" return "".join(dot) def traceback(matrix, rna, fold, i, L): """ Traceback through complete Nussinov matrix to find optimial RNA secondary structure solution through max b...
The main task of the code is to predict the secondary structure of an RNA sequence using the Nussinov algorithm, trace back the optimal base-pairing configuration via dynamic programming, and format the result as a dot-bracket notation string representing paired and unpaired nucleotides.
def getSecondaryStructure(rna): return dot_write(rna, traceback(nussinov(rna), rna, [], 0, len(rna)-1))
def createC1(dataset): C1 = [] for transaction in dataset: for item in transaction: if not [item] in C1: C1.append([item]) C1.sort() C1 = list(map(frozenset,C1)) return C1 def PruneSupport(Data,Ck,K): supp_count = suppGen(Data,Ck) Lk = [] for key in su...
The code implements a HyperCliqueMiner algorithm to discover frequent itemsets from transactional data, using support and hyper-confidence thresholds. It employs an Apriori-like approach, generating candidate itemsets (Ck), pruning them via support (minsupp) and hyper-confidence (minhconf), and storing valid itemsets i...
def HyperCliqueMiner(data,minsupp,minhconf,inpt): global dataset global min_supp global min_hconf dataset = data min_supp = minsupp min_hconf = minhconf Data= list(map(set,dataset)) K = 1 start_time = time.time() C1 = createC1(dataset) L1,SuppData = PruneSupport(...
def parse_bibliography(soup: BeautifulSoup) -> list[dict]: bibliography = soup.listBibl if bibliography is None: return [] entries = bibliography.find_all("biblStruct") structured_entries = [] for entry in entries: bib_entry = parse_bib_entry(entry) if bib_entry["title"]: ...
This function converts TEI XML data into a structured Paper object by extracting metadata, bibliography, abstract, body text, and back matter from a BeautifulSoup soup. It processes authors, citations, figures, and tables, normalizes references, and assembles all components into a Paper instance with paper_id, pdf_hash...
def convert_xml_to_json(soup: BeautifulSoup, paper_id: str, pdf_hash: str) -> Paper: metadata = extract_paper_metadata(soup.fileDesc) metadata["authors"] = clear_authors(metadata["authors"]) biblio_entries = parse_bibliography(soup) bibkey_map = {normalize_grobid_id(bib["ref_id"]): bib for bib in bibli...
def randomisation_functions(self): l=[] for i in self.para_category: if i=='integer': l.append(self._randint) elif i=='continuous': l.append(self._randuniform) elif i=='categorical': l.append(self._randchoice) se...
This code initializes a population for an optimization algorithm by setting parameters, generating initial individuals with fitness evaluations, and deciding between early or late termination strategies based on the specified condition. It prepares the population structure and fitness calculations for further evolution...
def solve(self, fitness, paras=OrderedDict(), bounds=[], category=[], **r): self.para_len=len(paras.keys()) self.para_dic=paras self.para_category=category self.bounds=bounds self.randomisation_functions() initial_population=self.initial_pop() self.cur_gen = [] ...
def get_colored_edges(chrome): return get_edges(chrome, 1) def two_break_on_graph(edges, indices): edges[indices[0]] = indices[2] edges[indices[2]] = indices[0] edges[indices[1]] = indices[3] edges[indices[3]] = indices[1] def graph_to_genome(black_edges, colored_edges): path = '' for cycle ...
The function performs a two-break rearrangement on a genome by converting it into a graph of colored edges, applying the two-break operation at specified indices, and then reconstructing the modified genome from the updated graph structure.
def two_break_on_genome(P, indices): colored_edges = get_colored_edges(P) two_break_on_graph(colored_edges, indices) return graph_to_genome(get_black_edges(P), colored_edges)
def get_colored_edges(chrome): return get_edges(chrome, 1) def find_non_trivial_cycle(red_edges, blue_edges): cycles = find_cycles(blue_edges, red_edges) for cycle in cycles: if len(cycle) > 2: return cycle[0], red_edges[cycle[0]], blue_edges[cycle[0]], red_edges[blue_edges[cycle[0]]] ...
This function sorts genome P into genome Q using two-break operations. It iteratively identifies non-trivial cycles between red edges (from P) and blue edges (from Q), applies two-break operations to resolve them, and yields the transformed P at each step until P matches Q.
def two_break_sort(P, Q): yield P red_edges = get_colored_edges(P) blue_edges = get_colored_edges(Q) current_2break = find_non_trivial_cycle(red_edges, blue_edges) while current_2break is not None: P = two_break_on_genome(P, current_2break) red_edges = get_colored_edges(P) cu...
def garnish_frame( frame ): """ Test modification to frame. Doesn't work well because some patches of images are pretty bright. """ # f = cv2.medianBlur( frame, 3 ) # f = cv2.GaussianBlur( frame, (5,5), 0 ) f = cv2.bilateralFilter( frame, 5, 50, 50 ) return f def filter_pixals( frames, plot ...
The main task of the code is to process an image file by analyzing frames to compute average activity, identify regions of interest (cells), and visualize their activity patterns. It loads image data, calculates pixel variation, detects cells, and generates plots showing average activity, computed ROIs, and cell activi...
def process_input( imgfile, plot = False ): global g_ global template_, avg_ global frames_, timeseries_ data = np.load( imgfile ) ## Play the read file here. #play( data ) frames_ = np.dstack( [ garnish_frame( f ) for f in data.T ] ) print( '[INFO] Total frames read %d' % len( frames_...
def run_training(model_name, df_train, target_col_name, feature_col_names=None, metric=Metrics.MAE, num_folds=5, single_fold=False, model_params=None, val_preds_col="val_preds", suppress_print=False, transform_target=False): fold_metrics_model = [] df_val_preds = pd.DataFrame...
This function trains a machine learning model using cross-validation, evaluates its performance with a specified metric (default: MAE), and optionally persists the trained models and validation predictions. It handles different model types (e.g., L2_Ridge), processes input data with given features and target, and retur...
def train_model(df, model_name, model_params, feature_col_names, target_col_name, metric=Metrics.MAE, num_folds=5, single_fold=False, persist_model=False, output_path="", transform_target=False): val_preds_col = "val_preds" print(f"training {model_name}") if model_name == Mo...
def help(): help_string = f"""\n Welcome To Database Analysis! (Version: 1.0)\n\t\t ~ Made by Md Zidan Khan\n{"-".ljust(46, "-")} \n Help \n-----------\n\nSyntax:\n\t\tdban.py [-h] \t\tdban.py [-d] <PATH TO DATABASE> [-s] \t\tdban.py [-d] <PATH TO DATABASE> [-t] <TABLE NAME> [-hd] <TABLE HEADER> [-id] <ROWID> [-w] ...
The main task of the code is to parse command-line arguments for database operations, validate inputs, and execute queries like fetching table data, rows, headers, or filtered results with options for ordering, limiting, or specifying conditions. It handles various argument combinations to interact with a database file...
def main(): table = "" header = "" rowid = "" where = "" order_by = "" limit = "" # Help if len(argv) == 1: help() exit(0) # Help if argv[1] == "-h": help() exit(0) if len(argv) < 4: print("Error: arguments must be equal to or greate...
def build_and_clean_record(self): raise NotImplementedError() def _init_metric(self): self.metric_val_dict = {metric:None for metric in self.metric_fn_dict} def evaluate_one_batch(self, batch): outputs_list_shared, outputs_list_dataset, named_v = self.calculate_one_batch(batch) self.coll...
The code evaluates a model on test data by iterating through batches, measuring each batch's processing time, initializing metrics, and returning predictions. It sets the model to evaluation mode, cleans records, and logs time costs for each batch.
def evaluate(self): self.model.eval() self.build_and_clean_record() self._init_metric() for batch in self.eval_loader: TestStartTime = time.time() self.evaluate_one_batch(batch) TestEndTime = time.time() TestTime = TestEndTime - TestStartTi...
def options(): #Prints menu and parses response print("----------------OPTIONS---------------") print("--> 1)\tLog in") print("--> 2)\tLog out") print("--> 3)\tAdd food to order") print("--> 4)\tView order") print("--> 5)\tUpdate order and checkout") print("--> 6)\tExit") chosen = Fa...
The main task of the code is to manage a user's interaction with a food ordering system through a menu-driven interface. It handles user login/logout, order placement, order viewing, and checkout processes. The function uses a loop to present options, validate user actions, and execute corresponding operations like log...
def JustHungry(Front): userID = None location = None order = [] print("--------------------------------------") print("-------------JUST HUNGRY!!------------") print() print("-------WELCOME TO JUST HUNGRY!--------") print() while True: item = options() if not userID =...
def fun(x, Hf, Hf_t, tau, sigma, fastRates): wts, rates = split2(x) return -loglikelihood(Hf, tau, sigma, fastRates, *split2(x)) def split2(x): #"""split and return an input numpy array into two equal-sized arrays""" #n = np.size(x)//2 return x[0], x[1:] def jac(x, Hf, Hf_t, tau, sigma, fastRates): ...
This function logs key metrics during an iterative optimization process. It appends the negative log-likelihood, NMSE, gradient norm, and derived values (CRC, BV, ALR) to global lists for each iteration. It also saves reconstructed weight and rate maps at specified steps. The task is to record optimization progress, en...
def log_results(xc): global niter, likelihood_logged, NMSE_logged, grad_logged, weight_recon_save, crc_logged, bv_logged, alr_logged, std_alr_logged global rate_map_saved, wt_map_saved global Hf, Hf_t, tau_m, tau_sigma global fastRate_vec_true, OPrate_vec_true, OPwt_vec_true likelihood_logged.append...
def apply_gravity(self): if self.velocity.y > 9: self.velocity.y = 9 self.velocity += self.gravity self.position += self.velocity def reset_animation_timer(self): if self.anim_start > self.anim_end-1: self.anim_start = 0 def idle(self): self.current_path...
This code updates a game entity's state by applying gravity, resetting animation timers, handling idle state, basic movement, and attack timer logic. It triggers attack animations if conditions are met and plays hit animations when hit. The method manages animations, movement, and attack states in a game loop.
def update(self): self.apply_gravity() self.reset_animation_timer() self.idle() self.basic_movement() self.attack_timer_toggle() if self.can_attack and self.start_timer == False\ and self.anim_start == 0: ...
def createInitialSol(self): self.sol = Solution() self.create_trucks() self.create_routes() self.sorted_savings_dict = self.savings() while len(self.sol.routes) != 0: self.addInTrucks() for i in self.sol.trucks: i.sequenceOfNodes.append(self.depo...
The code's main task is to solve an optimization problem by generating an initial solution, applying Tabu Search to refine it, and reporting the final solution's routes. It returns the optimized solution object after executing the search algorithm.
def solve(self): self.createInitialSol() self.TabuSearch() # self.TestSolution() self.ReportSolution(self.sol.routes) return self.sol
def send_purchase_command(product_name, product_count): acommand = world_amazon_pb2.ACommands() a_purchase_more = acommand.buy.add() a_purchase_more.whnum = 0 a_product = a_purchase_more.things.add() cur.execute("SELECT product_id FROM amazonapp_warehouse WHERE product_name = %s", (product_name,)) ...
This function processes front-end requests for "purchase more" or "new order". For "purchase more", it checks warehouse inventory and triggers bulk purchases if stock is insufficient. For "new order", it validates product availability, updates warehouse stock, creates orders in the database, and sends packing commands ...
def process_front_end_request(front_end_request): request_head = front_end_request.split(":")[0] request_body = front_end_request.split(":")[1] if request_head == "purchase more": product_name = request_body.split("-")[0] needed_count = int(request_body.split("-")[1]) ...