dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def __random_id__(self) -> str: """Randomly generate a 32 hex digit random id in the format of "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx". Returns: str: random id """ id = ''.join([hex(random.randint(0, 15))[-1] for _ in range(32)]) return '{}-{}-{}-{}-{}'.format(id[:8],...
This function requests comments from a given article URL by navigating to the page, scrolling to load content, extracting post and spot IDs, setting authentication headers and cookies, and triggering comment loading. It handles timeouts, scrolls repeatedly to ensure content loads, and authenticates to prepare for comme...
def request_routine(self, articleURL: str) -> None: """Request comments from a url. Args: articleURL (str): target url. """ super().request_routine(articleURL) try: self.driver.get(articleURL) except TimeoutException: pass ...
def decode_src(self, encoded, seed) -> str: '''decodes hash found @ vidsrc.me embed page''' encoded_buffer = bytes.fromhex(encoded) decoded = "" for i in range(len(encoded_buffer)): decoded += chr(encoded_buffer[i] ^ ord(seed[i % len(seed)])) return decoded def fetch_...
The function retrieves a video stream URL from vidsrc.me by determining the provider (IMDb/TMDb), constructing an embed URL, parsing available sources, decoding encrypted links, and returning the resolved stream URL along with a subtitle if specified. It handles redirects and different host domains (vidsrc.stream, 2emb...
def get_vidsrc_stream(self, name, media_type, code, language, season=None, episode=None) -> Optional[str]: provider = "imdb" if ("tt" in code) else "tmdb" url = f"https://vidsrc.me/embed/{media_type}?{provider}={code}" if season and episode: url += f"&season={season}&episode={episode...
def heightCal(self, node): if not node: return -1 return node.height def settleVoilation(self, data, node): balance = self.balanceCal(node) #case 1: if balance > 1 , Right Rotation:- Because, doubly left heavy situation. if balance > 1 and data < node.leftChild.data: print("Left s...
The code inserts a new node into a binary search tree recursively. It updates the height of the parent node after insertion and calls a balancing function to maintain tree structure, likely for an AVL tree, by handling violations caused by height differences between subtrees. Note: The description is 89 words and capt...
def insertNode(self, data, node): if not node: return Node(data) if data < node.data: node.leftChild = self.insertNode(data, node.leftChild) else: node.rightChild = self.insertNode(data, node.rightChild) #update the height of parent node. node.height = max(self.heightCal(...
def goodness(matrix,whole): return similarityOfWhole(matrix,whole)+C*(distanceOfWhole(matrix,whole)) def swap(arr,t1,m1,k1,t2,m2,k2): temp=arr[t1][m1][k1] arr[t1][m1][k1]=arr[t2][m2][k2] arr[t2][m2][k2]=temp return arr def increment(arr): for t in range(T): for m in range(M): ...
The code implements a local search optimization algorithm to improve the "goodness" of a matrix and array configuration. It iteratively swaps elements in the array, checking if each swap increases goodness. If not, it reverts the swap. After exhausting all possible swaps, if no improvement is found, it increments the a...
def optimize(matrix,arr): initialGoodness=goodness(matrix,arr) for t in range(T): for m in range(M): for k in range(K): for t1 in range(T): for m1 in range(M): for k1 in range(K): ...
def sortByGoodness(population): population.sort(reverse = True, key = lambda x:goodness(matrix,x)) def goodness(matrix,whole): return similarityOfWhole(matrix,whole)+C*(distanceOfWhole(matrix,whole)) def makeNextGeneration(parent): nextGen=[[]for i in range(populationSize)] #first best 10% from parent a...
This code performs a genetic algorithm optimization. It iteratively generates new populations, evaluates their "goodness" using a matrix, and retains the best solution found. The process runs for 200 generations, updating the optimal solution whenever a better one is found in the child population.
def optimize(population): sortByGoodness(population) ansgoodness=goodness(matrix,population[0]) ans=population[0] i=0 while i<200: i+=1 childPopulation=makeNextGeneration(population) sortByGoodness(childPopulation) change(childPopulation) temp=goodness(matrix,...
def get_files(name, data_dir): """ Returns lists of file paths of the images and numpy arrays containing the respective labels. Parameters: name (str): Name of the dataset. data_dir (str): Location of the dataset. Returns: train_image_files_ros (list): The list of file paths of...
The function converts the IDRID dataset into TFRecord format by splitting image-label pairs into training, validation, and test sets, writing them as shards, and generating metadata for TensorFlow Dataset (tfds) compatibility. It organizes files into specified directories, ensuring proper structure for downstream ML wo...
def create_tfrecords(data_dir, name, run_paths): """ Creates TFrecord files for the IDRID dataset. Parameters: data_dir (str): Location of the dataset. name (str): Name of the dataset. run_paths (dict): Dictionary containing all the required paths. """ # Get the list of fi...
def initialize_population(self): population = [] for _ in range(self.population_size): itinerary = self.model.generate_itinerary(self.data['num_travelers'], self.data['start_location'], self.data['destination'], self.data['budget'], ...
The code implements a genetic algorithm to find the optimal itinerary by iteratively evolving a population through selection, crossover, mutation, and elitism. It initializes a population, evaluates fitness, selects top individuals, generates new offspring, preserves elites, and returns the best itinerary after all gen...
def run_genetic_algorithm(self): # Initialize the initial population population = self.initialize_population() for generation in range(self.generations): # Evaluate the fitness of each individual in the population fitness_scores = [self.calculate_fitness(individual) for ...
def full_optimization_loop(n, l, w, p, bounds=[(-np.pi, np.pi), (0, 4*np.pi)], nshots=512, simulator='qasm_simulator', local_optimization_method='BFGS', optimal_cost=None): """ :param n: The number of nodes :param l: The number of qubits representing a node :param w: The weigh...
The function executes the Quantum Approximate Optimization Algorithm (QAOA) to solve the max-k-cut problem on a given graph. It optimizes QAOA parameters (beta, gamma) using a specified method, runs the quantum circuit with the optimized parameters, and returns a distribution of partition results along with parameter h...
def qaoa_run(G, l, p, local_optimization_method='Powell', nshots=512): """runs the qaoa algorithm for a given Graph and depth Args: G (graph): Graph of the max-k-cut problem l (int): Number of qubits per node p (int): qaoa depth local_optimization_method : method for the optimiza...
def full_optimization_loop(n, l, w, p, bounds=[(-np.pi, np.pi), (0, 4*np.pi)], nshots=512, simulator='qasm_simulator', local_optimization_method='BFGS', optimal_cost=None): """ :param n: The number of nodes :param l: The number of qubits representing a node :param w: The weigh...
The main task of the code is to execute the Quantum Approximate Optimization Algorithm (QAOA) on a given graph $ G $, optimizing parameters using a specified local optimization method, then running the quantum circuit with the optimized parameters to obtain a probability distribution of outcomes. It returns this distri...
def qaoa_run(G, l, p, local_optimization_method='Powell', nshots=512): n = G.number_of_nodes() k = l ** 2 weights = get_weight_matrix(G) R = compute_normalization_scale(weights) rescaled_weights = weights / R param_history, cost_history, circ_history = full_optimization_loop(n, l, rescaled_wei...
def qaoa_run(G, l, p, local_optimization_method='Powell', nshots=512): n = G.number_of_nodes() k = l ** 2 weights = get_weight_matrix(G) R = compute_normalization_scale(weights) rescaled_weights = weights / R param_history, cost_history, circ_history = full_optimization_loop(n, l, rescaled_wei...
This code implements a QAOA (Quantum Approximate Optimization Algorithm) solver for finding the maximum cut in a graph. It validates if input parameter `k` is a perfect square, runs QAOA with given iterations `p`, extracts top solutions from the probability distribution, calculates their costs, and returns the optimal ...
def qaoa_solver(G, k, p): l = np.log2(k) if l != int(l): print('Error: Qaoa only works if k=l**2 with integer-valued l') return 0 else: l = int(l) distribution_qaoa, param_history = qaoa_run(G, l, p, local_optimization_method='Nelder-Mead') plot_distribution_diagramm(G, dis...
def split(data: typing.List, depth: int = 0, split_done: bool = False) -> bool: if split_done: return split_done if isinstance(data, int): return split_done for pos, item in enumerate(data): if isinstance(item, int): if item >= 10: first = second = item /...
The code solves a puzzle involving adding and reducing "snail numbers" (as per Advent of Code 2021 Day 18). It reads input lines, initializes a number from the first line, then iteratively adds subsequent numbers while reducing them to maintain structure. It calculates the magnitude of the final number for Part 1. For ...
def solve(self, input_f=None): if not input_f: puzzle = Puzzle(year=2021, day=18) puzzle_data = puzzle.input_data.split("\n") else: puzzle_data = open(input_f).readlines() for pos, line in enumerate(puzzle_data): if pos == 0: self.n...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "] * sz) return board def print_board(board): s = "*" for i in range(len(board[0]) - 1): s += str(i % 10) + "|" s += str((len(board[0]) - 1) % 10) s += "*\n" for i in range(len(board)): s +=...
The main task of the code is to implement a Gomoku game where the computer and player take turns placing pieces on a board. The computer uses a search algorithm to determine its moves, while the player inputs coordinates. After each move, the game checks for a win or draw. The loop continues until a terminal game state...
def play_gomoku(board_size): board = make_empty_board(board_size) board_height = len(board) board_width = len(board[0]) while True: print_board(board) if is_empty(board): move_y = board_height // 2 move_x = board_width // 2 else: move_y, move_...
def getCost(self, X, y, reg=False): # Calculates the cost function on the given examples # Use reg=False when comparing training/test error across different models # Use cross entropy error total_error = 0 for i in range(len(X)): pred = self.predict(X[i]) ...
This code trains a neural network using RMSProp or Adadelta optimization, processing data in minibatches. It performs forward and backward propagation, computes gradients, applies weight decay, and updates weights. The function tracks training and test errors, adjusts learning rates, and supports early stopping. It han...
def train(self, X, y, iterations=100, learning_rate=0, grad_decay=0.9, epsilon=0.000001, adadelta=False, test_X=None, test_y=None, showCost=False): # Uses RMSProp or Adadelta to train the network # X is the set of features # y is the set of target values # Create copy of data for getCos...
def recombination_local_discrete(self): parent1, parent2 = random.sample(self.population, 2) child = [] sigma = [] for i in range(self.dimension): if random.random() < 0.5: child.append(parent1[0][i]) sigma.append(parent1[1][i]) els...
The code implements one generation of an evolutionary algorithm by generating offspring through specified recombination strategies (local/global discrete/intermediate), applying mutation with value clamping, performing survival selection, and recording the best fitness and average fitness of the population. It incremen...
def evolve(self): self.ps = 0 # Recombination for i in range(self.lambda_): if self.recombination == "local_discrete": self.offspring.append(self.recombination_local_discrete()) elif self.recombination == "global_discrete": self.offspring.a...
def get_patch_num(self, input_img_shape): patch_num = 1 + (self.get_height_patch_num(input_img_shape) * self.get_width_patch_num(input_img_shape)) return patch_num def get_head_num(self): if "dino" in self.model_name: return 6 if "s" in self.model_name else 12 return 6 if "sm...
The function extracts queries from a combined QKV tensor by reshaping and permuting the input, then returns the query component. It calculates patch and head numbers, splits the qkv tensor into query, key, and value parts, and isolates the query matrix for further processing in a transformer model.
def get_queries_from_qkv(self, qkv, input_img_shape): patch_num = self.get_patch_num(input_img_shape) head_num = self.get_head_num() embedding_dim = self.get_embedding_dim() q = qkv.reshape(patch_num, 3, head_num, embedding_dim // head_num).permute(1, 2, 0, 3)[0] return q
def get_patch_num(self, input_img_shape): patch_num = 1 + (self.get_height_patch_num(input_img_shape) * self.get_width_patch_num(input_img_shape)) return patch_num def get_head_num(self): if "dino" in self.model_name: return 6 if "s" in self.model_name else 12 return 6 if "sm...
The code extracts the 'Keys' component from a concatenated QKV tensor. It reshapes the input qkv tensor into a 4D structure, permutes dimensions to isolate keys, and returns the key tensor for attention mechanisms in vision transformers.
def get_keys_from_qkv(self, qkv, input_img_shape): patch_num = self.get_patch_num(input_img_shape) head_num = self.get_head_num() embedding_dim = self.get_embedding_dim() k = qkv.reshape(patch_num, 3, head_num, embedding_dim // head_num).permute(1, 2, 0, 3)[1] return k
def get_patch_num(self, input_img_shape): patch_num = 1 + (self.get_height_patch_num(input_img_shape) * self.get_width_patch_num(input_img_shape)) return patch_num def get_head_num(self): if "dino" in self.model_name: return 6 if "s" in self.model_name else 12 return 6 if "sm...
This function extracts the value vectors (V) from a concatenated QKV tensor. It reshapes the input tensor into patch-head dimensions, permutes axes to isolate V, and returns the extracted values for further processing in a transformer model.
def get_values_from_qkv(self, qkv, input_img_shape): patch_num = self.get_patch_num(input_img_shape) head_num = self.get_head_num() embedding_dim = self.get_embedding_dim() v = qkv.reshape(patch_num, 3, head_num, embedding_dim // head_num).permute(1, 2, 0, 3)[2] return v
def get_sample_origin() -> npt.ArrayLike: origin = np.array([random.uniform(0, 11), random.uniform(0, 11)]) return origin def get_vrand() -> npt.ArrayLike: vrand = np.array([random.random(), random.random()]) vrand = vrand/np.linalg.norm(vrand) return vrand def get_vfield(goal: npt.ArrayLike, start:...
The code generates and visualizes three sets of direction vectors (field, random, and combined) at sampled points toward a goal [5,5], plotting them as quiver arrows in blue, black, and red respectively to compare their orientations and magnitudes.
def plot_direction_vectors(): goal = np.array([5, 5]) num_samples = 60 vrand_arr = np.zeros((num_samples, 2)) vfield_arr = np.zeros((num_samples, 2)) vnew_arr = np.zeros((num_samples, 2)) origin_arr = np.zeros((num_samples, 2)) for i in range(num_samples): origin = get_sample_origi...
def print_header(): print("BLACKJACK!") print("Blackjack payout is 3:2") print() def user_input(): while True: player_money = int(input("Starting player money: ")) if player_money < 0 or player_money > 10000: print("Invalid amount. Must be from 0 to 10,000") else: ...
The main task of the code is to simulate a Blackjack game by initializing player/dealer cards, handling user input for bets, dealing cards, allowing the player to hit/stand, applying Blackjack rules, and determining outcomes. It manages card totals, game logic, and money updates based on game results.
def main(): dealer_cards = [] dealer_cards_total = 0 player_cards = [] player_cards_total = 0 # player_cards.append() print_header() player_money, bet_amount = user_input() # print("player money =", player_money) print("DEALER'S SHOW CARD:") deck = card_deck() card = d...
def remove_keys(restaurant): removals = [ 'attributes', 'categories', 'hours', 'is_open', 'review_count' ] for key in removals: restaurant.pop(key, None) return restaurant def sort_by_rank_and_location(self, user_location): if user_location[0] is N...
This code searches for restaurants based on a query string, ranks them using OkapiBM25, optionally sorts by proximity to user location, and returns the top results. It handles ranking limits, result trimming, and metadata processing to deliver a curated list of restaurant matches.
def find_restaurants(self, query_str, num_results, user_location): self.final_search_results = [] self.search_results = [] self.loc_sorted_results = [] self.num_results = num_results query = metapy.index.Document() query.content(query_str) ranker = metapy.index.Ok...
def random_init(self): self.chess.queens = [ random.randint(1, self.chess.size) for _ in range(self.chess.size)] def evaluation_function(self): result = 0 for i in range(self.chess.size): for j in range(i+1, self.chess.size): if self.chess.queens[i] == sel...
This code implements a simulated annealing algorithm to solve the N-Queens problem. It initializes randomly, iteratively evaluates states, generates successors, and probabilistically accepts worse solutions based on temperature. When temperature reaches zero, it switches to hill climbing. The loop terminates upon findi...
def sovle_problem(self): self.random_init() while True: E1 = self.evaluation_function() if E1 == 0: return (column, old_row) = self.set_random_successor() E2 = self.evaluation_function() T = self.schedule_function() ...
def _make_heading(self, heading, *, space_before=10, space_after=0): self.layout().addSpacing(space_before) self.layout().addWidget(QLabel(heading)) self.layout().addSpacing(space_after) def _make_combobox(self, field_name, *, values=(), ...
This code initializes a GUI configuration panel for generating PDFs. It sets up sections for template selection, font customization (body, heading, CJK), watermark choice, output directory selection with a folder picker, and an execute button. The interface includes combo boxes, font selectors, a read-only path editor,...
def __init__(self, parent=None): super().__init__(parent) layout = QVBoxLayout() self.setLayout(layout) self._fields = {} # field_name -> callable # template selection self._make_heading('Template', space_before=5) self._make_combobox('template_name', values=os...
def get_server(server: int) -> int: if server == UNKNOWN: server = random.choice([LEFT, RIGHT]) return server def sim_game(left: Player, right: Player, server=UNKNOWN) -> GameResult: server = get_server(server) res = GameResult() while ( max(res.points) < POINTS_IN_GAME or ab...
The function simulates a tennis set between two players, alternating server roles per game, until one player wins the set by reaching the required number of games or achieving a sufficient margin. If the set ends in a tie, a tiebreak game is played. It returns a SetResult object containing the game outcomes and the set...
def sim_set(left: Player, right: Player, server=UNKNOWN) -> SetResult: server = get_server(server) res = SetResult() while min(res.games) < GAMES_IN_SET and ( max(res.games) < GAMES_IN_SET or abs(res.games[LEFT] - res.games[RIGHT]) < MIN_GAMES_DIFF ): gr = sim_game(left, ...
def get_fa(fx, fy, ca): cx, cy = get_xy(ca) if get_norm(fx, fy) > EPS: return get_a(fx, fy) else: return get_a(fx - cx, fy - cy) def get_xy(a): return math.cos(a), math.sin(a) def get_a(x, y): return math.atan2(y, x) def angle_diff(alpha, beta, signed=True): pi2 = 2 * math.pi ...
This function optimizes the direction for a fish to move by performing a ternary search on angular parameters, minimizing a cost function involving velocity, distance, and angle differences. It calculates candidate directions, evaluates their time/distance trade-offs, and iteratively narrows the optimal angle range unt...
def fish_greedyopt(v, fx, fy, ca): fa = get_fa(fx, fy, ca) lx, ly = get_xy(fa + math.pi / 2) D = 1 - fx ** 2 + - fy ** 2 assert D >= 0 t = D ** 0.5 left = get_a(fx - t * lx, fy - t * ly) right = get_a(fx + t * lx, fy + t * ly) assert angle_diff(right, left) > 0 if left > right: ...
def get_xy(a): return math.cos(a), math.sin(a) def intersect_circle_ray(r, x, y, dx, dy): # (x + t * dx) ** 2 + (y + t * dy) ** 2 = r ** 2 # (dx ** 2 + dy ** 2) * t ** 2 + (2 * x * dx + 2 * y * dy) * t + (x ** 2 + y ** 2 - r ** 2) A = dx ** 2 + dy ** 2 B = 2 * x * dx + 2 * y * dy C = x ** 2 + y ...
The code implements a modified Shortest Path Faster Algorithm (SPFA) to compute the minimal angular discrepancy (best_diff) for each layer (0 to 1000) by iteratively updating values based on geometric intersections and angular comparisons. It processes nodes in a queue, calculates directional parameters, and updates ne...
def fish_spfa(v): SECTS_PER_PI = 180 LAST_LAYER = 1000 best_diff = [0] * (LAST_LAYER + 1) in_queue = [False] * (LAST_LAYER + 1) q = deque() for i in range(LAST_LAYER + 1): if i / LAST_LAYER > 1 / v: break best_diff[i] = math.pi if (i + 1) / LAST_LAYER > 1 / ...
def get_norm(x, y): return (x ** 2 + y ** 2) ** 0.5 def fish_opposite(v, fx, fy, ca): fa = get_fa(fx, fy, ca) left = fa - math.pi / 2 right = fa + math.pi / 2 while right - left > EPS: mid1 = (2 * left + right) / 3 mid2 = (left + 2 * right) / 3 dfx1, dfy1 = get_xy(mid1) ...
The function `fish_opposite_dash` conditionally executes either `fish_opposite` or `fish_dash` based on the value of `v` and the norm of `fx` and `fy`. If `v` is below a threshold (`EPS`) or the norm of `fx`, `fy` is small relative to `v`, it uses `fish_opposite`; otherwise, it uses `fish_dash`. This determines the com...
def fish_opposite_dash(v, fx, fy, ca): if v < EPS or get_norm(fx, fy) < 1 / v: return fish_opposite(v, fx, fy, ca) else: return fish_dash(v, fx, fy, ca)
def get_norm(x, y): return (x ** 2 + y ** 2) ** 0.5 def fish_opposite(v, fx, fy, ca): fa = get_fa(fx, fy, ca) left = fa - math.pi / 2 right = fa + math.pi / 2 while right - left > EPS: mid1 = (2 * left + right) / 3 mid2 = (left + 2 * right) / 3 dfx1, dfy1 = get_xy(mid1) ...
The function `fish_opposite_greedy` decides between two strategies based on input parameters: if `v` is below a threshold (`EPS`) or the norm of `(fx, fy)` is sufficiently small relative to `v`, it executes the `fish_opposite` method; otherwise, it uses `fish_greedy`. The choice depends on the magnitude of `v` and the ...
def fish_opposite_greedy(v, fx, fy, ca): if v < EPS or get_norm(fx, fy) < 1 / v: return fish_opposite(v, fx, fy, ca) else: return fish_greedy(v, fx, fy, ca)
def get_server(server: int) -> int: if server == UNKNOWN: server = random.choice([LEFT, RIGHT]) return server def sim_set(left: Player, right: Player, server=UNKNOWN) -> SetResult: server = get_server(server) res = SetResult() while min(res.games) < GAMES_IN_SET and ( max(res.gam...
This function simulates a tennis match between two players by repeatedly simulating sets, tracking set scores, switching servers when needed, and determining the overall winner based on sets won. It initializes a match result, iterates until the required number of sets is reached, updates set counts, switches servers a...
def sim_match(left: Player, right: Player, server=UNKNOWN) -> MatchResult: server = get_server(server) res = MatchResult() while max(res.sets) < SETS_IN_MATCH: sr = sim_set(left, right, server) res.sets_list.append(sr) res.sets[sr.winner] += 1 if len(sr.games_list) % 2 == 1: ...
def get_norm(x, y): return (x ** 2 + y ** 2) ** 0.5 def fish_opposite(v, fx, fy, ca): fa = get_fa(fx, fy, ca) left = fa - math.pi / 2 right = fa + math.pi / 2 while right - left > EPS: mid1 = (2 * left + right) / 3 mid2 = (left + 2 * right) / 3 dfx1, dfy1 = get_xy(mid1) ...
This function decides between two optimization strategies based on input parameters. If 'v' is below a threshold (EPS) or the norm of (fx, fy) is sufficiently small relative to 'v', it executes the 'fish_opposite' method. Otherwise, it applies the 'fish_greedyopt' approach, selecting the most efficient path for optimiz...
def fish_opposite_greedyopt(v, fx, fy, ca): if v < EPS or get_norm(fx, fy) < 1 / v: return fish_opposite(v, fx, fy, ca) else: return fish_greedyopt(v, fx, fy, ca)
def from_romans(elems): newelems = [] rom = False for elem in elems: if 'I' in elem or 'V' in elem or 'X' in elem or 'L' in elem or 'C' in elem or 'D' in elem or 'E' in elem: rom = True newelems += [str(from_roman(elem))] else: newelems += [elem] retur...
This code evaluates mathematical expressions, handling Roman numerals and units. It converts the input to Reverse Polish Notation (RPN), evaluates it, and returns the result as a Roman numeral or decimal string with a suffix.
def evaluate_expression(query): elems = query.split() (is_roman, elems) = from_romans(elems) (suffix, elems) = preprocess_units(elems) rpn = [] stack = [] for elem in elems: if is_number(elem): rpn = rpn + [elem] else: stack, newrpn = push_op_to_stack(elem...
def reproduce(self): """ Create new generation of candidate pool @return: """ while len(self.new_candidate_pool) < self.POP_SIZE: # while not enough children fa, ma = self.select_parent() children = self.get_children(fa, ma) children_names =...
This code performs evolutionary optimization by iteratively generating new populations through reproduction, evaluating fitness, ranking candidates, and adjusting mutation rates. It runs until termination criteria are met, then returns the best solution (fame) and its evaluation, along with feature count.
def evolve(self): finish = False while not finish: print('========================================================') print('Counter') print(self.generation_counter) # create new population self.reproduce() # replace old pool ...
def buildToc(line, toc, levels): line = cleanLine(line) secId = 's' if line[:4] == '####': raise UserWarning('Header levels greater than 3 not supported') elif line[:3] == '###': levels[3] += 1 secId += str(levels[1]) + '-' + str(levels[2]) + '-' + str(levels[3]) toc.appe...
This function generates a Table of Contents (TOC) for a Markdown file by parsing heading lines (starting with '#'), inserting the TOC at the specified location, and optionally printing it or saving to an output file. It skips existing "Table of Contents" sections, processes headings to create TOC entries, and writes th...
def toc(inFile, outFile=False, to_print=True): """ Generate the Table of Content for Markdown todo: not generating the heading according to the comments # in codes using the following online tool: https://ecotrust-canada.github.io/markdown-toc/ :type input_file: string :param input_file: th...
def permutator(key,permutationcommand): if(permutationcommand==1): givenpermutation=[3,5,2,7,4,10,1,9,8,6]# First permutation (P-10) (For key generation) elif(permutationcommand==2): givenpermutation=[6,3,7,4,8,5,10,9]# Second permutation (P-8)(For key generation) elif(permutationcommand==3)...
The code implements a simplified block cipher encryption using a Feistel network structure. It splits the plaintext into halves, applies an expansion permutation to the right half, XORs it with the key, processes the result through an S-box, and combines it with the original left half. The final output includes the tra...
def encryption(key,plaintext): codeword=plaintext #splitting codeword left=codeword[0:4] right=codeword[4:8] #Right to Expansion permutation newword=permutator(right,4) #Perform XOR operation with Key 1 newword=XOR(newword,key) #splitting word newleft=newword[0:4] newright=ne...
def keygenerator(key): key_1,key_2=[],[] print("The intial given key : "+key) codeword = [x for x in key]#the string is converted into array codeword=permutator(codeword,1)#then first permutation takes place #splitting the 10 bit keyword into two 5 bit keywords fivebit_1=codeword[0:5] f...
This code decrypts ciphertext using a key through a Feistel-like structure: it splits the key into two parts, applies initial permutation, performs two encryption steps with swapped halves, and reverses the initial permutation to retrieve the plaintext.
def decryption(key,ciphertext): key1,key2=keygenerator(key) codeword = [x for x in ciphertext] #initial permutation codeword=permutator(codeword, 3) #First step encryption firstflip,right=encryption(key2,codeword) #swapping variables left,right=swap(firstflip,right) secondflip=left+r...
def keygenerator(key): key_1,key_2=[],[] print("The intial given key : "+key) codeword = [x for x in key]#the string is converted into array codeword=permutator(codeword,1)#then first permutation takes place #splitting the 10 bit keyword into two 5 bit keywords fivebit_1=codeword[0:5] f...
The code implements a two-step encryption process using key-derived values and permutations. It generates two keys, applies initial permutation, encrypts plaintext with the first key, swaps halves, encrypts again with the second key, applies inverse permutation, and outputs ciphertext. It also initiates decryption.
def brain(key,plaintext): #Key generation key1,key2=keygenerator(key) codeword = [x for x in plaintext] #initial permutation codeword=permutator(codeword, 3) #First step encryption firstflip,right=encryption(key1,codeword) #swapping variables left,right=swap(firstflip,right) se...
def _check_data_type(self): """ Check if the specified data type is supported. Raises: ValueError: If the specified data type is not supported. Returns: bool: True if the data type is supported, False otherwise. """ if self.params["data_type"] no...
The main task of the code is to generate a processed RNA-seq data matrix for machine learning. It fetches RNA-seq metadata, extracts relevant features, and processes them into a structured DataFrame using the specified primary site and downstream analysis type (default: "DE"). The function validates data compatibility ...
def run_rna_seq_data_matrix_creation(self, primary_site, downstream_analysis="DE"): """ Run the GDCEngine to fetch and process the data. Returns: pd.DataFrame: The processed data matrix for machine learning. """ if self._check_data_type(): rna_seq_metadat...
def get_merlin_camera_length(self): return def get_convergence(self): ht = str(self.ht.GetHtValue()) clapt1_list = [1000, 150, 100, 70, 10] clapt2_list = [1000, 50, 40, 30, 20] clapt1_idx = self.apt.GetExpSize(0) clapt2_idx = self.apt.GetExpSize(1) if clapt1_idx ...
The main task of the code is to collect and organize system parameters, calibration data, and calculated values into a structured metadata dictionary. It gathers instrument settings (e.g., voltages, positions, lens configurations), calibration information, derived metrics (e.g., probe radius, overlap), and acquisition ...
def collect_metadata(self, print_to_screen=True): instrument = { 'HT(kV)': self.ht.GetHtValue() / 1000, 'A1(kV)': self.gun.GetAnode1CurrentValue(), 'A2(kV)': self.gun.GetAnode2CurrentValue(), 'CLApt1' : self.apt.GetExpSize(0), 'CLApt2' : self.apt.GetEx...
def get_twitter_follows(self): expire_days = self.config.expire_days if self.config.force_follows: log.debug("force get follows") expire_days = 0 if self.twitter_state.get("last_got_follows", 0) > (time.time() - (expire_days * 86400)): log.debug("not getting l...
This code automates following Twitter users by retrieving their Nostr public keys (npub), storing follower states to avoid duplicates, and using Nostr to follow each user. It logs into Twitter, scrapes bios for npubs, tracks processed followers, and publishes updated contacts via Nostr before closing the connection.
def auto_follow_twitter(self): for follower in self.get_twitter_follows(): if not self.already_seen(follower): self.twitter_login() npub = self.scrape_twitter_bio(follower) self.set_twitter_follower_state(follower, (npub, time.time())) ...
def create_voronoi_map_with_bounding_box(input_coordinates): map_height, map_width, max_x_coordinate, max_y_coordinate, min_x_coordinate, min_y_coordinate = get_map_dimensions( input_coordinates) map_of_points = [['.'] * map_height for _ in range(map_width)] number_of_points_in_safe_region = 0 ...
The main task of the code is to compute the maximum area of finite regions in a Voronoi diagram generated from input coordinates, while excluding infinite regions. It reads coordinates from a file, constructs a Voronoi map, identifies infinite regions, calculates areas for each finite region, and prints the largest are...
def main(): raw_coordinates = [(int(line.split(',')[0]), int(line.split(',')[1])) for line in open('./day_6_input.txt')] coordinates = {} coordinate_generator = (coordinate for coordinate in raw_coordinates) for c in LABELS: coordinates[c] = next(coordinate_generator) # print(coordinates) ...
def _cmap(ttfont): def _cmap_reducer(acc, u): acc.update(u) return acc unicode_cmaps = (t.cmap for t in ttfont['cmap'].tables if t.isUnicode()) return functools.reduce(_cmap_reducer, unicode_cmaps, {}) def get_ligature_dict_arr(ttfont): g = _ligatures(ttfont) return(list(g)) def get_glyph_names_wi...
The function `get_all_glyph_names` retrieves all glyph names from a TrueType font (`ttfont`). It first maps characters to glyphs using `cmap`, then processes ligature definitions to extract glyph names. If ligatures exist, it returns a dictionary of glyph names; otherwise, it returns the reversed `cmap` mapping glyphs ...
def get_all_glyph_names(ttfont): cmap = _cmap(ttfont) rev_cmap = {v: k for k, v in cmap.items()} ldarr = get_ligature_dict_arr(ttfont) names = {} for ld in ldarr: names.update(get_glyph_names_with_ligature_dict(ld,rev_cmap)) if(len(names)>0): return(names) else: rev_c...
def get_album(self, album_id): return self._get('albums/' + str(album_id)) def get_artist(self, artist_id): return self._get('artists/' + str(artist_id)) def get_track(self, track_id): return self._get('tracks/' + str(track_id)) def get_video(self, video_id): return self._get('videos/' +...
This function determines the type of an item (album, artist, track, or video) based on its ID by attempting to retrieve it using specific methods. It returns 'a', 'r', 't', or 'v' corresponding to the item type if successful, otherwise returns None after all attempts fail.
def get_type_from_id(self, id): result = None try: result = self.get_album(id) return 'a' except TidalError: pass try: result = self.get_artist(id) return 'r' except TidalError: pass try: ...
def create_rooms(self): self.rooms = [ Room("Lobby", "You are in the lobby. There is a receptionist desk here.\n\n", [], {"north": 1, "east": 3, "west": 2}), Room("Reception Area", "You are in the reception area. There is a waiting area and a phone here.\n\n", ["phone"]...
This code initializes a text-based game's GUI, setting up room navigation, inventory tracking, and user input handling. It creates labels for room details, items, and inventory, along with an entry field and submit button for player commands. The game state, including current room and inventory, is initialized, and eve...
def __init__(self, app): self.inventory = [] self.progress = 0 self.create_rooms() self.current_room = self.rooms[0] self.backup = False self.two_factor = False self.update = False self.app = app self.lbl_room = ctk.CTkLabel(self.app, text=self....
def total_dist(self,gene): sumDIST=0 #distance of path from start point to the end point for i in range(len(self.cities)-1): index1=gene[i] index2=gene[i+1] dist=self.calc_dist_no_round(self.cities[index1],self.cities[index2]) sumDIST+=dist ...
The code implements an evolutionary algorithm to optimize a solution by iteratively improving a population of candidate solutions. It selects the fittest individuals, replaces the worst with the best, applies crossover and mutation, and tracks the best solution's distance over time, stopping if a time limit is exceeded...
def evolution(self): start_time=time.time() for i in range(self.maxiter): curtime=time.time() if curtime>start_time+self.cutoff: break fitness_np=np.array(self.fitness) best_fitness_index=np.argmax(fitness_np) local_best_gene=se...
def load_data(self,filepath): print(filepath) file=open(filepath,'r') for i in range(5): line=file.readline() if i==2: self.node_num=int(line.strip().split(' ')[-1]) #create graph self.G=[[0 for i in range(self.nod...
The main task of the code is to initialize and execute an evolutionary algorithm when the flag is set. It seeds the random generator, loads data, generates an initial population, initializes fitness values, and initiates the evolution process via self.evolution(). Traces for time and validation are also prepared for mo...
def console(self,flag): #if flag==1 begin run if flag: random.seed(self.seed) self.load_data(self.filepath) self.pool=self.pop_gen() self.fitness=[0 for i in range(self.pop_size)] self.timetrace=[] self.valtrace=[] self....
def directory_maker(dir_list): """makes the directories in the list passsed to it""" for path in dir_list: if not os.path.exists(path): os.mkdir(path) else: continue def read_csv_data(path): """this function reads the csv data and returns a dict the dict contains ...
The code evaluates the performance of a six-page segmentation algorithm by comparing predicted bounding boxes against ground truth data. It calculates metrics such as correct, partial, missed, false positives, over/under-segmentation, overlapping predictions, and area precision/recall. These metrics are normalized and ...
def evaluate(): """computes evaluation-metrics as per the specifications of 'Performance Evaluation and Benchmarking of Six-Page Segmentation Algorithms'""" eval_dir = args.output_path image_target_dir = os.path.join(eval_dir, "images/") over_segmentation_dir = os.path.join(image_target_dir, "Over-S...
def setup_ribbon_base(j="", name="", follow_jnts=True, width=4, loc_shape=False): """ Makes a ribbon from a chain of joints, and distributes transform nodes to follow the ribbon using uv pin Args: j: top joint in hierarchy. Best if its children are only the joints you want on the surface na...
The code sets up a deformable rail spine structure with controls, constraints, and optional stretch functionality. It creates a ribbon curve, IK spline, and joints, connects them with aim/point constraints, and adds stretch mechanics via a blend node. The spine is skinned to controls, hidden groups are created, and nec...
def setup_rail_spine(j="", name="", neck="", stretch=True, width=4): """ Sets up a rail spine as demonstrated by Perry Leijten https://www.perryleijten.com/en/works/railSplineRD Args: j: top spine joint in hierarchy. Best if its children are only the joints you want on the surface name...
def get_proc_map(covars, data, proc_covars_func, perf_series=None): # Proc separate if passed if proc_covars_func is not None: covars = proc_covars_func(covars) # Residualize resid = get_resid(covars, data) # Generate cohens if no perf_series if perf_series is None: retur...
This function computes the Pearson correlation coefficient and p-value between a randomly sampled subset of data (or residuals) and a base map, after applying covariance processing and filtering NaN values and a threshold. It returns the correlation and significance of the overlap between the processed data and the bas...
def get_corr_size_n(covars=None, data=None, resid=None, base_map=None, proc_covars_func=None, perf_series=None, n=None, thresh=None): # Set a random seed based on another random seed (useful in multiproc context) np.random.seed(random.randint(1, 10000...
def setup_subjects(covars_df, data_df, template_path, contrast, n_jobs, verbose): def _print(*args, **kwargs): if 'level' in kwargs: level = kwargs.pop('level') else: level = 1 if verbose >= level: print(*args, **kwargs, flush=True) _print('Passed ...
The function computes reliability metrics by splitting data into groups, residualizing against covariates, and evaluating correlations across varying group sizes. It handles data loading, stratification, masking, and processes reliability through repeated splits, returning mean correlations, standard deviations, and p-...
def run_rely(covars_df, data_df=None, contrast=None, template_path=None, mask=None, index_slice=None, stratify=None, groups=None, proc_covars_func=None, perf_series=None, proc_type='split', thresh=None, min_size=5, max_size=1000, every=1, n_r...
def setup_subjects(covars_df, data_df, template_path, contrast, n_jobs, verbose): def _print(*args, **kwargs): if 'level' in kwargs: level = kwargs.pop('level') else: level = 1 if verbose >= level: print(*args, **kwargs, flush=True) _print('Passed ...
The function `load_resid_data` loads either residualized or non-residualized neuroimaging data for specified subjects, using a template path to locate files. It applies optional masking, slicing, and covariate-based residualization. The main task is to retrieve subject-specific data, process it according to covariates ...
def load_resid_data(covars_df, contrast, template_path, mask=None, index_slice=None, resid=True, n_jobs=1, verbose=1): ''' Loading residualized data. Or non-residualized... Note: Unlike run_rely, there is not proc_covars_func, as this function assumes just one group to load, therefore ...
def load_resid_data(covars_df, contrast, template_path, mask=None, index_slice=None, resid=True, n_jobs=1, verbose=1): ''' Loading residualized data. Or non-residualized... Note: Unlike run_rely, there is not proc_covars_func, as this function assumes just one group to load, therefore ...
This function performs a one-sample t-test on neuroimaging data, residualizing for covariates, applying masks, and correcting p-values via FDR. It returns test statistics, uncorrected/corrected p-values, Cohen's d effect sizes, and subject data, with optional masking and slicing.
def run_1samp_summary(covars_df, contrast, template_path, popmean=0, alpha=.05, mask=None, reverse_mask=True, index_slice=None, n_jobs=1, verbose=1): ''' For the t-test uses: https://docs.scipy.org/...
def _update_coin_current_price(self, coin, current_price): coin.current_price = current_price coin.last_update = timezone.now() coin.save() return coin def create_price_change(self, coin, previous_price, new_price): """Creates CoinPriceChange instance in our DB. Args: ...
This function updates the current prices of available coins in the system by fetching all tickers, matching them with existing Coin objects, and updating their prices. It tracks price changes and triggers decision-making logic for each updated coin, ensuring all coins are processed efficiently.
def update_coins_prices(self): """Updates price of coins that available for our system. """ tickers = self.client.get_all_tickers() coins = Coin.objects.all() # We cannot get recent price of a specific symbol, # thus we had to do something that not cool. Although, ...
def __get_cell(self, position: tuple): for cell in self.__all_cells: if cell.rect.collidepoint(position): return cell return None def __mark_cell(self, cell): if not cell.mark: mark = Area(cell, 0) self.__all_areas.add(mark) else: ...
This method handles button release events on a grid. When a button is released at a specific position, it checks if the cell exists and matches the pressed cell. Depending on the button type (1 or 3), it either picks or marks the cell, then triggers an interface update.
def btn_up(self, button_type: int, position: tuple): released_cell = self.__get_cell(position) if (released_cell is not None) and (released_cell == self.__pressed_cell): if button_type == 3: self.__mark_cell(released_cell) if button_type == 1: self...
def next(self, val): self.menu_items[self.current_choice] = self.item_font.render(self.menu_list[self.current_choice], True, (0, 0, 0)) # changes old choice to black if self.current_choice < 3: self.sett_items[self.current_choice] = self.item_font.render(" " + str(self.settings[self.current_choice]), True, (0...
This code handles user input events for a game menu, processing mouse movements and clicks to navigate menus, adjust settings, and trigger actions like starting the game. It also manages keyboard inputs for navigation, setting changes, and state transitions, returning results to update game states or exit.
def reason(self): for event in pygame.event.get(): if event.type == QUIT: #Closes the game pygame.quit() sys.exit() if event.type == MOUSEMOTION: # Mouse Movement Events used for selecting menu items for i in xrange(len(self.menu_rects)): if self.menu_rects[i].collidepoint(pygame.mouse.get_pos...
def current_player(state): 'Returns object for current player' return state['params']['players']['i'] def is_in_border(point): 'Define whether move is in border' return point <= WIDTH / 2 or point >= (CELLS_COUNT * WIDTH) - WIDTH / 2 def is_in_trace(move_x, move_y, trace): 'Define whether move is in...
The function `y_direction` calculates a score prediction for moving a player forward or backward (in the y-axis) based on the game state and a proposed `next_y` position. It checks if the move is valid (not out-of-bounds and not colliding with the player's own path) and returns the score if valid, otherwise 0. This aid...
def y_direction(state, next_y): 'score prediction once you are going to move forward or backward' player = current_player(state) current_x, _ = player['position'] is_available_move = not is_in_border(next_y) and not is_in_trace( current_x, next_y, player['lines']) return score(state, [curre...
def current_player(state): 'Returns object for current player' return state['params']['players']['i'] def is_in_border(point): 'Define whether move is in border' return point <= WIDTH / 2 or point >= (CELLS_COUNT * WIDTH) - WIDTH / 2 def is_in_trace(move_x, move_y, trace): 'Define whether move is in...
This function calculates the score for moving in the X-direction (forward/backward) based on the game state. It checks if the proposed move is valid (not out-of-bounds and not overlapping with the player's existing trace). If valid, it returns a score evaluating the new position relative to the player's territory; othe...
def x_direction(state, next_x): 'score prediction once you are going to move forward or backward' player = current_player(state) _, current_y = player['position'] is_available_move = not is_in_border(next_x) and not is_in_trace( next_x, current_y, player['lines']) return score(state, [next_...
def current_player(state): 'Returns object for current player' return state['params']['players']['i'] def y_direction(state, next_y): 'score prediction once you are going to move forward or backward' player = current_player(state) current_x, _ = player['position'] is_available_move = not is_in_b...
The function `moves_min_max` calculates heuristic scores for possible player movements (UP, DOWN, LEFT, RIGHT) in a game state. It determines the current player's position, then evaluates each direction's validity using `y_direction` (for vertical moves) or `x_direction` (for horizontal moves), adjusting coordinates by...
def moves_min_max(state): ''' Heuristics functionality to calculate score ''' player = current_player(state) current_x, current_y = player['position'] return { UP: y_direction(state, current_y + WIDTH), DOWN: y_direction(state, current_y - WIDTH), LEFT: x_direction(stat...
def moves_min_max(state): ''' Heuristics functionality to calculate score ''' player = current_player(state) current_x, current_y = player['position'] return { UP: y_direction(state, current_y + WIDTH), DOWN: y_direction(state, current_y - WIDTH), LEFT: x_direction(stat...
The main task of the code is to determine the movement direction for a game tick based on calculated moves, then send the command along with the current player's position, moves, and territory data. It processes the game state to select a directional command and transmits it with contextual information for further game...
def process_tick(state): ''' Define direction for each tick ''' moves = moves_min_max(state) cmd = direction(moves) return send(cmd, {'position': current_player(state)['position'], 'cmd': cmd, 'moves': moves, 'territory': current_...
def database(): conn = sqlite3.connect('plants.db') # creating a connection to the database c = conn.cursor() # creating a table to store the plant data c.execute('''CREATE TABLE IF NOT EXISTS plants (id INTEGER PRIMARY KEY, name TEXT, picture TEXT, ...
The main task of the code is to initialize a Tkinter GUI application named "PyFloraPosuda," configure its window properties, connect to a database, display a sign-in screen, and load a vase list interface, then start the GUI event loop to enable interactive operations.
def main(): global root root = tk.Tk() root.title("PyFloraPosuda") database() sign_in_screen(root) root.geometry("1600x975") vase_list(root) tk.mainloop()
def isSilkscreen(item): """Checks if an item is a visible silkscreen item.""" if item is None: return False elif not (item.IsOnLayer(pcbnew.B_SilkS) or item.IsOnLayer(pcbnew.F_SilkS)): return False elif hasattr(item, 'IsVisible'): if not item.IsVisible(): return F...
The code processes a PCB to move silkscreen text (reference and value labels) to avoid collisions with vias, pads, solder mask, and other footprints. It calculates bounding boxes, filters nearby elements within a maximum distance, and searches for valid positions to reposition silkscreen elements. The task ensures read...
def run(self): # Get PCB collision items # Get the vias (except buried vias) vias_all = [trk for trk in self.pcb.Tracks() if not self.ignore_via and isinstance(trk,pcbnew.PCB_VIA) and (trk.TopLayer() == pcbnew.F_Cu or trk.BottomLayer() == pcbnew.B_Cu)] # Get the PTH/NPTH pads tht...
def compute_top_order(X, eta_G, eta_H, normalize_var=True, dispersion="var"): n, d = X.shape order = [] active_nodes = list(range(d)) for i in range(d-1): H = Stein_hess_diag(X, eta_G, eta_H) if normalize_var: H = H / H.mean(axis=0) if dispersion == "var": # The one m...
The function performs causal structure learning by first computing a topological order (top_order) and then applying a specified pruning method (e.g., CAM, Stein, Fast) to refine the DAG. It returns the pruned graph (A_SCORE), top_order, and time metrics for each step.
def SCORE(X, eta_G=0.001, eta_H=0.001, cutoff=0.001, normalize_var=False, dispersion="var", pruning = 'CAM', threshold=0.1, pns=None, K=None): start_time = time.time() top_order = compute_top_order(X, eta_G, eta_H, normalize_var, dispersion) SCORE_time = time.time() - start_time start_time = time.t...
def load(data): data["neutral"]["text"] = load_data("neutral") data["racism"]["text"] = load_data("racism") data["sexism"]["text"] = load_data("sexism") def pre_process(data, stop_words): lowercase(data["neutral"]["text"]) lowercase(data["racism"]["text"]) lowercase(data["sexism"]["text"]) remove_urls(data["neu...
The code processes text data by loading, preprocessing (removing stopwords), and evaluating machine learning models for sentiment classification (racism, sexism, or combined datasets). It includes functions for parameter optimization (grid search), 10-fold cross-validation, and prediction generation. The main task is t...
def main(): print("Generating Data...") load(words) # The exact stop-words weren't defined in the paper. # It's unlikely I could come up with the same corpus the paper used. However, it is known # that the paper uses sklearn. Thus, it is very likely that the nltk english stopword corpus was used. stop_words = se...
def combine_percentage(data, combined, primaryPercentage, secondaryPercentage, tertiaryPercentage): random.shuffle(data["neutral"]["text"]) random.shuffle(data["sexism"]["text"]) random.shuffle(data["racism"]["text"]) combined["sexism"]["total"] = combine_data_2_percentage(data["neutral"]["text"], "neutral", prima...
The main task of the code is to train an SVM classifier using TF-IDF vectorization with n-grams (1-3) to detect racism/sexism in text data. It performs cross-validation over multiple runs, evaluates precision, recall, F1-score, and accuracy, and averages results across iterations. The approach avoids stop words and emp...
def train_predict_count(data_words, data_combined, tested_dataset, stop_words, count): precision = [] recall = [] f1 = [] accuracy = [] reports = [] for i in range(count): print("[" + str(i + 1) + " / " + str(count) + "]") # combine_percentage takes the raw tweet texts from 3 arrays (neutral, racism, sexism...
def combine_percentage(data, combined, primaryPercentage, secondaryPercentage, tertiaryPercentage): random.shuffle(data["neutral"]["text"]) random.shuffle(data["sexism"]["text"]) random.shuffle(data["racism"]["text"]) combined["sexism"]["total"] = combine_data_2_percentage(data["neutral"]["text"], "neutral", prima...
The code evaluates a machine learning model using k-fold cross-validation, applying TF-IDF vectorization on text data and a linear SVM classifier. It calculates precision, recall, F1-score, and accuracy across folds, aggregating results to assess model performance on labeled datasets, while ignoring stop words and warn...
def evaluate_model(data_words, data_combined, tested_dataset, stop_words, folds): precision = [] recall = [] f1 = [] accuracy = [] reports = [] print("Generating " + str(folds) + "-Fold Evaluation...") warnings.filterwarnings("ignore") # This approach splits the dataset into k portions # Therefore, unlike w...
def load(data): data["neutral"]["text"] = load_data("neutral") data["racism"]["text"] = load_data("racism") data["sexism"]["text"] = load_data("sexism") def load_list(filename): parent_dir = str(Path(__file__).parent) f = open(parent_dir + '\\' + filename) data = f.read().splitlines() return data def train_pred...
The code prepares datasets for text classification by combining neutral, racism, and sexism data, then evaluates models using a modified approach due to small dataset size. It loads data, filters stop-words, and runs predictions using a shuffled full dataset method to assess model performance on combined datasets, focu...
def main(): print("generating data...") # First, the files are loaded into three lists - "racism.json" gets loaded into "racism", "sexism.json" gets loaded into "sexism," and "neither.json" is loaded into "neutral." load(words) # Next, a list of manually selected stop-words are loaded in. These were selected manua...
def _initialize_simulation(self): self.W_M1, self.W_M3, self.W_M5, self.W_M6, self.W_M7, self.W_M10, self.W_M12, self.Vcm= \ np.array([1, 1, 1, 1, 1, 1, 1, 1.1]) # self.Vcm: initial input common-mode voltage """Run the initial simulations.""" action = np.array([self.W_M1, sel...
The code resets the environment by initializing the simulation, generating the initial observation and information, and returning them. It uses a seed for reproducibility, calls a parent class's reset method, and prepares the environment's starting state for an agent.
def reset(self, seed=None, options=None): super().reset(seed=seed) self._initialize_simulation() observation = self._get_obs() info = self._get_info() return observation, info
def check_bn(model): flag = [False] model.apply(lambda module: _check_bn(module, flag)) return flag[0] def _get_momenta(module, momenta): if isbatchnorm(module): momenta[module] = module.momentum def _set_momenta(module, momenta): if isbatchnorm(module): module.momentum = momenta[mod...
This function updates batch normalization (BN) layers in a neural network model by adjusting their momentum values based on the data from a given loader. It first checks if the model contains BN layers, resets their statistics, and then iteratively processes batches to dynamically compute and apply new momentum values....
def update_bn(loader, model, **kwargs): if not check_bn(model): return model.train() momenta = {} model.apply(reset_bn) model.apply(lambda module: _get_momenta(module, momenta)) num_samples = 0 for input, _ in loader: input = input.cuda() batch_size = input.data.size(...
def gen_feature(ligand_name, pocket_name): charge_idx = featurizer.FEATURE_NAMES.index('partialcharge') try: ligand = next(read_molecule(ligand_name)) except StopIteration: print("Problems with loading ligand from", ligand_name) raise ValueError("Ligand loading error") lig...
The code processes a dataset by reading input files, normalizing file paths relative to the dataset source, generating atomic and interaction features for protein-ligand pairs, filtering out problematic entries, and saving processed data as CSV and pickle files. It handles dataset splitting into train/test/validation s...
def process_dataset(dataset_source, output_path, cutoff, dataset_name): """Read dataset from dataset_name. Save processed dataset to output_path Paths in dataset are relative to the file with dataset """ if dataset_source.endswith('.tsv'): df = pd.read_csv(dataset_source, sep='\t') elif dat...
def get_attributes(): r = requests.get("https://swapi.co/api/people/1/?format=json") print("Available attributes: ", end="") a = [] a.extend(r.json().keys()) # for x in r.json().keys(): # a.append(x) # print(f"{x} = {r.json()[x]}") # print("") print(sorted(a, key=len)) so...
The main task of the code is to handle command-line arguments and retrieve data accordingly. If `--selection` is specified, it fetches attributes; if `--all`, it retrieves all characters. Otherwise, it splits the `--attribute` list and passes it to `get_data()` for targeted data retrieval.
def main(): if args.selection: get_attributes() elif args.all: get_characters() else: arg_list = args.attribute.split(",") get_data(arg_list)
def numba_is_in_2d(arr, vec2): """ Return filtering mask for values that occur in vec2. """ out = np.empty(arr.shape[0], dtype=numba.boolean) vec2_set = set(vec2) for i in numba.prange(arr.shape[0]): if arr[i][0] in vec2_set and arr[i][2] in vec2_set: ...
The code computes k-core decomposition of a graph, generating statistics for each k-core subset. It checks if precomputed stats exist; if not, it processes the graph, calculates coreness values, iteratively extracts k-core subgraphs, filters relevant triples, and computes/updates subset statistics. Finally, it saves th...
def get_k_core_stats(self): """ Provides stats about k-core subsets and performs the decomposition if they are not yet available. Select all entities that are contained in the k-cores (for all k) of the original graph and keep all interrelations. Note that multiple parallel edges only co...
def answer_question(): question = get_question() answers = get_answers() for i in range(len(correct_answers)): if correct_answers[i].question == question: clicker(answer_choice % (answers.index(correct_answers[i].answer)+1)) # add unique id to questions, search all answers to questions that match ...
The code automates a game loop by waiting for a clickable element, then repeatedly checking and printing the player's money, answering in-game questions, and entering a shop if needed, with delays to simulate natural gameplay.
def play(): global money WebDriverWait(driver, 300).until(EC.element_to_be_clickable((By.XPATH, three_lines_button))) print("Game is starting...") to_shop = answer_question() while True: money = get_money() print(f"Money: ${money}") to_shop = answer_question() if to_shop == 0: ...
def left(): #r = requests.post('http://localhost:5000/forward', data = {'key': 'value'}) print("left") r = requests.post('http://localhost:5000/left', data = {'player': str(PLAYER)}) print(r.text) #show(r.text) show(json.loads(r.text)) def right(): print("right") r = requests.post('http:...
This function handles keyboard input events, mapping specific key presses (e.g., 'l', 'r', arrow keys) to corresponding game actions like moving left/right, forward/backward, shooting, or quitting. It uses both `e.char` for alphanumeric keys and `e.keysym` for arrow keys, triggering predefined functions based on the in...
def keydown(e): global CAN #CAN.delete(ALL) #print("keydown function") if e.char == "l": #print("l, i.e., left button") left() if e.char == "r": right() if e.char == "f": forward() if e.char == "b": back() if e.char == "x": quit_gam...
def create_list_control(self, sizer): resize_widget = resizewidget.ResizeWidget(self) self.view_table = wx.ListCtrl(resize_widget, -1, size=(-1, 150), style=wx.BU_EXACTFIT | wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.SUNKEN_BORDER) self.view_table.InsertColumn(0, 'id', w...
This code initializes a GUI panel with a vertical layout, creating controls for managing snapshots (list, buttons, navigation, and details), binding layout events, and setting up a trait change listener for canvas layer properties.
def __init__(self, parent_panel, **kwargs): kwargs['style'] = wx.TAB_TRAVERSAL wx.Panel.__init__(self, parent_panel, **kwargs) # mProfile.profileOn(["animation_visgui.py"]) self.snapshots = list() self.parent_panel = parent_panel vertical_sizer = wx.BoxSizer(wx.V...
def add_snapshot(self, event): view_id = 'view_%d' % self.next_view_id self.next_view_id += 1 if view_id: # duration = 3.0 # view = self.get_canvas().get_view(vec_id) # video_view = VideoView.from_view(view)#, duration, ) video_view = VideoView.from_...
The code plays a sequence of 3D views, either saving them as a video (with OpenCV) or displaying in real-time. It validates user inputs for FPS, canvas size, and handles errors by defaulting to safe values. If saving, it captures frames, writes them to an MP4 file, and saves individual JPEGs. Otherwise, it uses a wx.Ti...
def play(self, save): for child1 in self.parent_panel.GetChildren(): for child2 in child1.GetChildren(): child2.Enable(False) self.stop_button.Enable() try: fps = float(self.framerate_text.GetValue()) except: # self.framerate_te...
def get_beat_number(self, T0): #Return current 16th note beat number beat_number = -1 bar_time_passed = self.check_time(T0) - BAR_TIME * self.get_bar_number(T0) while bar_time_passed > 0: bar_time_passed = bar_time_passed - SIXTEENTH_NOTE_TIME beat_number = beat_n...
This code calculates the current beat number and the offset within that beat for a given time T0. It adjusts the offset by subtracting half a sixteenth note's duration and increments the beat number if needed, wrapping to 0 when reaching 16. The result is a tuple of the beat number and adjusted offset in milliseconds, ...
def get_timing(self, T0): #Identify current beat number and player offset from it beat_number = self.get_beat_number(T0) beat_offset = round(((self.check_time(T0)-self.get_bars_passed_time(T0)-self.get_beats_passed_time(T0))*1000), 1) if beat_offset > SIXTEENTH_NOTE_TIME * 1000 / 2 : ...
def expand_box(box, expansion_factor): # Find the center of the box center_x = box[0] + (box[2] / 2) center_y = box[1] + (box[3] / 2) # Find the new width and height new_width = box[2] * expansion_factor new_height = box[3] * expansion_factor # Find the new top left corner new_x = center...
The code tracks an iris region in video frames using motion detection, updates the tracking box based on overlapping motion contours, and manages timing for opening/stopping an iris mechanism (e.g., a motor). It processes frames to detect changes, filters motion regions, adjusts the tracking box if valid motion is dete...
def track_and_open_iris(camera, tracking_box, timer, iris_open_delay, debug=False): end_time = time.time() + timer iris_open_time = time.time() + iris_open_delay iris_stop_time = iris_open_time + iris.OPEN_DURATION iris_opened = False iris_stopped = False pwm = None assert (end_time > iris...
def average(self,times): sum = 0 for i in range(times): # data = self.get_value() if data == 0 : times = times -1 else: sum = sum + data #print(times) #print("--------------------------") if(times == 0): times =1 return sum/times...
The main task of the code is to calculate and return the object's weight in grams by averaging multiple readings, adjusting for offset and calibration values based on the peel_flag status. It first takes an average of sensor readings, applies offset correction if needed, retrieves calibration data, and finally computes...
def read_weight(self,times): '''! @fn read_weight @brief Get the weight of the object @param times Take the average several times @return return the read weight value, unit: g ''' value = self.average(times) time.sleep(0.05) ppFlag = self.peel_flag() if ppFlag == 1: ...
def decodeBrancInstruction(self, i: str) -> dict: decoded = self.parse(i) predication: bool = decoded["predicate"] opcode: str = decoded["opcode"] ops: list[str] = decoded["operands"] assert opcode in ["loop", "loop.pip", "nop"], "Undefined instruction: {}".format(i) if...
The code simulates a single processor cycle by fetching and decoding instructions from memory, updating registers and memory based on ALU, multiplier, and memory operations, handling branch logic, and advancing the program counter. It processes each instruction bundle, executes operations, manages pipeline stages, and ...
def tick(self): ## PC Propagate if self.PC >= len(instructionMemory): inst = ["nop", "nop", "nop", "nop", "nop"] else: inst = instructionMemory[self.PC] assert len(inst) == 5, "Each bundle should always have 5 instructions" # Branch Unit will...
def __parse_json(self): output = [] file = open(self.filename, "r") program = json.load(file) for PC, instruction in enumerate(program): opcode = instruction.split(" ")[0].strip() registers = instruction[instruction.find(" "):].split(",") if opcode == ...
The code initializes a scheduler to process a JSON file, computes dependencies, schedules loops (with or without pip-based parallelism), and optionally dumps the generated schedule to a file or prints it. It parses input JSON, creates a dependency table, executes loop scheduling logic, and handles output based on flags...
def __init__(self, filename, pip=False, dump_to_file=False): self.filename = filename self.final_schedule = [] self.loop_start = 0 self.loop_end = 0 self.scheduled_slot = [] self.n_stages = 0 self.code = self.__parse_json() self.code_backup = copy.deepco...
def run_init(ctx, inputs): target_view = ctx.target_view() run_key = get_new_run_key(ctx, inputs) if run_key is None and run_key != "None": return False get_embeddings(ctx, inputs, target_view) return True def _handle_basic_inputs(ctx, inputs): method_choices = types.DropdownView() ...
The code processes input for a clustering task by initializing configurations, handling basic inputs, routing method parameters, setting the view target, and determining execution mode. It returns a property object with a clustering-specific form view, enabling user interaction for cluster creation from embeddings.
def resolve_input(self, ctx): inputs = types.Object() form_view = types.View( label="Clustering", description="Create clusters from embeddings" ) ready = run_init(ctx, inputs) if not ready: return types.Property(inputs, view=form_view) _handle_ba...
def event_loop(self): for e in pg.event.get(): if e.type == pg.QUIT: self.exit() else: self.state.get_event(e) def update(self): if self.state.exit: self.exit() if not self.state.running: self.flip_state() se...
The code's main task is to continuously run a loop while `self.running` is True, processing events, updating the application state, rendering graphics, and maintaining timing control to ensure smooth operation. The loop repeatedly calls `event_loop()` for input handling, `update()` for state changes, `draw()` for rende...
def run(self): while self.running: self.event_loop() self.update() self.draw() self.keep_time()
def sleep_for_sometime(self,sec=4): time.sleep(sec) def like_post(self): try: like_button_container = self.driver.find_element_by_class_name(LIKE_BUTTON_CLASS_NAME) like_button = like_button_container.find_element_by_xpath(LIKE_ICON) # like_icon.click() except...
The function processes a list of image URLs by navigating to each image, waiting for 4 seconds, liking the post, and commenting "This book is really good!" to automate social media interactions for a specific hashtag.
def clickon_picture_for_specific_hashtag(self,image_list): for image in image_list: self.driver.get(image) self.sleep_for_sometime(4) self.like_post() self.write_comment("This book is really good!")
def getname(): sys.path.append(r"C:\Users\M.Saood Sarwar\PycharmProjects\fyp\EBMPgui") from Signin import Geek p = Geek() username = p.getVal() return username def idToSongName(songListWithIds): songList = [] count=0 for i in songListWithIds: sql = ("""SELECT SongUrl,SongName FRO...
This function creates a GUI-based music player interface with playlist display, mood/history-based song recommendations, playback controls (play, pause, stop, rewind), volume adjustment, and user rating functionality. It loads images for buttons, initializes audio mixer, and handles window events, populating the playli...
def main(mood,calltype): from PIL import ImageTk win=Toplevel() win.bg_music = ImageTk.PhotoImage(file=r"C:\Users\M.Saood Sarwar\PycharmProjects\fyp\images\music.png") label=Label(win, image=win.bg_music) label.image = win.bg_music label.pack() global playlistBox playlistBox = Listbox(w...
def showImage(self,photo): self.label2 = Label(image=photo, width=200, height=200) self.label2.image = photo self.label2.place(x=650, y=200) def upgradefun(window,name,newPassword,confirmNewPassword,oldPassword): var=newPassword.get() var1=confirmNewPassword.get() if (var==var1): result...
The code creates a GUI window for updating a user's password, displaying a retrieved image, and allowing image browsing. It sets up password input fields, an 'Update Password' button, a 'Browse Pic' button, and a back button. The main task is to provide an interface for password modification and image management within...
def start(window,name): Label(window, image=window.bg_update).pack() import EBMPgui.Homepage image=EBMPgui.Homepage.readBLOB(name) if image!=None: showImage(window,image) newPassword=StringVar() confirmNewPassword = StringVar() oldPassword=StringVar() oldPasstxt = Entry(window, b...
def userlistgen(): global userlist chatnumlog = open(lib.logfile_chatnum, 'r').readlines() chatnumlog = re.search(r'(?<=\()\w+(?=\))', chatnumlog[-1]).group() userlist = [] print(chatnumlog) for users in range(int(chatnumlog)): user = open(lib.logfile_users, 'r').readlines() user...
This code initializes a bot that processes a reversed user list, interacts with a UI via mouse movements and clicks, logs user data, computes language-related tasks, and resets variables for each user iteration. The loop runs once due to the 'break' statement, handling automated actions like clipboard management and co...
def bot_init(): bot_on = True while bot_on: global userlist, userindex, totaltext userlistgen() userlist = userlist[::-1] print(userlist) for index in range(len(userlist)): pyperclip.copy('') logger(newuser=True) print('hey from for loo...
def extract_name(page_tree): artist_data = parse_xpath(page_tree, '//h1[@class="lotName"]/text()') artist_name = artist_data.split('(') return artist_name[0] if artist_name else '' def parse_xpath(page_tree, path, default_value=''): data = page_tree.xpath(path) return data[0] if data else default_va...
The main task of the code is to extract structured data from an HTML page tree, including artwork details like artist name, painting name, realized and estimated prices in GBP/USD, image URL, and sale date, organizing them into a dictionary with predefined keys for easy data processing or storage.
def extract_data(page_tree): return{ 'artist_name': extract_name(page_tree), 'painting_name': parse_xpath(page_tree, '//h2[@class="itemName"]/i/text()'), 'price_gbp': extract_price(page_tree, 'RealizedPrimary'), 'price_usd': extract_price(page_tree, 'RealizedSecondary'), 'est...
def apply_average_filter(data, window): for i in range(0, 3): data[:,i] = np.array(pd.Series(data[:,i]).rolling(window=window).mean()) return data def plot(data, title, plot_save_path): N = len(data) y = np.linspace(0, N/sampling_frequency, N) plt.plot(y, data) plt.title(title) plt.ylabel('ACCELERATI...
The main task of the code is to calculate heart rate (in BPM) from accelerometer data by applying filters to isolate relevant frequency ranges, performing Fast Fourier Transform (FFT) to identify dominant frequency, and returning heart rate as 60×max_frequency. It processes data through smoothing, bandpass filtering, a...
def calculate_heart_rate(normalized_data): smooth_data = apply_average_filter(normalized_data, average_filter_window_duration_hr) smooth_data = np.array(list(filter(lambda row: np.isfinite(np.sum(row)), smooth_data)), dtype=np.float64) plot(smooth_data[:,0], 'Smoothened Accelerometer Data - HR', 'plots/bio_watch/...
def plot_ax(data, title, plot_save_path): x = np.array(data[:,0]) N = len(x) y = np.linspace(0, N/sampling_frequency, N) plt.plot(y, x) plt.title(title) plt.ylabel('ACCELERATION Ax (m/s^2)') plt.xlabel('TIME (s)') draw_plot(plot_save_path) plt.close() def segment(data): size = len(data) print('Se...
The function processes accelerometer data for sleep monitoring by plotting raw data, segmenting and preprocessing it, converting time-domain signals to frequency-domain via FFT, applying a Kalman filter, and returning filtered results. It handles data validation and visualization steps to analyze sleep-related motion p...
def sleep_monitor(data, sampling_freq): global sampling_frequency sampling_frequency = sampling_freq plot_ax(data, 'Raw Accelerometer Data', 'plots/sleep_monitor/raw_ax.png') data = segment(data) if (len(data) == 0): print('Failed in data preprocessing: no data segments to process') return 0, 0 dat...
def plot(data, title, plot_save_path): N = len(data) y = np.linspace(0, N/sampling_frequency, N) plt.plot(y, data) plt.title(title) plt.ylabel('ACCELERATION Ax (m/s^2)') plt.xlabel('TIME (s)') draw_plot(plot_save_path) plt.close() def normalize(data): for i in range(0, 3): data[:,i] = sp.stats.zs...
The main task of the code is to process accelerometer data by normalizing it, calculate heart rate (HR) and breathing rate (BR) from the normalized data, and generate plots of raw and normalized data. It returns the computed HR and BR values while storing visualizations for analysis.
def bio_watch(data, sampling_freq): global sampling_frequency sampling_frequency = sampling_freq plot(data[:,0], 'Raw Accelerometer Data', 'plots/bio_watch/raw_ax.png') normalized_data = normalize(data) plot(normalized_data[:,0], 'Normalized Accelerometer Data', 'plots/bio_watch/normalized.png') hr = calcu...
def initialize_objects(params): # insert root object into the dict seed_obj = Sphere() base_color = params['base_color'] # color seed_obj.R = base_color[0] seed_obj.G = base_color[1] seed_obj.B = base_color[2] # seed_obj = Cube() objects = {} for g in range(params['generations'...
The code generates objects across successive generations by applying a list of functions to parent objects, creating child objects with unique IDs and directed edges in a graph. It iterates through generations, builds a graph structure, and returns a list of all generated objects.
def generate_objects(params): objects_dict, G = initialize_objects(params) for g, gen in enumerate(list(objects_dict.keys())[:-1]): next_gen = list(objects_dict.keys())[g + 1] print('generation:', gen) new_objects = [] # apply functions to every object in previous gen and store ...
def initialize_objects(generations=4): seed_obj = Sphere() # seed_obj = Cube() objects = {} for g in range(generations): key_name = f"gen{g}" objects[key_name] = [] objects['gen0'] = [seed_obj] return objects def generate_func_list(params, g): dx, shrink_factor, col_delta, ...
The main task of the code is to generate a sequence of object generations by iteratively applying a set of functions to objects from the previous generation. Starting with an initial set of objects, it processes each generation, applies function lists (which may include stochastic effects) to create new objects for the...
def generate_objects(params): objects_dict = initialize_objects(params['generations']) for g, gen in enumerate(list(objects_dict.keys())[:-1]): next_gen = list(objects_dict.keys())[g + 1] print('generation:', gen) new_objects = [] # apply functions to every object in previous ge...
def save_image( self, imageUrl: str, comic_seo: str = "", chap_seo: str = "", imageName: str = "0.jpg", isThumb: bool = False, overwrite: bool = False, ) -> str: saveFullPath = f"{CONFIG.IMAGE_SAVE_PATH}/{comic_seo}/{chap_seo}" Path(saveFullPa...
The function downloads and processes a list of manga images by saving them with specific naming conventions, converting formats, and generating JSON-formatted image sources. It handles first/last images with special combining logic, logs errors, and returns a structured result string.
def download_images(self, comic_seo: str, chap_seo: str, imageUrls: list): res = [] imagesCount = len(imageUrls) for i in range(imagesCount): try: imageUrl = imageUrls[i] if "_" in imageUrl: imageName = imageUrl.split("_")[-1] ...
def get_comic_details(self, soup, slug): bookInfo = soup.find("div", class_="book-info") cover = bookInfo.find("div", class_="cover") detail = bookInfo.find("div", class_="detail") metaBox = detail.find("div", class_="meta") imgCover = self.get_cover_img_from(cover) titl...
This function crawls comic details and chapters from a source, checks for existing entries in the database, inserts new comics/chapters, updates comic last-update time, and sends Discord notifications for new chapters. It handles URL normalization, error logging, and rate-limiting between chapter crawls.
def crawl_comic_details(self, soup, comic_seo): comic_data = self.get_comic_details(soup, comic_seo) comicTitle = helper.format_condition_str(comic_data["title"]) condition = f'post_title = "{comicTitle}"' be_comic = database.select_all_from( table=f"{CONFIG.TABLE_PREFIX}post...
def get_current_player(self): """Return the next player based on the the board itself.""" # calculating the current count of X' and O's on the board x_count = 0 o_count = 0 for row in self._board: for cell in row: if cell == "X": x_...
The method `make_move` validates a player's move in a game (e.g., Tic-Tac-Toe) by checking if the player is authorized, if it's their turn, and if the move is within bounds. If valid, it updates the game board with the player's symbol ('X' or 'O') and returns the updated game status. It raises specific errors for inval...
def make_move(self, player, move): """Takes player ('X' or 'O') and the move (as a 2-tuple) as input, determine if the move is valid, and make the move on the board. Lastly, update game status. """ # Validate if the player's name is one of the player. if player != self._...
def winning_moves_gen( c_board: Board, free_squares: Set[Tuple], num: int, color: Tuple ) -> Generator: return ( (row, col) for (row, col) in free_squares if winning_move(row, col, c_board, num, color) ) def well_oriented(row: int) -> bool: return row % 2 != 0 def max_blocking_co...
The code generates potential moves in a board game by prioritizing winning strategies, blocking opponents, and evaluating well-oriented positions. It yields winning moves if turns exceed 8, then blocking moves. It filters free squares into well-aligned positions, checks for blocking continuations, and yields generators...
def strategies( free_squares: List[Tuple], c_board: Board, turns_count: int, num: int, color: Tuple ) -> Generator: if turns_count >= 8: winning_moves = winning_moves_gen(c_board, free_squares, num, color) yield winning_moves blocking_moves = winning_moves_gen(c_board, free_squares, num...
def get_patient_by_id(self, patient_id): token = self.get_access_token() headers = {"Authorization": f"Bearer {token}"} response = requests.get(f"{self.BASE_URL}/Patient/{patient_id}", headers=headers) return response.json() if response.status_code == 200 else None def get_location_by_id...
This code creates a FHIR Task resource in a healthcare system, using patient/practitioner data from a mapping, transcribed text as the task description, and a bucket as the code text. It authenticates with an access token and posts the task to a FHIR server, returning the response if successful.
def create_patient_request(self, mapping, transcribed_text, bucket): practitioner_id = mapping.practitioner_id patient_id = mapping.patient_id location_id = mapping.bed_id patient_res = self.get_patient_by_id(patient_id) location_res = self.get_location_by_id(location_id) ...
def _(message): return message def norm_path(path): if path is None: path = '' return os.path.normpath(path) def check(self, source, target): if source.filePath is None: raise Error(f'{_("File type is not supported")}.') if not os.path.isfile(source.filePath): ...
The code exports a novel from a source file to a target file by reading the source's novel data, transferring it to the target, and writing it, while updating UI status messages. It handles exceptions, displaying errors if they occur, and confirms successful export otherwise.
def export_from_yw(self, source, target): self.ui.set_info_what( _('Input: {0} "{1}"\nOutput: {2} "{3}"').format(source.DESCRIPTION, norm_path(source.filePath), target.DESCRIPTION, norm_path(target.filePath))) try: self.check(source, target) source.novel = Novel() ...
def _(message): return message def norm_path(path): if path is None: path = '' return os.path.normpath(path) def check(self, source, target): if source.filePath is None: raise Error(f'{_("File type is not supported")}.') if not os.path.isfile(source.filePath): ...
The function creates a yWriter project file from a source to a target path. It checks if the target file exists, reads the source novel data, transfers it to the target, and writes it. Errors are caught, and UI messages inform the user of success or issues. The task involves file validation, data transfer, and user fee...
def create_yw7(self, source, target): self.ui.set_info_what( _('Create a yWriter project file from {0}\nNew project: "{1}"').format(source.DESCRIPTION, norm_path(target.filePath))) if os.path.isfile(target.filePath): self.ui.set_info_how(f'!{_("File already exists")}: "{norm_path...
def _(message): return message def norm_path(path): if path is None: path = '' return os.path.normpath(path) def check(self, source, target): if source.filePath is None: raise Error(f'{_("File type is not supported")}.') if not os.path.isfile(source.filePath): ...
This function transfers data from a source novel file to a target file within a software application, handling errors and updating the UI with status messages. It reads the target's novel structure, assigns it to the source, reads the source data, writes it to the target, and notifies the user of completion or errors. ...
def import_to_yw(self, source, target): self.ui.set_info_what( _('Input: {0} "{1}"\nOutput: {2} "{3}"').format(source.DESCRIPTION, norm_path(source.filePath), target.DESCRIPTION, norm_path(target.filePath))) self.newFile = None try: self.check(source, target) ...
def selenium_launch(array_vars): url = array_vars[0] aDesiredJobTitles = array_vars[1] import sys import os.path import os from typing_extensions import final from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver...
The code searches a webpage for specific job titles using BeautifulSoup. If found, it extracts links and writes job listings; if not, it launches Selenium to continue searching for buttons and job titles, handling relative/absolute URLs accordingly.
def searchForDesiredJobs(array_vars): url = array_vars[0] aButtonNames = array_vars[1] aDesiredJobTitles = array_vars[2] html_page = urllib.request.urlopen(url) soup = BeautifulSoup(html_page, "html.parser") # print(soup) # get all text from all tags # print(aDesiredJobTitles[0]) for...
def parse_message(self,received_msg): parts = received_msg.split(" ") prefix = None user = None channel = None irc_command = None irc_args = None text = None text_command = None text_args = None if parts[0].startswith(":"): pre...
The code processes incoming chat messages by parsing and executing commands. It handles "click" actions by splitting text and triggering clicks, converts other commands for keyboard input, and manages IRC protocols like PONG responses. It also checks for specific message formats, filters out irrelevant data, and execut...
def handle_message(self,received_msg): if len(received_msg) == 0: return message = self.parse_message(received_msg) print(f'> {message}') # print(message.text) # print(message.text_args) if message.user != None and message.text != None and message.t...