dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_velocity(m, T): vels = np.linspace(0, 5000, 5000) probs = v_distribution(vels, m, T) out_vel = np.array(random.choices(vels, probs, k=3)) return out_vel def get_snap_time(): t_snap = np.linspace(0, 5000, 5000) probs = t_snap_distribution(t_snap) out_t_snap = random.choices(t_snap, ...
This code simulates a particle's trajectory under gravitational forces, tracking its position, velocity, collisions, and escape/smash events. It initializes a particle with random position and velocity, then iteratively updates its state using time steps determined by collision, snapshot, and maximum velocity constrain...
def launch_particle(): position = [] velocity = [] snaps_pos = [] snaps_vel = [] collisions = 0 #max_dt = 10 s = np.array([0, 0, 0]) while np.count_nonzero(s) == 0: s = np.random.normal(size=3) x = r_hom*(s/np.linalg.norm(s)) v = get_velocity(m_H, T_hom) alive = Tr...
def convert_creators(converted_creators, orig_creators): for orig_creator in orig_creators: converted_creator = convert_person(orig_creator) ensureEmpty(orig_creator) converted_creators.append(converted_creator) def convert_contributors(converted_contributors, orig_contributors): for ori...
This function converts original related item data into a structured format by mapping creators, contributors, identifiers, resource types, titles, and publication years from the input dictionary, while ensuring specific fields are emptied after processing.
def convert_related_items(converted_related_items, orig_related_items): for orig_related_item in orig_related_items: converted_item = {} convert_creators(converted_item.setdefault('creators', []), orig_related_item.pop('itemCreators', [])) convert_contributors(converted_item.setdefault('cont...
def save_model_to_config(ckpt_model_name, vae_model_name): config = getConfig() if 'model' not in config: config['model'] = {} config['model']['stable-diffusion'] = ckpt_model_name config['model']['vae'] = vae_model_name if vae_model_name is None or vae_model_name == "": del config...
The code handles image rendering requests by configuring model parameters, creating rendering tasks, and returning response data with status, queue info, and task identifiers. It includes error handling for process failures and pending tasks, raising appropriate HTTP errors (500, 503) when exceptions occur during rende...
def render(req : task_manager.ImageRequest): try: save_model_to_config(req.use_stable_diffusion_model, req.use_vae_model) req.use_stable_diffusion_model = resolve_ckpt_to_use(req.use_stable_diffusion_model) req.use_vae_model = resolve_vae_to_use(req.use_vae_model) new_task = task_man...
def unload_models(): if thread_data.model is not None: print('Unloading models...') if thread_data.device != 'cpu': if not thread_data.test_sd2: thread_data.modelFS.to('cpu') thread_data.modelCS.to('cpu') thread_data.model.model1.to("cpu") ...
The function `reload_model` unloads existing models and filters, then loads a new model checkpoint to replace the current one, likely for updating or retraining purposes.
def reload_model(): unload_models() unload_filters() load_model_ckpt()
def initialize_parameters_deep(layer_dims): np.random.seed(1) parameters = {} L = len(layer_dims) for l in range(1, L): parameters["W" + str(l)] = np.random.randn( layer_dims[l], layer_dims[l - 1] ) / np.sqrt( layer_dims[l - 1] ) # * 0.01 parame...
This code trains a multi-layer neural network for binary classification using gradient descent. It initializes parameters, performs forward and backward propagation, updates weights iteratively, tracks costs, and measures execution time. The model learns to minimize binary cross-entropy loss over specified iterations w...
def nn_Llayers_binary( X, Y, layer_dims, learning_rate, number_iterations, print_cost=False ): start_time = time() np.random.seed(1) costs = [] # initialize model parameters parameters = initialize_parameters_deep(layer_dims) # loop through the iterations for i in range(0, number_iter...
def parse_args(progname, args): infile = outfile = None autorun = False while args: opt = args.pop() if opt == "-o": if args: if outfile is not None: fatal(progname, "You can only specify one outfile") outfile = args.pop() ...
The main task of the code is to compile a program from an input file to an output file. It processes command-line arguments, reverses them to extract the program name, parses input/output files and an autorun flag, lexes the input file into a program structure, compiles it using the parsed parameters, and prints a succ...
def main(): ra = list(reversed(sys.argv)) progname = ra.pop() infile, outfile, autorun = parse_args(progname, ra) program = lex_file(progname, infile) compile_program(progname, program, outfile, infile, autorun) print("compilation successful")
def get_schedule_name(event): return event["ResourceProperties"]["ScheduleName"] def is_schedule_ready(schedule_name): is_ready = False schedule = sm.describe_monitoring_schedule(MonitoringScheduleName=schedule_name) status = schedule["MonitoringScheduleStatus"] if status == "Scheduled": lo...
The main task of the code is to handle updates for a schedule by checking its existence. If the schedule is not found (ResourceNotFound), it delegates to `create_handler` to initialize it. Otherwise, it logs unexpected errors and re-raises exceptions, ensuring proper resource management and error handling during schedu...
def update_handler(event, context): """ If this is an update for new schedule then call create_handler """ schedule_name = get_schedule_name(event) logger.info("Updating schedule: %s", schedule_name) try: is_schedule_ready(schedule_name) except ClientError as e: if e.response...
def str_to_bin(some_string): byte_array = bytearray(some_string, "utf8") str_bin = "" for byte in byte_array: binary_representation = format(byte, '08b') str_bin += binary_representation return str_bin def pad(plain_bin): # get length of p L = len(plain_bin) # add ...
The code computes the SHA-256 hash of a plaintext message by first converting it to binary, padding it to meet block size requirements, splitting it into 512-bit blocks, and iteratively applying the Merkle-Damgard construction using a compression function (SHA_box). The resulting hash is converted from binary to hexade...
def SHA256(plaintext): # convert plaintext to binary p_bin = str_to_bin(plaintext) # Step 1: padding p_pad = pad(p_bin) # Step 2: Merkle - Damgard # slice the plaintext into 512 bit blocks p_blocks = slice_p(p_pad, 512) # use SHA_box to obtain cipher # initial h h = SHA_box(IV,...
def _make_proper_policy(self) -> np.ndarray: """ Creates a proper initial policy, by iterating through the list of predecessor states. Returns: Proper initial policy. Raises: AssertionError: If no initial policy is provided, and no list of predec...
The code implements the Modified Policy Iteration algorithm to solve a Markov Decision Process (MDP). It iteratively evaluates and improves a policy until convergence, using an initial policy (or generating one if unspecified). The process alternates between updating the value function via policy evaluation and refinin...
def modified_policy_iteration(self, initial_policy: Optional[np.ndarray] = None) -> List[int]: """ Solves the MDP using a Modified Policy Iteration Algorithm. Args: initial_policy: Optional; Array with the size of the number of states, representing the action ...
def read_input(): """ Reads the data from the input file and sets up the MDP """ try: while True: line = input_file.readline().strip() if line.startswith('states'): read_states() elif line.startswith('action'): read_action(line.split()[...
The main task of the code is to solve a Markov Decision Process (MDP) problem using different algorithms—value iteration (VI), policy iteration (PI), or modified policy iteration (MPI)—based on input flags. It reads initial policy data, executes the selected method(s), and prints the resulting policies. The function al...
def solve(vi=True, pi=True, mpi=False): """ Gets the last folder name from path_dir """ read_input() initial_policy = read_initial_policy() if vi: p1 = mdp_problem.value_iteration() print_res(p1, 'VI') # v = mdp_problem.get_V().copy() if pi: p2 = mdp_problem.policy_ite...
def managment_assessment_menu(): assessment_input = input(""" Welcome to the Assessment Menu Please select from the following: [1]View Personal Competency Summary [2]View Competency Results Summary Any additional input for Main Menu >""") if assessment_input == '1': email = logged_user.email c...
The main task of the code is to handle user authentication via password verification and present a role-based menu system. It allows logged-in users (Manager or User) to navigate options like viewing assessment data, editing profiles, logging out, or quitting. The code ensures access control by displaying different men...
def run_menu(): while True: password = input('Please enter your password:\n>') result = logged_user.check_password(user_email,password,cursor) if result: print('Login Success') break else: print("Login failed try again.") while True: ...
def createP(self): list = random.sample(range(self.size**2), self.size**2) if (self.size==4): return self.createP15(list) index = 0 for i in range(self.size): for j in range(self.size): self.board[i][j] = list[index] index += 1 ...
The code initializes a sliding puzzle of size n x n (e.g., 3x3, 4x4) by calculating the board dimensions from the input 'size'. It creates a solvable puzzle matrix if 'new' is True, repeatedly generating puzzles until one is solvable. The heuristics h1, h2, h3 are computed for pathfinding algorithms, while 'f1' and 'so...
def __init__(self, size,new): # n x n size of puzzle 3,4,5(8,15,24) self.size = int((size+1) ** (1/2)) self.board = [[0 for x in range(self.size)] for y in range(self.size)] # matrix self.f1=0 self.new=new if (new): solvable = self.crea...
def H(m): size = len(m) # if m is too long break it into two hashes if(size > 128): m = H(m[0:size//2]) + H(m[size//2:]) #pad m if its too short #if len(m) != 128: #pdb.set_trace() m = m + "0" *(128 - len(m)) return hashPadded(m[:64], m[64:]) def bit(h,i): out = bin(int(h,16))[2:].zfill(256)[...
The code generates a digital signature (R, S) for a message m using a secret key sk and public key pk. It computes a hash of sk, derives a scalar 'a', generates a random value 'r', computes R via scalar multiplication of a base point B with r, and derives S by combining r, a hash of R/pk, and a modulo operation with a ...
def signature(m,sk,pk): h = H(sk) a = 2**(b-2) + sum(2**i * bit(h,i) for i in range(3,b-2)) r = Hint(''.join([h[i] for i in range(int(b//8),int(b//4))]) + m) R = scalarmult(B,r) h = Hint( hashPadded(encodepoint(R) , encodepoint(pk)) + m) S = (r + h * a) % l return R, S
def Hint(m): #this is engineered to match the libsnark #packing gagdget which willl convert h # to a field element h = H(m) tmp = [] tmp2 = [] out = 0 size = 2*b + 1 for i in range(size)[::-1]: tmp.append(bit(h,i)) tmp3 = str(bit(h,i)) + "+ " + str(out) + "+ " + str(out) + "= " out =...
The function verifies a digital signature by checking if the equation `scalarmult(B, S) == pointAddition(R, scalarmult(pk, h))` holds, where `h` is a hash of the message and public key. If not, it raises an exception, confirming the signature's validity or invalidity.
def checkvalid(R, S,m,pk): A = pk h = Hint(hashPadded(encodepoint(R) , encodepoint(pk)) + m) if scalarmult(B,S) != pointAddition(R,scalarmult(A,h)): raise Exception("signature does not pass verification")
def turn_wifi_on(): os.system("sudo rfkill unblock wifi") print("Turning on") crono_start = time.time() while not check_router(): crono_end = time.time() if (crono_end - crono_start) < 20: print("Waiting") time.sleep(2) else: print("Unable to ...
The main task of the code is to attempt to perform a sequence of operations—turning WiFi on, connecting to MQTT, measuring values, and turning WiFi off—with a retry mechanism. If any step fails, it recursively retries up to `try_count` times. If all attempts fail, it exits the program with an error message.
def sgp30code(try_count): if try_count > 0: try: time.sleep(2) turn_wifi_on() crono_start = time.time() client = connect_mqtt(crono_start) print("Listo") turn_wifi_off() measure_values() try_count = 5 exc...
def check_router(): response = os.system("ping -c 1 192.168.0.1") return response == 0 def setup(try_count): print(".") if try_count > 0: try: global dhtDevice dhtDevice = adafruit_dht.DHT22(board.D4) i2c = busio.I2C(board.SCL, board.SDA, frequency=100000) ...
The code configures GPIO pins, unblocks WiFi, removes network configuration files, and applies netplan settings. It waits for router detection by toggling a GPIO signal, then executes setup and sensor initialization functions with a given try count.
def config(try_count): GPIO.output(27, GPIO.LOW) GPIO.output(22, GPIO.HIGH) os.system("sudo rfkill unblock wifi") os.system("sudo rm /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg") os.system("sudo rm /etc/netplan/10-my-config.yaml") os.system("sudo netplan apply") while not check_rout...
def send(self, pkt): self.submit_log(False, pkt) graph.edges.get((self.id, pkt.receiver.id))['object'].deliver(pkt) def dijkstra(self): self.routing_table = {} dijkstra = nx.single_source_dijkstra_path(self.LSDB, self.id, weight='weight') for k, v in dijkstra.items(): ...
The code implements a non-blocking neighbor synchronization and link-state routing protocol. It sends hello packets to establish neighbor relationships, acquires semaphores for synchronization, updates the link-state database (LSDB), runs Dijkstra's algorithm for shortest path calculation, and floods link-state adverti...
def non_blocking(): # down if starter: self.send(Packet({'id': self.id, 'neighbors': self.neighbors.keys()}, 'hello', self, dst, nbr=True)) self.nbr_sem.acquire() self.neighbors[self.nbr_in.msg['id']] = self.sec # 2_way ...
def submit_log(self, is_in: bool, pkt): self.log_lock.acquire() self.logs.append( dict(zip(headers, [(datetime.now() - global_start_time).__str__(), self.id, is_in, pkt.sender.id if type(pkt.sender) == Router else pkt.sender.ip, p...
This code processes incoming network packets to maintain routing information. It handles 'hello' packets by updating neighbor relationships and the Link State Database (LSDB), then floods LSA packets to propagate topology changes. For LSA packets, it updates the LSDB with new edges, runs Dijkstra's algorithm for routin...
def receive(self): while True: self.inp_sem.acquire() pkt = self.inp.pop() self.submit_log(True, pkt) if monitor: print('%d:' % self.id, pkt) if pkt.nbr: self.nbr_in = pkt self.nbr_sem.release() ...
def send(self, pkt): self.submit_log(False, pkt) graph.edges.get((self.id, pkt.receiver.id))['object'].deliver(pkt) def dijkstra(self): self.routing_table = {} dijkstra = nx.single_source_dijkstra_path(self.LSDB, self.id, weight='weight') for k, v in dijkstra.items(): ...
This code increments a timer and manages network neighbor relationships by sending hello packets every 10 seconds, checking for stale neighbors (30-second timeout), removing outdated links from the link-state database (LSDB), recalculating shortest paths with Dijkstra's algorithm, and flooding link-state advertisements...
def sec_passed(self): self.sec += 1 # send hello to neighbors if self.sec % 10 == 0: for k in self.neighbors.keys(): self.send(Packet({'id': self.id, 'neighbors': self.neighbors.keys()}, 'hello', self, graph.nodes.get(k)['object'])) ...
def expense_manager(): while True: print() print_horizontal_line() print('\t\tExpense Manager') print_horizontal_line() print() print("Today's date: ", current_datetime.strftime("%Y-%m-%d")) print() print("Enter any number on the menu to perform action...
This code defines a user interface loop for a Personal Finance Manager application. It displays a menu with options to access expense management, investment tracking, savings goals, or exit. The loop continuously prompts for input, validates it, and directs users to corresponding functions. Error handling ensures inval...
def interface(): while True: print() print("Time: ", current_datetime.strftime("%H:%M:%S")) print("\nEnter any number on the menu to perform actions:") print('1. Expense Manager') print('2. Investment Portfolio') print('3. Savings Goal Manager') print('4. Exit...
def load_dataset(): """Load dataset from path listed in arguments. Uses exclude.py file to selectively remove troublesome reactions Returns trimmed dataset with only reactions with args.min_prec <= no. of precursors <= args.max_prec """ # Load raw data with open(args.dataset, 'r') as json_fi...
The function `build_and_save_df` compiles reaction data into a structured pandas DataFrame, including reaction details, stoichiometry vectors, Magpie embeddings, Roost-formatted precursor data, and action sequences. It preprocesses and saves these features, splits the dataset into training/test/val subsets, and stores ...
def build_and_save_df(): """Assembles all data together into a pandas DataFrame and saves as csv. Saves ---------------- elem_dict: dict Dictionary of mapping stoich vector to elements magpie_embed: dict Dictionary mapping precursors to magpie embeddings (for use ...
def get_reaction_emb(fold_id, ensemble_folds, dataset, fea_len, set_name): model = init_model(fea_len) criterion, _, _, = init_optim(model) params = {"batch_size": args.batch_size, "num_workers": args.workers, "pin_memory": False, "shuffle": False, ...
(The main task of the code is to load and prepare training, test, and validation datasets for a reaction prediction model, create necessary directories, and either generate reaction embeddings or train/evaluate an ensemble model based on command-line arguments. It handles dataset subsetting, validation set configuratio...
def main(): train_set = ReactionData( data_path=args.train_path, fea_path=args.fea_path, elem_dict_path=args.elem_path, prec_type=args.prec_type, amounts=args.amounts ) orig_prec_fea_len = train_set.prec_fea_dim # print('orig precursor fea dim', orig_prec_fea_le...
def generate_hstring(h_list, set_char, prefix, set_len, str_len): """ :return: """ if(str_len == 0): # Append to list h_list.append(prefix) return for i in range(set_len): # Next character of input added newPrefix = prefix + set_char[i] generate_hs...
The main task of the code is to compute expected emission and transition probabilities (E-step) in a probabilistic model, updating E_ijn and E_ijzw matrices based on observed read sequences, quality scores, and parameters like eta0, eta1, pi, and tau. It processes all possible h-length nucleotide combinations, performi...
def e_func(eta0, eta1, pi, gamma, read, quality, tau, h): beta_out = np.ones((2, pow(4, h))) nuc = ['A', 'C', 'G', 'T'] list_of_hstrings = [] sample_space = generate_hstring(list_of_hstrings, nuc, "", len(nuc), h) alpha = alpha_func(eta0, eta1, pi, gamma, read, quality, tau, h) print("Alpha:",...
def solve(position): global answer if check_for_win(position) != 'Draw': return check_for_win(position) if is_full(position): return 'Draw' if forced_play(position): return 'Draw' plays = get_plays(position) check_play = np.array([solve(plays[i]) for i in range(len(plays)...
The main task of the code is for the AI to play a move in a Tic-Tac-Toe game by solving the board, updating the GUI with the AI's move, checking for a win or draw, and handling game outcomes like displaying "AI wins!" or "Draw!" while disabling the corresponding buttons to prevent further interaction.
def ai_plays(): global board, buttons, turn, answer if turn % 2 == 0: solve(board) for i in range(3): for j in range(3): board[i][j] = answer[i][j] buttons[i][j].config(text=board[i][j]) if board[i][j] != ' ': button...
def whose_turn(position): turn_helper = 0 for i in range(3): for j in range(3): if position[i][j] != ' ': turn_helper += 1 return 'X' if turn_helper % 2 == 0 else 'O' def clear(): global board, buttons, answer for i in range(3): for j in range(3): ...
This function handles a tic-tac-toe move by updating the board with 'X' or 'O', checking for a win/draw, displaying results, and triggering AI's turn. It disables the clicked button, checks all rows/columns/diagonals for three-in-a-row, shows win/draw messages, clears the board if needed, and increments the turn counte...
def action(row, column): global board, buttons, turn board[row][column] = 'X' if whose_turn(board) == 'X' else 'O' buttons[row][column].config(text=board[row][column], state='disabled') for i in range(3): if board[i][0] == board[i][1] == board[i][2] != ' ': messagebox.showinfo(None, ...
def create_drivers_passengers_table(): database = r"pythonsqlite.db" sql_create_drivers_table = """ -- drivers table CREATE TABLE IF NOT EXISTS drivers ( id integer PRIMARY KEY, name text NOT NULL, ...
The main task of the code is to create a database table for drivers and passengers, connect to a SQLite database, retrieve a passenger list, select a specific passenger, and use the `match()` function to generate and print a message based on that passenger's data. The redundant commented-out lines are for testing or in...
def main(): create_drivers_passengers_table() #create_drivers_passengers() - this is redundant, does not need to be run more than once database = r"pythonsqlite.db" conn = create_connection(database) #select_all_passengers(conn) - these are stepping stones to get db to work #select_all_drivers(c...
def wrap_message( payload: MessagePayload, network: NetworkInfo = DEFAULT_NETWORK ) -> MessageWrapper: payload_type = message_mapping_inv[type(payload)] header = MessageHeader(payload_type, network) wrapper = MessageWrapper(header, payload) return wrapper def serialize_message(message: MessageWrappe...
The code tests the handshake message handling by creating a handshake payload, wrapping it, serializing it into bytes, and then deserializing it to verify correctness. It checks if the wrapped message can be properly converted to and from its serialized form, ensuring the handshake process works as expected.
def test_handshake(): payload = MessageHandshake(query=randbytes(32), response=None) original = wrap_message(payload) print("origi:", original) data = serialize_message(original) print("serialized:", data) final = deserialize_message_with_header(data) print("final...
def write_header(outfile): outfile.write('# Code generated by cfonts_to_py.py\n') outfile.write('import TFTfont\n') def process(infile, outfile, sourcefile): chars_processed = 0 horiz, vert = 0, 0 name = getname(sourcefile) phase = 0 header_done = False offset = 0 index = [offset] ...
This function consolidates data from multiple source files into a single destination file by writing a header, processing each source file's content, and appending a trailer. It handles I/O operations with error handling for OS-related issues.
def load_c(sourcefiles, destfile): try: with open(destfile, 'w') as outfile: write_header(outfile) for sourcefile in sourcefiles: with open(sourcefile, 'r') as f: process(f, outfile, sourcefile) write_trailer(sourcefiles, outfile) e...
def _is_reachable(board1, board2): """Return True if two N-Puzzle state are reachable to each other.""" return _parity(board1) == _parity(board2) def eightPuzzleH2(state, goal_state): """ Return the total Manhattan distance from goal position of all tiles. Parameters ---------- state : Eigh...
The code tests a graph-search algorithm for solving an 8-puzzle problem. It initializes a goal state and a randomly generated reachable start state. Using a greedy frontier with heuristic `eightPuzzleH2`, it performs graph search to find a path from the start to the goal state. The function outputs the solution steps, ...
def test_by_hand(verbose=True): """Run a graph-search.""" goal_state = EightPuzzleState([[1, 2, 3], [4, 5, 6], [7, 8, 0]]) init_state = EightPuzzleState.initializeState() while not _is_reachable(goal_state.board, init_state.board): init_state = EightPuzzleState.initializeState() #eightPuzzl...
def m2k(m): k_axis = np.logspace(-2, 25, 10000) m_axis = k2m(k_axis) # np.interp needs x_axis to be increasing m_axis = m_axis[::-1] k_axis = k_axis[::-1] r = np.interp(m, m_axis, k_axis) return r def PBH_Variance( A = 1, Sigma = 1, x = np.logspace(-2, 2, 100), ...
This function calculates a parameter 'r' related to primordial black hole (PBH) abundance, using inputs like amplitude (A), width (Sigma), critical mass scale (kc), mass spectrum (m), and clustering parameter (DeltaC). It computes PBH variance (S2), a Beta factor from Gaussian statistics, and derives 'r' via a scaling ...
def Phi_Kernel( A = 0.2, Sigma = 1.5, kc = 1e8, m = np.logspace(-8, 2, 1000), DeltaC = 0.45 ): k = m2k(m) x = k/kc S2 = PBH_Variance(A = A, Sigma = Sigma, x = x) b1 = np.exp(-DeltaC**2 / (2*S2)) b2 = np.sqrt(2*S2/(np.pi * DeltaC**2)) Beta = b1*b2 ...
def Merger_Rate_Lite(fbh, mc, z, Use_S2, S1_method): t0 = 4.3523939036782445e+17 t = p21ct.z2t(z) R0 = 3.14061016E6 * mc**(-32/37) * fbh**(53/37) * (t/t0)**(-34/37) S = S_Factor(fbh = fbh, sbh = 0, mc = mc, M = 2*mc, m_ave = mc, m2_ave = mc**2, mf_model = 2, t = t, Use_S2 = Use_S2, S1_method = S1_metho...
This function calculates the merger rate of black holes (BHs) at a given redshift $ z $, considering parameters like BH mass fraction ($ fbh $), mass model ($ mf\_model $), and scaling factors. It uses precomputed data tables for $ z=0 $, integrates over mass distributions, and scales results to arbitrary $ z $ values....
def Merger_Rate( fbh = 1e-2, mc = 20, sbh = 0.6, z = 0, mf_model = 1, sbh_width = 10, nm = 100, Use_S2 = 0, S1_method = 0, Use_interp = 1, S_Tab_Len = 200, show_status = 0): if mf_model == 2: if PyLab...
def Phi_Kernel( A = 0.2, Sigma = 1.5, kc = 1e8, m = np.logspace(-8, 2, 1000), DeltaC = 0.45 ): k = m2k(m) x = k/kc S2 = PBH_Variance(A = A, Sigma = Sigma, x = x) b1 = np.exp(-DeltaC**2 / (2*S2)) b2 = np.sqrt(2*S2/(np.pi * DeltaC**2)) Beta = b1*b2 ...
The main task of the code is to compute and fit a primordial black hole (PBH) mass distribution profile using a kernel function. It calculates the PBH fraction (fbh) via integration, identifies the peak mass (mc), and determines the distribution width (Width) by minimizing chi-squared differences between theoretical an...
def Phi_Profile( A = 0.2, Sigma = 1.5, kc = 1e8, DeltaC = 0.45, map_nx = 500 ): Small = 1e-40 Width_Min = 1e-2 Width_Max = 20 f = lambda m: Phi_Kernel(A = A, Sigma = Sigma, kc = kc, DeltaC = DeltaC, m = m) Peak = np.log10(k2m(kc)) m_vec, Phi_v...
def dOmGW0h2_dlnk_slow_vec(A = 1.0, kc = 1.0, Sigma = 1.0, k = np.logspace(-3, -3, 50), nu = 1000, nv = 100, ncpu = 1): f = lambda x: dOmGW0h2_dlnk_slow(A = A, kc = kc, Sigma = Sigma, k = x, nu = nu, nv = nv) if ncpu == 1: r = Function_Array(f, k) else: r = Parallel(n_jobs=ncpu)(delayed(f)(x...
This function computes the derivative of the GW energy density (dOmeGW0h2/dlnk) using either fast interpolation from precomputed tables or slow numerical integration. It handles edge cases like small/large Sigma by switching to delta approximation or direct computation. The result is scaled to primordial or today's val...
def dOmGWh2_dlnk( f = np.logspace(-4, 4, 100), fc = 1.0, k = np.logspace(-4, 4, 100), kc = 1.0, A = 1.0, Sigma = 0.5, Use_Freq_Domain = True, Use_Today_Value = True, Use_Delta_Approx = True, Use_Fast_Mode = True, nu = 1000, ...
def load_data_to_dataframe(raw_filepath=RAW_TSV_FILEPATH, cleaned_tsv_filepath=CLEANED_TSV_FILEPATH, verbose=False): """ Cleans the data from spending.tsv and loads into a DataFrame object. :param raw_filepath: Filepath to the raw spending.tsv file :param cleaned_tsv_filepath: Filepath to where the cle...
The main task of the code is to load spending data from a TSV file into a DataFrame, compile transactions into a structured dictionary organized by year and month, and save the processed data as a text file. It accepts parameters for specifying years/months, parallel processing (threading/multiprocessing), and file pat...
def perform_data_compilation( years=None, months=None, use_threading=False, use_multiprocessing=False, raw_filepath=RAW_TSV_FILEPATH, cleaned_filepath=CLEANED_TSV_FILEPATH, cleaned_txt_filepath=SPENDING_DATA_TXT_FILEPATH, ): """ Driver function to load data/cleaned_spending.tsv into ...
def _prepare_round(self): # Resets anything round-specific self.deck = self._deckFactory.build_deck(self._curr_round) self.hands = self.deck.deal_hands(self.config.num_players, self.config.hand_size) self.played_cards = [[] for _ in range(self.config.num_players)] self._score_com...
The main task of the code is to execute a multi-round game loop, preparing and playing each round, calculating scores, and displaying intermediate results. It iterates through configured rounds, updates scores per round, and computes final player scores by aggregating round-wise results, ultimately printing the final s...
def _game_loop(self): for round in range(self.config.num_rounds): self._curr_round = round # Prepare this round self._prepare_round() print(f'Playing round {self._curr_round + 1}') self._play_round() # Compute score for the round ...
def _init_render(self) -> None: self.fig, axis = plt.subplots() self.fig.canvas.manager.set_window_title("Snake") field = self.field.numpy() extent = (0, field.shape[1], field.shape[0], 0) self.img = axis.imshow( field, vmin=-1.0, vmax=1.0, ...
The code runs a game using a provided neural network model, taking actions based on the model's predictions, updating the environment state, and rendering each step. It initializes the game, loops until termination, logs debug info, and handles game-over conditions when the reward is -1.
def play_agent(self, model: torch.nn.Module) -> None: """Runs game with model.""" sleep_seconds = 0.05 done = False step = 0 self._init_render() state = self._reset() self._render(step=step) while not done: step += 1 time.sleep...
def set_flow_pkt(self): self.set_flow_mean_std("fwd", "pkt") self.set_flow_mean_std("bwd", "pkt") self.set_flow_len_size_min_max_mean_std() def set_flow_iat(self): self.set_flow_mean_std("all", "iat") self.set_flow_mean_std("fwd", "iat") self.set_flow_mean_std("bwd", "iat...
This method converts network flow data into a structured pandas DataFrame, aggregating statistical features like packet sizes, inter-arrival times, duration, speed, direction-specific metrics (forward/backward), TCP flags, and header/window sizes. It compiles these into a single row with predefined columns for machine ...
def to_df(self, source, label=None): if label is None: label = "NeedManualLabel" self.set_flow_pkt() self.set_flow_iat() self.set_flow_duration(self.ts) self.set_flow_speed(self.ts) self.set_flow_dp_ratio() return pd.DataFrame([[self.flow["all"]["i...
def set_flow_pkt(self): self.set_flow_mean_std("fwd", "pkt") self.set_flow_mean_std("bwd", "pkt") self.set_flow_len_size_min_max_mean_std() def set_flow_iat(self): self.set_flow_mean_std("all", "iat") self.set_flow_mean_std("fwd", "iat") self.set_flow_mean_std("bwd", "iat...
The main task of the code is to convert flow data into a structured feature list for analysis, including packet statistics, inter-arrival times, traffic direction metrics, flags, and timestamps. It aggregates forward/backward/all flow attributes, calculates statistical measures (mean, std, min, max), and appends a labe...
def to_list(self, source, label=None): if label is None: label = "NeedManualLabel" self.set_flow_pkt() self.set_flow_iat() self.set_flow_speed() self.set_flow_dp_ratio() return [self.id, datetime.fromtimestamp(self.timestamp), ...
def getRawData(): print("---getRawData---") annotation_folder = './annotations/' annotation_file = './annotations/captions_train2014.json' '''if not os.path.exists(os.path.abspath('.') + annotation_folder): annotation_zip = tf.keras.utils.get_file('captions.zip', ...
The main task of the code is to perform image captioning by retrieving raw data, preprocessing it into training and test datasets, training a model on the training data, evaluating it on the test dataset, and executing a custom model run. The workflow includes data handling, model training, and evaluation for generatin...
def main(): print("Image Captioning Main") raw = getRawData() dataset_train, dataset_test = preprocessData(raw) model = trainModel(dataset_train) runModel(model, dataset_test) runCustom(model)
def load_csv_data(file_path: str, data_class: DataClass) -> List[DataClass]: """Load data from a CSV file into a list of data classes""" result = [] with open(file_path) as csvfile: reader = csv.DictReader(csvfile) for row in reader: result.append(data_class.from_dict(row)) ...
The main task of the code is to generate historical order data by loading customer and product information from CSV files, creating synthetic orders for the past day, and saving the generated orders as a JSON file. The function handles data loading, order generation with specified parameters, and output storage, loggin...
def run(customers_path: str, products_path: str): """Run the order generator""" customers = load_csv_data(customers_path, Customer) products = load_csv_data(products_path, Product) log.info("Generating historical data") orders = generate_historical_data( # Yesterday date.today() - t...
def normalize_matrix(mat): ''' Normalizes cost matrix. Parameters ---------- mat : dict Cost matrix. Returns ------- new_mat : dict Normalized cost matrix. ''' new_mat = mat.copy() time_list = [] for origin in mat: for destination in mat[origin]...
The function calculates an accuracy score by comparing a submitted route (`sub`) to an actual route (`actual`) using a cost matrix and a gap penalty. It normalizes the cost matrix, computes sequence deviation (`seq_dev`), and multiplies it by the ERP (Edit Distance with Real-Valued Costs) per edit (`erp_per_edit`). The...
def score(actual, sub, cost_mat, g=1000): ''' Scores individual routes. Parameters ---------- actual : list Actual route. sub : list Submitted route. cost_mat : dict Cost matrix. g : int/float, optional ERP gap penalty. Irrelevant if large and len(actual)...
def route2list(route_dict): ''' Translates route from dictionary to list. Parameters ---------- route_dict : dict Route as a dictionary. Returns ------- route_list : list Route as a list. ''' if 'proposed' in route_dict: stops = route_dict['proposed'] ...
The code evaluates a submission's routes against actual routes by checking validity, calculating scores using cost matrices, and returning an average submission score. It assigns invalid scores to unmatched or invalid routes, computes valid scores via a scoring function, and aggregates results into a dictionary with ro...
def evaluate(actual_routes, submission, cost_matrices, invalid_scores): ''' Calculates score for a submission. Parameters ---------- actual_routes_json : str filepath of JSON of actual routes. submission_json : str filepath of JSON of participant-created routes. cost_matrice...
def nf1_loss(self, boxes1, boxes2): return self.inclusion_loss(boxes1, boxes2), l2_side_regularizer(boxes1, log_scale=True) + l2_side_regularizer(boxes2, log_scale=True) def nf2_loss(self, boxes1, boxes2, boxes3): inter_box = self.intersection(boxes1, boxes2) return self.inclusion_loss(inter_box...
The forward method computes multiple loss components for a relation network model using box embeddings. It processes input data to calculate losses for different constraints (nf1-nf4, disjoint, role inclusion/chain) by comparing embedded boxes, applying relation/scaling embeddings, and summing losses for optimization. ...
def forward(self, data): nf1_min = self.min_embedding[data[0][:,[0,2]]] nf1_delta = self.delta_embedding[data[0][:,[0,2]]] nf1_max = nf1_min+torch.exp(nf1_delta) boxes1 = Box(nf1_min[:, 0, :], nf1_max[:, 0, :]) boxes2 = Box(nf1_min[:, 1, :], nf1_max[:, 1, :]) nf1_loss, nf...
def nf1_loss(self, boxes1, boxes2): return self.inclusion_loss(boxes1, boxes2), l2_side_regularizer(boxes1, log_scale=True) + l2_side_regularizer(boxes2, log_scale=True) def nf2_loss(self, boxes1, boxes2, boxes3): inter_box = self.intersection(boxes1, boxes2) return self.inclusion_loss(inter_box...
The code computes multiple loss components for different box relation types (nf1-nf4, disjoint, nf3_neg) by embedding min/max values from input data, constructing Box objects, and applying specialized loss functions. It aggregates losses and regularization terms (e.g., l2_side_regularizer) across various box pairs and ...
def forward(self, data): nf1_min = self.min_embedding[data[0][:,[0,2]]] nf1_delta = self.delta_embedding[data[0][:,[0,2]]] nf1_max = nf1_min+torch.exp(nf1_delta) boxes1 = Box(nf1_min[:, 0, :], nf1_max[:, 0, :]) boxes2 = Box(nf1_min[:, 1, :], nf1_max[:, 1, :]) ...
def phrase_hovering(self, phrase): """ Controls phrase hovering actions. """ if self.hovered_phrase != phrase: self.hovered_phrase = phrase if self.hovered_phrase.known: self.create_highlights(phrase) def reset_pos(self): self.s = 0 self.p = 0 def ...
This method handles phrase selection based on mouse states. When the mouse is pressed (DOWN), it highlights the phrase, sets it as selected, and triggers hovering logic. On mouse release (UP), if the phrase matches the selected one, it marks it as known, resets UI states, generates new XML content, and flags changes. I...
def phrase_selection(self, phrase, mousestate: MouseState): """ Handles phrase selection. """ if mousestate == MouseState.DOWN: phrase.colour = (255, 0, 0) # creating highlights if the phrase is known self.hovered_phrase = None self.phrase_hovering(phrase)...
def phrase_hovering(self, phrase): """ Controls phrase hovering actions. """ if self.hovered_phrase != phrase: self.hovered_phrase = phrase if self.hovered_phrase.known: self.create_highlights(phrase) def phrase_selection(self, phrase, mousestate: MouseState): ...
The function checks each paragraph's characters to find the first one whose rectangle contains the given coordinate. If found, it triggers hovering and selection actions for that phrase. If no match is found, it clears hover and highlight states, and resets selection if the mouse was released.
def phrase_interaction(self, coord, mousestate: MouseState): """ Goes through each paragraph and runs phrase functions on the first character at the given coordinate. If no such character is found, resets hovering and selection variables. """ for para in self.para_groups[:self.p ...
def calcBindEnergyA(A, Z): # Call function to calculate a5 a5 = calcA5(A, Z) # calculate binding energy from given formula B = a1*A - a2*(A**(2/3)) - a3*(Z**2 / A**(1/3)) - a4*((A-2*Z)**2 / A) + a5/A**(1/2) return B def calcBindEnergyB(A, Z): # Call function to calculate a5 a5 = calcA5(A, Z...
The main task of the code is to calculate and display the binding energy, binding energy per nucleon for an atom with mass number 58 and atomic number 28, identify the most stable nucleus based on binding energy per nucleon, and execute an additional calculation via `calcBindEnergyD()`. It uses four functions to analyz...
def main(): print("-----------------------------------------------------------------------------------------") print("The binding energy for an atom with mass number 58 and atomic number 28") print(calcBindEnergyA(58, 28)) print("-------------------------------------------------------------------------...
def calculate_mean_sum(self, start, end): sum_ = 0 prob_sum = self.calculate_prob_sum(self, start, end) if prob_sum != 0: for i in range(start, end): prob_of_pixel = self.calculate_prob_atPixel(self, i) var_1 = i * prob_of_pixel var_2 =...
This function calculates the variance of a probability distribution over a range of integers [start, end). It computes the weighted average of squared differences from the mean, where each value's contribution is weighted by its probability. The result is the variance, representing the spread of the distribution.
def calculate_variance(self, start, end): sum_ = 0 mean_sum = self.calculate_mean_sum(self, start, end) prob_sum = self.calculate_prob_sum(self, start, end) if prob_sum != 0: for i in range(start, end): var_1 = i - mean_sum var_2 = var_1 * var_...
def validate_args( self, training_set_file: str, input_col: Optional[str], output_col: Optional[str] ) -> bool: if self.validate_training_set_file(training_set_file): if self.validate_input_output_col(input_col, output_col): return True return False def train_...
The code initializes a model with parameters like learning rate, training data file, and normalization settings. It validates arguments and either trains the model or prints an error based on validation results.
def __init__( self, learning_rate: float, training_set_file: str, input_col: Optional[str] = None, output_col: Optional[str] = None, normalize: bool = True, debug: bool = False, float_precision: int = 0 ): self.l...
def import_articles(): data = pd.read_csv('articles_cleaned.csv') return data.to_dict(orient = 'records') def text_corpus_lib_parser(corpus_list): parsed = map(lambda x: parse_dict(x), corpus_list) return list(parsed) def parse_dict(dict_e): lowerfied = map_dict(dict_e, str.lower) cleanified = m...
The main task of the code is to perform document search by comparing a given search text against a corpus of articles. It processes the text data, vectorizes both the corpus and search query, calculates similarity using dot product and Euclidean distance, sorts results by similarity scores, and exports the ranked outpu...
def run(data = import_articles(), search_text = "An entrepreneur tends to bite off a little more than he can chew hoping he’ll quickly learn how to chew it yolo a to Amir"): corpus_lib = text_corpus_lib_parser(data) search_doc = {"from": "search", "text": search_text} parsed_search_doc = parse_dict(search_d...
def get_dsomm(): dsomm_yaml = Path("vocabularies/dsomm.yaml") if not dsomm_yaml.exists(): url = "https://raw.githubusercontent.com/wurstbrot/DevSecOps-MaturityModel/master/src/assets/YAML/generated/generated.yaml" r = requests.get(url) dsomm_yaml.write_text(r.text) return yaml.sa...
The main task of the code is to parse DSOMM data into an RDF graph, execute queries on the graph, and serialize the resulting knowledge graph into Turtle format (dsomm-t2.ttl) for testing and validation purposes.
def test_parse_dsomm(): activities = get_dsomm() g = Graph() parse_dsomm(activities, g) query_data(g) g.serialize(format="text/turtle", destination="tests/out/dsomm-t2.ttl")
def parse_command_line(): parser = argp.ArgumentParser() parser.add_argument( '--agg-align', '-a', type=lambda x: pl.Path(x).resolve(strict=True), dest='align', required=True, help='Path to aggregated contig-to-reference alignment table.' ) parser.add_arg...
(The code processes genomic data by merging tables, filtering contigs, and exporting results. It parses command-line arguments, combines alignment and motif data, selects chromosome-specific contigs, filters relevant statistics columns, sorts data by length, and writes outputs to TSV, BED, and text files. Directories a...
def main(): args = parse_command_line() df, motifs = merge_aggregated_tables(args.align, args.motifs, args.chrom) selected = select_chrom_contigs(df, args.chrom) keep_chrom_stats_columns = fnt.partial(keep_stats_columns, args.chrom) keep_columns = list(filter(keep_chrom_stats_columns, selected.col...
def get_absolute_scores_models_csv_path(): return os.path.join(os.path.dirname(__file__), '..', 'results', "models_tested.csv") def to_template_name(st): return regularize_model_name(escape_files_name(st).upper()) def escape_files_name(st): return st.replace('/', '_') def calculate_model_template(model_name...
The code processes model evaluation scores from a CSV file, aggregates best-performing models and their metrics (avg scores, rankings), and generates a markdown table summarizing key results. It filters models with sufficient test data, formats model names, escapes special characters, and compiles a dictionary containi...
def calculate_template_dict(): templates_dict = {} best_per_model = [] best_cols = ("Pretrained", "Best model", "Avg.", "Pretrained Avg.", "Ranking") best = [] minimum_tested = 5 scores_df = pd.read_csv(get_absolute_scores_models_csv_path()) templates_dict['BASE_NAME'] = [] templates_dic...
def load_data_from_json(file_path): """Loads data from JSON file stored at `file_path`""" return db.read_text(file_path).map(json.loads) def filter_data(data): """Filters data, selecting items created after the `MIN_YEAR`, returning back a pandas DataFrame object""" filter_lambda = lambda item: ge...
The main task of the code is to load and preprocess text data, train a classifier model, save the trained model, and evaluate its performance. The process includes downloading NLTK resources, filtering/transforming data, preprocessing for storage, training a classifier, and assessing accuracy on a test set, while track...
def setup(): """Load, preprocess and save the formatted data""" start_time = time.time() nltk.download([ 'punkt', 'stopwords', 'wordnet', 'averaged_perceptron_tagger' ]) print("Loading data...") documents = load_data_from_json(DATASET_FILE_PATH) df = filter...
def scrub_homepage(self, sim_rec_match): """ Find the first video ID on the homepage for which the channel ID is in self.scrubbing_channels """ # assert(self.driver.current_url == 'https://www.youtube.com') self.log('Checking homepage for video from unwanted channel.') ...
The code automates marking videos as "Not interested" on a platform by locating and clicking UI elements via XPath. It identifies unwanted videos, navigates to their menu, selects the "Not interested" option, and submits the report, handling potential errors gracefully.
def not_interested(self, sim_rec_match=False): unwanted_video_id = self.scrub_homepage(sim_rec_match=sim_rec_match) time.sleep(10) if unwanted_video_id: menu_path = "//div[@id='contents']" \ "//div[@id='content' and @class='style-scope ytd-rich-item-renderer...
def scrub_homepage(self, sim_rec_match): """ Find the first video ID on the homepage for which the channel ID is in self.scrubbing_channels """ # assert(self.driver.current_url == 'https://www.youtube.com') self.log('Checking homepage for video from unwanted channel.') ...
This code identifies unwanted videos on a homepage, locates the corresponding menu, and clicks the "don't recommend channel" option to exclude it from recommendations, with error handling for interaction issues.
def no_channel(self, sim_rec_match=False): unwanted_video_id = self.scrub_homepage(sim_rec_match=sim_rec_match) time.sleep(10) if unwanted_video_id: menu_path = "//div[@id='contents']" \ "//div[@id='content' and @class='style-scope ytd-rich-item-renderer']" ...
def log(self, message, exception=False): """ Print and log the same message """ if exception: print(message) self.logger.exception(message, stack_info=True) else: print(message) self.logger.info(message) def __interact_with_action_b...
The `video_action` method attempts to perform a specified action (like, dislike, subscribe) on a video by interacting with buttons below the video screen. It retries up to 5 times if initial attempts fail, logging success or failure. The `turn_on` parameter toggles the action (e.g., enabling/disabling a like/dislike), ...
def video_action(self, action, turn_on=True): """ Attempt the 'action' of pressing one of the buttons right below the video screen By 'action' we mean 'like', 'dislike', or 'subscribe'. turn_on was added to accomodate 'un-disliking' a video (via setting turn_on to False). Un-disl...
def load_videopage(self, vid_id): """ Load the videopage """ youtube_watch_url = 'https://www.youtube.com/watch?v=' self.log('Loading video ID {0}.'.format(vid_id)) videopage_url = youtube_watch_url + vid_id self.driver.get(videopage_url) def save_videopage(self,...
This method loads a video page, waits for a specified buffer time, saves the video page data, retrieves the video duration, increments the videopage level counter, and returns the duration in seconds.
def __load_and_save_videopage(self, vid_id): """ Load a videopage, wait, and then save the recommendations """ self.load_videopage(vid_id) time.sleep(LOAD_BUFFER_SECONDS) self.save_videopage(vid_id) duration = self.get_videopage_seconds() self.videopage_l...
def __load_and_save_homepage(self): """ Load the homepage, wait, and then save its recommendations """ self.__load_homepage() time.sleep(LOAD_BUFFER_SECONDS) self.__save_homepage() self.homepage_level += 1 def log(self, message, exception=False): """ ...
This method attempts to load and save a homepage by calling a private method. It handles potential exceptions like element not found or key errors, logging the error and safely failing to prevent crashes.
def load_and_save_homepage(self): try: self.__load_and_save_homepage() # Might be a bit broad with key error except (EC.NoSuchElementException, KeyError) as e: self.log(e) self.fail_safely()
def __load_and_save_videopage(self, vid_id): """ Load a videopage, wait, and then save the recommendations """ self.load_videopage(vid_id) time.sleep(LOAD_BUFFER_SECONDS) self.save_videopage(vid_id) duration = self.get_videopage_seconds() self.videopage_l...
The main task of the code is to load a video page, wait for its content, save the associated recommendations, and return the duration of the process. It handles potential exceptions like missing elements or key errors by logging them, failing safely, and returning 0 to avoid crashes.
def load_and_save_videopage(self, vid_id): """ Load a videopage, wait, and then save the recommendations """ try: duration = self.__load_and_save_videopage(vid_id) return duration # Might be a bit broad with key error except (EC.NoSuchElementExcept...
def scrub_homepage(self, sim_rec_match): """ Find the first video ID on the homepage for which the channel ID is in self.scrubbing_channels """ # assert(self.driver.current_url == 'https://www.youtube.com') self.log('Checking homepage for video from unwanted channel.') ...
This code identifies unwanted recommended videos by their IDs, locates their corresponding video cards using XPath, and attempts to click and dislike them. It handles exceptions if the video is not interactable or found, ensuring safe execution while logging errors.
def dislike_recommended(self, sim_rec_match=False): unwanted_video_id = self.scrub_homepage(sim_rec_match=sim_rec_match) if unwanted_video_id: video_card_path = "//div[@id='contents']" \ "//div[@id='content' and @class='style-scope ytd-rich-item-renderer']" \ ...
def game_pause(): largeText = pygame.font.Font('freesansbold.ttf',90) TextSurf, TextRect = text_objects("Paused",largeText,red) TextRect.center = ((display_width/2),(display_height/2)) gameDisplay.blit(TextSurf, TextRect) while pause: for event in pygame.event.get(): if even...
This code defines a game loop for a car racing game where the player controls a car to avoid moving obstacles. It handles user input for movement and pausing, updates obstacle positions, checks collisions, and redraws the screen. The loop continues until a crash or exit event occurs, tracking dodged obstacles and updat...
def game_loop(): global pause #pygame.mixer.music.play(-1) #placing car on screen x = (display_width * 0.45) y = (display_height * 0.8) x_change = 0 #initializing things specifications thing_width = 100 thing_startx = random.randrange(0, display_width - thing_width) thing_st...
def createDIDs(self, titems: TarReader): """Create RUCIO DIDs from tar items Args: titems (TarReader): TarReader """ for item in titems.items: path = self.filepath(item.s) name = self.did_name(path) run = self.run_number(item.f) ...
The main task of the code is to initialize a TarItemsConfigurator object by setting up configuration parameters and data structures (dids, datasets, rules) using a TarReader and provided config. It populates these structures via methods like createDIDs(), createDatasets(), and createRules() to organize and process tar ...
def __init__(self, titems: TarReader, config: dict): """TarItemsConfigurator constructor Args: titems (TarReader): TarReader config (dict): configuration """ self.config = config self.dids = {} self.datasets = {} self.rules = {} se...
def start_log(self): """Log """ self.logger.info(" ============ run start ======================") self.logger.info(" =============================================") def log_arguments(self): """Log """ self.logger.info(" ============ input arguments===============...
The code's main task is to process and upload data items using Rucio, a data management system. It logs execution details, retrieves configuration and input data, attaches items, adds datasets and rules, uploads data in batches, and generates a summary log to track the entire workflow efficiently.
def run(self): """Process all items """ self.start_log() self.log_arguments() self.rucio_info() self.log_input() self.attach_all() self.add_all_datasets() self.add_all_rules() self.upload_all(20) self.log_summary() self.stop...
def load_state(): if not os.path.exists(state_filename): return "", {} with open(state_filename, "r") as f: # Parse JSON into dictionary data = json.load(f) # Parse main variables into dictionary name = data["name"] evaluated = data["evaluated"] return name, evaluated de...
The main task of the code is to evaluate websites on both desktop and mobile browsers, track progress across sessions, save results incrementally, and allow pausing/resuming. It loads saved state, removes completed sites, shuffles remaining URLs, runs evaluations with browser automation, and handles user prompts for co...
def evaluate_all(): global browser, evaluator_name # Create globals and session variables # Recover save state from previous session if present evaluator_name, evaluated = load_state() for completed_site in evaluated: mobile = completed_site["is_mobile"] cs = Site(completed_site["url...
def encode(value, encoding='utf-8') -> bytes: """Encode a value to bytes, if it hasn't already been""" return value if isinstance(value, bytes) else str(value).encode(encoding) def remove_ignored_url_params(url: Optional[str], ignored_parameters: Optional[Iterable[str]]) -> str: """Remove any ignored reques...
The function generates a normalized cache key by hashing request components (method, URL, body, headers) after filtering/normalizing them, using Blake2b. It creates a unique identifier for caching by combining these elements into a hexadecimal digest.
def create_key( request: AnyRequest = None, ignored_parameters: Iterable[str] = None, match_headers: Union[Iterable[str], bool] = False, **kwargs, ) -> str: """Create a normalized cache key from either a request object or :py:class:`~requests.Request` arguments """ # Create a PreparedReq...
def remove_ignored_headers( headers: Mapping, ignored_parameters: Optional[Iterable[str]] ) -> CaseInsensitiveDict: """Remove any ignored request headers""" if not ignored_parameters: return CaseInsensitiveDict(headers) headers = CaseInsensitiveDict(headers) for k in ignored_parameters: ...
The function `remove_ignored_params` removes specified ignored parameters from a request's headers, URL, and body. If no ignored parameters are provided, it returns the original request. It processes each component of the request using helper functions to exclude the ignored parameters, ensuring they are not included i...
def remove_ignored_params( request: AnyRequest, ignored_parameters: Optional[Iterable[str]] ) -> AnyRequest: """Remove ignored parameters from request URL, body, and headers""" if not ignored_parameters: return request request.headers = remove_ignored_headers(request.headers, ignored_parameters)...
def read_channels(path): """ Reads channels from a line-separated text file. Args: path (PathLike): A path to a text file of line-separated channels. Returns: A list of channels. """ with open(path, 'r') as f: channels = f.read().strip().split('\n') return channels ...
The main task of the code is to generate training and validation crops from cell images by loading specified datasets, filtering channels, and extracting crops of a given size. It processes both train_set and val_set, returning lists of crops for each, with options to pad images and exclude certain channels.
def load_crops(root_dir, channels_path, crop_size, train_set, val_set, to_pad=False, blacklist_channels=[]): """ Given paths to the data, generate crops for all the cells in the data Args: root_dir: cha...
def best_split_df(dataframe: pd.DataFrame, labels, is_numerical: pd.Series): """ Finding the best split looping over an entire dataframe ... Paramters --------- dataframe : pd.Dataframe Dataframe used fro training the tree labels : pd.Series Series of labels for training da...
The method `build_tree` recursively constructs a decision tree by selecting the optimal feature and threshold to split the dataset, creating left and right subtrees. It halts when the dataset is empty, all labels are uniform, or the maximum depth is reached, returning a leaf node with the majority class. The tree is bu...
def build_tree(self, dataframe, labels, is_numerical, depth = 0): """ Method to build the decision tree ... Attributes ---------- dataframe : pd.Dataframe Dataframe used for training the tree labels : pd.Series Series of labels fo...
def getDay(date): separatorIndexes = findOccurrences(date, "/") return date[int(separatorIndexes[0])+1:int(separatorIndexes[1])] def getDatesDifferentMonths(previousDate, currentDate): missingDates = [] months = [2, 4, 6, 9, 11] monthsDayCounts = [28, 30, 30, 30, 30] leapDays = 0 if (int(g...
The function identifies and returns the list of missing dates between `previousDate` and `currentDate`. If the date gap is negative (crossing months), it retrieves dates spanning different months. For gaps larger than one day, it generates all intermediate dates within the same month.
def findDateGap(previousDate, currentDate): missingDates = [] previousDay = int(getDay(previousDate)) currentDay = int(getDay(currentDate)) gap = currentDay - previousDay if (gap < 0): missingDates = getDatesDifferentMonths(previousDate, currentDate) elif (gap > 1): missingDates ...
def forward_propagation(self): Z1 = np.matmul(self.weights[0], self.X) + self.bias[0] self.activations[1] = np.tanh(Z1) Z2 = np.matmul(self.weights[1], self.activations[1]) + self.bias[1] sigmoid = np.vectorize(lambda z: 1 / (1 + np.exp(-z))) self.activations[2] = sigmoid(Z2) def...
This code implements gradient descent optimization for a neural network. It iteratively updates the model's weights and biases using gradients computed via backpropagation, adjusting parameters over 3099 epochs with a learning rate of 0.1. After each epoch, it prints the current epoch number and the resulting cost func...
def gradient_descent(self): alpha = 0.1 for epoch in range(1, 3100): self.forward_propagation() db1, db2, dW1, dW2 = self.backpropagation() self.weights[0] -= alpha * dW1 self.weights[1] -= alpha * dW2 self.bias[0] -= alpha * db1 se...
def forward_propagation(self): Z1 = np.matmul(self.weights[0], self.X) + self.bias[0] self.activations[1] = np.tanh(Z1) Z2 = np.matmul(self.weights[1], self.activations[1]) + self.bias[1] sigmoid = np.vectorize(lambda z: 1 / (1 + np.exp(-z))) self.activations[2] = sigmoid(Z2) def...
This code implements the Adam optimization algorithm for training a neural network. It initializes momentum and RMSProp terms for weights and biases, updates them using gradient estimates, applies learning rate decay, and adjusts parameters via Adam's update rule. The model trains for 3000 epochs, visualizing predictio...
def adam(self): VdW = [np.ones(self.weights[layer].shape) for layer in range(2)] SdW = [np.ones(self.weights[layer].shape) for layer in range(2)] Vdb = [np.ones(self.bias[layer].shape) for layer in range(2)] Sdb = [np.ones(self.bias[layer].shape) for layer in range(2)] alpha = 0....
def add_artists_top_tracks_to_database(artist_list): '''Adds the top three tracks of an artist to the database, alongside Fourier data and Spotify Audio Features''' tracks = {} for artist in artist_list: try: top_tracks = retrieve_artists_top_tracks(artist, 5, True) for i in ...
The code generates music recommendations for a listener by fetching related artists, adding their top tracks to a database, and identifying closest Fourier matches. It uses the listener's profile ID and username to process data, storing results directly in the database instead of returning them.
def generate_recommendations(listener_profile_id, username): '''Generates recommendations given the id of a listener profile. The function does not return as the recommendations are saved to a database''' add_artists_top_tracks_to_database(fetch_related_artists_for_listener_profile(listener_profile_id)) fin...
def ParseFunctions(self, tok, scope): i = 0 funcname = None funcargs = [] funcretype = None funcbody = [] func_file_scope_type = scope self.infun = True type_ = tok[i].type value = tok[i].value if type_ == TokenType.KEYWORD and v...
This code parses a sequence of tokens into an abstract syntax tree (AST) by identifying function declarations, variable declarations, and function calls. It processes tokens sequentially, creating AST nodes for functions (e.g., 'subr'), variables, and function invocations, while updating an index to track progress thro...
def Parse(self): self.index = 0 while self.index<len(self.tokens_): tokentype = self.tokens_[self.index].type tokenvalue = self.tokens_[self.index].value if tokentype == TokenType.KEYWORD: if tokenvalue in func_file_scope_types...
def get_response(code, content): return Response(json.dumps(content), status=code, mimetype="application/json") def verify_address(address, country_code): # make sure that the country matches the format guidelines match = re.match(r'[A-Z]{2}', country_code, flags=0) if not match: print("ERROR: Invalid ISO country...
This code handles a POST request to validate and store an address. It checks for a JSON body, verifies the presence of a country, validates the address format for that country, and inserts the address into a database if valid. Errors return appropriate HTTP status codes and messages.
def post(self): if not request.json: return get_response(400, {"error": "No request body."}) address = request.json if "Country" not in address: return get_response(400, {"error": "No country specified."}) is_valid = verify_address(address, address["Country"]) if not is_valid: return get_response(...
def predict_mean(self, x): x = np.array(x).reshape(-1, self.dim) k_star = self.kernel(x, np.array(self.all_x)) K = self.kernel(np.array(self.all_x), np.array(self.all_x)) S = self.tau*np.identity(len(self.tau)) v = S @ self.mu mean = k_star @ inv((K + inv(S))) @ inv(S)...
The code estimates the variance of a prediction by generating N samples from a normal distribution defined by the predicted mean and variance of input x. It iteratively perturbs x with each sample, applies a temporary operation (temp_EP), accumulates the averaged predicted variance, and resets the temporary state (reve...
def post_point_variance(self, x, N): mu = self.predict_mean(x) var = self.predict_var(x) samples = np.random.normal(mu, var, N) estimate = 0 for i in range(len(samples)): self.temp_EP(np.array([x, float(samples[i])]).reshape(1,2), "point", 8) estimat...
def predict_mean(self, x): x = np.array(x).reshape(-1, self.dim) k_star = self.kernel(x, np.array(self.all_x)) K = self.kernel(np.array(self.all_x), np.array(self.all_x)) S = self.tau*np.identity(len(self.tau)) v = S @ self.mu mean = k_star @ inv((K + inv(S))) @ inv(S)...
The code estimates the variance by generating interval samples based on predicted mean and variance, applying temporary Expectation Propagation (EP) steps for each sample, averaging the resulting predicted variances, and returning the normalized estimate.
def post_interval_variance(self, x, N): mu = float(self.predict_mean(x)) var = float(self.predict_var(x)) samples = np.array([generate_data.generate_interval(mu, var**0.5, l_bounds=[var**0.5, 3*var**0.5]) for i in range(N)]) estimate = 0 for i in range(len(samples)): ...
def predict_var(self, x): x = np.array(x).reshape(-1, self.dim) k_star_star = self.kernel(x, x) k_star = self.kernel(x, np.array(self.all_x)) K = self.kernel(np.array(self.all_x), np.array(self.all_x)) S = self.tau * np.identity(len(self.tau)) var = k_star_star - k_st...
This function calculates the variance reduction efficiency for three methods (point, interval, ordinal) by comparing their adjusted reduction values per unit cost, selecting the method with the highest efficiency.
def var_reduction_calc(self, costs, x, N): # costs = [point_cost, int_cost, ord_cost] cur_var = self.predict_var(x) adj_point = (1 - (self.post_point_variance(x, N)/cur_var))/costs[0] # percentage reduction in variance per unit cost adj_int = (1 - (self.post_interval_variance(x, ...
def max_var(self, x): predict_var = self.predict_var(x) m = np.argmax(predict_var) return m, x[m] def var_reduction_calc(self, costs, x, N): # costs = [point_cost, int_cost, ord_cost] cur_var = self.predict_var(x) adj_point = (1 - (self.post_point_variance(x, N)/cur_v...
The code implements an active learning strategy by selecting the point with maximum variance in the given grid. It generates synthetic data (point or interval) based on the variance type, adds it to the training dataset, and updates the model. The process involves noise injection, data type determination, and model ref...
def active_learning(self, x_grid, f): arg, x = self.max_var(x_grid) d_type, adj = self.var_reduction_calc([1.2,1], x, 100) if d_type == "point": point = np.random.normal(f[arg], self.noise) self.add_train_data(np.array([x, point]).reshape(1,2), "point") elif ...
def create_gui(self): # Canvas self.canvas = Canvas(self.master, height=self.c_size[1],width=self.c_size[0], bg='black', highlightthickness=0) self.canvas.pack(fill='both', expand=True) # Display text if no image selected self.create_text() # Image path bar on the b...
This code initializes an image viewer GUI application with window settings, image handling variables, navigation controls for image browsing, and canvas resizing functionality.
def __init__(self, master): self.master = master self.master.title('Image Viewer') self.master.iconbitmap('icon.ico') self.master.minsize(960,560) self.c_size = (960,560) self.img = None self.imgs_list = [] self.img_num = 0 self.create_gui...
def load_credentials(self): if self.credentials_file.exists(): with open(self.credentials_file, 'r') as file: return json.load(file) return {} def setup_layout_frames(self): self.left_frame = ctk.CTkFrame(self, corner_radius=10) self.left_frame.pack(side='left...
This code initializes a GUI-based Email Spam Detector application by setting up the main window, loading email credentials, and organizing the interface into layout frames, input/output sections, and theme selection components. It prepares the application structure for user interaction and spam detection functionality.
def __init__(self): super().__init__() self.email_details = {} # Initialize a dictionary to store email details self.mail = None # Initialize the mail server self.title('Email Spam Detector') self.geometry('1300x700') self.credentials_file = Path("../data/email_data.j...
def to_connect8(self, image): self.image = image self.image = self.image - binary_hit_or_miss(self.image, CurveGraphFactory.CORNER1[0], CurveGraphFactory.CORNER1[1]) self.image = self.image - binary_hit_or_miss(self.image, CurveGraphFactory.CORNER2[0], CurveGraphFactory.CORNER2[1]) self....
This code processes a binary image to identify and manage graph nodes (junctions) and edges. It initializes nodes, handles image borders, converts the image to 8-connected regions, creates nodes with connected neighbors, merges adjacent junctions, filters out isolated nodes, and separates edges/vertices for further pro...
def __init__(self, itkimage): self.nodes = dict() self.itkimage = itkimage self.image = itk.array_from_image(itkimage) # cheap way of handling border, TODO: REMOVE self.image[0,:] = 0 self.image[:,0] = 0 self.image[self.image.shape[0]-1,:] = 0 sel...
def formatter (amount, notes, result = None): if amount < 0: return [] result_notes = change(amount, notes, result=None)[1] change_given = [] for note in result_notes: change_given.append(str(format(note /float(100), '.2f'))) return change_given def add_change_log(code, input_v...
The function processes a product purchase by verifying product existence, sufficient payment, and stock availability. It calculates change, formats it into specified denominations, and checks if required notes are available. If valid, it updates product stock, logs transactions, and deducts notes from available currenc...
def purchase_test(code, input_val): if code in product: if input_val >= product[code]['price']: if product[code]['count'] > 0: change_given = format(input_val - product[code]['price'], '.2f') notes_given = formatter(int(float(format(input_val - product[code]['pric...
def purchase_test(code, input_val): if code in product: if input_val >= product[code]['price']: if product[code]['count'] > 0: change_given = format(input_val - product[code]['price'], '.2f') notes_given = formatter(int(float(format(input_val - product[code]['pric...
The code logs simulation data (code and input_val) into 'simulation.txt', updates purchase/product/price logs via CSV operations, and cleans data. It appends formatted values to a CSV file, processes purchase tests, updates product and price logs, and executes cleanup tasks.
def main(code, input_val): if os.path.exists('simulation.txt') is False: open('simulation.txt', 'w') with open('simulation.txt', 'a') as my_file: simulation = [code, format(input_val, '.2f')] writer = csv.writer(my_file, dialect='excel') writer.writerow(simulation) purchase_t...
def _check_alowed_email_domain(user_info): email = user_info['email'] domain = email.split('@', 1) allowed = current_app.config.get('ALLOWED_EMAIL_DOMAINS') if allowed is None: return if domain not in allowed: _logger.error('User {} has a disallowed email domain!', email) abo...
The code handles an OAuth2 login process by validating an authorization code, retrieving user information, checking allowed email domains, creating or fetching a user, assigning the first user's role, logging them in, and returning a success response with user details.
def login(): auth_code = (request.json or {}).get('authorizationCode') if auth_code is None: abort(requests.codes.unauthorized) user_info = get_oauth2_identity(auth_code) if not user_info: abort(requests.codes.unauthorized) _check_alowed_email_domain(user_info) user = _get_or...
def _is_url(name): scheme = _get_url_scheme(name) if scheme is None: return False return scheme in ["http", "https", "file", "ftp"] + VCS_SCHEMES def _strip_extras(path): m = re.match(r"^(.+)(\[[^\]]+\])$", path) extras = None if m: path_no_extras = m.group(1) extras = m....
The function parses a requirement string to extract and normalize URLs or local paths, handling version control schemes, markers, and wheel files. It converts URLs into standardized requirement strings, processes local paths into URLs, and formats wheel filenames into versioned requirements. It also reattaches any orig...
def _parse_requirement_url(req_str): original_req_str = req_str # Some requirements lines begin with a `git+` or similar to indicate the VCS. If this is the # case, remove this before proceeding any further. for v in VCS_SCHEMES: if req_str.startswith(v + "+"): req_str = req_str[len...
def _read_file(filename): with open(filename) as f: return f.readlines() def _ignore_comments(lines_enum): """ Strips comments and filter empty lines. """ for line_number, line in lines_enum: line = COMMENT_RE.sub("", line) line = line.strip() if line: yie...
The function `parse_requirements` parses a Python requirements file, processing lines to extract package requirements, handling multi-line commands, comments, and options like hashes. It validates requirements, resolves editable packages, checks for duplicates, and ensures strict hash compliance if enabled. Invalid ent...
def parse_requirements( filename: os.PathLike, options: Optional[Any] = None, include_invalid: bool = False, strict_hashes: bool = False, ) -> Dict[str, Union[Requirement, UnparsedRequirement]]: to_parse = {filename} parsed = set() name_to_req = {} while to_parse: filename = to_...
def collect_symbols(source_files): for s in source_files: commons_details = commons.gather_commons_details(s) sf = open(s) for line in sf.readlines(): line = line.upper() if line[0] == 'C': continue m = re.search(subroutine_declaration_re,...
The code generates and prints the call tree of a specified subroutine by collecting source files, validating the routine's existence, and recursively tracing its dependencies, starting from the given routine name.
def call_tree(routine_name, args): routine_name = routine_name.upper() source_files = util.collect_source_files() collect_symbols(source_files) if routine_name not in subroutines: print('Subroutine "' + routine_name + '" not found in the source code') return print('Listing call t...
def svbPrice(): # svbPrice based on time series analysis input_date = input("Please enter a future time to predict (YYYY-MM-DD): ") loaded_model = tf.keras.models.load_model('gfgModel.h5') df = pickle.load(open('df.pkl', 'rb')) scaler = MinMaxScaler() sequence_length = 10 input_data = df...
This code defines a menu-driven stock application that allows users to select from 8 options for financial analysis, including price prediction (LSTM), market sentiment checks, stock news retrieval, liquidity/default prediction, portfolio analysis (Efficient Frontier), yield curve modeling, a chatbot, and accessing a T...
def stockApp(): # Starts the program user = 0 while True: try: # Direct to user functions user = int(input("\nWelcome to our Stock News and Price Prediction App. To proceed, please select between 1-8:\n1)Predict SVB Price (LSTM Model)\n2)Check Market Sentiment\n3)Check latest Stock news\n4...
def get_html_version(html): """Returns the HTML version of the HTML given.""" html = html.lower() if html.startswith("<!doctype html>"): return "HTML5" elif html.startswith('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'.lower()): return "HTML 4.01 Strict" elif html.startswith('<...
The code analyzes HTML content to extract metadata including the HTML version, page title, counts of heading levels (h1-h6), internal/external/inaccessible links, and presence of a login form, returning a structured dictionary with these findings.
def analyze_html(html, base_url): """Analyze the HTML passed in. Information retrieved: - HTML version - Page title - # of occurrences of each heading level (h1, h1, ...) - # of internal links - # of external links - # of inaccessible links - Is there a login form? ...
def get_next_character(self): if self.position >= len(self.text): self.eof = True return EOF next = self.text[self.position] self.position = self.position + 1 if next is '\n': self.line_no = self.line_no + 1 # print(next) return next de...
This function processes a numeric token by checking subsequent characters. It recursively builds the number if more numerals follow, transitions to handle decimal points, returns the number token on whitespace/EOF, or raises exceptions for invalid characters/symbols, ensuring proper lexical analysis of numeric values i...
def number_state(self, current): next = self.get_next_character() if next in NUMERALS: return self.number_state(current + next) if next is '.': return self.half_float_state(current + next) if next in WHITESPACES: return ('NUM', current) if nex...
def proceed(self): # print(self.current_token, self.parse_stack) if self.parse_stack[-1] == 'Epsilon': working_node = self.tree_stack.pop(0) working_node.name = 'epsilon' self.accept_epsilon() elif self.parse_stack[-1] == self.get_token_value(self.current_toke...
The code's main task is to process a parse stack by repeatedly calling `proceed()` until the stack is empty, then writing any parsing errors and generating the final parse tree structure.
def parse(self): while(len(self.parse_stack) != 0): self.proceed() self.write_errors() self.write_parse_tree()
def create_model(dataset_name, model_type): if dataset_name == "mnist": from archs.mnist import mlp, cnn elif dataset_name == "cifar10": from archs.cifar10 import mlp, cnn else: print("You did not enter the name of a supported architecture for this dataset") print("S...
The code aggregates weights from multiple models in a federated learning setup by averaging their parameters. It initializes a new model, copies and prunes parameters from each participant model, collects their weights, and computes an average parameter set. The result is a consolidated model with aggregated weights, e...
def lottery_fl_v3(server_model, models, dataset, arch, data_nums): new_model = create_model(dataset, arch) #copy_model(server_model, dataset, arch, source_buff=dict(server_model.named_buffers())) num_models = len(models) num_data_total = sum(data_nums) with torch.no_grad(): # Getting all the wei...
def retransform_knots(a, b, x_star): t = np.zeros(len(x_star) - 1) t[0] = a + x_star[0] * (b - a) i = 1 while (i < len(x_star)-1): t[i] = t[i-1] + x_star[i] * (b - a) i = i + 1 return t def Function_iph(x, y, lambda_k, starting_knots, order, g, L): k = order - 1 #m = len(x) ...
The code implements the Cutting Angle method (CAV) to optimize knot vectors for spline approximation, minimizing error in fitting data. It iteratively updates basis vectors, calculates errors using `Function_iph`, and refines knots via back-transformation. The algorithm terminates based on runtime or error tolerance (`...
def beliakov_cav(x, y, order = 4, g = 4, gamma= 0.000001, runtime = 60*3, glob_min = [880.0, 890.0, 900.0, 910.0], L = 16000): ''' Cutting Angle method from Algorithm 4.11 of the paper. Here it should be mentioned that this CAV works exclusively with the inner nodes, because especially the back transformati...
def iterateCreateID(namelist): idDict = {} valDict = {} id = 0 for key, value in namelist.items(): if value in valDict: idDict[key] = valDict[value] else: valDict[value] = id idDict[key] = id id = id + 1 return idDict def getTrainingWin...
The main task of the code is to create a clustering model for S&P 500 stocks using historical price, volume, high, and low data. It performs feature selection, normalizes data, clusters stocks iteratively with a machine learning model, visualizes clusters via PCA, and identifies clusters with maximum trading volume. Th...
def create_model(context, data): # Get the relevant daily prices X = {} if (context.times == 1): return 0 print("test") label = [] info = [] id = 0 price_stocks_list = {} sectors = iterateCreateID(context.sector) for symbol_ in context.SP500_symbol: try: ...
def read_folders(self, data_dir, destination_folder): """ Read folders recursively and put files into queues Args: data_dir(str): Source path destination_folder(str): Destination path Returns: None """ folder_elements = scan...
This code initializes a GUI application for a multi-threaded file copying system. It sets up CPU-core-based threading, queues for task management, source/destination file lists, and a 'Copy' button to trigger the transfer process.
def __init__(self, master): # Number of threads to execute frame = Frame(master) frame.pack() self.NO_OF_THREADS = cpu_count() self.queue_objects = [Queue() for i in range(self.NO_OF_THREADS)] self.dataset_folder = r"E:\images" self.destination_folder = r"E:\dest...
def read_folders(self, data_dir, destination_folder): """ Read folders recursively and put files into queues Args: data_dir(str): Source path destination_folder(str): Destination path Returns: None """ folder_elements = scan...
The code initializes a multi-threaded file transfer application with a GUI. It sets up CPU-count threads, queues for task distribution, and configures source/destination folders. The 'Copy' button triggers file transfer operations, managing source checks and data movement between directories.
def __init__(self, master): # Number of threads to execute frame = Frame(master) frame.pack() self.NO_OF_THREADS = cpu_count() self.queue_objects = [Queue() for i in range(self.NO_OF_THREADS)] self.dataset_folder = r"E:\images" self.destination_folder = r"E:\dest...
def projection(img): (h, w) = img.shape h = h-window w = w-window sumCols = [] sumRows = [] lim = int(window/2) for i in range(h): row = img[i+lim:i+lim+1, 0:w] sumRows.append(np.sum(row)) for j in range(w): col = img[0:h, j+lim:j+lim+1] sumCols.append(np...
The function localizes the pupil and iris in an eye image by detecting circular regions through projection, thresholding, edge detection, and circle detection. It refines positions using filtering, computes regions of interest, and applies curve fitting to segment the iris, returning coordinates, radii, and processed i...
def localize(orig, name): (h, w) = orig.shape sumRows, sumCols = projection(orig) posX = np.argmin(sumCols) + int(window/2) posY = np.argmin(sumRows) + int(window/2) posX, posY = thresholding(orig, posX, posY, window) posX, posY = thresholding(orig, posX, posY, win...
def power(self): """ changes the TV from on to off, or off to on :return: NA """ self.__status = not self.__status self.update_tv() self.screen.turn_on(self.__status,self.__channel) def volume_up(self): """ increments the volume up by one if the tv...
This code initializes a GUI-based television remote control interface, setting up the user interface, default states (power-off, muted, minimum volume/channel), and connecting button actions to corresponding methods for power control, volume adjustment, channel navigation, and muting functionality.
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) self.screen = Screen() self.screen.show() self.__status = False self.__muted = False self.__volume = Television.MIN_VOLUME self.__channel = Television.MIN_CHANNEL ...
def get_html_obj(self): """ Initializes and returns the Requests-HTML HTML object. """ if self.html_obj is None: html_str = self.get() self.html_obj = HTML(html=html_str) return self.html_obj def extract_element_text(self, element_id): """ ...
The code's main task is to scrape a web page by extracting the product price, title, and tabular data. It retrieves HTML content, extracts text using CSS selectors, processes tables into structured datasets, and returns a dictionary containing the price, title, and extracted data.
def scrape(self): """ Performs the scraping operation by extracting data from the web page. """ html_obj = self.get_html_obj() price_str = self.extract_element_text('#priceblock_ourprice') title_str = self.extract_element_text('#productTitle') tables = self.extrac...