dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def check_complete(self, Final_table): Arr = [] for i in range(len(Final_table)): ### We put in an array where the is no transition if the array is null it's complete for j in range(len(Final_table[i])): if len(Final_table[i][j]) == 0 or Final_table[i][j] ==[""]: ...
This code completes a deterministic finite automaton (DFA) by adding a new sink state 'p' to handle missing transitions. It identifies empty cells in the transition table, fills them with 'p', appends a new row/column for the sink state, populates its transitions with 'p' for all symbols, and returns the updated DataFr...
def completion_synchronous(self, NameFile, incomplete_table, all_states): empty = self.check_complete(incomplete_table) for i in range(len(empty)): coord = empty[i] incomplete_table[coord[0]][coord[1]] = "p" incomplete_table.append([]) symbols = self.nb_symbols_to...
def get_cometqe_scores(hyps, srcs, commodel): cometqe_input = [{"src": src, "mt": mt} for src, mt in zip(srcs, hyps)] # sentence-level and corpus-level COMET outputs = commodel.predict( cometqe_input, batch_size=8, progress_bar=True ) torch.cuda.empty_cache() return outputs def get_comst...
The function `get_scores_auto` computes quality scores for generated hypotheses (`hyps`) using different models based on the `sco` parameter. It supports CometQE, Comet, and Comstyle models, or post-hoc rescoring. It loads the appropriate model, evaluates scores, tracks computation time, and returns the scores. The tas...
def get_scores_auto(hyps, srcs, refs, sco="cqe", dset = "", device="cuda:1"): totaltime = -1 # comet qe if sco=='cqe': cometqe_path = download_model(cometqe_model, cometqe_dir) model = load_from_checkpoint(cometqe_path).to(device) model.eval() starttime = time.time() ...
def _get_arguments() -> argparse.Namespace: """Reads command-line arguments Returns: argparse.Namespace: command-line arguments """ print("Getting input args", flush=True) parser = argparse.ArgumentParser() parser.add_argument( "--config", required=True, type=s...
The main task of the code is to initialize and execute a configurable process by parsing command-line arguments, loading a JSON configuration file, converting it into a structured configuration object, constructing a runtime agent, and triggering the execution of the configured run.
def main() -> None: print("Starting main", flush=True) # Get command line arguments args = _get_arguments() # Read configuration file config_json = _read_json_file(args.config) # Create envelope of configuration config = from_dict(data_class=ConfigurationEnvelope, data=config_json) #...
def isLeaf(tree): text, left, right = tree if left is None and right is None: return True else: return False def playleaf(tree): text, left, right = tree text = ast.literal_eval(text) answer = yes(f"Is it {text['name']}?") if(answer == True): print('I got it!') ...
The function plays a game using a decision tree, recursively navigating left or right based on yes/no answers to the current node's question. It returns a modified tree with updated subtrees reflecting the game's outcome, learning from each response to refine future decisions.
def play(tree): """plays the game once by using the tree to guide its questions. However. Returns a new tree that is the result of playing the game on the original tree and learning from the answer""" text, left, right = tree if isLeaf(tree): return playleaf(tree) elif yes(text): ...
def isLeaf(tree): text, left, right = tree if left is None and right is None: return True else: return False def playleaf(tree): text, left, right = tree text = ast.literal_eval(text) print(f"The recommendation for you is {text['name']}\n") answer = yes('Do you want more in...
The function `play(tree)` simulates a game by recursively traversing a tree structure based on user responses. It updates the tree by modifying subtrees (left or right) depending on whether the current node's text is confirmed as "yes" or not. If the node is a leaf, it processes the leaf node. The function returns a ne...
def play(tree): """plays the game once by using the tree to guide its questions. However. Returns a new tree that is the result of playing the game on the original tree and learning from the answer""" text, left, right = tree if isLeaf(tree): return playleaf(tree) elif yes(text): ...
def yes(prompt): answer = input(prompt).lower() if(answer == 'yes'or answer == 'y'or answer == 'yup'or answer == 'sure'): return True elif (answer == 'no'or answer == 'n'or answer == 'nah'or answer == 'nope'): return False else: return yes("Please enter 'yes' or 'no': ") def load...
The main task of the code is to run a 20 Questions game engine, allowing users to load or create a decision tree, play the game repeatedly, and save the tree for future use. It handles user input for game options, tree loading/saving, and game loop execution with yes/no prompts for continuing play or saving progress.
def main(): """Main Function for 20 Questions""" # Write the "main" function for 20 Questions here. Although # main() is traditionally placed at the top of a file, it is the # last function you will write. print('Welcome to My Game Engine!\n') option = input('Which option do you want ? \n1. Gam...
def loadTree(treeFile): lines = treeFile.readlines() lines = [line.strip() for line in lines] return load(lines)[0] def play(tree): """plays the game once by using the tree to guide its questions. However. Returns a new tree that is the result of playing the game on the original tree and learning...
The code implements a simple game engine with two options: Game Search and Game Recommendation. If the user selects Game Recommendation, it loads a decision tree from a file, repeatedly plays the game using the tree, and asks if the user wants to continue. The loop ends when the user declines, then exits with a farewel...
def main(): print('Welcome to My Game Engine!\n') option = input('Which option do you want ? \n1. Game Search\n2. Game Recommendation\n') if(option == '1'): search() elif(option == '2'): filename = 'tree.txt' treeFile = open(filename, 'r') tree = loadTree(treeFile) ...
def fetch_and_write_txt_data(folder_name, filename, url): response = requests.get(url) if response.status_code == 200: # Call function to save content write_txt_file(folder_name, filename, response.text) print(f"Text data saved to {filename}") else: print(f"Failed to fetch ...
The main task of the code is to fetch data from specified URLs (text, CSV, Excel, JSON), save them into designated folders with specific filenames, and process each file to generate result files. It demonstrates data handling by downloading, storing, and analyzing different data formats, then outputting processed resul...
def main(): ''' Main function to demonstrate module capabilities. ''' print(f"Name: {'datafun-03-analytics-Nolan Moss'}\n") # Url variables txt_url = 'https://www.gutenberg.org/cache/epub/6130/pg6130.txt' csv_url = 'https://raw.githubusercontent.com/MainakRepositor/Datasets/master/Weather%20Da...
def ready(self, n_steps, dt, lims=None): self.propagate(n_steps, dt) self.set_grid(lims) self.assign_pts() def compute_pd(self): """ Description: Computes probability in each box in the grid """ coords = np.genfromtxt('{}/coordinates.csv'.format(self.save_folder),...
The main task of the code is to compute d-dimensional, 2D, and 1D probability densities using the Euler-Maruyama method. It initializes parameters with `ready()`, calculates the full density with `compute_pd()`, and iteratively computes marginal (1D) and pairwise (2D) densities across all dimensions via nested loops.
def compute_all(self, n_steps, dt, lims=None): """ Description: Computes all d, 2 and 1 dimensional densities Args: n_steps: number of steps in Euler-Maruyama dt: time-step in Euler-Maruyama """ self.ready(n_steps, dt, lims=None) self.compute_pd()...
def bestMove(currentPlayer): if(isMaximizingPlayer(currentPlayer)): bestScore = -math.inf; #As Best score should be maximum for maximizing player isMaximizing = True; else: bestScore = math.inf; # As Best score should be minimum for minimizing player isMaximizing = False; ...
The code implements a Tic-Tac-Toe game where the player ('0') competes against a CPU ('X'). It randomly selects the starting player, alternates turns, validates user input, and uses a bestMove function for CPU decisions. The game checks for a winner after each move and declares a tie if the board fills without a winner...
def play(): print("Welcome! You are '0' and CPU is 'X'") currentPlayer = random.choice([0,1]); #Choose random first player if(currentPlayer == 0): print("CPU goes first"); else: print("You go first"); for i in range(9): if (currentPlayer == 0): # CPU will play ...
def updateBoard(): """ This function updates the GUI of board """ #Drawing the initial board positions; for y in range(1, n+1): #1,2,3 for x in range(1, n+1): val = positions[y][x]; colorNode((x,y), numColors[val]) label = Text(Point((x-0.5)*grid_side, (y-0.5)*grid_side)...
The main task of the code is to update the game board, calculate and print the heuristic value of the current position, execute the AI's move logic, and display available movement options. The commented-out lines suggest additional diagnostic outputs for move analysis, but the core functionality focuses on board state ...
def main(): updateBoard(); print(heuristicValueOfPosition(positions)) ai(); #print(findPlacesToMove()); #print(findNextMove(1)) print(findPlacesToMove());
def hValPoint(node): return (abs(node[0] - endPoint[0]) + abs(node[1] - endPoint[1])) def openHeapChangePriority(i, p): global openMinHeap; oldP = openMinHeap[i]; openMinHeap[i] = p; #new value if(p < oldP): openHeanSiftUp(i); else: openHeapSiftDown(i);
This function updates a node's parent and path cost in a pathfinding algorithm (likely A*), adjusts its priority in the open heap if a cheaper path is found, and recursively propagates these changes to its neighbors. It ensures optimal paths by revising g-values and f-values (g + h), reordering the open heap, and updat...
def updateSuccessor(node, parentOfNode, nodeGVal): global openMinHeap; global openHeapSize; global openNodesListHeap; global closedNodesList; global closedNodesVals; global parent global gValue; global fValue; global nodeVisit; if nodeVisit[node[0]][node[1]] == False: return; ...
def hValPoint(node): return (abs(node[0] - endPoint[0]) + abs(node[1] - endPoint[1])) def openHeapInsert(node, val): global openMinHeap; global openHeapSize; global openNodesListHeap; openHeapSize += 1; if(len(openMinHeap) > openHeapSize): #i.e. Arrat size is bigger than no. of elements in it ...
This function implements Best-First Search using Manhattan distance as the heuristic to navigate a grid. It maintains open (priority queue) and closed lists to track nodes, updates node costs when better paths are found, and visualizes the search process by coloring nodes and displaying f-values. The algorithm extracts...
def explore_BestFirstSearch(): """ Our Heuristic will be manhattan distance """ global path; global openMinHeap; global openHeapSize; global openNodesListHeap; global closedNodesList; global closedNodesVals; global startPoint; global endPoint; global parent global gValue; ...
def initializeGame(): """ This function initializes the board with walls and place the pacman at start and marks the end position. """ #Coloring the background black win.setBackground(color_rgb(0,0,0)); for i in range(1,11): for j in range(1,11): center = Point((i-0.5)*grid_side,(...
The code initializes a game, constructs an adjacency dictionary for a graph, performs best-first search for pathfinding, retrieves the path via backtracking, moves Pac-Man, and waits for a mouse click to close the window. The main task is to execute a Pac-Man-style pathfinding simulation using best-first search and vis...
def main(): initializeGame(); createAdjencyDict(); #explore(startPoint); explore_BestFirstSearch() getPathBacktracking(); #scolorPathBlack() movePackMan(); #getMounse() + close(): It wait untilsomeone clicks and doing so closes it win.getMouse(); win.close();
def get_valid_moves(self): valid_moves = [] player = self.current_player opponent = -player for i in range(self.board_size): for j in range(self.board_size): if self.board[i][j] == 0: for direction in [(0, 1), (1, 0), (0, -1), (-1, 0), (1...
This function simulates a random game playout by repeatedly selecting random valid moves until the game ends. It handles scenarios where players have no moves by switching turns. Finally, it returns a score of 1, -1, or 0 based on the winner (BLACK, WHITE, or draw).
def simulate_random_playout(self): current_player = self.current_player temp_board = np.copy(self.board) while not self.done: valid_moves = self.get_valid_moves() if not valid_moves: self.current_player = -self.current_player valid_moves ...
def next(self): self.curr_idx += 1 if self.curr_idx < len(self.tokens): self.curr = self.tokens[self.curr_idx] def power(self): return self.bin_op(self.atom, [TOKEN_POWER], self.factor)
This function parses a factor, which is a number with an optional leading plus/minus sign, and returns its abstract syntax tree (AST) node representation. It handles unary operators by recursively parsing the factor and wrapping it in a UnaryOpNode if a '+' or '-' token is present. If no sign is found, it delegates to ...
def factor(self): """ Return a node representation of a factor. A factor is a number with plus or minus sign. """ promise = ParserPromise() token = self.curr # Additional (plus/minus) in front of a factor is # also considered to be a part of the factor. ...
def loop_event(self): for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: self.running = False elif event.type == QUIT: self.running = False return self.running def draw_open_bg(self): py...
This code defines a game loop managing game states, rendering visuals, handling events, and controlling game flow. It checks for enemy creation, level progression, and game over conditions, updating the display at 60 FPS. The loop transitions between opening screen, active gameplay, and end-game states, with logic for ...
def run(self): """Game loop""" global LAST_ENEMY_ENTER, next_level, leve_difficulty, level, target_difficulty, level_reset_time, \ next_level_font_30, next_level_font_60, WITH clock = pygame.time.Clock() FPS = 60 while self.running: self.loop_event() ...
def create_error_label(self): self.download_btn.hide() self.error_label.move(150, 30) self.error_label.resize(500, 70) self.error_label.setText('There was an error retrieving the data\nPlease try again') self.error_label.setAlignment(Qt.AlignCenter) self.error_label.setSt...
The submit function retrieves country-specific data, handles network errors, and updates the UI with the latest information. It clears input, processes JSON responses, displays error messages if data is invalid, and shows info/delete/download buttons upon success.
def submit(self): self.download_label.hide() country = self.input_country.text() self.input_country.setText('') try: response = get_data(country) except requests.exceptions.RequestException: print('Check your Internet connection!') response = ...
def _health_check(self): if not self._base_url: raise ValueError("base_url is empty") if not validators.hostname(self._base_url) and not validators.url( self._base_url ): raise ValueError(f"base_url {self._base_url} is not valid") def bucket_exists(self, bucke...
The main task of the code is to simulate uploading a file from the local file system to a specified bucket in a mock Minio server. It verifies bucket existence, reads the file's binary data, and invokes `put_object` with parameters like file content, size, content type, metadata, and encryption settings to complete the...
def fput_object( self, bucket_name: str, object_name: str, file_path: str, content_type: str = "application/octet-stream", metadata=None, sse=None, progress=None, part_size: int = 0, # num_parallel_uploads: int = 3, # tags = None, ...
def extract_name_from_port_name(port_name): chars = port_name.split("/") name = chars[len(chars) - 1] return name def __set_lines_per_rotation(self, lines_per_rotation): message = rhino.LINES_PER_ROTATION_MESSAGE message[rhino.DATA_INDEX] = lines_per_rotation self.__write...
The code initializes a Modbus instrument for a motor controller, configuring serial communication parameters (baud rate, parity, etc.), setting timeouts, and initializing motor settings like acceleration, speed, and encoder lines per rotation. It also sets default states for rotation direction, enables braking, and pos...
def __init__(self, port_name, slave_address): # Parameters self.__instrument = modbus.Instrument(port_name, slave_address, modbus.MODE_ASCII) self.__instrument.serial.baudrate = 9600 self.__instrument.serial.parity = modbus.serial.PARITY_NONE self.__instrument.bytesize = 8 ...
def total_accidentals( components: List[Component], ds=0.05, dt=0.0001 ) -> float: prompt = 0. delayed = 0. for comp in components: prompt += comp.total_singles delayed += comp.del_singles total = prompt * delayed * ds * dt return total * 60 * 60 * 24 def maxbg( signa...
The function adjusts component activities based on background and total accidentals, revising isotopic activities and returning new Component instances with updated parameters. It calculates background shares, revises activities, and constructs modified components, handling edge cases like missing inputs or unimplement...
def budget( components: List[Component], signal: float, t3sigma: float, params: namedtuple, totacc: float = 0, mbg: float = 0, method='e', update: bool = False ) -> List[Component]: revcomponents = [] if not totacc: totacc = total_accidenta...
def randomCoord(): xCoord = random.randrange(leftBorder, rightBorder) yCoord = random.randrange(topBorder, bottomBorder) return [xCoord, yCoord] def mutate(children, cCoords): #I coded the random towers in a stupid way and I don't want to change it now so this is what we've got towers = ["dartMonkey...
The function creates offspring monkeys by combining genes from the top two performing parents (based on scores), using crossover strategies like alternating genes and splitting parent elements. It introduces mutations, adds random towers for diversity, verifies child validity, and returns the new generation of monkeys ...
def createChildren(monkeys, coords, score): sorted = [] sorted.append(score[0]) #this is stupid but I have to do it like this because sorted = score passes it by value and sorts score which I don't want sorted.append(score[1]) sorted.append(score[2]) sorted.append(score[3]) sorted.append(score[4...
def randomCoord(): xCoord = random.randrange(leftBorder, rightBorder) yCoord = random.randrange(topBorder, bottomBorder) return [xCoord, yCoord] def mutate(children, cCoords): #I coded the random towers in a stupid way and I don't want to change it now so this is what we've got towers = ["dartMonkey...
The code creates children monkeys by selecting top-performing parents based on scores, performing crossover (alternating genes), mutation, and preserving the top scorer. It generates seven offspring through genetic recombination, verifies their coordinates, and returns the new generations for further evolution in a gen...
def createChildren(monkeys, coords, score): sortedScore = [] sortedScore.append(score[0]) #this is stupid but I have to do it like this because sorted = score passes it by value and sorts score which I don't want sortedScore.append(score[1]) sortedScore.append(score[2]) sortedScore.append(score[3]) ...
def generate_result_struct(interface_name, method_name, output_params): # Do we actually need a structure? if not syscall_stub_gen.is_result_struct_required(output_params): return None # Generate the structure: # # #[repr(C)] # #[derive(Debug, Clone, Copy, PartialEq, Eq)] # pu...
The code generates Rust function stubs for system call interfaces, handling parameter marshaling, IPC calls, and result unmarshaling. It constructs a function with inline comments, parameter setup, message register configuration, capability handling, and output processing based on architecture, word size, and specified...
def generate_stub(arch, wordsize, interface_name, method_name, method_id, input_params, output_params, structs, use_only_ipc_buffer, comment, mcs): result = [] if use_only_ipc_buffer: num_mrs = 0 else: if mcs and "%s-mcs" % arch in syscall_stub_gen.MESSAGE_REGISTERS_FOR_ARCH: nu...
def section_break(original_resume_text: str) -> list[str]: pattern = r'\b[A-Z]+\b' # find all the words that are fully uppercased res = list(re.finditer(pattern, original_resume_text)) # find only those uppercased words that are also NOUN res = [x for x in res if nlp(x.group())[0].pos_ == 'NOUN'] ...
The function identifies the experience level for each skill in a resume by analyzing sections, extracting skills, and mapping them to the maximum years of experience, defaulting to 1 if unspecified, then returning a sorted dictionary of skills with their experience levels in descending order.
def skills_experience_level_identification(resume: str, skills_api: set, clean: bool=True) -> dict: res = {} # break down resume string into sections sections = section_break(resume) for section in sections: date_list = date_search(section) experience_sec = experience_tagging(date_list)...
def extract_skills(resume_text: str, skills_api: pickle, clean: bool=True) -> set: if clean == True: resume_text = preprocess(resume_text) # create a set of skills in lowercase from the resume skillset = set([i for i in set([i.lower() for i in generate_list_of_skills(resume_text)])]) # find...
The code processes a DataFrame to extract significant skills from text data using an API, maps each entry's ID to its identified skills, and returns a dictionary of these significant skills.
def create_skills_required_dictionary(df: pd.DataFrame, skills_api: set,clean: bool=True) -> dict: df["Skills"] = df["Text"].apply(lambda x: extract_skills(x,skills_api,clean)) skills_dic = {} for index, row in df.iterrows(): skills_dic[row.ID] = row.Skills table = get_significance_table(df,skil...
def section_break(original_resume_text): pattern = r'\b[A-Z]+\b' # find all the words that are fully uppercased res = list(re.finditer(pattern, original_resume_text)) # find only those uppercased words that are also NOUN res = [x for x in res if nlp(x.group())[0].pos_ == 'NOUN'] ans = [] ...
The main task of the code is to identify and assign experience levels to skills mentioned in a resume. It processes resume sections, extracts skills using an API, maps each skill to its corresponding experience level (from dates), assigns default levels for untagged skills, and returns a sorted dictionary of skills by ...
def skills_experience_level_identification(resume, skills_api, clean=True): res = {} sections = section_break(resume) for section in sections: date_list = date_search(section) experience_sec = experience_tagging(date_list) for key in experience_sec: for start, end in exp...
def skills_experience_level_identification(resume: str, skills_api: set, clean: bool=True) -> dict: res = {} # break down resume string into sections sections = section_break(resume) for section in sections: date_list = date_search(section) experience_sec = experience_tagging(date_list)...
The function identifies skill gaps in a candidate's resume compared to industry and job-specific requirements, then recommends courses (categorized by competency levels) to address these gaps. It uses a doc2vec model to match course descriptions with required skills, providing tailored suggestions for both job readines...
def final_course_suggestion_d2v(resume_text: str, peer_industry: str, job_name: str, skills_api: set, resume_skills_required_pickle: dict, job_skills_required_pickle: dict, ...
def skills_experience_level_identification(resume: str, skills_api: set, clean: bool=True) -> dict: res = {} # break down resume string into sections sections = section_break(resume) for section in sections: date_list = date_search(section) experience_sec = experience_tagging(date_list)...
The function identifies skill gaps in a resume relative to industry standards and job-specific requirements, then recommends courses (categorized by competency levels) to address these gaps. It uses a Spacy model to match course descriptions with required skills, providing tailored suggestions for both job readiness an...
def final_course_suggestion_spacy(resume_text: str, peer_industry: str, job_name: str, skills_api: set, resume_skills_required_pickle: dict, job_skills_required_pickle: dict, ...
def get_mission_xml(self, summary): ''' Build an XML mission string.''' spawn_end_tag = ' type="mob_spawner" variant="' + MalmoSim.MOB_TYPE + '"/>' return '''<?xml version="1.0" encoding="UTF-8" ?> <Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Abou...
The main task of the code is to run multiple simulation episodes in a Malmo environment, where an agent interacts with the environment by processing observations, calculating optimal yaw angles for movement, executing actions, and collecting rewards. It initializes the environment, iterates through episodes, tracks age...
def run_sim(self, exp_role, num_episodes, port1, serv1, serv2, exp_id, epi, rsync): '''Code to actually run simulation ''' env = malmoenv.make() env.init(self.get_mission_xml(MalmoSim.MOB_TYPE + " Apocalypse"), port1, server=serv1, server2=serv2, port2=(port1 + exp_role), role=exp_role, ex...
def find_transaction_to_address(p2sh): zcashd.importaddress(p2sh, "", False) txs = zcashd.listunspent() for tx in txs: if tx['address'] == CBitcoinAddress(p2sh): print("Found tx to p2sh", p2sh) return tx def find_redeemblocknum(contract): scriptarray = parse_script(contra...
The main task of the code is to redeem funds from a P2SH contract after a timelock period has expired. It checks if the current block count meets the required lock time, constructs a signed transaction with the redeem script, verifies the script, and submits the transaction to the blockchain, returning the transaction ...
def redeem_after_timelock(contract): p2sh = contract.p2sh fundtx = find_transaction_to_address(p2sh) amount = fundtx['amount'] / COIN if (fundtx['address'].__str__() != p2sh): print("no fund transaction found to the contract p2sh address ",p2sh) quit() # print("Found fundtx:", fundt...
def find_transaction_to_address(p2sh): bitcoind.importaddress(p2sh, "", True) txs = bitcoind.listunspent() for tx in txs: # print("tx addr:", ) # print(type(tx['address'])) # print(type(p2sh)) if tx['address'] == CBitcoinAddress(p2sh): print("Found tx to p2sh", p2...
The main task of the code is to redeem funds locked in a P2SH (Pay-to-Script-Hash) Bitcoin contract after a timelock period has expired. It verifies the timelock condition, constructs a signed transaction to transfer the funds to a refund address, and submits the transaction to the blockchain once the lock is satisfied...
def redeem_after_timelock(contract): p2sh = contract.p2sh fundtx = find_transaction_to_address(p2sh) amount = fundtx['amount'] / COIN if (fundtx['address'].__str__() != p2sh): print("no fund transaction found to the contract p2sh address ",p2sh) quit() print("Found fundtx:", fundtx)...
def calculate_probability_of_default(self): """ Calculates the probability of default for each counterparty. Returns: - probability: a dictionary of probability of default values, indexed by counterparty name """ probability = {} for key, value in self._traverse_...
The code calculates the total potential loss from counterparty defaults by aggregating Credit Valuation Adjustment (CVA) values. It computes default probabilities, loss given default (LGD), and CVA for each counterparty using stored exposure and risk weight data, then sums these CVAs to determine the overall potential ...
def calculate_potential_loss(self): """ Calculates the potential loss due to counterparty default for the exposures and risk weights stored in the CCRRWA instance. Returns: - potential_loss: the potential loss due to counterparty default """ # Calculate the probability o...
def non_word_error(self, word): error = random.choices([1, 2], weights=[0.8, 0.2])[0] if len(word) == 2: kind = random.choice(["i", "s"]) elif len(word) == 1: kind = "i" else: kind = random.choice(["i", "s", "d"]) index = random.choice(range(le...
This code evaluates a spell checker's accuracy by introducing either real-word or non-word errors into test sentences, comparing corrected outputs to original sentences, and saving results in JSON format. It calculates and returns the average accuracy across all test cases.
def evaluation(self, is_real=False): eval = [] accuracy = 0 name = "real-word.json" if is_real else "non-word.json" for sent in tqdm(self.test_tokens, desc="Spell Check Evaluation"): result = {"Original Sentence": " ".join(sent)} if sent: token = r...
def load_NDC102RXCUI2atc4(self): if not os.path.exists(f"{self.path}/NDC102RXCUI2atc4.csv"): NDC102RXCUI2atc4 = pd.read_csv( request.urlopen( "https://drive.google.com/uc?id=1I2G6fsBDXDiAK95qFWwtnl3Ib2MaLeCx" ), dtype={"NDC10": str,...
The code loads drug-related mappings (NDC, RXCUI, ATC, names, SMILES) and constructs a fully connected graph of codes, timing the process to prepare data for analysis or graph-based operations.
def load(self): tic = time.time() print("----- preparing code mappings -----") # NDC10, RXCUI, ATC4 self.load_NDC102RXCUI2atc4() # NDC11, RXCUI self.load_NDC112RXCUI() # Name, SMILES self.load_drugbank() # NDC11, Name self.load_NDC112Name()...
def cut_ctr(array: np.ndarray, sizes: tuple) -> np.ndarray: """ Cut a multi-dimensional array at its center, according to sizes :param array: multidimensional array :param sizes: tuple of the same length as array.ndim :return: multidimensional array, center cut """ array = array.copy() i...
The main task of the code is to extract and average noise fingerprints from a set of images. It processes each image by converting it to a numpy array, cropping it, extracting noise features, and appending them to a list. After processing all images, it computes an average fingerprint from the collected noise data and ...
def main(image_set): return_lst.clear() fingerprint.clear() prnu.clear() for image in image_set: #print(f"image size: {image.size}") img = np.asarray(image) img = cut_ctr(img, 800, 1000, 2) return_lst.append(noise_extract(img)) average_fingerprint(return_lst) re...
def define_clfs_params(grid_size): """Define defaults for different classifiers. Define three types of grids: Test: for testing your code Small: small grid Large: Larger grid that has a lot more parameter sweeps """ clfs = {'RF': RandomForestClassifier(n_estimators=50, n_jobs=-1), ...
The function `find_best_model` performs grid search to evaluate and identify the best machine learning model for a given dataset. It takes a DataFrame, grid size (test/small/large), outcome variable, and optional file name. Using predefined classifiers and parameter grids, it trains models on prepared training data, ev...
def find_best_model(df: pd.DataFrame, grid_size: str, outcome_var: str, file_name=None): """ Use grid search to find best model Input: - df: pandas dataframe - grid_size: one of 3 possible values: 'test', 'small', 'large' - outcome_var: the outcome variable - file_name: file name of the csv ...
def under_sampling(df: pd.DataFrame, response_col: str): df_one = df.loc[df[response_col] == 1] df_zero = df.loc[df[response_col] == 0] if len(df_one) < len(df_zero): df_zero = df_zero.sample(n=len(df_one)) else: df_one = df_one.sample(n=len(df_zero)) return pd.concat([df_zero, df_on...
The code processes an e-commerce dataset by removing outliers, applying under-sampling to balance the 'CVR' class, selecting the best predictive model, training a random forest for 'CVR' prediction, and evaluating a baseline decision tree's AUC. The goal is to optimize and validate machine learning models for conversio...
def main(): df = pd.read_csv('./data/ECommerceDataSet.csv') # Remove outliers df = df.loc[df['SessionRevenue'] != 500000] # Apply under sampling df = under_sampling(df, 'CVR') # Find the best model find_best_model(df, 'small', 'CVR', 'ml_results_after_undersampling.csv') # Fit the best m...
def tokenize_caps_list(captions): """ tokenize list of captions """ tokens = [] for c in captions: # same procedure as in build_vocab script tokens += tokenize_caption(c) return tokens def tokenize_caption(c): # clean from left <start> <end> <unk> <pad> tokens c = re.sub(r'(<sta...
The main task of the code is to analyze lexical diversity and vocabulary overlap in generated captions compared to a training set. It calculates OOV token/type percentages, token/rank metrics, and evaluates gained/lost vocabulary types. The code also assesses how often captions containing newly introduced types are cor...
def main(args): # read files with open(join(args.coco_ann_dir, 'captions_val2014.json')) as f: val_ann_df = pd.DataFrame(json.load(f)['annotations']) with open(join(args.coco_ann_dir, 'captions_train2014.json')) as f: train_ann_df = pd.DataFrame(json.load(f)['annotations']) with open(ar...
def load_media() -> Media: """Load the media from the file system.""" return Media( cat_sprites={ direction: [ pygame.image.load( str( PACKAGE_DIR / f"media/images/cat_{direction.name.lower()}{i}.png" ...
The main task of the code is to execute a game that utilizes a joystick for input, with command-line options to display the version, list connected joysticks, or select a specific joystick. It initializes Pygame, loads media, processes joystick and keyboard events, updates the game state, renders scenes, and maintains ...
def main(prog: str) -> int: """ Execute the main routine. :param prog: name of the program to be displayed in the help :return: exit code """ pygame.joystick.init() joysticks = [ pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count()) ] parser = argparse.Arg...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument("input_file", help='the file to be predict.') parser.add_argument("--saved_models", required=True, nargs='+', help='the trained models used for prediction.') parser.add_argument("--asm_source", required=True, help='the file that gene...
The code aggregates predictions from multiple models on a dataset, computes prediction errors, and marks these errors in an assembly source file. It loads input data, splits features/targets, iterates through saved models to generate predictions, combines results, calculates errors, and annotates the original assembly ...
def main(): args = get_args() data = utils.toDf(args.input_file) sum_prediction = [] X, Y = xy(data) for model in args.saved_models: print('##### predict with model: %s ########' % model) round_prediction = predict(model, data, X, Y) if len(sum_prediction) == 0: s...
def read_csv_filters (self, file_path): data = pd.read_csv(file_path) self.all_pass_filter_csv_real = data['real'] self.all_pass_filter_csv_imag = data['imag'] self.write_on_combobox() def get_combobox_value(self): self.selected_mode_str = self.filters_comboBox.currentText() ...
This code initializes a GUI dialog for a filter application, setting up plotting canvases, connecting UI elements to functions for frequency response plotting, filter parameter handling, CSV data loading, and user interactions. It prepares the interface for displaying and modifying filter characteristics, with methods ...
def __init__(self, main): super(MyDialog, self).__init__() # Load the UI Page uic.loadUi(r'all_pass.ui', self) #-----------------creats canvas-------------------------------------- self.canvas_phase = MplCanvas(self, width=5, height=4, dpi=100) self.layout_phase = QtWi...
def Fetch_Filings_Annual(Api_Key): api_query = QueryApi(api_key = Api_Key) # Now run query to get all the 10-K filings for Southwestern Airlines using ticker LUV query = { "query": { "query_string": { "query": "(formType:\"10-K\") AND ticker:LUV" } ...
The code performs horizontal analysis on financial data by fetching annual filings using an API key, converting the data into a structured dataframe, and generating visualizations or analysis plots from the processed data.
def Horizontal_Analysis(Api_Key): accession_numbers = Fetch_Filings_Annual(Api_Key) result= Main_Dataframe(accession_numbers) plotting_variables(result)
def shadow_hamiltonian(self, weights, p): # Compute shadow: S(x,p) = H(x,p) + dt2 / 24 UT_x M-1 U_x loss = self.target(weights) force = self.compute_gradients(loss,weights) dt2d24 = self.step_size * self.step_size / 24.0 H_x_p = self.hamiltonian(weights, p) Uq_M_Uq = torch.matmul(fo...
The main task of the code is to perform sampling using the S2HMC (Shadow Hamiltonian Monte Carlo) algorithm. It initializes parameters, iteratively generates samples via Hamiltonian dynamics with pre/post-processing steps, applies Metropolis-Hastings acceptance/rejection, adapts the step size during the burn-in period,...
def run(self): print(":::::::::: Running S2HMC :::::::::::") # initialise variables samples = [] log_lik = [] weights = self.weights_0 n_accepted = 0 importance_weights = [] #weighting for observables # initialise adaptation parameters Hbar_old, eps_...
def checkDict(s): for id,p in enumerate(s): if(p[1]!='Dis' or p[1]!='Dis-impact'): for k in disCom: if p[0].find(k)!=-1 and re.match(regNoun,p[2]): s[id]=tuple([p[0],"Dis",p[2]]) elif p[0].find(k)!=-1: s[id]=tuple([p[0],"Dis...
The main task of the code is to process the input string `s` through a sequence of validation/transformation functions: checking dictionary terms, time formats, numbers, locations, and distances, returning the modified string after applying all rules.
def posRules(s): s=checkDict(s) s=check_tim(s) s=check_num(s) s=check_loc(s) s=check_dis(s) return s
def checkDict(s): for id,p in enumerate(s): if(p[1]!='Dis' or p[1]!='Dis-impact'): for k in disCom: if p[0].find(k)!=-1 and re.match(regNoun,p[2]): s[id]=tuple([p[0],"Dis",p[2]]) elif p[0].find(k)!=-1: s[id]=tuple([p[0],"Dis...
The main task of the code is to sequentially apply five validation/transformation functions (`checkDict`, `check_dis`, `check_tim`, `check_num`, `check_loc`) to the input `s`, updating it at each step, and finally returning the processed result. Each function likely enforces specific rules or formats related to diction...
def posRules(s): s=checkDict(s) s=check_dis(s) s=check_tim(s) s=check_num(s) s=check_loc(s) return s
def setting(mode): if mode=='0': #Advanced mode modifier=1#modification tagTable=1#complete table of tags with "other" tags also tokenArray=1#array of tokenized sentence elif mode == '1': #Viewer mode modifier=0 tagTable=0 tokenArray=0 elif ...
The function `validateInput` processes and validates user input text by tokenizing it, checking against a predefined vocabulary, and predicting part-of-speech or tag labels using a model. It handles unknown words by substituting them with a placeholder, pads sequences to a fixed length, applies post-processing rules, a...
def validateInput(strCustom,sett,method): checkForNew=0 modifier,tagTable,tokenArray=setting(sett) outStr=[] #strCustom="this is a dummy text" A=word_tokenize(strCustom) posA=nltk.pos_tag(A) A,pos_A=zip(*posA) #print(pos_A) #print(A) A_test=[] if tokenArray==1: print(...
def get_request_info(request): res = re.search('.* (\?.*|\*) WHERE { (.*) }(.*)', request) if res: variable = res.group(1) triples = res.group(2) limit = res.group(3) triples = re.findall('(\?[^\s]*|<[^\s]*>|VALUES|{.*})', triples) triples = [prepare_URI(i) for i in trip...
This function evaluates the correctness of a SPARQL query by comparing generated triples against a response. It calculates the ratio of correct triples to total triples, returning counts for both. The process involves parsing the query, splitting triples into groups, validating each against response data, and counting ...
def evaluate_request(request, response, entity, predicate): """ request: SPARQL sended to Wikidata response: dictionary of returned variables, eg: { '?s1': 'URI', '?o1': 'literal' } entity: entity's label as in VANiLLa predicate: predicate's label (get it from question relation) returns number o...
def canvas_frame_top(self): """ Create a canvas frame contains three canvas : param frame : tk.Frame() : Frame tkinter """ frame = tk.Frame(self) self.canvas1 = tk.Canvas(frame, bg="white") self.canvas2 = tk.Canvas(frame, bg="white") self.canvas3 = tk.Canv...
The main task of the code is to initialize and layout a GUI by creating multiple frames (top, bottom, correlation, text) using `canvas_frame_top`, `canvas_frame_bottom`, `correlation_frame`, and `text_frame` methods, then arranging them vertically with `pack` and calling `setup_graph` to finalize the UI components.
def init_components(self): """Create components and layout the UI.""" # setting up frames top_frame1 = self.canvas_frame_top() lower_frame2 = self.canvas_frame_bottom() correl_frame3 = self.correlation_frame() text_frame = self.text_frame() top_frame1.pack(side=tk...
def init_brand_and_carbody(self): """Initialize brand list and carbody list""" self.brands = list(self.car.brand_list.copy()) self.brands.insert(0, "") self.brands.pop() self.carbody_list = list(self.car.carbody_list.copy()) self.carbody_list.insert(0, "") def combobox_ca...
The main task of the code is to initialize and layout UI components by creating multiple frames for categories, graphs, correlations, and a progress bar, configuring their positions and properties, and setting up a default graph, all within a Tkinter-based application interface.
def init_components(self): """Create components and layout the UI.""" self.init_brand_and_carbody() # setting up frames top_frame1 = self.combobox_category_frame() top_frame2 = self.category_button_frame() top_frame3 = self.graph_button_frame() canvas_frame = self...
def __setup_video_capture(self, name=""): # Define the codec and create VideoWriter object width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) + 0.5) height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) + 0.5) size = (width, height) fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', ...
This code processes a video or image to detect and track objects across frames. It initializes video capture, processes up to 20 frames, updates detection data with frame indices, and returns collected detection information. The function handles video input/output, frame-by-frame object detection, and stores results in...
def detect_objects_in_video(self, image=None, file=0, load=True, name=""): if load: self.cap = cv2.VideoCapture(file) else: self.cap = image # Define the codec and create VideoWriter object if self.write: self.__setup_video_capture(name=name)...
def previmgclicked(self): self.image_clicked(self.cursor-1 if self.cursor != 0 else 10000000000000000000000) def nextimgclicked(self): self.image_clicked(self.cursor+1) def displaylabelclicked(self): #check displaylabelbutton state, then update using image_clicked method try: ...
This code handles keyboard events to control image navigation and UI toggles. Pressing 'A' navigates to the previous image, 'D' to the next. 'E' toggles display labels and triggers their update. 'C' toggles image selection mode and selects the current image. The function maps specific keys to corresponding UI actions i...
def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_A: self.previmgclicked() elif event.key() == QtCore.Qt.Key_D: self.nextimgclicked() elif event.key() == QtCore.Qt.Key_E: self.displaylabelbutton.toggle() self.displaylabelclicked() ...
def generate_random_points(self, num_points: int) -> None: self.enable_all(False) time_1 = time() self.progress_bar.resetFormat() self.progress_bar.setValue(0) self.points = [] while len(self.points) < num_points: x = random.randint(0, self.im_width - 1) ...
This code initializes a GUI application for generating Voronoi diagrams or superpixel art from user-uploaded images. It sets up a window with controls to adjust parameters (e.g., points, region size), toggle visual elements (points/lines/colors), and switch between modes. The interface includes image upload/save button...
def __init__(self) -> None: super().__init__() self.diagram = np.full((DEFAULT_HEIGHT, DEFAULT_WIDTH, 3), 255, np.uint8) self.line_diagram = None self.image = None self.show_points = True self.show_lines = True self.show_colors = True self.im_height = D...
def add_ball(self): if self.ball is not None: self.ball.delete() board_coords = self.board.get_pos() x = (board_coords[2] + board_coords[0]) * 0.5 self.ball = Ball(self.canvas, x, 40) self.board.set_ball(self.ball) def update_lives_text(self): text = 'Lives: %...
The main task of the code is to initialize a game setup by adding a ball, updating lives display, rendering start instructions, and binding the Enter key to trigger the game start. It prepares the game environment for user interaction and initiates gameplay upon key press.
def setup_game(self): self.add_ball() self.update_lives_text() self.text = self.draw_text(300, 80, ' Press the Enter key to start\nClick the Quit button to quit game') self.canvas.bind('<Return>', lambda _: self.start_game())
def createMatrix(n): matrix=[] for i in range(n): row = [] for j in range(n): element=0 row.append(element) matrix.append(row) return matrix def addObstacles(matrix,obstacles,obstacle): for i in range(len(obstacles)): ...
The main task of the code is to calculate the number of squares a queen can attack on an n×n chessboard, considering obstacles. It creates a board, places obstacles if specified, and counts valid moves from the queen's position (rq, cq), returning the total attackable squares while accounting for obstructions.
def queensAttack(n,k,rq,cq,obstacles): board=createMatrix(n) if k==len(obstacles) and k>0 : board=addObstacles(board,obstacles,1) quenMoves=countQuenMoves(board,rq,cq) return quenMoves
def furtherSplit(p): t = [] for i in p: for l in splitString(i): t.append(l) return t def trimTitleSelling(title): trimmedTitle = title while("[H]" in trimmedTitle): trimmedTitle = trimmedTitle[1:] trimmedTitle = trimmedTitle[2:] while("[W]" in trimmedTitle): ...
This code searches Reddit posts for items matching query terms in titles and extracts prices from their text. It filters for 'SELLING' flaired posts, validates prices, and stores relevant data (ID, title, link, price, date) in a database. It also updates user records and returns query results, similar queries, and proc...
def searchFor(self, query=''): lst = [] qw = furtherSplit(nltk.word_tokenize(query)) for i in self.hw.search(query=query): if '$' in i.selftext: trimmedTitle = trimTitleSelling(i.title) if i.link_flair_text == 'SELLING' and isSubsetofList(qw, furtherSp...
def distance(p1: pd.Series, p2: pd.Series, box: np.ndarray, periodic: bool) -> tuple: dx = p2.x - p1.x dy = p2.y - p1.y dz = p2.z - p1.z if periodic: dx, dy, dz = periodic_conditions([dx, dy, dz], box) dst = np.sqrt(dx ** 2 + dy ** 2 + dz ** 2) return dst, (dx, dy, dz) def...
This function identifies hydrogen bonds by checking distance (0.25-0.35 Å) and angle (90-180°) criteria between a central atom, oxygen atom, and hydrogen atoms in a molecular system. It filters bonds between different molecules, uses periodic boundary conditions via the box parameter, and returns a DataFrame containing...
def hydrogen_bonds(center: pd.Series, oxygen: pd.DataFrame, hydrogen1: pd.Series, hydrogen2: pd.Series, box: np.ndarray): bonds = pd.DataFrame(columns=['mol', 'atom', 'x', 'y', 'z', 'ox_mol']) # i is the oxygen atom of the neigbour molecule for index, i in oxygen.iterro...
def __create_cells(self): for col in range(self.__num_cols): cell_col = [] for row in range(self.__num_rows): cell_col.append(Cell(self.__win)) self._cells.append(cell_col) for col in range(self.__num_cols): for row in range(self.__num_rows...
This code initializes a maze generator by setting up a grid of cells with specified dimensions and sizes, creating walls between cells, resetting visited flags, and establishing entrance/exit points to form a maze structure.
def __init__(self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None): self._cells = [] self.__x1 = x1 self.__y1 = y1 self.__num_rows = num_rows self.__num_cols = num_cols self.__cell_size_x = cell_size_x self.__cell_size_y = cell_size_y ...
def H_score(n, m, D, d, y, r): res = 0 for i in range(n): res += H_subscore(i, n, m, D, d, y, r) res = simplify(expand(res)) return res def H_score_local(n, m, D, d, y, r, locality): res = 0 for i in range(n): res += H_subscore_local(i, n, m, D, d, y, r, locality) res = simpl...
The function constructs a Hamiltonian expression by combining H_score (with optional locality-based approximation), penalty terms (H_max, H_cons, H_trans, H_norm), and simplifies it into a quadratic form using symbolic matrices d, y, and r. It returns the simplified quadratic Hamiltonian for optimization or physics sim...
def hamiltonian_para(n, m, D, delta_max, delta_cons, delta_trans, delta_norm, locality = None, use_y = True): # one local is true == use approx H_score d = MatrixSymbol("d", n, n) y = None if use_y: y = MatrixSymbol("y", n, 2) r = MatrixSymbol("r", int(n*(n-1)/2), 1) # only up-right if...
def unary (self): # Optional +/- if self.checkToken ('TK_ADDITION') or self.checkToken ('TK_SUBTRACTION'): self.emitter.emit (self.curToken.text) self.nextToken () self.primary () def checkToken(self, kind): return kind == self.curToken.kind def nextToken(self): ...
This method parses and emits multiplication/division operators between unary expressions. It first processes a unary term, then repeatedly checks for * or / tokens, emitting them and advancing the tokenizer while processing subsequent unary terms, enabling handling of chained multiplicative operations.
def term (self): self.unary () # Can have 0 or more*// expressions while self.checkToken ('TK_MULTIPLICATION') or self.checkToken ('TK_DIVISION'): self.emitter.emit (self.curToken.text) self.nextToken () self.unary ()
def term (self): self.unary () # Can have 0 or more*// expressions while self.checkToken ('TK_MULTIPLICATION') or self.checkToken ('TK_DIVISION'): self.emitter.emit (self.curToken.text) self.nextToken () self.unary () def checkToken(self, kind): return...
This code parses an arithmetic expression composed of terms separated by '+' or '-' operators. It starts by parsing a term, then repeatedly checks for addition/subtraction operators. When found, it emits the operator, advances the token stream, and parses the next term, effectively building the expression by combining ...
def expression (self): self.term () # Can have 0 or more +/- and expressions while self.checkToken ('TK_ADDITION') or self .checkToken ('TK_SUBTRACTION'): self.emitter.emit (self.curToken.text) self.nextToken () self.term ()
def checkToken(self, kind): return kind == self.curToken.kind def nextToken(self): self.curToken = self.peekToken self.peekToken = self.lexer.getToken() def match(self, kind): if not self.checkToken(kind): self.abort ("Expected " + kind + ", got " + self.curToken.kind) ...
This code parses and emits C-style code for Pascal-like statements: it handles program declarations, writeln output (strings/expressions), variable declarations, and statement terminators, while maintaining symbol tables and generating appropriate printf/variable assignments.
def statement (self): # Check the first token to see what kind of token it is # Check if program keyword is here if self.checkToken ('TK_PROGRAM'): self.nextToken () self.match ('TK_IDENTIFIER') self.match ('TK_SEMICOLON') self.match ('TK_NEWLINE'...
def expression (self): self.term () # Can have 0 or more +/- and expressions while self.checkToken ('TK_ADDITION') or self .checkToken ('TK_SUBTRACTION'): self.emitter.emit (self.curToken.text) self.nextToken () self.term () def isComparisonOperator (self): ...
This method parses a comparison expression, ensuring it contains at least one comparison operator followed by an expression. It first processes an initial expression, then checks for and emits comparison operators, parsing subsequent expressions in a loop. If no comparison operator is found initially, it aborts with an...
def comparison (self): self.expression () # Must be at least one comparison operator and another expression. if self.isComparisonOperator(): self.emitter.emit(self.curToken.text) self.nextToken() self.expression() else: self.abort("Expected...
def checkToken(self, kind): return kind == self.curToken.kind def nextToken(self): self.curToken = self.peekToken self.peekToken = self.lexer.getToken() def statement (self): # Check the first token to see what kind of token it is # Check if program keyword is here if se...
The code generates a C program by emitting the main function structure, skipping unnecessary newlines, parsing statements until EOF, and appending the return statement. It constructs valid C code by handling tokens and ensuring proper syntax for the main function.
def program (self): self.emitter.headerLine ('#include <stdio.h>') self.emitter.headerLine ('int main (void){') # We need to ignore some newlines as they maybe newlines inside the code for readability while self.checkToken ('TK_NEWLINE'): self.nextToken () # Parse a...
def run_strategy_1(candlestick_data_resampled, stock_name, interval): combinations = list( itertools.product( ema_short, ema_long, rsi_window, rsi_buy_threshold, rsi_sell_threshold, take_profit_percentage, stop_loss_percenta...
The main task of the code is to process stock candlestick data for a given interval, apply multiple trading strategies, aggregate their results, and save them as CSV files. It reads raw data, preprocesses it, runs four strategies, filters valid outputs, converts results to a structured DataFrame, and stores them in a d...
def train_single_model(file: str): stock_name = file.replace(".csv", "") interval = "24H" try: candlestick_data = pd.read_csv(os.path.join("raw", file)) candlestick_data["time"] = pd.to_datetime( candlestick_data["timestamp"] / 1000, unit="s" ) candlestick_data = ...
def build_df_filelists(domain, var_list, config_list, ref_time_list, val_start = -999, val_end = -999, ana_align_to = 'none', include_t0 = False, use_no_da = False, partial_duration = -999): ''' Create a dataframe of filelists and configuration specs for multiple configurations Dataf...
The main task of the code is to generate a dictionary of filelists for requested evaluations, splitting them into chunks if necessary to manage memory. It processes forecast and verification configurations, checks partial durations for specific settings, and ensures filelists align with the latest analysis time. Chunks...
def get_filelists(specs, variable, i = 0): ''' create a dictionary of filelists for all requested evaluations, break into chunks if necessary ''' config_list = [specs.fcst_config, specs.verif_config] # when processing only a portion of the forecast, need to pass the partial duration into filel...
def scale(self, size): return int(round(size * self.LCD.font_scale)) def update_songs(self): songs_list = os.listdir("Songs") self.DOMTree = minidom.parse(self.xml_file_name) for song in songs_list: element = self.DOMTree.createElement("Choose_song") element.appen...
This code initializes an LCD display based on user settings, loads an XML configuration file, sets up screen parameters, and prepares UI elements for a menu system. It configures display settings, initializes image rendering, parses XML data, and prepares variables for screensaver, LED animations, and user preferences,...
def __init__(self, xml_file_name): if args.display == '1in3': self.LCD = LCD_1in3.LCD() self.font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', self.scale(10)) else: self.LCD = LCD_1in44.LCD() self.font = ImageFont.load_defaul...
def to_snake_case(name:str | None = None) -> str: # See: https://stackoverflow.com/a/1176023/3592884 # name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower() if not name: return '' name = SNAKE_CASE_RE_1.sub(r'\1_\2', name) return S...
This function generates Python function bodies for Ethereum contract interactions. It filters out non-function entries, events, and role-related functions, then creates call/transaction wrappers using PEP8-style argument names. It differentiates between view/pure functions and transactions, generating code that either ...
def function_body(function_dict:Dict, custom_contract=False) -> str: body = '' if function_dict['type'] != 'function': return body contract_func_name = function_dict.get('name') func_name = to_snake_case(contract_func_name) # Exclude functions for different reasons: # - Constructors ha...
def is_lowest_point(heightmap, i, j): point = heightmap[i][j] return point_is_lower_than_coordinates(point, heightmap, i+1, j) and point_is_lower_than_coordinates(point, heightmap, i-1, j) and point_is_lower_than_coordinates(point, heightmap, i, j+1) and point_is_lower_than_coordinates(point, heightmap, i, j-1...
The code reads a heightmap from "input.txt", identifies all lowest points, calculates their risk levels, finds basins starting from these points, and computes the product of the three largest basin sizes. It then prints this product. The main task involves processing a 2D grid to determine basin sizes and their mathema...
def main(): input_file = "input.txt" with open(input_file) as file: # read lines lines = file.readlines() lines = [line.rstrip() for line in lines] heightmap = [] # iterate lines for line in lines: heightmap.append(list(map(int, list(line)))) ...
def check_bingo(bingo): return check_horizontal(bingo) or check_vertical(bingo) def calculate_result(input_number, finished_bingo): # calculate result # find sum of unmarked numbers on this board sum = 0 for bingo_line in finished_bingo: for bingo_number in bingo_line: if not bin...
The code reads input from a file, processes it into a list of Bingo cards, and simulates a Bingo game by marking numbers on the cards. It checks for completed Bingo cards after each number is called, calculates the result when a Bingo is achieved, and returns the result. The main task is to simulate Bingo gameplay, tra...
def main(): input_file = "input.txt" with open(input_file) as file: # read lines lines = file.readlines() lines = [line.rstrip() for line in lines] input = lines[0].split(',') input = [int(x) for x in input] print(input) # remove first two lines ...
def preprocess_img(self, img): # fit the image into a 256x256 square shape = np.r_[img.shape] pad = (shape.max() - shape[:2]).astype('uint32') // 2 img_pad = np.pad( img, ((pad[0],pad[0]), (pad[1],pad[1]), (0,0)), mode='constant') img_small = c...
This code processes an input image to detect hand keypoints and bounding boxes. It preprocesses the image, identifies palm regions, crops them, and predicts keypoints using a model. If `get_kp` is True, it returns detected keypoints and bounding boxes; otherwise, only bounding boxes. It handles multiple hands, validate...
def __call__(self, img, get_kp = True): ''' img is the image to be processed (np.array) if get_kp is False, only the bounding box is returned. Keypoints will return an empty list ''' # Process image img_pad, img_norm, pad = self.preprocess_img(img) ...
def preprocess_img(self, img): # fit the image into a 256x256 square shape = np.r_[img.shape] pad = (shape.max() - shape[:2]).astype('uint32') // 2 img_pad = np.pad( img, ((pad[0],pad[0]), (pad[1],pad[1]), (0,0)), mode='constant') img_small = c...
This code processes an image to detect hand keypoints and bounding boxes. It preprocesses the image, determines bounding boxes (either from previous frames or new predictions), and extracts hand keypoints via cropping and prediction. If `get_kp` is False, only bounding boxes are returned. Keypoints are transformed back...
def __call__(self, img, get_kp = True): ''' img is the image to be processed (np.array) if get_kp is False, only the bounding box is returned. Keypoints will return an empty list ''' # Process image img_pad, img_norm, pad = self.preprocess_img(img) ...
def amdf_score(data, index, shift): return np.sum(np.abs(data[index:index + shift] - data[index + shift:index + 2 * shift])) / shift def continuous_average(ln): if ln < 2: A = [0.5] * ln B = [0.5] * ln else: # B = np.arange(0, ln) * (1/(ln - 1)) # A = 1-B p = np_arang...
This function accelerates an audio signal while preserving pitch by adaptively selecting optimal time shifts between overlapping segments. It uses cross-correlation and AMDF-based pitch detection to determine shifts, combining segments with weighted averaging to minimize phase distortion. The process prioritizes pitch ...
def speedup_pitch_aware(data, SR: int, verbose=False): # does not interfere much with phases max_shift = SR * DEFAULT_WINDOW_SIZE_MS // 1000 min_shift = max_shift // 3 res = [0] * (len(data) // 2) i = 0 prev_shift = max_shift while i < len(data): if i + 2 * max_shift > len(data): bre...
def subbands_iterator(data, sample_rate, num_bands): sample_width = sample_rate * SUBBAND_FILTER_SIZE_MS // 1000 sample_width += 1 - sample_width % 2 half_bands = num_bands // 2 + 1 window = sample_rate / num_bands for freq_idx in range(half_bands): freq = freq_idx * window multiplic...
The code processes audio data by splitting it into subbands, applying pitch-aware speeding up to each subband, and recombining them. It aims to adjust the audio's tempo while preserving quality. If errors occur (e.g., due to insufficient bands), it doubles the number of bands and retries. The function returns the proce...
def algorithm2(data, sample_rate: int, num_bands=NUM_BANDS, fallback_to_twice_num_bands=True): # TODO: for some regions of audio different number of bands are preferable. # We may understand where it happens and choose the bands adaptively # sometimes Remez filter raises Exceptions. We try doubling nu...
def get_window(length): a = pi / length res = synthesize(1, a, (a - pi) / 2, length) return res def strong_signals(data, weights, highlights, freq_dist): data = np.multiply(data, weights) N = len(data) # TODO: perform large FFT only when found a non-highlighted frequency? while (N & (N - 1))...
This function decomposes input data into pure signals using overlapping windowing and iterative purification. It initializes window sizes, computes weights, and iteratively extracts strong signals, purifies them, and updates residual data. The purified signals are synthesized and accumulated in 'res', while remaining d...
def speedup_pure_decomposition(data, SR: int, iters: int, verbose=False): # TODO: have the windows more overlapping. For this we need to change the loc steps and the weights. # TODO: maybe the synthesize weights should not be as the weights for finding the pure signals? window_size = (SR * DEFAULT_WINDOW_SI...
def advance(self): # print(self.curr_char) self.pos.advance(self.curr_char) self.curr_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None def make_relationship(self): self.advance() if self.curr_char == '-': return Token(TT_UNDIR_REL) el...
This code tokenizes input by iterating through characters, appending tokens for symbols like braces, commas, and colons, handling strings and identifiers, and returning a list of tokens with an EOF marker. It skips whitespace, processes newlines, and raises an error for invalid characters.
def lex(self): tokens = [] while self.curr_char != None: if self.curr_char in ' \t': self.advance() elif self.curr_char in '\n': tokens.append(Token(TT_NEWLINE)) self.advance() elif self.curr_char == '{': ...
def on_exit(): global game_running, game_stopped game_stopped = True while game_stopped: exit_surface = font_obj.render('ESC to leave', True, (255, 255, 255), c.SPACE) exit_2_surface = font_obj.render('L-CLICK to continue', True, (255, 255, 255), c.SPACE) exit...
The function `game_input()` processes user input events in a Pygame application. It checks for quit events (window close or ESC key) to trigger an exit, and handles key press/down/up events by calling corresponding handler functions (`on_key_down`, `on_key_up`, `on_exit`). It uses `pg.key.get_pressed()` to detect key s...
def game_input(): global game_running key_input = pg.key.get_pressed() for event in pg.event.get(): if event.type == pg.QUIT or key_input[pg.K_ESCAPE]: on_exit() elif event.type == pg.KEYDOWN: on_key_down(event) elif event.type ...
def make_window(theme): sg.theme(theme) menu_def = [['&Application', ['&Exit']], ['&Help', ['&About']]] right_click_menu_def = [[], ['Edit Me', 'Versions', 'Nothing', 'More Nothing', 'Exit']] # Table Data data = [["John", 10], ["Jen", 5]] headings = ["Name", "Score"] layout...
The main task of the code is to create a GUI application using PySimpleGUI that handles user interactions through an event loop. It processes events like popups, progress bars, graph drawing, file operations (open/folder, PDF extraction/deletion), theme changes, and preview navigation. The code dynamically updates the ...
def main(): window = make_window(sg.theme()) # This is an Event Loop while True: window, event, values = sg.read_all_windows(timeout=100) # keep an animation running so show things are happening if event not in (sg.TIMEOUT_EVENT, sg.WIN_CLOSED): print('============ Event...
def set_power_mode(self, value, blocking=True): """Set power mode""" if value not in (SLEEP_MODE, FORCED_MODE): print("Power mode should be one of SLEEP_MODE or FORCED_MODE") self.power_mode = value self._set_bits(CONF_T_P_MODE_ADDR, MODE_MSK, MODE_POS, value) whil...
The code retrieves sensor data from a device by repeatedly checking for new measurements, processes the raw register values into calibrated parameters (temperature, pressure, humidity, gas resistance), stores them in `self.data`, and returns `True` on success or `False` after 10 attempts.
def get_sensor_data(self): """Get sensor data. Stores data in .data and returns True upon success. """ self.set_power_mode(FORCED_MODE) for attempt in range(10): status = self._get_regs(FIELD0_ADDR, 1) if (status & NEW_DATA_MSK) == 0: t...
def _get_regs(self, register, length): """Get one or more registers""" if length == 1: return self._i2c.read_byte_data(self.i2c_addr, register) else: return self._i2c.read_i2c_block_data(self.i2c_addr, register, length) def soft_reset(self): """Initiate a soft res...
This code initializes a BME680 sensor by setting up I2C communication, verifying the chip's presence via its ID, resetting the device, configuring power mode, calibration data, oversampling rates, and enabling gas measurements to prepare for environmental data collection.
def __init__(self, i2c_addr=I2C_ADDR_PRIMARY, i2c_device=None): BME680Data.__init__(self) self.i2c_addr = i2c_addr self._i2c = i2c_device if self._i2c is None: import smbus self._i2c = smbus.SMBus(1) self.chip_id = self._get_regs(CHIP_ID_ADDR, 1) ...
def createhashtable(): """Creates a SQLite DB Table""" result = False query = "CREATE TABLE files (file TEXT, md5 TEXT)" conn = connectdb() try: if not conn is None: if not tableexists('files'): cursor = conn.cursor() try: curso...
The main task of the code is to initialize and populate a hash table structure by first creating the hash table, then generating an index for it, and finally inserting a file's name and its corresponding MD5 hash value into the table. This setup enables efficient data retrieval and lookup operations using the hash tabl...
def setuphashtable(fname, md5): """Setup's the Hash Table""" createhashtable() createhashtableidx() inserthashtable(fname, md5)
def md5indb(fname): """Checks if md5 hash tag exists in the SQLite DB""" items = [] qry = "SELECT md5 FROM files WHERE file= ?" args = (fname,) conn = connectdb() try: if not conn is None: if tableexists('files'): cursor = conn.cursor() try: ...
This function checks if a file's MD5 hash has changed compared to a stored value in a database. If the stored hash exists and differs from the provided MD5, it updates the database and returns True. If no stored hash exists, it initializes the database entry. The function returns True if the file has changed, False oth...
def haschanged(fname, md5): """Checks if a file has changed""" result = False oldmd5 = md5indb(fname) numits = len(oldmd5) if numits > 0: if oldmd5[0] != md5: result = True updatehashtable(fname, md5) else: setuphashtable(fname, md5) return result
def is_terminal_node(board): return evaluate(board) != SCORES[EMPTY] or not any(EMPTY in row for row in board) def print_board(board): for row in board: print(" | ".join(map(lambda x: "X" if x == PLAYER_X else "O" if x == PLAYER_O else " ", row))) print("---------") def get_best_move(board): ...
The code implements a tic-tac-toe game where a human player (X) competes against a computer (O). The game alternates turns, validates moves, and uses a best-move function for the computer's strategy. It checks terminal states, displays the board, and declares the winner or a tie upon completion.
def play_game(): board = initial_board current_player = PLAYER_X while not is_terminal_node(board): print_board(board) if current_player == PLAYER_X: row, col = map(int, input("Enter row and column (0-2) for X: ").split()) if board[row][col] == EMPTY: ...
def parse_rocks(data): rocks = {} for line in data: px, py = line[0] for x, y in line[1:]: for rx, ry in line_from_to(px, py, x, y): rocks[rx, ry] = "#" px, py = x, y return rocks def get_input(): with open("input") as f: for line in f.rea...
This code simulates sand falling into a cave formed by rocks. It parses rock positions, calculates the maximum y-coordinate, and iteratively adds sand units until they can no longer fall. The loop increments a counter (s) for each successfully placed sand unit. The process stops when falling_sand returns False, indicat...
def part1(): rocks = parse_rocks(get_input()) s = 0 max_y = max(y for _, y in rocks) while True: if not falling_sand(rocks, (500, 0), max_y, False): break s += 1 return s
def parse_rocks(data): rocks = {} for line in data: px, py = line[0] for x, y in line[1:]: for rx, ry in line_from_to(px, py, x, y): rocks[rx, ry] = "#" px, py = x, y return rocks def get_input(): with open("input") as f: for line in f.rea...
The code simulates sand falling into a cave formed by rocks, counting how many units of sand come to rest before no more can fall. It parses rock positions, determines the maximum y-coordinate, and repeatedly attempts to drop sand from (500, 0) until it can't settle. The count 's' is incremented each successful drop, r...
def part2(): rocks = parse_rocks(get_input()) s = 0 max_y = max(y for _, y in rocks) while True: if not falling_sand(rocks, (500, 0), max_y, True): break s += 1 return s
def openConnection(): # Create a connection to the database conn = None try: # Parses the config file and connects using the connection string conn = mariadb.connect( user="injury_surv_editor", password="v3kwo052yzy140wn46twc5n9007wu04x", host="172.16.31.1...
The code registers a user by inserting their account, password, and type into a database table. If the user type is 'player', it attempts to register them in another table via `addAth()`. It returns the generated user ID on success or "Fail" if any error occurs during the process, including database errors or failed pl...
def register(account, password, type): conn = openConnection() try: curs = conn.cursor() # Insert the new user userid=key('userId', 'User') curs.execute( "Insert into User (userId, account, password, type) values (%r, %r, %r, %r)" %(userid, account, passwo...
def _find_all_layouts(info_data, keyboard): """Looks for layout macros associated with this keyboard. """ layouts, aliases = _search_keyboard_h(Path(keyboard)) if not layouts: # If we don't find any layouts from info.json or keyboard.h we widen our search. This is error prone which is why we wa...
The main task of the code is to generate a structured `info.json` file for a QMK keyboard by aggregating data from `rules.mk`, `config.h`, and `info.json`, validating the output against a JSON schema, and ensuring required components like layouts and community layout macros are present. It processes keymaps, layouts, a...
def info_json(keyboard): """Generate the info.json data for a specific keyboard. """ cur_dir = Path('keyboards') rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk') if 'DEFAULT_FOLDER' in rules: keyboard = rules['DEFAULT_FOLDER'] rules = parse_rules_mk_file(cur_dir / keyboar...
def circumference_point(center_point, radius, angle): """ Returns a point that is located at a given distance (radius) and at a given angle (angle in degrees) from a reference point (center_point). center_point: [latitude, longitude] of the reference point radius: distance from the reference point in m...
The code generates a list of waypoints around a delivery location by creating points on a circular path, selects the closest waypoint to the vehicle's starting position, and constructs a path list starting from the vehicle's location, followed by selected waypoints spaced at specified intervals.
def main(args): # generate some points around the delivery location tmp_wp_list = [] for degs in range(0, 360): x, y = circumference_point( center_point=[args.delivery_location_lat, args.delivery_location_lon], radius=args.radius, angle=degs ) tmp_...
def fst_bat(score): print("\nSTART Batting") while(1): try: user_runs = int(input("Enter a number(1-6): ")) if(user_runs > 6): print("Invalid Entry!!!") continue except ValueError: print("Inva...
The function `brfchoice` prompts the user to select between batting (B) or bowling (F). Based on the input, it calls `fst_bat` or `fst_bowl` functions with a `score` parameter. If the input is invalid, it recursively re-prompts the user until a valid choice is made, ensuring the game proceeds with the selected action.
def brfchoice(): choice = input("Enter B for batting or F for Bowling: ") if(choice.lower() == "b"): print("\nYou Chose Batting") fst_bat(score) elif(choice.lower() == "f"): print("\nYou Chose Bowling") fst_bowl(score) ...
def fn_upload_pdf(mv_pdf_input_file, mv_processing_message): """Upload pdf file into 'pdf-data' folder if it does not exist""" lv_file_name = mv_pdf_input_file.name if not os.path.exists("pdf-data"): os.makedirs("pdf-data") lv_temp_file_path = os.path.join("pdf-data",lv_file_name) ...
This code creates a Streamlit app for interactive Q&A using uploaded product user manuals. It allows users to upload PDF manuals, processes their content, and enables real-time chat where users ask questions and receive AI-generated answers based on the uploaded document. The app maintains chat history, provides proces...
def main(): # -- Streamlit Settings st.set_page_config("Chat With Your Product User Manual") st.header("Chat With Your Product User Manual💁") st.text("") st.text("") st.text("") # -- Display Processing Details mv_processing_message = st.empty() st.text("") st.text("") # --...
def get_reduced_data(): # load the dataset dataset = pd.read_csv('honey_sample.csv') # split into input (X) and output (y) variables X_data = dataset.loc[:, ['Li', 'Na', 'Mg', 'Al', 'P', 'K', 'V', 'Mn', 'Fe', 'Cu', 'Zn', 'Ga', 'Rb', 'Sr', 'Nb', 'Mo', 'Pd', 'Sb', 'Ba', 'Ce', ...
The code evaluates a K-Nearest Neighbors (KNN) classifier using 10-fold cross-validation. It computes accuracy, precision, recall, sensitivity, F-measure, and AUC for each fold, then averages these metrics across all folds. The function uses reduced or original data, predicts classifications, and accumulates true/false...
def run_knn(number_neighbors, reduced): if reduced == 1: data = get_reduced_data() else: data = get_data() k_fold = KFold(n_splits=10, shuffle=True) tp = 0 tn = 0 fp = 0 fn = 0 accuracies = [] precisions = [] recalls = [] sensitivities = [] f_measures = ...
def load_movie_data(): """ This function loads movie data from a csv file. Returns: movie_data (list): a list of dictionaries containing movie data """ movie_data = [] # open csv file and read data into a list with open('main_data/A_complete_data.csv', 'r') as csvfile: rea...
The main task of the code is to initialize a GUI-based movie recommendation application. It sets up the interface with labels, buttons for user feedback (Like/Dislike), and initializes data structures (movie data, user preferences, queues) to manage recommendations. The app allows users to interactively rate movies, tr...
def __init__(self, root): """ The constructor for the MovieRecommendationApp class. Parameters: root (tk.Tk): the root window """ self.root = root self.root.title("Movie Recommendation Program") self.movie_data = load_movie_data() self.movie_...
def generate_graph(): """ Method for Generating a graph from scraped data :returns: 1. graph in the form of adjancency list 2. hashmap of weights between two vertices 3. list of currencies 4. list of keys (unique IDs) generated by currencies """ rates, strs, keys = scrape() graph, weights = defaultdict...
The code detects arbitrage opportunities in a graph using the Bellman-Ford algorithm. It initializes distances, processes edges via a queue, and identifies negative cycles. If detected, it calculates arbitrage profit using the cycle and edge weights. The function returns None, None after processing.
def arbitrage(src): G, W, strs, keys = generate_graph() D = {i: float("inf") for i in G} D[src] = 0.0 parents = {} # Bellman-Ford Queue queue = deque([src]) queued = set([src]) calls = 0 while queue: v = queue.popleft() queued.remove(v) calls, cycle = relax(v, D, W, G, parents, queue, queued, calls) i...
def get_all_movies(self, path): return list(filter(lambda x: x.split('.')[-1].lower() in self.extensions, glob.glob(f"{path}\\**\\*", recursive=True))) def get_movie_data_value(self, key): return self.get_JSON_data()[key] def save_all_movies(self): self.path = self.json_data["parent_path"] ...
The code scans and organizes movie data by retrieving all movies from a specified parent path, saving them, and setting parent/sub-file references for processing.
def scan_functions(self): self.all_movies = self.get_all_movies(self.get_movie_data_value("parent_path")) self.save_all_movies() self.set_parent_files(self.get_movie_data_value("parent_path")) self.set_sub_files()
def calc_max_dist(particles, dt, N, grav, g, q_int): v = calc_max_v(particles, N, grav, g, q_int) max_dist = v * dt return max_dist def calc_expt_av_dist(vel_range, dt): # Approx # sample_num = 10000000 # a = np.random.uniform(vel_range[0], vel_range[1], sample_num) # b = np.r...
The code checks if particles might pass through each other by comparing calculated distances (maximum, expected average, actual average) with twice the smallest particle radius. If any distance exceeds this threshold, it warns the user to adjust time step (dt) or max_speed. Otherwise, it confirms parameters are safe, e...
def speed_check(particles, dt, vel_range, N, grav, g, q_int): max_dist = calc_max_dist(particles, dt, N, grav, g, q_int) expt_av_dist = calc_expt_av_dist(vel_range, dt) actual_av_dist = calc_actual_av_dist(particles, dt, N) rad = calc_extreme_val(particles, 'rad', minimum=True) if actual_...
def create_particles_list(D, N, box_shape, vel_range, mass_range, rad_range, q_range, e, rand_init, read_init, particle_df, run_id): particles = [] for i in range(N): if (rand_init): particle = create_rand_pa...
The main task of the code is to simulate the motion of particles under gravitational, magnetic, and electric forces with customizable parameters. It initializes particles, checks energy conservation, and saves simulation data. The code creates a unique run directory, sets physical constants, generates or reads particle...
def main(): # Check unique id, and create directory for data run_id = '28' if Path('sim_data/' + run_id).is_dir(): raise ValueError('run_id has been used before') else: Path('sim_data/' + run_id).mkdir() N = 4 # Number of particles. Default = 6 steps = 2000 - 1 # N...
def get_all_info_from_match(match_id): dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL') connection=cx_Oracle.connect(user='ESPN',password='espn',dsn=dsn_tns) cursor=connection.cursor() #getting squad_ids sql="select squad_id from squad where trim(match_id)=trim(:match_id)" cursor.execute(sql,{'m...
The main task of the code is to allow an authenticated admin to edit match details, including updating player scores and match status. It retrieves match and squad data, processes toss outcomes to determine batting/bowling order, stores session variables for temporary data, and handles POST requests to update player st...
def edit_match(request,match_id): if 'admin_logged' in request.session: if request.session['admin_logged']!=True: return redirect(login) else: return redirect(login) match=get_all_info_from_match(match_id) squad1_id=match.get('squad1_id') squad2_id=match.get('squad2_id') name1=get_squad(squad1_id) name2=g...
def get_all_info_from_match(match_id): dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL') connection=cx_Oracle.connect(user='ESPN',password='espn',dsn=dsn_tns) cursor=connection.cursor() #getting squad_ids sql="select squad_id from squad where trim(match_id)=trim(:match_id)" cursor.execute(sql,{'m...
This code retrieves and processes match data, including teams, player squads, toss results, batting order, scores, and match outcomes. It prepares context variables for rendering a template (`view_match.html`) with details like team names, scores, match status, and result, ensuring correct order and data presentation f...
def view_match(request,match_id): match=get_all_info_from_match(match_id) squad1_id=match.get('squad1_id') squad2_id=match.get('squad2_id') name1=get_squad(squad1_id) name2=get_squad(squad2_id) squad1=[] squad2=[] for player in name1: squad1.append(player.get('player_id')) for player in name2: squad2.appen...
def get_cursor(): dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL') connection=cx_Oracle.connect(user='ESPN',password='espn',dsn=dsn_tns) cursor=connection.cursor() return cursor def get_teams_in_tournament(tournament_id): dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL') connectio...
The code generates a tournament point table by calculating each team's points based on match outcomes (wins, losses, draws). It retrieves tournament rules, iterates through matches, updates team statistics, and sorts teams by points before rendering the result in an HTML template.
def user_point_table(request,tournament_id): cursor=get_cursor() sql="select point_w, point_nr from tournament where trim(tournament_id)=trim(:tournament_id)" cursor.execute(sql,{'tournament_id':tournament_id}) result=cursor.fetchone() point_w=int(result[0]) point_nr=int(result[1]) teams=get_teams_in_tournament(...
def get_cursor(): dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL') connection=cx_Oracle.connect(user='ESPN',password='espn',dsn=dsn_tns) cursor=connection.cursor() return cursor def get_teams_in_tournament(tournament_id): dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL') connectio...
The function identifies the top 5 players in a tournament based on runs, wickets, and boundaries by querying match data, aggregating statistics, sorting them, and returning the top performers in each category.
def top_scorers(tournament_id): cursor=get_cursor() teams=get_teams_in_tournament(tournament_id) runs={} wickets={} boundaries={} matches=matches_in_tournament(tournament_id) for match_id in matches: match=get_all_info_from_match(match_id) squad1_id=match.get('squad1_id') squad2_id=match.get('squad2_i...