dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def build_startTimes(): startTimes = [] # create list of start times, 1/2 hour increments startTimes2 = [] for s in range(7,10): startTimes2.append("0" + str(s) + ":00 AM") startTimes2.append("0" + str(s) + ":30 AM") for s in range(10,12): startTimes2.append(str(s) + ":00 AM...
The main task of the code is to generate detailed HTML scheduling pages for each room in `theRooms`, saving them in an "HTML" directory. It constructs HTML files with headers, body content (including start times, room data, and timestamps), and footers. The code handles missing room data gracefully, ensures the output ...
def make_schedDetail(theRooms, SoC, spInvRooms): days = ("M","T","W","R","F") startTimes2 = build_startTimes() for r in theRooms: # Define the directory and file path directory = "HTML" filepath = directory+"/"+ r + "_schedDetail.html" # Create the directory if it does not e...
def mainMenu(): # display UI print("\nWhat would you like the robot to do?") print("0) exit") print("1) move") print("2) retreive IR Data") print("3) take picture") # receive user input try: menuInp = int(input(">>> ")) return menuInp except: return def moveMenu(): while 1: print("\n\tWhich direction...
The main task of the code is to run an infinite loop displaying a menu, processing user input to execute actions like movement, IR commands, image capture, or exiting. It handles selections via conditional branching and closes a serial connection upon exit.
def main(): while 1: menuInp = mainMenu() if menuInp == 0: return elif menuInp == 1: # call move function moveMenu() elif menuInp == 2: # call IR function sendIRCommand() elif menuInp == 3: captureImg() else: # default print("NOT A VALID OPTION") ser.close()
def convert_to_tensors(list_to_convert): if list_to_convert != []: return [tf.convert_to_tensor(list_to_convert[0])] + convert_to_tensors(list_to_convert[1:]) else: return [] def inference(model, batch_images, n_classes, flip_inference=True, scales=[1], preprocess_mode=None): x = preprocess(...
The function evaluates a model's performance on a dataset by computing accuracy and Intersection over Union (IoU) metrics. It processes batches, performs inference, updates a confusion matrix, and calculates accuracy using TensorFlow metrics. Optional parameters allow image output, multi-scale inference, and preprocess...
def get_metrics(loader, model, n_classes, train=True, flip_inference=False, scales=[1], write_images=False, preprocess_mode=None, n_samples_max=None): if train: loader.index_train = 0 else: loader.index_test = 0 accuracy = tf.metrics.Accuracy() conf_matrix = np.zeros((n_...
def get_file_paths(filter_type, file_prefix): if filter_type == 1: OUT_FILE_JSON = 'data/' + file_prefix + 'twitter_dump_by_keywords.json' OUT_FILE_CSV = 'data/' + file_prefix + 'twitter_dump_by_keywords.csv' OUT_FILE_FILTERED_CSV = 'data/processed/' + file_prefix + 'twitter_dump_by_keywords...
The main task of the code is to process and append collected tweets to CSV/JSON files based on filtering parameters. It retrieves tweet data, preprocesses it, and saves results to specified output files, distinguishing between raw and filtered datasets. The function handles both initial collection and post-processing s...
def main(USE_FILTER, FILE_PREFIX): global OUT_FILE_JSON, OUT_FILE_CSV, OUT_FILE_FILTERED_CSV, OUT_FILE_FILTERED_JSON, SEARCH_QUERY OUT_FILE_JSON, OUT_FILE_CSV, OUT_FILE_FILTERED_CSV, OUT_FILE_FILTERED_JSON, SEARCH_QUERY = get_file_paths( USE_FILTER, FILE_PREFIX) print(f"Current Number of processed ...
def variables_of_clause (self, c : Rule) -> set : variables = set() if isinstance(c.head, Function): for term in c.head.terms: variables.update(self.variables_of_term(term)) if c.body == []: return variables if isinstance(c.body, RuleBody): for term in c.body.terms: variables.update(self.variab...
The function `freshen` renames all variables in a given clause `c` with fresh (unique) variables. It identifies variables in `c`, maps each to a new fresh variable using a dictionary `theta`, and substitutes these in the clause. This ensures variable names in the clause are distinct, preventing conflicts during operati...
def freshen(self, c: Rule) -> Rule: c_vars = self.variables_of_clause(c) theta = {} for c_var in c_vars: theta[c_var] = self.fresh() return self.substitute_in_clause(theta, c)
def freshen(self, c: Rule) -> Rule: c_vars = self.variables_of_clause(c) theta = {} for c_var in c_vars: theta[c_var] = self.fresh() return self.substitute_in_clause(theta, c) def unify (self, t1: Term, t2: Term) -> dict: return self.unifyHelper(t1, t2, {}) def substitute_in_term (self, s : dict, t : Term...
The function performs non-deterministic resolution in logic programming by randomly selecting clauses from a rule set to unify with the current goal. It iteratively replaces goals with clause bodies, applying substitutions, until the resolvent is empty. If no clauses unify, it backtracks recursively. The main task is t...
def nondet_query (self, program : List[Rule], pgoal : List[Term]) -> List[Term]: goal = pgoal.copy() resolvent = goal.copy() while len(resolvent) > 0: random_index_goal = random.randint(0, len(resolvent) - 1) random_goal = resolvent[random_index_goal] unify_clause = [] for clause in program: ...
def freshen(self, c: Rule) -> Rule: c_vars = self.variables_of_clause(c) theta = {} for c_var in c_vars: theta[c_var] = self.fresh() return self.substitute_in_clause(theta, c) def unify (self, t1: Term, t2: Term) -> dict: return self.unifyHelper(t1, t2, {}) def substitute_in_term (self, s : dict, t : Term...
This code implements a depth-first search (DFS) algorithm for resolution theorem proving in logic programming. It recursively resolves goals against clauses in a program, unifying terms and substituting variables to derive solutions. When the resolvent (current goals) is empty, the accumulated pgoal (partial solution) ...
def dfs(self, program: List[Rule], resolvent: List[Term], pgoal : List[Term], solutions:List[Term]) -> List[List[Term]]: if len(resolvent) == 0: solutions.append(pgoal) return solutions while len(resolvent) > 0: chosen_goal = resolvent[0] resolvent.remove(chosen_goal) for clause in program: c...
def compute_content_loss(content_features, combination_features): original_image = content_features[CONTENT_LAYER_NAME] generated_image = combination_features[CONTENT_LAYER_NAME] return tf.reduce_sum(tf.square(generated_image - original_image)) / 2 def total_variation_loss(image, result_width): a = tf....
The code computes a total loss for an image generation task by combining content loss, style loss (using either a correlation chain or standard method), and total variation loss. It extracts features from the input image and reference features, calculates individual losses, and returns a weighted sum of these losses al...
def compute_loss(feature_extractor, combination_image, content_features, style_features, result_width): combination_features = feature_extractor(combination_image) style_reference_features = feature_extractor(style_features) loss_content = compute_content_loss(content_features, combination_features) ...
def pushNode(self, node): if node != None: isNodeSafe = self.canvaArea.isOutsideObstacleSpace(node) if isNodeSafe: isNodeInClosedList = node.coord in self._closedList if not isNodeInClosedList: nodeInWorkspace = self.isNode...
This function implements a pathfinding algorithm using a priority queue (heapq) to explore nodes. It starts from a given node, iteratively expands nodes, checks if a goal is reached, and visualizes the process. If the goal is found, it stores the solution node; otherwise, it prints "SOLUTION NOT FOUND" after exhausting...
def createNodeTree(self): self.pushNode(self.startNode) lastPercent = 0 while(self._openList): # pops an element from the top of the list tempNode = heapq.heappop(self._openList) self._closedList.add(tempNode.coord) ...
def GetDataRoot(self): return self.dataRoot def GetDevice(self): return self.device def SaveModel(self, fileName): torch.save(self.net.state_dict(), fileName) def Test(self,valList): if isinstance(valList, str): with open(valList, "rt", newline='') as f: patie...
The code trains a neural network for medical image segmentation using cross-entropy loss and Adam optimizer. It processes patient data in batches, splits into training/validation sets, and iteratively updates the model over 1000 epochs. It tracks training loss, validates periodically using AUC/DICE metrics, and saves m...
def Train(self,trainList,valPerc=0.0,snapshotRoot="snapshots", seed=6112): batchSize=16 labelWeights = torch.Tensor([1.0]*self.numClasses) historyLength = 30 learningRate = 1e-3 ShowWarnings(False) numEpochs=1000 print(f"Info: numClasses = {self.numClasses}, dila...
def display_coordinates(x, y): turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.write(f"({x}, {y})", align="left", font=("Arial", 12, "normal")) def draw_line(x1, y1, x2, y2): turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) def savecoor(list_name, initial_...
This code allows users to interactively draw shapes using Python's turtle module. It captures initial coordinates, lets users choose to draw lines, cubic Bezier curves, or close polygons, with error handling for invalid inputs. Coordinates are displayed, and users can save figures with custom names. The loop repeats un...
def Drawnewlif(): global x2,y2 while True: # Get user input for the initial point while True: try: x1, y1 = eval(turtle.textinput("User Input", "Enter the initial coordinate (x, y): ")) break except NameError: turtle.penup() ...
def printPositions(lesReines): grille = [[0] * tailleGrille for _ in range(tailleGrille)] output = "" it = 0 for i in lesReines: grille[it][i] = 1 it = it + 1 for i in range(tailleGrille): for j in range(tailleGrille): if grille[i][j] == 1: output...
The main task of the code is to solve the N-Queens problem using a simulated annealing algorithm. It initializes a chessboard configuration, evaluates its cost, executes the optimization process, and outputs the final queen positions, solution cost, and computation time in milliseconds.
def main(): lesReines = list(range(tailleGrille)) printPositions(lesReines) print(F(lesReines)) start_time = time.time() res = recuit(lesReines) stop_time = time.time() - start_time printPositions(res) print(F(res), ' prises') print("temps : ", stop_time * 1000)
def next_bowler(team_bowlers,last_bowler): values=np.array(list(team_bowlers.values())) if sum(values)<=3: values=values.tolist() r=list(team_bowlers.keys())[values.index(max(values))] team_bowlers[r]-=1 else: values=(values/sum(values)).tolist() while(1): r=list(team_bowlers.keys())[roulette(values)] ...
This function simulates a cricket innings, tracking runs, wickets, and bowler performance. It initializes batsmen and bowlers, iterates through overs and balls, calculates scores using a probabilistic model, updates player statistics, and returns the total score and balls faced. The simulation handles wicket falls, run...
def play_innings(batsmen,bowlers,innings,venue,target,bdf,bodf): global striker global non_striker global notout_probability1 global notout_probability2 global next_down global cur_run global striker_runs global non_striker_runs global striker_balls global non_striker_balls global wicket_prob nxt_bowler=''...
def getFilepathsFromInput () -> Union[str, str, str]: # First get the filepaths # Try it with choosers # print("Let's choose some CSV's for making a Pyomo .dat file!") # input("Press any key to choose decision variable CSV.") # Tk().withdraw() #hide tk window since this is not a full GUI program # objFilepath ...
The code's main task is to parse input CSV files containing objective and constraint data, validate the data, convert it into a structured FinalModel object, and write this model to a parameter file. The process involves reading input files, ensuring data integrity, transforming data into a model, and exporting the res...
def main(): # Step 1: Get + Read Input objFilepath, constFilepath, paramFilepath = getFilepathsFromInput() print() print("Now parsing & converting...") objData = openAndReadObjectiveCSV(objFilepath) constData = openAndReadConstraintCSV(constFilepath) # Step 2: Validate the data & produce a FinalModel object o...
def parsePositionals(args_obj, options): for positional in args_obj: if (match := re.match(r'(?P<key>\w+):(?P<value>.+)', positional)) != None: options.replacements[match.group("key")] = match.group("value") elif (match := re.match(r'(?P<key>\w+)=(?P<value>.+)', positional)) != None: options.flags...
This function parses command-line arguments, validates input/output requirements, configures options, and compiles a file by preprocessing, tokenizing, and generating output. It handles version/help flags, ensures both input and output are provided, and executes compilation steps if valid arguments are given.
def parseArgs(args_obj): do_compile = False options = utils.options() parsePositionals(args_obj.positionals, options) if args_obj.version: print(PROG_NAME + " version " + str(VERSION)) exit() if args_obj.help: print(HELP_MENU) print("builtin preprocessor flags:") for i in options.flags:...
def i_find_refs(self): self.logger.log("compiler", "finding references", 3) for primary_scene in self.tokens: for secondary_scene in self.tokens[primary_scene]: self.scene_refs.append(primary_scene + "." + secondary_scene) if self.tokens[primary_scene][second...
The main task of the code is to parse and compile configuration data from tokens, handling scenes, interactions, and references. It validates field definitions, processes "require" and "types" directives, resolves scene references, and structures parsed information into a data hierarchy. The code checks for errors in s...
def parse(self): self.i_find_refs() # find the number of scenes # and compile info cnt = 0 for i in self.tokens: for p in self.tokens[i]: cnt += 1 if self.tokens[i][p]["type"] == "config": config_scene = self.tokens...
def load_seq(args): """ I figure there are a couple of ways I'd want to specify the sequences, from low to high complexity: 1) Just one fucking sequence. 2) One sequence, but with an offset 3) Several sequences. In the case of several sequences, I would need some way to determine which sequence...
The code calculates rotation scores for DNA nanostructures by loading CAD files, processing sequences, evaluating rotation criteria, and saving/plots results based on user-defined parameters. It handles multiple designs, checks file overwrite conditions, and outputs statistics or visualizations as specified.
def calculate_rotation_scores(args): global VERBOSE VERBOSE = args['verbose'] or 0 # Get sequence(s): seqs = load_seq(args) # What to score: score_criteria_list = get_score_criteria_list(args) if VERBOSE > 1: print("score criteria list:") print(yaml.dump(score_criteria_list)...
def filter_paf(paf_path, min_qcov=0.95): """ Filter a PAF file according to specified criteria. Return a list of PAF records """ records = [] with PafFile(paf_path) as paf: for record in paf: if record.mlen / record.qlen >= min_qcov: records.append(record)...
The code detects chimeric gene models by analyzing transcript mappings to a genome. It processes GFF files, genome FASTA, and transcript mappings (via Minimap2), filters high-quality alignments, identifies regions with multiple transcripts, and detects chimeric genes spanning these regions. Results are output as a list...
def main(): # command line arguments DESC = "detect_chimeric_genes.py: detect chimeric gene models based on transcript mapping" USAGE = "python detect_chimeric_genes.py -h (display full usage doc)" parser = ArgumentParser(description=DESC, usage=USAGE) parser.add_argument('-g', '--gff', help='Input ...
def cli_init(): cli_gi(_commit=False) subprocess.call(["git", "init"]) def cli_commit(s: str): call_multiline( """ git add . git commit -m {} """.format( shlex.quote(s) ) ) def cli_push(): if not subprocess.check_output(["git", "config", "remote.origin.url"]):...
This function provides a command-line interface (CLI) menu for a version control system, allowing users to select actions like initializing a repository, committing changes, pushing to a remote, or pulling updates. It routes user input to corresponding functions, handling workflow steps such as committing with a messag...
def cli_default(): choice = input( trim_indent( """ What do you want to do? 1. {init} 2. {commit} 3. {cpush} 4. {gi} 5. {push} 6. {pull} Please select [1-6]: """.format( **CMD ) ) ) if choice == "1": cli_in...
def exportrepo(repo_root): cmd = ["git", "-C", repo_root, "fast-export", "--all"] return parseexport(subprocess.check_output(cmd)) def cleandir(path): for the_file in os.listdir(path): file_path = os.path.join(path, the_file) try: if os.path.isfile(file_path): os....
This function filters blobs from a source Git repository using specified name and blob filter functions, processes them in parallel, and exports the filtered result to a destination repository. It exports the source, identifies relevant blobs, applies filters, replaces filtered data, and imports the modified history in...
def filterblobs(src_repo, dst_repo, name_filter_fun, blob_filter_fun, branch="master"): # Export the source repository. print("Exporting the source repository (" + src_repo + ")...") commands = exportrepo(src_repo) # Filter all the data blobs. print("Filtering blobs...") # Get a list of filter...
def cli_default(): choice = input( trim_indent( """ What do you want to do? 1. {init} 2. {commit} 3. {cpush} 4. {gi} 5. {push} 6. {pull} Please select [1-6]: """.format( **CMD ) ) ) if choice == "1": cli_in...
The code processes command-line arguments to execute Git-like operations (init, commit, push, etc.) based on user input. It handles default actions, commit messages, and error cases, providing interactive prompts when necessary.
def main(): argv = sys.argv if len(argv) <= 1: cli_default() elif argv[1] == "init": cli_init() elif argv[1] in {"commit", "cpush"}: try: cli_commit(argv[2]) except IndexError: cli_commit(input("Please input your commit message: ")) if arg...
def __generate_chains(self): dic = IndexDict(self.__vor.ridge_vertices) # ignition value must be dead end point(which has only 1 neighbor) ignition_idx = -1 for key, value in dic.items(): if len(value) == 1: ignition_idx = key break #...
The code optimizes a Voronoi diagram's line by generating chains, creating vertex chains, and regenerating ridges. It returns True if optimization succeeds (chains exist) or False if no chains are generated.
def __optimize_line(self) -> bool: # generate chains in voronoi diagram self.__chains = self.__generate_chains() if len(self.__chains) == 0: return False # generate vertex chains based on chains vertex_chains = self.__generate_vertex_chains(self.__chains) ...
def __generate_chains(self): dic = IndexDict(self.__vor.ridge_vertices) # ignition value must be dead end point(which has only 1 neighbor) ignition_idx = -1 for key, value in dic.items(): if len(value) == 1: ignition_idx = key break #...
The main task of the code is to regenerate chains using optimized values, identify unfinished vertices and ridges, delete them, and reorganize remaining ridges. It removes incomplete geometric elements from a structure, ensuring data consistency by updating chains, pruning invalid components, and restructuring residual...
def __delete_unfinished(self) -> None: # regenerate chain by optimized value self.__chains = self.__generate_chains() # calculate unfinished vertices and ridges unfinised_vertices = self.__unfinished_vertices() ridge_to_delete = self.__ridges_to_delete(unfinised_vertices) ...
def run_non_optimized(self, generate_result=True) -> Result: # run voronoi self.__run_voronoi(self.__boundary_lined_points + self.__triangle_lined_points + self.__line_lined_points + self.__points) # calculate unr...
The main task of the code is to execute an optimized process by first running a non-optimized version, iteratively refining it through line optimization and removing unfinished components, then generating and returning the final optimized result.
def run_optimized(self) -> Result: # run voronoi self.run_non_optimized(False) while True: if not self.__optimize_line(): break self.__delete_unfinished() return self.__generate_result()
def run_non_lined(self) -> Result: self.__run_voronoi(self.__boudnary_points + self.__triangle_points + self.__line_points + self.__points) return self.__generate_result() def run_non_deleted(self) -> Result: self....
The code defines a `run` method that executes different processing strategies based on the `type` parameter, returns the result, and optionally generates a plot. It selects between non-lined, non-deleted, non-optimized, or optimized execution paths and triggers plotting if enabled.
def run(self, type = run_type.optimized, plot = True) -> Result: if type == run_type.non_lined: result = self.run_non_lined() elif type == run_type.non_deleted: result = self.run_non_deleted() elif type == run_type.non_optimized: result = self.run_non_optimized() elif type == run...
def checksIfTheNetworkIsNotCutOff(nodes, g): for i in nodes: for j in nodes[nodes.index(i):]: if i != j: if not bfs(i, j, g): return False return True def new_g(discardedLinks, g): newG = [] # print(newG) for path in g: # print(path[1]...
The function identifies the first link in the discardedLinks list whose removal does not disconnect the network. It checks each link by temporarily removing it from the discarded list, reconstructing the graph, and verifying connectivity. If a valid link is found, it returns that link; otherwise, it returns the origina...
def findTheLinkForKeepingTheNetworkNotCutOff(nodes, discardedLinks, g): for link in discardedLinks: if checksIfTheNetworkIsNotCutOff(nodes, new_g(newDiscardedLinks(discardedLinks, link), g)): return [link] return discardedLinks
def setupUI(self): ui_file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), 'Shiva.ui') main_widget = load_ui(ui_file_path, self) layout = QtGui.QVBoxLayout() layout.addWidget(main_widget) self.setLayout(layout) # Get a reference to all required widgets ...
This code initializes a GUI component with feedback listener integration, setting up UI elements and channel configuration for a system interacting with a 'shiva' interface, including widgets for channel groups, note selection, value bars, and threshold sliders.
def __init__(self, parent=None, shiva=None): QtGui.QWidget.__init__(self, parent) LevelFeedbackReaderListener.__init__(self) # Interface to board is required self.shiva = shiva self.shiva.addFeedbackListener(self) self.enabled_channels = [0, 1, 0, 0, 0, 0, 0, 0] ...
def recalc_covmat(self): idx_reduced = [] for i in range(self.loc.shape[0]): if not tf.where(tf.equal(self.idxs, i)).shape[0]: idx_reduced.append(i) self.idx_reduced = tf.constant(idx_reduced, dtype=tf.int32) self.loc_reduced = tf.gathe...
This code performs iterative optimization using a proposal distribution, adjusting parameters via likelihood maximization with temperature annealing. It updates the covariance matrix when indices change, handles numerical stability, and terminates early if convergence criteria are met, returning optimized parameters an...
def calc_point(self, zip_data): vals, idxs, file_number = zip_data print(rank,':',idxs, file_number) self.val = vals if not tf.reduce_all(idxs == self.idxs): self.idxs = idxs self.recalc_covmat() T=1.0 self.prop_dist...
def XYUnitary0(J, dt): return expm(-1.j * XYMatrix(J) * dt) def interactionUnitary(XY, Bx, theta, dt): return np.matmul(XY, BxyUnitary(Bx, theta, dt)) def BzMatrix(Bz): return Bz*(np.kron(np.kron(np.kron(Z, I), I), I) + np.kron(np.kron(np.kron(I, Z), I), I) + np.kron(np.kron(np.kron(I, I), Z), I) + np.kron(...
The code simulates the time evolution of a quantum state under interaction Hamiltonians, varying parameters θ, and computes the z-component of magnetization (mz) at each step. It initializes a state vector, applies unitary operations iteratively, and collects mz values in an array for analysis.
def interactionm(J, Bx, Theta, dt): U = np.kron(np.kron(np.kron(I, I), I), I) XY = XYUnitary0(J, dt) psi0 = np.matrix([[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [1]]) mzarray = [] for theta in Theta: U = np.matmul(interactionUnitary(XY, Bx, theta, dt), U) ...
def get_state(self): url = '{0}/dispatch/jobs/{1}'.format(self.host, self.run_job) return get(url).json()['state'] def kill_subproc(self): print('Terminating job.') self.experiment_process.terminate() try: self.experiment_process.wait(timeout=10) except Timeou...
The code monitors an experiment process, waiting up to 1 second. If it times out, it checks the state: if state 2, it kills the subprocess; else, it ends the experiment and sets the state to 'polling'. This handles process termination or completion based on timeout and state checks.
def run_experiment(self): try: self.experiment_process.wait(1) except TimeoutExpired: state = self.get_state() if state == 2: self.kill_subproc() else: self.end_experiment() self.state = 'polling'
def _prob_h_v(self, visible_data): return sigmoid( self.bias_h + np.dot( visible_data, self.weight ) ) def _data_mean(self, visible_data, hidden_data): data_length = len(visible_data) visible_mean = np.average(visible_data, axis=0) hidden_mean = np.average(hidden_data, axis=0) ...
This code trains a model using contrastive divergence. It iterates for a specified time, computing data and model expectations, then updates weights and biases by adding gradients (differences between data and model expectations) scaled by the learning rate to minimize reconstruction error.
def train(self, data, learning_rate=0.01, learning_time=1000): for i in range(learning_time): data_sig = self._prob_h_v(data) data_visible, data_hidden, data_weight = self._data_mean(data, data_sig) model_visible, model_hidden, model_weight = self._contrastive_divergence(data...
def find(root, key): v, last, next = root, root, None while v != None: if v.key >= key and (next == None or v.key < next.key): next = v last = v if v.key == key: break if v.key < key: v = v.right else: v = v.left root = splay(last...
This function splits a splay tree into two subtrees based on a given key. It first searches for the key, splays the found node to the root, then separates the tree into left and right subtrees by severing the root's left child. Both subtrees are updated and returned, enabling operations like splitting ranges in self-ad...
def split(root, key): result, root = find(root, key) if result == None: return(root, None) right = splay(result) left = right.left right.left = None if left != None: left.parent = None update(left) ; update(right) return(left, right)
def forwardPropagation(self,net, inputs): for layer in net: newInputs = [] for neuron in layer: activation = self.activate(inputs, neuron.weights) neuron.output = self.transfer(activation) newInputs.append(neuron.output) inputs ...
This code trains a Multi-Layer Perceptron (MLP) using backpropagation. It iterates through epochs and data examples, performing forward propagation to compute outputs, calculating mean squared error, executing backward propagation to adjust weights, and updating network parameters with a specified learning rate to mini...
def trainingMLP(self, net, data, noOutputTypes, learningRate, noEpochs): for epoch in range(0, noEpochs): for i, example in enumerate(data[0]): inputs = example computedOutputs = self.forwardPropagation(net, inputs) expected = [data[1][i]] ...
def getCenterColor(color_image_box, color_image, segment3yBottom, segment3xBottom): # A is center A = np.copy(color_image[segment3yBottom, segment3xBottom]) A = np.float16(A) A1 = np.copy(color_image[segment3yBottom - 2, segment3xBottom - 2]) A1 = np.float16(A1) A2 = np.copy(color_image[segment3...
The function estimates the rotation angle of an object in an image by combining manual angle estimation, CNN-based classification, and noise reduction. It processes the image, crops relevant regions, and uses a neural network to predict the angle, then selects the best angle from manual and CNN results, returning the e...
def getRotateAngle(pred, predRowsegment3Bottom, color_image, color_image_box, segment3yBottom, segment3xBottom, color_image_old, color_image_old1, rotCNN, oldAngle): # remove noise by average last 2 and current images color_image = cv2.addWeighted(color_image, 0.5, color_image_old, 0.5, 0) ...
def FTBS ( gridx, phi0, c , nt): "FTBS scheme for linear advection on initial array profile phi0" "Using Courant number c, for nt time-steps, on a space grid gridx" "Returns the final advected profile\ " Check_periodic_boundary(phi0) # number of grid points nx = gridx.nx ...
The function `run_schemes` executes four advection schemes (FTBS, CTCS, CNCS, Lax-Wendroff) on an initial profile `phi0` using a specified Courant number `c` and grid `gridx` over `tsteps` time steps, returning the final advected profiles from each method.
def run_schemes( gridx, phi0, c , tsteps ): "Runs all the advection schemes on initial array profile phi0, " "using Courant number c, for nt time-steps, on a space grid gridx." "Returns the final advected profiles.\ " phiFTBS = FTBS( gridx, phi0, c , tsteps ) phiCTCS = CTCS( gridx, phi0, c , ...
def bleu_metric(self, data, eval_dial_list=None): gen, truth = [], [] for dial_id, dial in data.items(): if eval_dial_list and dial_id not in eval_dial_list: continue for turn in dial: # excepoch <bos_resp>, <eos_resp> gen.append(" ...
The main task of the code is to compute and aggregate multiple evaluation metrics for dialog systems, including BLEU scores, joint goal accuracy, slot-level F1 and accuracy, action prediction (ASPN) F1, and context-to-response success/match rates. It processes input data to calculate these metrics, organizes them into ...
def run_metrics(self, data, domain="all", file_list=None): metric_result = {'domain': domain} bleu = self.bleu_metric(data, file_list) jg, slot_f1, slot_acc, slot_cnt, slot_corr = self.dialog_state_tracking_eval( data, file_list) metric_result.update( {'joint_g...
def wrap_git_and_exit(args): wrap_git(args) sys.exit(0) def inject_reference_repo_arg(args, root_dir, repo): repo_path = root_dir / repo if not repo_path.is_dir(): return args original_args = args args = drop_pre_command_git_args(args) dropped_args = len(original_args) - len(args) ...
The main task of the code is to configure logging, retrieve environment variables for directory paths, process command-line arguments, inject a reference repository argument, add Git alternates, log the wrapped Git command, and execute it. It also conditionally updates required remotes if specified, handling exceptions...
def main(): # Initialize the logger. log_level = os.getenv(_LOG_LEVEL_ENV_VAR, default=_DEFAULT_LOG_LEVEL) log_format = "[%(filename)s (%(process)d)] %(levelname)s: %(message)s" logging.basicConfig(level=getattr(logging, log_level), format=log_format) # Options can be configured via (in priority or...
def get_headline(): # get headline and teaser print('getting headline') url = 'https://mars.nasa.gov/news/' soup = get_soup(url) # get most recent article li = soup.find('li', class_="slide") headline = li.find('h3').text teaser = li.find('div',class_="article_teaser_body").text return headline, teaser def get...
(The code scrapes Mars-related data including headlines, teasers, images, tables, and hemisphere information, compiles it into a dictionary, connects to a MongoDB database, drops existing records to avoid duplicates, inserts the new data, and returns the dictionary.)
def scrape(): # get data and create dict headline, teaser = get_headline() mars_dict = {'mars_news_headline':headline,'mars_news_teaser':teaser} featured_image_url = get_feature_pic() mars_dict.update({'mars_image_url':featured_image_url}) html_table = get_table() mars_dict.update({'mars_table_data':html_table...
def get_args(): p = argparse.ArgumentParser(add_help=True, description='This script will attempt to extract GPS data from dashcam video files and output it in GPX format.') p.add_argument('-i',metavar='input',nargs='+',help='input file(s), globs (eg: *) or directory(ies)') p.add_argument('-o',metavar='outpu...
The main task of the code is to process input files to extract GPS data, handling cases where GPS chunks are missing by direct search. It aggregates valid GPS points, generates a GPX file, and writes it to an output file. If no GPS data is found, it exits with an error. The code ensures robust GPS data extraction and o...
def main(): in_files,out_file=get_args() for f in in_files: process_file(f) if(len(gps_data) == 0): print("Can`t find GPS chunks at file %s, try direct searching..." % f) process_file_wo_gps_chunk(f) #try find GPS data directly gpx=get_gpx(gps_data,out_file) prin...
def parse_input(lines, part): hands_and_bids = [(hand, int(bid)) for hand, bid in (line.split() for line in lines)] frequencies = [ {"counts": Counter(hand), "hand": hand, "bid": bid} for hand, bid in hands_and_bids ] if part == 1: return frequencies if part == 2: ret...
The code processes input lines to parse hands and bids, ranks them based on hand strength, calculates total winnings from the ranked list, and prints the result.
def part_1(lines): hands_and_bids = parse_input(lines, 1) hab_by_rank = rank_hands_and_bids(hands_and_bids, 1) total_winnings = calculate_total_winnings(hab_by_rank) print(total_winnings)
def parse_input(lines, part): hands_and_bids = [(hand, int(bid)) for hand, bid in (line.split() for line in lines)] frequencies = [ {"counts": Counter(hand), "hand": hand, "bid": bid} for hand, bid in hands_and_bids ] if part == 1: return frequencies if part == 2: ret...
The code processes input lines to parse hands and bids, ranks them, calculates total winnings based on their rankings, and prints the result.
def part_2(lines): hands_and_bids = parse_input(lines, 2) hab_by_rank = rank_hands_and_bids(hands_and_bids, 2) total_winnings = calculate_total_winnings(hab_by_rank) print(total_winnings)
def colorize(color, text): return color + text + colors.NORMAL def print_vis_w(self, vis_w): for vi in vis_w: mw_spms = \ vi.get('mw_spm_its', []) + vi.get('mw_spm_phrases', []) vi_text = vi.get('vi_text') vi_text = colorize(colors.WHITE, vi_text) ...
This function processes a list of structured data blocks (`sblocks`), formatting and appending their contents to `self.text` with color-coded highlights. It iterates through each block, extracts labels and senses, and applies specific formatting rules (e.g., bold cyan for block numbers, yellow for definitions, magenta ...
def print_sblocks(self, sblocks): for sblock in sblocks: sn_block_num = sblock.get('sn_block_num', '') scnt = sblock.get('scnt', '') self.text += colorize(colors.BOLDCYAN, sn_block_num) + ' ' for key, value in scnt.items(): if key == 'sblock_label...
def print_headword(self, headword): headword_text = headword.get('headword_text', '') headword_prons = headword.get('headword_prons', '') fl = headword.get('fl', '') homograph = headword_text.get('homograph', '') text = headword_text.get('text', '') if homograph: ...
This code processes a dictionary entry by iterating through its key-value pairs. For each key, it calls specific methods to format and append corresponding data to `self.text`, adding newlines after certain entries. The main task is to structure and format the entry's content into a cohesive text representation by hand...
def print_entry(self, entry): for key, value in entry.items(): if key == 'headword': self.print_headword(value) elif key == 'hw_infos': self.print_hw_infos(value) elif key == 'snote': self.print_snote(value) elif key...
def parse_headword(self, headword): headword_json = {} headword_text = headword.find('span', class_='hw_txt') headword_prons = headword.find_all('span', class_='hpron_word') fl = headword.find('span', class_='fl') if headword_text: headword_text_json = {} ...
This function parses HTML elements from a BeautifulSoup object, extracting structured data into a dictionary. It iterates through child elements of an entry, identifies their HTML class, and maps them to corresponding fields (e.g., headword, notes, labels) using specialized parsing methods. Text is cleaned and formatte...
def parse_entry(self, entry): entry_json = {} for child in entry.children: if isinstance(child, bs4.element.Tag): class_ = child.attrs['class'][0] if class_ == 'hw_d': entry_json['headword'] = self.parse_headword(child) eli...
def attempt_to_mate(male, female): ''' Returns: True, if mating succeeded False, otherwise ''' assert(male.model == female.model) # Which model we currently use current_model = male.model if female.does_care_after_cubs: return False # Females prefer higher levele...
The main task of the code is to generate encounters between mature bears based on their behavior and season. It uses a Poisson distribution to determine encounter count, filters eligible bears, and triggers mating or attacks. During mating season, opposite-sex bears attempt reproduction, with the female giving birth if...
def generate_encounters(self): ''' Generate encounters for a bear ''' # Only fully mature bears can have enco assert(self.is_under_parental_care == False) if self.behavior == 'coward' and self.model.season != 'mating': # Cowards don't initiate encounters outside of t...
def hunt(self, sheep, assistant=None): ''' Calculate the probability of success dependent on the hunter's level and the assistant's level ''' level = self.level if assistant: # Use the average value of level level = (self.level + assistant.level // 2) ...
This code simulates an agent's step in a model, decrementing energy, hunting a random sheep if available, managing parental care (chasing cubs or decrementing care countdown), generating encounters when not under care, and triggering death if energy depletes.
def step(self): #self.random_move() self.energy -= 1 # If there are sheep present, eat one sheep = self.model.schedule.get_agents_by_breed(Sheep) if len(sheep) > 0: sheep_to_eat = random.choice(sheep) if self.is_under_parental_care: self.h...
def get_articles(query, library=paper_dir_filepath, top_k=5): """This function gets the top_k articles based on a user's query, sorted by relevance. It also downloads the files and stores them in arxiv_library.csv to be retrieved by the read_article_and_summarize. """ search = arxiv.Search( quer...
The code's main task is to execute function calls for fetching and summarizing arXiv articles. It processes incoming messages, identifies function names like `get_articles` or `read_article_and_summarize`, parses arguments, retrieves search results or summarizes text, appends outcomes to messages, and returns responses...
def call_arxiv_function(messages, full_message): """Function calling function which executes function calls when the model believes it is necessary. Currently extended by adding clauses to this if statement.""" print("Using function: ", full_message["message"]["function_call"]["name"]) if full_message["...
def text_to_matrix(temp_string): ans=[[],[],[],[]] for i in range(4): for j in range(4): ans[j].append(hex(ord(temp_string[4*i+j]))) return ans def round_value(plain_state,key_state): output=[[],[],[],[]] for i in range(4): for j in range(4): output[i].append(...
This code implements the AES encryption algorithm by converting plaintext and key into matrices, performing initial rounds, key expansion, and subsequent AES rounds with substitution and shifting operations, finally returning the encrypted ciphertext.
def aes_enc(plain_text,key_text): plain_state=text_to_matrix(plain_text) key_state=text_to_matrix(key_text) pre_round=round_value(plain_state,key_state) m_k=[] for i in range(10): otp=key_expansion(key_state,i) # matrix_to_text(otp) m_k.append(otp) key_state=otp.copy(...
def text_to_matrix(temp_string): ans=[[],[],[],[]] for i in range(4): for j in range(0,8,2): ans[i].append("0x"+temp_string[8*i+j]+temp_string[8*i+j+1]) return ans def key_expansion(state,pos): temp=[[],[],[],[]] t_matrix=[] for i in range(4): t_matrix.append(state[i]...
This code decrypts AES-encrypted text using a 128-bit key. It converts ciphertext and key into matrices, performs key expansion, applies inverse AES transformations (inv_shift_row, inv_sub_byte), executes 9 decryption rounds with round keys, and finally reconstructs plaintext from the decrypted matrix by converting hex...
def aes_dec(cipher_text,key_text): cipher_state=text_to_matrix(cipher_text) key_state=text_to_matrix(key_text) m_k=[] for i in range(10): otp=key_expansion(key_state,i) # matrix_to_text(otp) m_k.append(otp) key_state=otp.copy() o2=round_value(cipher_state,m_k[9]) ...
def aes_enc(plain_text,key_text): plain_state=text_to_matrix(plain_text) key_state=text_to_matrix(key_text) pre_round=round_value(plain_state,key_state) m_k=[] for i in range(10): otp=key_expansion(key_state,i) # matrix_to_text(otp) m_k.append(otp) key_state=otp.copy(...
The code performs AES encryption on plaintext by padding it to 16-byte blocks, using a 16-character key (padded with '#'). It processes each block, encrypts them sequentially, and returns the encrypted result, the key as a string, and the padded plaintext.
def encryption(plaintext,keytext): temp_text="" if len(keytext) <16 : keytext+="#"*(16-len(keytext)) if len(plaintext)%16 !=0 : plaintext+="#"*(16-len(plaintext)%16) temp_text+=plaintext else: temp_text+=plaintext keytext=keytext[:16] iii=0 result="" while...
def load_input_file(filename): global genre_list with codecs.open(filename, "r","utf-8-sig") as fp: genre_list = json.load(fp) def get_albums_for_genre(genre, delay=5,debug=False): subgenres_root = data_dump["genres"][-1]["subgenres"] subgenres_root.append({"name": genre['name'], "artists": []})...
The main task of the code is to download and process music genre/subgenre data from an input file, iterate through each subgenre to retrieve album information while measuring processing time, and save the structured results to an output file. It includes error handling for missing input files and organizes data into a ...
def download(input_file, output_file): if not os.path.exists(input_file): print(f"Input File {input_file} does not exist") return load_input_file(input_file) for genre in genre_list["genres"]: data_dump["genres"].append({"name":genre["name"],"subgenres":[]}) for subgenre in ...
def fade_in(t, offset=1.0): return ti.min(ti.exp(t + offset), t) def render_grad(dist, cnt=350): # ref: https://github.com/ElonKou/biulab/blob/master/shaders/shadertoy/sdf2d1.fs col = ti.Vector([0.0, 0.0, 0.0]) if (dist < 0.0): col = inner_col else: col = outer_col col = col * (1...
This function modifies a color gradient based on input distance and time by applying trigonometric transformations and blending components. It scales the distance with a sine function, generates a gradient, and dynamically adjusts the color channels (x, y, z) using sine and cosine waves modulated by time to create a ti...
def render_in(dist, t): c = fade_in(t) dist = dist * ti.sin(c) * 1.45 col = render_grad(dist, min(c * 13, 250)) col.x = mix(col.x, 1.0, ti.sin(c * 2.3) * 0.9) col.z = mix(col.z, 1.0, ti.cos(c * 3.1) * 0.9) col.y = mix(col.y, 0.0, ti.sin(c * 0.67) * 0.3) return col
def step_1(self): """ Remove entries that occur 'bottom' or less times and entries that occur 'top' or more times. Store those entries as a dictionary with two keys '{bottom}_or_less' and '{top}_or_more'. """ removed = { f'{self.bottom}_or_less': [ k for k, v in self.vocab.items() if v <= ...
The code filters a vocabulary by applying four sequential steps (step_1 to step_4), saving intermediate results with step-specific names and logging removed entries at each stage. It starts with the initial vocabulary size, processes each step to refine the vocabulary, and最终 stores the filtered vocabulary after the fou...
def filter(self): """ Dump a filtered vocabulary starting with the one in 'vocab_file' by executing the four steps explained in the docstring. Each is performed by a different function. After each step, an intermediate result is saved, named as 'vocab_file' and the step that was just performed appended ...
def new_attendance_sheet(): attendance_sheet_number = int(input('Sheet number:')) # noinspection PyBroadException try: attend_file = open('attendance' + str(attendance_sheet_number) + '.txt') attend_file.read() attend_file.close() print('This file already exists ') except...
The main task of the code is to provide a menu-driven attendance management system. It allows users to create new attendance sheets, switch between sheets, record attendance, read existing sheets, and check absentees through a looped interface. The program continuously displays options for these tasks and executes corr...
def main_attendance(): print('~~~Attendance.exe~~~') while True: print('1:Make a new attendance sheet') print('2:Change sheet number') print('3:Attendance') print('4:Attendance sheet reader') print('\tType exit to exit the program') option_selector = input(':-->')...
def details(self,mail): mail_details = self.analyze_mail_body(mail[6],mail[2]) print (mail_details) window = Toplevel(self) window.title('Additional Details') window.protocol('WM_DELETE_WINDOW',lambda x=window:self.reset_textvar(x)) topFrame = Frame(window) topFrame.grid(row=0,column=0,sticky=N+E+W+S) ...
The code implements a pagination system to display a subset of emails from `self.unique_mail` in a GUI grid. It splits the input page range, iterates through the specified emails, and dynamically generates labels for folder, subject, sender, date, and interactive buttons (Details, Conversation). A combobox allows user ...
def pagination(self,page): page_view_start = int(page.split('-')[0].strip()) page_view_end = int(page.split('-')[1].strip()) row=5 print (self.unique_mail[0]) for mail in self.unique_mail[page_view_start:page_view_end]: col = 0 folder_label =Label(self.mail_frame,anchor=W, text = str(mail[1]),bg='alice ...
def export_excel(self,l): p = os.path.join('.','FILES') file_name = f"download_{datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}.xlsx" print (file_name) filepath = p if os.path.exists(p): pass else: os.mkdir(p) filepath = os.path.join(p,file_name) print (filepath) data = [] sent_time_pattern = r...
This code creates a GUI with three buttons ("FETCH BETWEEN DATES", "REFRESH", "EXPORT TO EXCEL"), a pagination combobox, and layout frames. It configures ttk styles, arranges widgets using grid, and sets up functionality for data fetching, refreshing, exporting, and pagination in a mail management application.
def create_widgets(self): style = ttk.Style(self) style.configure("C.TButton", background="white", font=("Fixedsys", 10, 'bold'), foreground='black') style.configure("C.TCombobox", background="white", font=("Fixedsys", 10, 'bold'), foreground='black') utility_frame = Frame(self, bg='black') utility_frame.gr...
def initiate_thread_for_mail_extraction(self): self.threads = {} t = threading.Thread(target=self.get_mails) self.threads['mail_extraction'] = t t.start() def initiate_thread_for_mail_details(self): t = threading.Thread(target=self.get_mail_data) t.start() self.threads['mail_details'] = t def get_user_lis...
The code initializes a GUI application for email management, setting up a database connection, background threads for mail extraction and details, GUI layout with grid, fonts, and user interface elements. It prepares to handle user lists and creates widgets for interaction, using threading and SQLite for data processin...
def __init__(self, master=None): self.mail_list = None self.q = queue.Queue() self.SESSION = os.getlogin() + '_' + str(datetime.now()) self.conn = sql.SQLInterface('maildb.db') self.initiate_thread_for_mail_extraction() self.initiate_thread_for_mail_details() super().__init__(master) self.grid(row=0,col...
def compute_e1(n_batch, pred_masks, true_masks): sum_e1 = 0 for i in range(n_batch): tpfn = compute_tfpn(pred_masks[i],true_masks[i]) fp, fn = tpfn['fp'], tpfn['fn'] sum_e1 += fp+fn return sum_e1/n_batch def compute_dice(n_batch, pred_masks, true_masks): sum_dice = 0 for i in...
The function `evaluate_circle` assesses the performance of predicted segmentation masks and edges against ground-truth data using metrics like Dice coefficient, IoU, E1, and Hsdf. It computes these metrics for a batch of predictions and returns them as percentages (E1, IoU, Hsdf) and raw Dice score, aiding in evaluatin...
def evaluate_circle(pred_masks, true_masks, pred_edges, true_edges, dataset_name): """Evaluation without the densecrf with the dice coefficient""" n_batch = true_masks.size()[0] e1 = compute_e1(n_batch, pred_masks, true_masks) dice = compute_dice(n_batch, pred_masks, true_masks) iou = compute_miou(...
def get_response_then_get_soup(url): """ Param: url (str) url from a tripadvisor webpage. Returns: a soup object of the BeautifulSoup library. [Motivation: Often, getting a response from a website using the grequests library can take a long time. It is more efficient to try again after a certai...
The main task of the code is to gather a specified number of attraction URLs from Tripadvisor by iterating through pages, extracting links, and handling pagination until the required count is reached or an error occurs.
def get_all_top_links(url, num_attractions): """ param: url (str) - the url for the homepage of top attractions for a particular city on tripadvisor.com param: num_attractions (int) - the number of attraction-urls to gather starting from the homepage and continuing on to the next page (and the ext p...
def retrieve_data(soup): """ [Retrieves the relevant data for a TripAdvisor attraction page and returns it as a dictionary. Parameters] param: soup (BeautifulSoup) - A BeautifulSoup object representing the HTML of the attraction page. Returns (dict) - A dictionary containing the name, rating, and ot...
This function asynchronously scrapes TripAdvisor attraction data from provided URLs in batches, parses HTML content, extracts statistical information, compiles it into a DataFrame, and returns the sorted DataFrame by city and TripAdvisor rank.
def attractions_data(urls, ranks, batch_size): """ param: lst (list)- a list of urls of tourist attraction webpages from tripadvisor.com param: batch_size (int) - the number of urls to get a response from in an asynchronous grequests get() function. return: data_df (pandas.DataFrame) - contains all the ...
def all_search(self, typed): ''' Description: Lets user search for words that are in the currently displayed receipt data in the table Args: typed : str (the text that the user has typed in the search bar) ''' self.tree_table.bind('<<TreeviewSelect>>', lambda event: self.ta...
The code creates a new window with a search bar and table view to display and search through stored receipt data, enabling real-time filtering and column sorting with Tkinter.
def search_window (self): ''' Description: Opens a new window that has the table view ui and the searchbar where you can search through all the data. Args: None Returns: None ''' global new_window, search_window_style # Globaling the varables new_window and search_windo...
def themes (self, theme ): ''' Description: Controls the colour scheme of the whole program, including the main window and any subwindows. Args: theme : str (colour theme that the program is switching to) ''' self.theme = theme self.mode_button.configure(text= "Dark Mo...
The main task of the code is to initialize a GUI application for managing hire receipts. It loads data from a JSON file, sets up a Tkinter window with themed styling, creates input fields for user data entry, implements navigation and search functionality for receipts, and provides options to switch themes, clear data,...
def __init__(self,root): ''' Description: When the Main_window class is run, the __init__ function will automatically run. Args: root : Const (Initiates tkinter) Returns: None ''' global style , receipt_data_display, data , receipt_list # Lets the variables "style", "rec...
def readFileToList(filename): #eprint("Reading data from",filename) lines=filename.readlines() result=[] for x in lines: result.append(x.rstrip().split('\t')) filename.close() return result def read_file(submission_path, nb_labels=2, nb_samp=10): """ Read the tsv file """ # unzipped submission data is alway...
The code evaluates prediction files against gold standard data for multiple tasks (EMP, EMO, PER, IRI, CONV), computes metrics like Pearson correlations and F1-scores, validates alignment between predictions and labels, and writes results to a 'scores.txt' file in the output directory.
def score(input_dir, output_dir): # unzipped reference data is always in the 'ref' subdirectory truth_file = open(os.path.join(input_dir, 'ref', 'goldstandard.tsv')) goldList = readFileToList(truth_file) nb_samp = len(goldList) truth_file_CONV = open(os.path.join(input_dir, 'ref', 'goldstandard_CONV.tsv')) gold...
def add_entry(self, person, embeddings, train_classifier=True): """Adds entry (person, embeddings) to database :param person: new entry :param embeddings: new entry's list of embeddings :param train_classifier: train classifier (default: True) """ screen_data(person, embe...
The main task of the code is to initialize a database with provided data and metadata, configure distance metrics, and set up a classifier. It validates metadata, initializes data structures, applies normalization settings, populates the database with embeddings, and trains a classifier using the input data.
def set_data(self, data, metadata): """Sets data property :param data: new data in form {name: embedding vector, ...} :param metadata: data metadata """ assert metadata, "metadata must be provided" self._db = {} self._stripped_db = {} self._stripped_names...
def predict(self, img, detector, margin=10, flip=False, verbose=True): """Embeds and normalizes an image from path or array :param img: image to be predicted on (BGR image) :param detector: FaceDetector object :param margin: margin for MTCNN face cropping (default: 10) :param fli...
This code performs facial recognition by analyzing an input image to determine if a face matches known identities. It uses embeddings from `self.predict` and compares them against a database using either cosine similarity or adaptive thresholding. The function returns the detected face, recognition status, best match i...
def recognize(self, img, *args, verbose=True, mode="cosine", **kwargs): """Facial recognition :param img: image array in BGR mode :param args: will be passed to self.predict :param verbose: verbose or not (default: True) :param kwargs: will be passed to self.predict :para...
def _keras_init(self, filepath): """Initializes a Keras model :param filepath: path to model (.h5) """ import tensorflow.compat.v1 as tf # noqa self.mode = "keras" self.facenet = tf.keras.models.load_model(filepath) self.img_shape = self.facenet.input_shape[1:3...
The code initializes a FaceNet object for face recognition, loading a model (Keras, TensorFlow, TFLite, or TensorRT) based on the specified file type and path. It configures GPU memory allocation if enabled, validates model/data paths, and sets up a classifier (default: SVM). The object also prepares data storage for e...
def __init__( self, model_path=DEFAULT_MODEL, data_path=DB_LOB, input_name="input", output_name="embeddings", input_shape=(160, 160), classifier="svm", gpu_alloc=False, ): """Initializes FaceNet object :param model_path: path to model (...
def data_aug(xf): print('before aug', xf.shape) x1 = flip_aug(xf) x2 = pca_aug(xf) xf = np.concatenate((xf, x1, x2), axis=0) print('after aug', xf.shape) return xf def LR(x_train, y_train, x_test, y_test): clf = LogisticRegression() clf.fit(x_train, y_train) print(" <INFO> train ...
The code performs gender classification on facial images using augmented data. It loads images and labels, splits them into training/test sets, augments training data, extracts features via FaceHop, applies logistic regression (LR) and SVM on different feature subsets (all and hop2+hop3), and evaluates classification p...
def main(): #folder_path = dirname(getcwd()) folder_path = getcwd() lfwlabels = get_gender_label(folder_path) lfw_raw = get_image_array(folder_path) train_images, test_images, y, yt = train_test_split(lfw_raw, lfwlabels, test_size=0.2, stratify=lfwlabels) print(train_images.shape, y.shape) ...
def create_dict(): """Verkijg de input van de gebruiker. Open het bestand en kijk of de zoekterm in het bestand voorkomt. Maak een dictionary met de artikelen als key waar de zoektermen in voorkomen. De values in de dictionary bestaan uit de gevonden genen. :return: Dictionary met gevonden artikelen...
The main task of the code is to generate a results page displaying a table of findings. It calls helper functions to create a data dictionary, retrieve gene names, and construct a table. The final output renders an HTML template with the generated table, passing the results for display.
def result(): """Deze functie roept de functies aan. :return:De resultaten pagina met een tabel met alle resultaten. """ dict_result, zoekwoord, gen_or_disease = create_dict() gennamen = genpanel_inlezen() result_all = tabel(dict_result, zoekwoord, gennamen, gen_or_disease) return render_tem...
def generate_random_route(self): """ Generates a random route """ self.unvisit_all_cities() starting_city = self.cities[0] self.visit_city(starting_city) visited_cities = 1 random_route = np.empty(0) random_route = np.append(random_route, starting...
This code implements a genetic algorithm to solve a routing problem, likely the Traveling Salesman Problem. It initializes a population of random routes, iterates through generations by selecting parents, generating offspring, applying mutation, and retaining the best solution. The goal is to evolve an optimal route by...
def genetic(self, no_cromosome): """ docstring """ num_generations = 5000 self.no_of_variables = len(self.cities)+1 self.sol_per_pop = no_cromosome self.population_size = (self.sol_per_pop, self.no_of_variables) self.num_parents_mating = int(self.sol_per_p...
def generate_random_route(self): """ Generates a random route """ self.unvisit_all_cities() starting_city = self.cities[0] self.visit_city(starting_city) visited_cities = 1 random_route = np.empty(0) random_route = np.append(random_route, starting...
This code implements a simulated annealing algorithm to optimize two components—'route' and 'bag'—by iteratively modifying and evaluating their quality. It explores better solutions while allowing occasional worse moves based on temperature, gradually reducing temperature to converge toward optimal configurations. The ...
def simulated_annealing(self): temperature_origin = 1000000000000000000000000 temperature = 1000000000000000000000000 it = 0 stop = self.iteration random_route = self.generate_random_route() best_route = copy.copy(random_route) random_...
def read_excel(filepath): file_doc, extension = get_file(filepath) data = generate_data_from_excel(file_doc, extension, as_dict=True) return data def validate_excel_row(d): res = [] for i in ["pnr", "e_ticket", "passenger_name", "routing", "pax_name", "total_amount"]: if i not in d: res.append(i) return ","....
The main task of the code is to import ticket data from an Excel file, validate required fields, and create/update "ticket Entry" records in a system. It processes each row, handles e-ticket numbers, links to passengers/customers/suppliers, checks for existing entries, sets standard and custom fields, and tracks import...
def insert_tickets(filepath): data = read_excel(filepath) count = 0 for row in data: d = frappe._dict(row) unfilled_fields = validate_excel_row(d) if unfilled_fields: frappe.throw("Some Fields are Required in Excel File: "+unfilled_fields) count += 1 ticket_entry = frappe.get_doc({"doctype": "ticket Ent...
def docs_to_groups(documents): """ Creates groups of 'similar' files - files in the same directory from the same repository. :param documents: list of strings in the format 'repo//path@commit' :return: dictionary that stores 'repo//path/to/dir' and related indices of documents """ groups = defau...
This function processes document data by splitting repositories into training/test sets, creating data generators, and training a neural network model with specified architecture and hyperparameters to learn document representations.
def pipeline(data_loc, test_size=0.1, batch_size=512, val_batch_size=2000, samples_per_repo=4, seed=1989, hidden_sizes=[32, 64, 128], activation="relu", dropout_rate=0.1, optimizer="rmsprop", steps_per_epoch=1000, validation_steps=100, max_queue_size=10, workers=4, ep...
def serviceLookup(self,serviceName): """ Looks up pxGrid service information serviceName: Name of pxGrid service """ return(self.sendpxGridRequest('ServiceLookup',{'name':serviceName})) def getAccessSecret(self,peerNodeName): """ Retrieve Access Secret to communicate to a pxGrid node peerNodeName: Nam...
This function sends a POST request to a specified API endpoint on a service, using service configuration details to construct the URL and authenticate with a secret. It returns parsed JSON response data if the status code is 200, an empty dictionary for 204, or raises an exception for other status codes, including erro...
def sendpxGridAPI(self,serviceName,apiName,data={},**kwargs): serviceInfo=self.serviceLookup(serviceName) nodeName=serviceInfo['services'][0]['nodeName'] restBaseUrl=serviceInfo['services'][0]['properties']['restBaseUrl'] secret=self.getAccessSecret(nodeName) url="{}/{}".format(restBaseUrl,apiName) headers=...
def __checkMac(self,macAddress): """ Raise an exception if MAC Address is not valid """ if not self.__isValidMac(macAddress): raise Exception("Invalid MAC Address (must be HH:HH:HH:HH:HH:HH) {}".format(macAddress)) def __checkIP(self,ipAddress): """ Raise an exception if IP Address is not valid """ i...
This function retrieves ANC Policy assignments for an endpoint using its MAC Address and NAS-IP-Address by validating inputs and querying the pxGrid API. It checks MAC/IP validity, then sends a request to the 'getEndpointByNasIpAddress' API endpoint with the provided identifiers to fetch policy assignments.
def ancGetEndpointByNasIpAddress(self,macAddress,nasIpAddress): """ Retrieves endpoint to ANC Policy assignments based on MAC Address and NAS-IP-Address. This feature was added in 2.6P7 macAddress: Endpoint MAC Address nasIpAddress: Device IP Address """ self.__checkMac(macAddress) self.__checkIP(nasIpA...
def __checkMac(self,macAddress): """ Raise an exception if MAC Address is not valid """ if not self.__isValidMac(macAddress): raise Exception("Invalid MAC Address (must be HH:HH:HH:HH:HH:HH) {}".format(macAddress)) def __checkIP(self,ipAddress): """ Raise an exception if IP Address is not valid """ i...
This function applies an ANC (Automated Network Configuration) policy to an endpoint using its MAC address and NAS IP address, without requiring network connectivity. It validates the inputs and sends an API request to the pxGrid system to enforce the specified policy on the endpoint.
def ancApplyEndpointPolicy(self,policyName,macAddress,nasIpAddress): """ Apply ANC Policy by MAC Address and NAS-IP-Address. Endpoint does not need to be connected to the network. This feature was added in 2.6P7 policyName: Name of ANC Policy macAddress: MAC Address of endpoint nasIpAddress: Device IP Addr...
def __checkMac(self,macAddress): """ Raise an exception if MAC Address is not valid """ if not self.__isValidMac(macAddress): raise Exception("Invalid MAC Address (must be HH:HH:HH:HH:HH:HH) {}".format(macAddress)) def __checkIP(self,ipAddress): """ Raise an exception if IP Address is not valid """ i...
This function clears ANC (Advanced Network Control) policies from an endpoint device by sending a request to the pxGrid API, using the provided MAC address and NAS-IP address as identifiers. It first validates the inputs and then triggers the policy removal via the 'clearEndpointPolicy' API call.
def ancClearEndpointPolicy(self,macAddress,nasIpAddress): """ Clear ANC Policy from endpoint by MAC Address and NAS-IP-Address. This feature was added in 2.6P7 """ self.__checkMac(macAddress) self.__checkIP(nasIpAddress) return(self.sendpxGridAPI(pxGridServices.anc,'clearEndpointPolicy',{'macAddress':macAdd...
def print_help(self): """Print out a help message""" cmds = { "exit the program": ("exit", "quit", "stop", "q"), "print this text": ("help", "h"), "pull remote changes": ("get", "load", "pull"), "push local changes": ("post", "put", "push", "commit"), ...
The code defines a command-line interface (CLI) to manage and display a list of messages. It formats and prints user data with IDs, usernames, and messages, then processes user commands like 'exit', 'help', 'get', 'post', 'update', 'send', and 'edit' to control data retrieval, submission, synchronization, and message c...
def cli(self): ID_LEN = 6 USR_LEN = 16 MSG_LEN = 112 exit = False while not exit: print("-" * (USR_LEN + MSG_LEN)) print(f"ID{' ' * (ID_LEN - 2)}USER{' ' * (USR_LEN - 4)}MESSAGE{' ' * (MSG_LEN - 7)}") for c, item in enumerate(self.the_list): ...
def _most_common_label(self, y): counter = Counter(y) most_common = counter.most_common(1)[0][0] return most_common def _best_criteria(self, X, y, feat_idxs): """ This function determines the column and the column value that would give the highest information gain. "...
This function recursively builds a decision tree by selecting the best feature and threshold for splitting data based on information gain, creating left and right subtrees until stopping criteria (max depth, purity, or sample count) are met, then returning a node with the split details or a leaf node with the most comm...
def _grow_tree(self, X, y, depth=0): """ This is a recursive function which grows the tree. It iterates through all the columns and column values and performs classification based on the highest information gain. """ n_samples, n_features = X.shape n_labe...
def segment(data, max_time, sub_window_size, stride_size): sub_windows = np.arange(sub_window_size)[None, :] + np.arange(0, max_time, stride_size)[:, None] row, col = np.where(sub_windows >= max_time) uniq_row = len(np.unique(row)) if uniq_row > 0 and row[0] > 0: sub_window...
This code processes sensor and annotation data by cleaning, resampling, and segmenting time-series data into windows. It extracts features from physiological signals (EDA, BVP), Kinect joint angles, and raw sensor data, aligns segments with labels, and filters out invalid segments. The output includes segmented data, l...
def process(self, write_tfrecord=True): annotation = self.all_data[0] data = self.all_data[1] e4_data = self.all_data[-1] kp_data = self.all_data[-2] # sort data based on timestamp annotation.sort_values('unixtime') data.sort_values('unixtime') # drop du...
def _read(self): assert self.is_valid() with open(self.cache, "rb") as fobj: data = load(fobj) return data def is_valid_data(self, data): keys = {"called_by", "caller_args", "created_at", "usernames"} if keys != data.keys(): return False if data["...
This code updates a user's cached data status in a stored dataset. It validates input, reads existing data, updates the specified username's cached status, and saves the changes.
def set(self, username, cached_user_data): assert isinstance(cached_user_data, bool) data = self._read() assert self.is_valid_data(data) data["usernames"][username] = cached_user_data self._save(data)
def get_token_auth_header(): auth_header = request.headers.get('Authorization', None) if not auth_header: raise AuthError({ 'code': 'authorization_header_missing', 'description': 'Authorization header is expected.' }, 401) parts = auth_header.split() if parts[0]....
The code defines a wrapper function that authenticates requests by validating a JWT token, verifying its payload, and checking user permissions. If successful, it executes the original function; if an AuthError occurs, it returns a JSON error response with details.
def wrapper(*args, **kwargs): try: token = get_token_auth_header() payload = verify_decode_jwt(token) check_permissions(permission, payload) #return f(payload, *args, **kwargs) return f(*args, **kwargs) except AuthEr...
def is_carmichael_number(n: int): # O(n^2) x = 2 while x < n: if gcd(x, n) == 1: if pow(x, n-1, n) != 1: return False x = x + 1 return True def gcd(a: int, b: int) -> int: """ Time Complexity: O(log a * b) in bits Space Complexity: needs O(a * b) for ...
The function performs the Fermat primality test with k iterations to determine if a number N is prime, composite, or a Carmichael number. It checks edge cases first (e.g., even numbers, small primes) and uses modular exponentiation to verify if a randomly chosen base a satisfies a^(N-1) ≡ 1 mod N. If any test fails, it...
def fermat(N: int, k: int) -> str: """ Time Complexity: O(n^2) + k * (O(log n) + O(log n * a) + O(n^2) == O(n^2) Space Complexity: O(k + N + a) """ if N == 2: # O(1) return 'prime' # 0, 1, and even numbers are composite if not N & 1 or N <= 1: # O(1) return 'composite' ...
def print_board(board): for row in board: print(" | ".join(row)) print("-" * 9) def check_winner(board): # Check rows, columns, and diagonals for a winner for i in range(3): if board[i][0] == board[i][1] == board[i][2] != ' ': return board[i][0] # Winner in a row ...
This code implements a Tic-Tac-Toe game where a human player (X) competes against an AI (O). The game initializes a 3x3 board, alternates turns, checks for wins/ties after each move, and uses the `best_move` function for AI strategy. It prints the board state and declares outcomes like "You win!", "AI wins!", or "It's ...
def play(): board = [[' ' for _ in range(3)] for _ in range(3)] while True: print_board(board) # Human player move row = int(input("Enter the row (0, 1, or 2): ")) col = int(input("Enter the column (0, 1, or 2): ")) if board[row][col] == ' ': board[row][col]...
def prepare_device_lists(self): # Opening files and filling "local" device lists self.trusted_devices = File_Handler.load_trusted_file() self.suspicious_devices = File_Handler.load_suspicious_file() # Clear 'Found' lists for new scan self.found_trusted = [] self.found_sus...
The main task of the code is to perform a network scan using Nmap to detect available hosts, categorize them as trusted or suspicious based on predefined lists, update the UI with scan results, save updated device lists to files, and send an email notification with scan outcomes. It handles errors, manages UI elements ...
def scan_button(self): # Setting initial parameters self.prepare_device_lists() # Clear Device Frame for new scan results to be added for child in self.device_frame.winfo_children(): child.destroy() self.root.update() self.progress_bar['value'] = 5 # Upda...
def _build_forward(self): config = self.config N, M, JX, JQ, VW, VC, d, W = \ config.batch_size, config.max_num_sents, config.max_sent_size, \ config.max_ques_size, config.word_vocab_size, config.char_vocab_size, config.hidden_size, \ config.max_word_size JX = tf.shape(self.x)[2] ...
This code initializes a TensorFlow model by setting up placeholders for input data, defining necessary variables like global step, and building forward computation and loss functions. It prepares the model for training or evaluation by initializing components such as variable EMA and merging summaries.
def __init__(self, config, scope, rep=True): self.scope = scope self.config = config self.global_step = tf.get_variable( 'global_step', shape=[], dtype='int32', initializer=tf.constant_initializer(0), trainable=False) # Define forward inputs here N, M, JX, JQ...
def countCommonEdges(): pictures, numberCommonEdges = parseAllPictures(), {} for picId, picture in pictures.items(): allEdges, edgeList = getAllOtherEdges(pictures, picId), getPotentialEdges(picture) numberCommonEdges[picId] = sum([edge in allEdges or edge[::-1] in allEdges for edge in edgeList]...
The code processes images to detect and mark a snake's head, body, and tail using regex patterns and specific indices. It replaces detected parts with 'O's, then calculates the total number of '#' symbols remaining in the final image, likely representing water roughness.
def getWaterRoughness(): pictures, numberCommonEdges = countCommonEdges() pictureMap, orientedPictures = buildImage(pictures, numberCommonEdges, 0) for picId, picture in orientedPictures.items(): orientedPictures[picId] = removeBorder(picture) body = re.compile("#[#.]{4}##[#.]{4}##[#.]{4}###") ...
def straightPath(self): # Creates first path block which others build from. self.my_Path = Path(self, 175, 200) # After each object is created, it is added to the path group and the # all sprites group in order to facilitate detecting collisions, # and so that they can be drawn e...
This function initializes a new game by setting up player characters, collectable items, path elements, and collision detection systems. It creates sprite groups, initializes scores, spawns randomized paths with collectables, and prepares the game environment for execution.
def new_game(self): #self.play_Smusic() #Plays the shuffled song self.score = 0 self.flip_score = 0 self.degs = 0 self.insx = 180 #Instructions appear each round # Create a sprite group of all sprites self.all_sprites_group = pygame.sprite.Group() #...
def bfs_search(src, target, visited_states): q = Queue() q.put((src, 0)) while not q.empty(): curr, g = q.get() if target == curr: return visited_states visited_states.append(curr) adj = possible_moves(curr, visited_states) scores = [] selected_moves = [] ...
The code solves a problem by finding a path from a source state to a target state using either BFS or another search algorithm, then prints each step of the solution path along with the target state.
def solve(src, target, bfs=True): visited_states = [] if bfs: res = bfs_search(src, target, visited_states) else: res = search(src, target, visited_states, 0) if res: i = 0 for state in res: print('move :', i + 1, end="\n") print() dis...
def _filter_aips(self, aips): """Return only original AIPs (no replicas) with status UPLOADED.""" return [ aip for aip in aips if aip["status"] == "UPLOADED" and aip["replicated_package"] is None ] def check_if_aip_in_database(self, uuid): """Check if ...
The code downloads METS files for Archival Information Packages (AIPs) from a storage service, optionally filtering to only those with replicas. It checks if each AIP is already in a database, skips existing entries, and downloads/records new ones, logging errors if downloads fail.
def download_all_mets_files(self, with_replicas_only=False): am = AMClient( ss_url=self.storage_service_url, ss_user_name=self.storage_service_username, ss_api_key=self.storage_service_api_key, ) aips = self._filter_aips(am.aips()) for aip in aips: ...
def generateNearPosition(parent, max_lat, max_lng): lat = parent[0]+max_lat*(random()*2-1) while lat > 90: lat -= 90 while lat < -90: lat += 90 lng = parent[1]+max_lng*(random()*2-1) while lng > 180: lng -= 180 while lng < -180: lng += 180 return [lat, lng] def isInLand(pos, cellsi...
The main task of the code is to iteratively find the optimal land-based barycenter (center of mass) for a set of coordinates by generating random positions near a starting point, validating they lie on land, and refining the search area over iterations to minimize a cost function. It returns the best position and a tra...
def findLandBarycenter(coordinate_list, barycenter): if len(coordinate_list) == 1: return coordinate_list[0] bary_trace = [] # list of list of all valid random positions at each iteration #TODO : Three constant to fine tune k = 50 iterations = 50 multiplier = 1.2 retry = 5 span_lat_max = 90 ...
def uint8_to_bit_string(uint8_array): return ''.join(format(byte, '08b') for byte in uint8_array) def HuffmanEncoding(input_array, steps): symbolWithProbs = CalculateProbability(input_array, steps) the_symbols = symbolWithProbs.keys() the_probabilities = symbolWithProbs.values() the_nodes = [] ...
The code performs Huffman compression and decompression on a raw image file. It reads an 8-bit image, converts it to a bitstring, encodes it using Huffman coding with 8 steps, saves the compressed data, then decompresses it using the same Huffman tree, writing the result to a new raw file. Finally, it checks if the dec...
def main(): steps = 8 input_image_path = "2_img_.raw" compressed_path = "2_img_compressed_huffman1.bin" decompressed_path = "2_img_decompressed_huffman1.raw" # Read Image as uint8 image_samples = np.fromfile(input_image_path, dtype='uint8') input_bit_string = uint8_to_bit_string(image_samp...
def get_request_re(url, params): logging.info('Running GET Request from RE function') # Request Headers for Blackbaud API request headers = { # Request headers 'Bb-Api-Subscription-Key': RE_API_KEY, 'Authorization': 'Bearer ' + retrieve_token(), } re_api_response = http.get...
This function updates a constituent's phone number in a system by checking if the provided phone number exists in the database. If it exists, it marks it as primary; if not, it adds the new number as primary. It also updates related tags for synchronization and verification.
def update_phones(df, const_id): logging.info('Proceeding to update phone') phone = df['contactno'] if phone: # Get Phone numbers present in RE url = f'https://api.sky.blackbaud.com/constituent/v1/constituents/{const_id}/phones' params = {} api_response = get_request_re(u...
def get_request_re(url, params): logging.info('Running GET Request from RE function') # Request Headers for Blackbaud API request headers = { # Request headers 'Bb-Api-Subscription-Key': RE_API_KEY, 'Authorization': 'Bearer ' + retrieve_token(), } re_api_response = http.get...
This function updates or adds a constituent's education details in the Blackbaud system based on provided DataFrame data. It checks existing records via API, matches IIT Bombay entries, and updates/patches fields like class_of, department, and hostel if valid. If discrepancies exist (e.g., conflicting data or multiple ...
def update_education(df, const_id): logging.info('Proceeding to update Education') class_of = df['batch'] department = df['dept'] hostel = df['hostel'] if class_of != '' or department != '' or hostel != '': # Get education present in RE url = f'https://api.sky.blackbaud.com/constit...
def get_request_re(url, params): logging.info('Running GET Request from RE function') # Request Headers for Blackbaud API request headers = { # Request headers 'Bb-Api-Subscription-Key': RE_API_KEY, 'Authorization': 'Bearer ' + retrieve_token(), } re_api_response = http.get...
The code updates a constituent's address in a system (RE) by either modifying an existing address (if a match is found via fuzzy logic) or creating a new one using geocoding. It constructs a cleaned address string from input data, checks against existing RE addresses, and, if no match exists, uses Nominatim to geocode ...
def update_address(df, const_id): logging.info('Proceeding to update address') new_address = str(df['address1']) + ' ' + str(df['address2']) + ' ' + str(df['city']) + ' ' + str(df['state']) + ' ' + str(df['country']) + ' ' + str(df['zipcode']) new_address = new_address.replace(';', ' ').replace('\r\n', ' ...
def get_request_re(url, params): logging.info('Running GET Request from RE function') # Request Headers for Blackbaud API request headers = { # Request headers 'Bb-Api-Subscription-Key': RE_API_KEY, 'Authorization': 'Bearer ' + retrieve_token(), } re_api_response = http.get...
The code updates a constituent's email address in Raisers Edge, ensuring the provided email is set as primary if it exists, or creating a new primary email if it doesn't. It then adds "Sync source" and "Verified Email" tags for tracking.
def update_email(email, const_id): logging.info('Updating email address') # Check whether email exists in Raisers Edge url = f'https://api.sky.blackbaud.com/constituent/v1/constituents/{const_id}/emailaddresses' params = {} api_response = get_request_re(url, params) if email.lower() in [x['ad...
def get_gender(name): loaded_model = load_model() try: name = name.lower() except: name = name.casefold() # Normalize the name to remove diacritic marks and special characters name = unicodedata.normalize('NFKD', name).encode('ASCII', 'ignore').decode('utf-8') name = prepare_e...
The code creates a constituent (individual or organization) in a system via API based on donor data. It parses names, determines gender, and sets parameters for individuals, or uses company names for organizations. It sends POST requests to create the constituent, assigns a code, and notifies of the new record.
def create_constituent(df): logging.info('Creating a new constituent') # Verify whether the donor is Individual or Organisation affiliation = df['affilation'] company_name = df['companyname'] name = df['name'] if pd.isnull(company_name) and affiliation not in ['Foundation', 'Corporate Non CSR'...
def pagination_api_request(url, params): logging.info('Paginating API requests') # Housekeeping housekeeping() # Pagination request to retreive list while url: # Blackbaud API GET request re_api_response = get_request_re(url, params) # Incremental File name i = 1 ...
The main task of the code is to download email addresses from an API endpoint, process the data into a structured DataFrame by selecting specific columns, and store the filtered data into a database table named 'constituent_list'. The function handles API pagination, data transformation, and persistent storage of const...
def get_emails(): logging.info('Downloading emails from RE') url = 'https://api.sky.blackbaud.com/constituent/v1/emailaddresses?limit=5000' pagination_api_request(url, {}) email_df = load_from_JSON_to_DB() email_df = email_df[['constituent_id', 'address']].copy() load_to_db(email_df, 'constitu...
def pagination_api_request(url, params): logging.info('Paginating API requests') # Housekeeping housekeeping() # Pagination request to retreive list while url: # Blackbaud API GET request re_api_response = get_request_re(url, params) # Incremental File name i = 1 ...
The main task of the code is to download constituent phone data from an API, process it into a structured DataFrame by selecting specific columns, and load the filtered data into a database table named 'constituent_list'. The function handles pagination, data extraction, and database insertion for phone records.
def get_phones(): logging.info('Downloading phones from RE') url = 'https://api.sky.blackbaud.com/constituent/v1/phones?limit=5000' pagination_api_request(url, {}) phone_df = load_from_JSON_to_DB() phone_df = phone_df[['constituent_id', 'number']].copy() load_to_db(phone_df, 'constituent_list'...
def pagination_api_request(url, params): logging.info('Paginating API requests') # Housekeeping housekeeping() # Pagination request to retreive list while url: # Blackbaud API GET request re_api_response = get_request_re(url, params) # Incremental File name i = 1 ...
The function downloads a list of campaigns from the Raisers Edge API, processes the JSON response into a structured DataFrame, selects specific columns ('campaign_id', 'description', 'id'), and loads the filtered data into a database table named 'campaign_list' for storage and further analysis.
def get_campaign_list(): logging.info('Downloading Campaign list from Raisers Edge') # Get Campaign List url = 'https://api.sky.blackbaud.com/nxt-data-integration/v1/re/campaigns?limit=5000' params = {} pagination_api_request(url, params) campaign_df = load_from_JSON_to_DB() campaign_df = ...
def pagination_api_request(url, params): logging.info('Paginating API requests') # Housekeeping housekeeping() # Pagination request to retreive list while url: # Blackbaud API GET request re_api_response = get_request_re(url, params) # Incremental File name i = 1 ...
The main task of the code is to download constituent data from the Raisers Edge API, process it into a structured format (DataFrame), and store it in a database table named 'valid_constituents'. It retrieves data via paginated API requests, extracts constituent IDs, and persists the results for further analysis or use.
def get_constituents(): logging.info('Downloading constituents from Raisers Edge') # Get Constituent list url = f'https://api.sky.blackbaud.com/constituent/v1/constituents?list_id={CONSTITUENT_LIST}&fields=id&limit=5000' params = {} pagination_api_request(url, params) constituent_df = load_fro...