dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def logValues(self, action): maxWaitTimes = self.getMaxWaitTimeOnStops() mean = sum(maxWaitTimes)/len(maxWaitTimes) actions = ['Hold', 'Skip', 'No action'] occDisp = self.occupancyDispersion() self.dfLog = pd.concat([self.dfLog, pd.DataFrame.from_records([{'meanWai...
The code processes a reinforcement learning agent's action (hold, skip, or proceed) for a bus at a stop, updates passenger counts, adjusts bus stop durations, simulates until the next decision point, and returns the new state, reward, and episode status. It also logs data and generates visualizations at episode termina...
def step(self, action): self.gymStep += 1 print("GYM STEP: ", self.gymStep) self.logValues(action) ##################### # APPLY ACTION # ##################### # hold the bus if action == 0: stopData = traci.vehicle.ge...
def get_next_token(self): """Lexical analyzer (also known as scanner or tokenizer) This method is responsible for breaking a sentence apart into tokens. """ while self.current_char is not None: if self.current_char.isspace(): self.skip_whitespace() ...
This function evaluates a simple arithmetic expression consisting of two integers and an operator (PLUS, MINUS, MULT, or DIV). It parses the left integer, operator, and right integer, performs the corresponding arithmetic operation, and returns the result. The current token is advanced sequentially through the expressi...
def expr(self): """expr -> INTEGER PLUS INTEGER""" self.current_token = self.get_next_token() left = self.current_token self.eat(INTEGER) op = self.current_token self.eat(recognise_operator(op.value)) right = self.current_token self.eat(INTE...
def build_model(train): #list of lists(sentences) of tuples Acount = {} # 2D dictionary for tag to tag counts Bcount = {} # 2d dictionary for tag to word count for sentence in train: sentence = nltk.pos_tag(sentence) #print(sentence) prevtag = '<s>' ...
The code defines a chatbot that processes user input using a pre-trained model. It tokenizes input sentences, builds a model for response generation, and enters a loop to handle user queries. The bot recognizes greetings, responds appropriately, and terminates upon 'Bye' or 'thanks'. It uses NLTK for tokenization and a...
def main(): flag=True lists = [] sentences = Mcorpus.split('.') for sentence in sentences: lists.append((nltk.word_tokenize(sentence))) tagModel, wordModel = build_model(lists) print("\n Paul: I am ready. Type something and press enter to talk to me. If you want to exit, type Bye!") ...
def build_vocab(corpus): v = {} for word in corpus: if word not in v: v[word] = 0 if word in v: v[word] += 1 v["<DollarSign>"] = 10 print("Vocabulary of size "+str(len(v))+" built from given corpus.") return(v) def replace_unknown_words(tree...
The code builds a vocabulary from the Brown corpus, trains a probabilistic context-free grammar (PCFG) on Treebank parsed sentences (after replacing unknown words), and evaluates the PCFG's performance on test sentences by comparing generated parses with gold-standard parses, assessing its ability to model syntactic st...
def main(): # Build vocabulary dictionary from brown corpus Mvocab = build_vocab(corpus = brown.words(categories=['news', 'editorial', 'reviews', 'religion', 'hobbies','lore', 'government', 'learn...
def _get_listener_msg(self, message): """Load json and attempt to get message by key.""" try: listener_msg = json.loads(message) except Exception as e: self.log.error('Invalid listener message: {0}'.format(str(e))) listener_msg = None return listener_...
This method processes listener messages by extracting job details, storing them if new, and triggering scheduling or cleanup based on job status. It ensures jobs are tracked, persists data to JSON, and acknowledges messages after handling.
def _handle_listener_message(self, message): """ Callback for listener messages. """ listener_msg = self._get_listener_msg(message.body) job_id = None if listener_msg: status = listener_msg['status'] job_id = listener_msg['id'] if job_id ...
def readFileContents(self): fin = files("stock_market_bytetheory.data").joinpath(self.filename) csvin = csv.reader(open(fin)) rows = [row for row in csvin] del rows[0] return rows def cleanFileContents(self, fileContents): cleanedContents = [] for row in fileConte...
The code reads and processes file contents by first reading the file, cleaning its data, organizing it by ticker symbols, and returning the structured data organized by ticker.
def parse(self): fileContents = self.readFileContents() cleanedFileContents = self.cleanFileContents(fileContents) dataOrganizedByTicker = self.organizeFileContentsByTicker(cleanedFileContents) return dataOrganizedByTicker
def get_modules_in_filelist(verilog_module_filename, cc_filelist): with open(args.in_all_filelist) as fl: lines = fl.readlines() for line in lines: path = line.strip() basepath = os.path.basename(path) ext = basepath.split(".")[-1] if (ext == "v") or (ext == "sv"): modules = g...
The main task of the code is to generate and manage Verilog and C++ filelists for hardware modules, ensuring unique naming of common modules between different hierarchies. It processes module hierarchies from JSON inputs, identifies overlapping modules, renames duplicates, and writes separate filelists for top-level an...
def main(): verilog_module_filename = dict() cc_filelist = list() get_modules_in_filelist(verilog_module_filename, cc_filelist) modules_under_model = get_modules_under_hier(args.model_hier_json, args.dut) modules_under_top = get_modules_under_hier(args.top_hier_json) common_modules = modules_under_t...
def dump_commands(cf): """dump a tree of all the known API commands""" walk(cf, '') def convert_zones_to_identifier(cf, zone_name): """zone names to numbers""" params = {'name':zone_name, 'per_page':1} try: zones = cf.zones.get(params=params) except CloudFlare.exceptions.CloudFlareAPIErr...
(The main task of the code is to provide a command-line interface (CLI) for interacting with the Cloudflare API. It parses command-line arguments to set parameters like output format (JSON/YAML), HTTP method (GET/POST/PUT/DELETE), and API parameters. The script processes key-value parameters, constructs API requests dy...
def cli4(args): """Cloudflare API via command line""" verbose = False output = 'json' raw = False dump = False method = 'GET' usage = ('usage: cli4 ' + '[-V|--version] [-h|--help] [-v|--verbose] [-q|--quiet] [-j|--json] [-y|--yaml] ' + '[-r|--raw] ' +...
def probe_media(self, path): """Probe video file using ffprobe """ ffprobe_command = [ self.ffprobe, "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", "--", path ] try: ...
This code initializes a media analyzer by probing a file's metadata, extracting video/audio stream details, calculating display resolution and format, and parsing attributes. If verbose is True, it prints the filename, sample/display resolutions, duration, and file size.
def __init__(self, path, verbose: bool = False, ffprobe: str = "ffprobe"): self.ffprobe = ffprobe self.probe_media(path) self.find_video_stream() self.find_audio_stream() self.compute_display_resolution() self.compute_format() self.parse_attributes() if v...
def grid_desired_size( grid, media_info, width=Config.contact_sheet_width, horizontal_margin=Config.grid_horizontal_spacing): """Computes the size of the images placed on a mxn grid with given fixed width. Returns (width, height) """ desired_width = (width - (grid.x - 1) ...
The code generates a video contact sheet by arranging selected frames in a grid layout, incorporating media metadata in a customizable header and optional timestamps on each frame. It calculates dimensions, prepares text layers, and composites frames with timestamps and metadata using alpha blending for transparency.
def compose_contact_sheet( media_info, frames, args): """Creates a video contact sheet with the media information in a header and the selected frames arranged on a mxn grid with optional timestamps """ desired_size = grid_desired_size( args.grid, media_info, ...
def error_exit(message): """Print an error message and exit""" error(message) sys.exit(-1) def total_delay_seconds(media_info, args): """Computes the total seconds to skip (beginning + ending). """ start_delay_seconds = math.floor(media_info.duration_seconds * args.start_delay_percent / 100) ...
The code generates a video contact sheet by selecting key frames, arranging them in a grid, and saving the result as an image. It handles file validation, parameter checks, frame selection, composition, and output management, with options for custom grids, intervals, manual timestamps, and thumbnail extraction.
def process_file(path, args): """Generate a video contact sheet for the file at given path """ if args.is_verbose: print("Considering {}...".format(path)) args = deepcopy(args) if not os.path.exists(path): if args.ignore_errors: print("File does not exist, skipping: {}"...
def LR_pos(spin,epsilon): ''' For different values of spin and epsilon, the location of the light ring is different. The function IterativeFunc is called for different ranges of epsilon by adjust the minimum and maximum of the radial coordinate R. If the range is too ...
The function `gamma0` calculates the inverse of the dimensionless damping time at a light ring for given spin and epsilon values. It first determines the light ring position using `LR_pos`. If valid, it computes a complex expression involving polynomials and square roots of terms derived from `com_term`. If the ratio o...
def gamma0(spin,epsilon): ''' Once the light ring location given the value of spin and epsilon is found, we evaluate the inverse of dimensionless damping time at the light ring of a given the value of spin and epsilon. (The negative sign is conventional.) Due to the presence ...
def remove_empty_columns(data): data = data.dropna(how='all', axis=1) data = data[0:] return data def prepare_review_data(data, stop, lm, words): data['text'] = data['text'].astype(str) data['text'] = data['text'].apply(lambda x: " ".join(x.lower() for x in x.split())) data['text'] = data['text'...
The code trains a text classifier using labeled reviews. It preprocesses data by removing empty columns, preparing features with stopwords and language models, converts data into classifier format, and trains a ConditionalExponentialClassifier with two iterations for text classification tasks.
def train_classifier(train_reviews, stop, lm, words): train_reviews = remove_empty_columns(train_reviews) train_reviews = prepare_review_data(train_reviews, stop, lm, words) classifier_train_data = create_classifier_data(train_reviews) # You can change the classifier type by modifying below cl = nlt...
def remove_empty_columns(data): data = data.dropna(how='all', axis=1) data = data[0:] return data def prepare_review_data(data, stop, lm, words): data['text'] = data['text'].astype(str) data['text'] = data['text'].apply(lambda x: " ".join(x.lower() for x in x.split())) data['text'] = data['text'...
The function processes test reviews by removing empty columns, preparing review data using stop words, language model, and vocabulary, then structuring the processed data into a classifier-ready format for machine learning tasks.
def prepare_test_data(test_reviews, stop, lm, words): test_reviews = remove_empty_columns(test_reviews) test_reviews = prepare_review_data(test_reviews, stop, lm, words) classifier_test_data = create_classifier_data(test_reviews) return classifier_test_data
def robot_reset(fr, fl, br, bl): fr.setVelocity(0) fl.setVelocity(0) br.setVelocity(0) bl.setVelocity(0) def object_info(img, img_width, img_height): object_data = [] #center point, area imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray, 50, 255, 0) im, co...
The code controls a robot in a simulation to navigate, avoid zombies, and collect berries. It initializes sensors (GPS, cameras, etc.), processes real-time data, detects objects via camera recognition, and adjusts movement (turning/forward) to prioritize berry collection while evading zombies. The robot's health is mon...
def main(): robot = Supervisor() # get the time step of the current world. timestep = int(robot.getBasicTimeStep()*2) #health, energy, armour in that order robot_info = [100,100,0] passive_wait(0.1, robot, timestep) pc = 0 timer = 0 robot_node = robot.getFromDef("Youbot") tran...
def calculate_height(self, node): if node is None: return -1 return node.height def handle_violation(self, node): while node is not None: node.height = max(self.calculate_height(node.left_node), self.calculate_height(node.right_node)) + 1 self.violation_hel...
This code inserts a new node into a binary tree, recursively traversing left or right subtrees based on data comparison. It updates the height of nodes after insertion and triggers a violation handling mechanism to maintain tree balance, likely part of an AVL tree implementation.
def insert_node(self, data, node): # we have to go to the left subtree if data < node.data: if node.left_node: self.insert_node(data, node.left_node) else: node.left_node = Node(data, node) node.height = max(self.calculate_height(no...
def handle_violation(self, node): while node is not None: node.height = max(self.calculate_height(node.left_node), self.calculate_height(node.right_node)) + 1 self.violation_helper(node) node = node.parent def get_predecessor(self, node): if node.right_node: ...
This function recursively removes a node with the specified data from a binary tree, handling three cases: leaf nodes (no children), nodes with one child, and nodes with two children. It updates parent pointers, deletes the node, and calls `handle_violation` to maintain tree properties. For two-child nodes, it swaps da...
def remove_node(self, data, node): if node is None: return if data < node.data: self.remove_node(data, node.left_node) elif data > node.data: self.remove_node(data, node.right_node) else: if node.left_node is None and node.right_node is ...
def checkIfGoalState(self): for i in range(0, len(self.state), 4): side = self.state[i:i+4] if side.count(side[0]) != 4: return False return True def generateNormalForm(self, state): state = self.checkCube(state) oppositeColor = {"O": "R", "G": "B"...
This function implements the A* algorithm to solve a Rubik's Cube puzzle. It explores states by generating valid moves, avoiding duplicates, and prioritizing nodes using a heuristic. The algorithm tracks the number of nodes explored, the solution path (moves), and execution time. It returns the optimal move sequence, n...
def aStar(self): if self.checkIfGoalState(): return self.movesList, 0, 0.0 start = time() cubes = [self] opened = [self.state] closed = set() nodeCount = 0 while opened: # Open the first state in the list state0 = opened.pop(0) ...
def get_data_from_athena(query_athena, as_df: bool = False): conn = pyathena.connect( s3_staging_dir=S3_STAGING_DIR, region_name=REGION_NAME ) with conn.cursor() as cur: if as_df: cur.execute(query_athena) df = as_pandas(cur) return df r...
This function identifies new healthcare facility CNES IDs not present in the database, retrieves their data, renames columns, and uploads the updated DataFrame to S3 as a Parquet file, ensuring only new entries are added to avoid duplicates.
def update_healthcare_facilities(cnes_ids): query_cnes_geolocation = f""" SELECT DISTINCT cnes_id FROM final.covid19_healthcare_facilities WHERE cnes_id IN ({cnes_ids}) """\ .replace("[", "")\ .replace("]", "") cnes_ids_hf = get_data_from_athena(query_cnes_geol...
def find_prefix_path(base_path, node): conditional_patterns = {} for child in node.children.values(): prefix_path = [] current = child while current.parent: prefix_path.append(current.item) current = current.parent if len(prefix_path) > 1: cond...
This function recursively mines frequent itemsets from a header table using the FP-Growth algorithm. It generates new itemsets by adding sorted items to the current prefix, appends them to the results, and recursively processes conditional subtrees built from pattern bases, ensuring all combinations meeting min_support...
def mine_tree(header_table, min_support, prefix, frequent_item_sets): sorted_items = [item[0] for item in sorted(header_table.items(), key=lambda x: x[1][0])] for item in sorted_items: new_frequent_set = prefix.copy() new_frequent_set.add(item) frequent_item_sets.append(new_frequent_set...
def pre_process_image(self, img, skip_dilate=False): """Uses a blurring function, adaptive thresholding and dilation to expose the main features of an image.""" # Gaussian blur with a kernal size (height, width) of 9. # Note that kernal sizes must be positive and odd and the kernel must...
The code processes an image to extract and recognize digits from a grid. It reads an image, preprocesses it, detects the corners of the largest polygon, crops and warps the image, infers a grid structure, and extracts digits for further analysis or recognition.
def __init__(self, img): self.cv2 = __import__('cv2') self.np = __import__('numpy') self.operator = __import__('operator') self.image = self.cv2.imread(img, self.cv2.IMREAD_GRAYSCALE) # self.show_image(self.image) processed = self.pre_p...
def calculate_hueristics(self, variables): return [(self.most_constrained_vars(k, variables), (k , variables[k])) #self.most_constraining_vars(k, variables), #(k, self.least_constraining_val(k, variables))) for k, v in variables.items()] d...
This code solves a puzzle using backtracking with heuristic selection of variables. It recursively assigns values to variables, checking for a solution, and backtracks if a value leads to a dead end. The heuristic minimizes the next node to assign, enhancing efficiency.
def solve(self): # base case, no more variables can be assigned thus puzzle must be solved if self.variables == {}: return self.puzzle # gets next node based on hueristics node = min(self.calculate_hueristics(self.variables))[-1] print(self.i, self.puzzle, end='\r')...
def convert(self, x): return ''.join(map(str, x)) def pretty_print(self, puzzle, msg): print(msg, end='\t') print(puzzle[0:3] + '|' + puzzle[3:6] + '|' + puzzle[6:9], end='\n\t') print(puzzle[9:12] + '|' + puzzle[12:15] + '|' + puzzle[15:18], end='\n\t') ...
The code initializes a Sudoku solver, imports necessary modules, sets up puzzle variables, and executes a solving algorithm. It tracks solving time and steps, prints the input/output puzzles, and uses backtracking with constraint propagation to find a solution.
def __init__(self, puzzle): self.queue = __import__("queue") self.copy = __import__('copy') self.math = __import__("math") self.time = __import__("time") self.i = 0 # initiales variables self.puzzle = puzzle self.size = int(self.math.sqrt(len(pu...
def create_poetry_packages(self, root_dir, cache_dir, deploy_downstream): """Gets all poetry packages required by each downstream project from the given cache directory.""" poetry_list = self.get_all_poetry(root_dir, deploy_downstream) for poetry in poetry_list: packages = self.get_p...
The main task of the code is to deploy poetry packages to a specified repository. It generates package lists, retrieves repository credentials, uploads packages to the repository, and logs any non-deployable packages. The function handles configuration, artifact caching, and authentication to ensure successful deployme...
def deploy_poetry(self, repo_name, downstream, io): logging.basicConfig(level=logging.INFO) config = Config.create() poetry_list = self.create_poetry_packages( os.getcwd(), config.artifacts_cache_directory.absolute().as_posix(), downstream, ) r...
def getDataFromAPI(): global receivedData # declare a global receivedData variable global weatherData # declare a global weatherData variable receivedData = urequests.get(url, headers=headers) # store requested data in receivedData weath...
The code's main task is to retrieve weather data from an API, store and organize it in a variable, display the processed text on an LCD screen, and enable text scrolling. It sequentially executes API data fetching, data storage, LCD text rendering, and scrolling functionality to present dynamic weather information on a...
def run_code(): getDataFromAPI() # get weatherData from the API storeDataFromAPI() # store and organize data from the API in a variable displayTextToLCD() # display the text to the LCD screen scrollText()
def _rotate_to_zero(self): print("Rotate to Zero degree...") self.sleep() rot1, rot2 = 0, 0 min_speed = 0.1 delta = 0.005 ornt = self.read_robot_orientation() norm = np.linalg.norm(ornt) if ornt[0] > 0: rot1, rot2 = min_speed, -min_speed ...
This function rotates a robot to align with a target by calculating the angular difference (alpha), determining the rotation direction (sign), and adjusting the robot's orientation using a loop until its rotation norm falls within a specified range of the target angle.
def rotate_robot_to_target(self): print("Rotate to target...") self._rotate_to_zero() alpha = self._get_angles_between_robot_and_target() print("ALPHA: " + str(alpha)) sign = True # right side rad_alpha = 0 if alpha < 180: sign = True ...
def get_latest_version() -> Version: raw_rss = requests.get(RELEASES_RSS_URL).text rss = parse_xml(raw_rss) version = ( rss.childNodes[0] .getElementsByTagName("channel")[0] .getElementsByTagName("item")[0] .getElementsByTagName("title")[0] .childNodes[0] .nod...
The function `check_and_prompt` checks if a newer version exists compared to the current version. If so, it prompts the user to upgrade; if the user agrees, it performs the upgrade. If the user declines or no newer version exists, it informs the user they are already up to date. The task involves version comparison, us...
def check_and_prompt(): latest_version = get_latest_version() if latest_version > VERSION and prompt(VERSION, latest_version): upgrade(VERSION, latest_version) return else: # FIXME: also gets printed out if answered no to the prompt print("Great, you're already up to date!")
def resolve_self_repository_shorthand(gh: Github, repo: str) -> str: """ Adds USERNAME/ to a `repo` that has no slashes """ if "/" not in repo: return gh.get_user().login + "/" + repo return repo def resolve_defaults( column: Optional[str], project: Optional[str], default_project...
This function creates a GitHub issue or project card with specified attributes like title, body, labels, milestone, and assignees. It handles authentication, resolves repository/project details, validates inputs, and either creates an issue or card based on flags. It returns an Idea object with metadata, including URLs...
def push_to_repo( auth_cache: Optional[str], body: str, title: Optional[str], repo: str, project: Optional[str], column: Optional[str], assign: list[str], self_assign: bool, milestone: Optional[str], label: list[str], default_project: Optional[str], default_column: Option...
def resolve_defaults( column: Optional[str], project: Optional[str], default_project: str, default_column: str, repo_full_name: str, username: str, ) -> tuple[str, str]: """ Resolves defaults for `COLUMN` and `PROJECT` using `--default-*` arguments ``repo_full_name`` must be of the f...
The main task of the code is to create and display a GitHub card with a given body and title, using specified or default project/column parameters. It formats the title into the body as an `<h1>` to avoid duplication, resolves project/column details, handles authentication, and optionally opens the generated card's URL...
def push_to_user( body: str, title: Optional[str], project: Optional[str], column: Optional[str], create_missing: bool, auth_cache: Optional[str], dry_run: bool, open: bool, default_project: str, default_user_project: str, default_column: str, default_user_column: str, ...
def create_logger(name): """ creates a logger with a given name and adds a file handler to it""" logger = logging.getLogger(name) logger.setLevel(logging.INFO) file_handler = logging.FileHandler(config.LOGGER_NAME) file_handler.setLevel(logging.INFO) formatter = logging.Formatter(config.FORMAT) ...
The main task of the code is to manage dataframes dictionary creation, updating, and printing, while interacting with a MySQL database. It processes command-line arguments to create/update dataframes, API data, and database structures. The code reads or generates dataframes and API data from pickle files, handles excep...
def main(): """ allows for dataframes dictionary creation, update, and printing. in addition, allows for creating and updating the mysql database using the dataframes dictionary """ parser = argparse.ArgumentParser() parser.add_argument(config.CDICT, f'{config.SPACE}{config.CDICT}', help=config.CDICT_HE...
def _get_action_values(self, state, valid_actions, action_type='pos'): # Convert from numpy array to tuple state = tuple(state) #if self.train_mode: # # Return saved action values. If this is the first time this state is visited, # # set all values to zero # retu...
The code updates the Q-table during training by estimating future rewards using the maximum Q-value of valid actions, then selects the next action based on the updated Q-values. It uses gamma for discounting future rewards and operates only when train_mode is active.
def step(self, state, valid_actions, reward): # At every other step: update the q-table and take the next action # Since the game hasn't finished yet, we can use current knowledge of the q-table # to estimate the future reward. if self.train_mode: #if self.train_mode: pos_val...
def count_children(self, parent_address): if parent_address == 'root': return len(self.root[self.index_child]) else: return len(self.select_children(parent_address)) def select_children(self, node_address): if node_address == 'root': return self.root[self.inde...
This code repositions an item within a hierarchical structure by adjusting its rank relative to its siblings. It validates the new rank against the current rank and sibling count, updates the item's rank, and adjusts the ranks of affected siblings to maintain order. Finally, it sorts the items under the parent node to ...
def reposition_item(self, item_address, new_rank): current_rank = item_address[-1] parent_address = item_address parent_address.pop() if len(parent_address) == 0: parent_address = 'root' item_sibling_count = self.count_children(parent_address) ...
def count_children(self, parent_address): if parent_address == 'root': return len(self.root[self.index_child]) else: return len(self.select_children(parent_address)) def select_children(self, node_address): if node_address == 'root': return self.root[self.inde...
The function creates a new node as the first child of a specified parent node. It generates the new node's address by appending the parent's children count to the parent's address, constructs the node with this address and name, adds it to the parent's children list, then repositions it as the first child to maintain o...
def new_node(self, parent_address, new_item_name): # count children of parent node you are inserting into. the count will be used for the new_item's address. if the parent node has # 2 children (child 0 and child 1), the last index of the new item's address will be 2. siblings_count = self.coun...
def count_children(self, parent_address): if parent_address == 'root': return len(self.root[self.index_child]) else: return len(self.select_children(parent_address)) def select_children(self, node_address): if node_address == 'root': return self.root[self.inde...
This function inserts a node into a specified position under a parent node in a tree structure. It validates the new rank, temporarily assigns the node as the last child, updates its address, appends it to the parent, readdresses its children, and repositions it to the desired rank.
def insert_node(self, node, new_parent_address, new_rank=0): siblings_count = self.count_children(new_parent_address) if new_rank > siblings_count or new_rank < 0: return 'INVALID NEW RANK' # first insert node as the last child of its parent, later we will sort it again temp...
def get_valid_moves(self): valid_moves = [] if self.redMarbles > 0: valid_moves.append(('red', 1)) if self.blueMarbles > 0: valid_moves.append(('blue', 1)) return valid_moves def make_move(self, pile, num): if pile == 'red': self.redMarbles -= ...
The main task of the code is to determine the optimal move for the computer player using the minimax algorithm with alpha-beta pruning. It iterates through all valid moves, simulates each move, evaluates the resulting game state recursively, and selects the move with the highest evaluated value at the specified depth, ...
def get_computer_move(self, depth): best_move = None max_val = -float('inf') for move in self.get_valid_moves(): self.make_move(move[0], move[1]) self.current_player = 2 val = self.minimax(depth - 1, -float('inf'), float('inf')) self.make_move(move...
def dim_location(): df1 = transform_population_data() df1 = df1[["Federal Information Processing Standards (FIPS) Code", "State", "Area name", "Rural-Urban Continuum Code 2013"]] df2 = transform_employment_data() df2 = df2[["Urban_influence_code_2013"]] Dim_location = pd.concat([df1, df2], ax...
The main task of the code is to load preprocessed data into a PostgreSQL database. It connects to the database, generates three DataFrames (location, population, and fact tables), and uses the `load_data` function to insert these datasets into specified tables: 'locationdata', 'populationdata', and 'pandemicdata'. The ...
def final_stage(): # Calling load function to commit loading to the db conn = psycopg2.connect("host=<host> dbname=<database> user=<user> password=<password>") df_location = dim_location() df_population = dim_population() df_factable = fact_table() load_data(conn, df_location, 'locationdata') ...
def stem(x, filters, kernel_size=3, padding='same', strides=1): # print("one") conv = Conv2D(filters, kernel_size, padding=padding, strides=strides)(x) # print("two") conv = conv_block(conv, filters, kernel_size, padding, strides) # print("three") shortcut = Conv2D(filters, kernel_size=1, paddin...
This code defines a ResUNet model for image segmentation, using an encoder-decoder structure with residual blocks. It processes input images through downsampling (encoder), a bottleneck bridge, and upsampling (decoder) with skip connections, finally outputting 4-class segmentation maps via a sigmoid-activated convoluti...
def ResUNet(img_h, img_w): # print(img_h) f = [16, 32, 64, 128, 256] inputs = Input((img_h, img_w, 1)) # print(inputs) ## Encoder e0 = inputs # print(e0) # print("right before first stem") e1 = stem(e0, f[0]) # print("right after first stem") e2 = residual_block(e1, f[1], s...
def get_rundir(pdb, run, suffix): """Return directory to use for this simulation run. Parameters ---------- pdb : string pdb file path. run : int run number. If 0 (or less than 0), this method finds all (say n) rundirs corresponding to these parameters and uses run = n + 1. ...
The script generates simulation jobs by creating directories, copying input files (PDB, PSF, TCL), and producing job scripts for batch submission. It accepts parameters like number of runs, file paths, computational resources, and suffixes. For each run, it validates required files, constructs a run directory, generate...
def main(): parser = argparse.ArgumentParser(description='Script to generate jobs for simulations. ' 'The script saves job in ~/jobs directory and also ' 'prints the job path prefix with qsub, so that you can ' ...
def __list_str(self, list): output = "" for j in list: output += j return output def __final_combination(self): return self.__combinations[random.randint(0, 5)] def __encryption(self, data, pixel1, pixel2, pixel3): # different methods are called bits for each of ...
This function embeds given data into a grayscale image by modifying pixel values in triplets, using an encryption method. It adjusts image dimensions to ensure compatibility, stores data sequentially, and appends a predefined pattern if space remains. If data exceeds storage capacity, it returns the partially embedded ...
def data_to_gray_image(self, img, data): img = cv2.imread(img) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = np.array(img) if isinstance(data, list): data = self.__list_str(data) if isinstance(data, str): pass else: data = str(data)...
def __list_str(self, list): output = "" for j in list: output += j return output def __final_combination(self): return self.__combinations[random.randint(0, 5)] def __encryption(self, data, pixel1, pixel2, pixel3): # different methods are called bits for each of ...
The code embeds given data into an RGB image using a custom encryption method, adjusting image dimensions and processing pixel pairs to store data. It handles data conversion, checks storage capacity, and returns the modified image along with a flag indicating if all data was successfully embedded or if some data remai...
def data_to_img_rgb(self, img, data): img = cv2.imread(img) if isinstance(data, list): data = self.__list_str(data) if isinstance(data, str): pass else: data = str(data) index_counter_data = 0 combination_index = 0 flag = None ...
def Conv2D(filters, kernel_size, name, use_bias=False, bias_regularizer=None, kernel_regularizer=l2_reg()): return keras_layers.Conv2D( filters=filters, kernel_size=kernel_size, padding='same', kernel_initializer='glorot_normal', kernel_regularizer=kernel_regularizer, ...
This code defines a residual block with two convolutional layers, batch normalization, squeeze-and-excitation (SE) attention, and a residual connection. It processes input `x` through two Conv2D layers with ReLU activation, applies SE to enhance feature representation, adds the original input (residual connection), and...
def ResidualBlock(x, filters, name): out = Conv2D(filters=filters, kernel_size=3, name=name + '/residual_block/1')(x) out = BatchNorm(scale=False, name=name + '/residual_block/1')(out) out = ReLU()(out) out = Conv2D(filters=filters, kernel_size=3, name=name + '/residual_block/2')(out) out = BatchNo...
def ConvBlock(filters, kernel_size, name, batch_scale=False): def block(x): out = Conv2D(filters=filters, kernel_size=kernel_size, name=name + '/conv_block')(x) out = BatchNorm(scale=batch_scale, name=name + '/conv_block')(out) out = ReLU(name=name + '/conv_block/re_lu')(out) return...
This function constructs a neural network model with multiple heads for value estimation, policy prediction, and moves-left tracking. It uses convolutional layers, residual blocks, and separate heads for different tasks. The model is built based on specified dimensions and can include optional policy head configuration...
def create_model(model_dims: ModelDimensions, policy_head=None): num_filters, num_blocks, input_dims, output_size, moves_left_size = model_dims['num_filters', 'num_blocks', 'input_dims', 'output_size', 'moves_left_size'] input_shape = (input_dims.input_h, input_dims.input_w, input_dims.input_c) state_input ...
def run_provided_inputs_phase(self, inputs_path: str): """ Run the inputs in the provided directory against the SUT. """ with os.scandir(inputs_path) as it: for entry in it: if entry.name.endswith(".cnf") and entry.is_file(): _, stderr, _ ...
The code runs a fuzzer loop against a System Under Test (SUT), generating dummy test files to prevent errors, executing provided inputs, and alternating between generation-based and mutation-based fuzzing strategies. It tracks progress, handles exceptions, and ensures test files are generated within a timeout period. T...
def start(self): """ Run the main fuzzer loop. """ print(f"Running fuzzer against SUT in {self.solver_source_path}") # This is needed so LabTS does not complain about missing files in case the fuzzer # does not generate enough test files in 180 seconds. These files are ...
def get_hard_pair(self,df1,df2,same=True): n1 = len(df1.index) n2=len(df2.index) size = n1*n2 temp_pairs = [np.zeros((size, self.h, self.w, self.c)) for i in range(2)] idx = 0 for r1i,row1 in df1.iterrows(): for r2i,row2 in df2.iterrows(): ...
The main task of the code is to generate batches of image pairs for contrastive learning, where each batch contains a mix of positive (same class) and negative (different class) pairs. It uses random sampling and hard-negative mining strategies, with a 1/5 chance of selecting hard examples via `get_hard_pair`. The func...
def get_batch(self): while True: # Create holder for batches pairs = [np.zeros((self.batch_size, self.h, self.w, self.c)) for i in range(2)] targets = np.zeros((self.batch_size,)) targets[self.batch_size // 2:] = 1 # half are positive half are negative ...
def get_hard_pair(self,df1,df2,same=True): n1 =len(df1.index) n2=len(df2.index) size = n1*n2 temp_pairs = [np.zeros((size, self.h, self.w, self.c)) for i in range(2)] idx = 0 for _,row1 in df1.iterrows(): image1 = row1['Path'] ...
This function generates batches of image pairs (positive/negative) for training a Siamese network. It creates two image tensors per batch, with half labeled as positive (same class) and half as negative (different classes). Depending on a random condition, it either samples hard pairs using `get_hard_pair` or randomly ...
def get_batch(self): global first while True: # Create holder for batches pairs = [np.zeros((self.batch_size, self.h, self.w, self.c)) for i in range(2)] targets = np.zeros((self.batch_size,)) targets[self.batch_size // 2:] = 1 # half are positi...
def steadyState(self, yRes, b2Res, state0): 'Function to evaluate the steady state of the resident dynamics' # Caluclate this with the numerical ODE solution stateODE = solve_ivp(lambda t, state: self.resDynamics(t, state, yRes, b2Res), (0,self.TEco), state0, method='BDF').y[:,-1] return(stateODE) def alpha12...
The function calculates the fitness of a parasite's mutant trait (b2Mut) relative to resident traits (yRes, b2Res) by evaluating steady-state population dynamics. It computes fitness using a formula involving terms derived from the steady-state values (S, I1, I12) and parameters (b, gamma, alpha, beta). The result, (b2...
def fitnessFunb2(self, b2Mut, yRes, b2Res): ''' Fitness function for parasite ''' # Steady state at resident trait values SS = self.steadyState(yRes, b2Res, self.state0) S = SS[0] I1 = SS[1] I2 = SS[2] I12 = SS[3] # Fitness function A = S*(self.b + self.gamma1 + self.gamma2 + self.alpha12fun(yRe...
def steadyState(self, yRes, b2Res, state0): 'Function to evaluate the steady state of the resident dynamics' # Caluclate this with the numerical ODE solution stateODE = solve_ivp(lambda t, state: self.resDynamics(t, state, yRes, b2Res), (0,self.TEco), state0, method='BDF').y[:,-1] return(stateODE) def alpha12...
The function `selGrad` calculates selection gradients at a position `(y, b2)` in trait space by computing fitness (`fitm`, `fitp`) and selection gradients (`selm`, `selp`) for two traits. It uses steady-state values (S, I1, I2, I12) and derived formulas involving parameters like `alpha`, `gamma`, `beta`, and `delta`. T...
def selGrad(self, y, b2, t=0): ''' Calculate the selection gradient at a position (y, b2) in trait space ''' SS = self.steadyState(y, b2, self.state0) S = SS[0] I1 = SS[1] I2 = SS[2] I12 = SS[3] # Find the selection gradients at this value Am = S*(self.b + self.alpha12fun(y,b2) + self.gamma1 + sel...
def collatz_read(s): """ read two ints s a string return a list of two ints, representing the beginning and end of a range, [i, j] """ a = s.split() return [int(a[0]), int(a[1])] def collatz_eval(i, j, the_cache): """ i the beginning of the range, inclusive j the end of the range...
The function `collatz_solve` processes input lines from a reader, computes the maximum Collatz cycle length for number pairs `(i, j)` using a cache for efficiency, and writes results to a writer. It iterates through each line, reads `i` and `j`, evaluates their cycle lengths with caching, then prints the result. The ca...
def collatz_solve(r, w): """ r a reader w a writer """ the_cache = {} for s in r: i, j = collatz_read(s) v = collatz_eval(i, j, the_cache) collatz_print(w, i, j, v)
def collatz_read(s): """ read two ints s a string return a list of two ints, representing the beginning and end of a range, [i, j] """ a = s.split() return [int(a[0]), int(a[1])] def collatz_eval(i, j, the_cache): """ i the beginning of the range, inclusive j the end of the...
The main task of the code is to process input lines from a reader, compute Collatz cycle lengths for integer pairs (i, j) using cached results for efficiency, and write the computed values to a writer. It iterates through each line, skips empty lines, reads i and j, evaluates the maximum cycle length between them, and ...
def collatz_solve(r, w): """ r a reader w a writer """ the_cache = {} for s in r: if not s.strip(): continue i, j = collatz_read(s) v = collatz_eval(i, j, the_cache) collatz_print(w, i, j, v)
def check_format(image): ''' Checks given format ''' return Image.open(image).format def SSIM_bytes_relationship(image, temp): ''' Given an image, returns a value that represent its SSIM-bytes relationship byteSSIM = bytes/SSIM ''' try: os.makedirs(temp) # Folder to store re...
The main task of the code is to determine the optimal image format (PNG or WebP) for a given PNG image by comparing their Bytes-SSIM relationship. It calculates metrics for both formats, prioritizes WebP if its SSIM is ≥0.9, otherwise defaults to PNG. The function returns the best format's efficiency metrics, including...
def try_best_SSIM_bytes(image, temp, only_name, host): ''' Given an image, if it is a PNG, finds the best image format by calculating Bytes-SSIM relationship for original and webp formats. Returns the Bytes-Effeciency metric for the best format ''' img_name = only_name format = check_format(imag...
def check_6_dice_combos(roll: set): values_count_dict = roll_to_dict(roll) unique_values_of_roll = set(values_count_dict.values()) # account for all of the special pairs that use 6 dice (in order of points descending) # 6 of a kind if unique_values_of_roll == {0, 6}: return 3000 # 2 tri...
The function determines the score of a dice roll by checking for specific combinations in a prioritized order: first 6-dice combinations, then 5/4-dice, then 3-dice. It returns the calculated score based on the first valid combination found.
def get_score_of_roll(roll: set): points = None if len(roll) == 6: points = check_6_dice_combos(roll) if points == None and len(roll) <= 6: points = check_5_4_dice_combos(roll) if points == None: points = check_3_dice_combos(roll) return points
def all_combos(num_of_dice: int): assert num_of_dice < 7 all_combos = list(product("123456", repeat=num_of_dice)) return all_combos def find_unique_combos(x_dice_combos: list): combos_sum_dict = {} for roll in x_dice_combos: new_key = "" for die in roll: new_key +...
The code calculates the average score of all possible combinations when rolling a specified number of dice. It generates all combinations, processes them into unique entries, assigns scores, and computes the mean. The function returns both the scored combinations and the average score for the given number of dice.
def find_mean_score_of_x_dice(num_of_dice: int): x_dice_combos = all_combos(num_of_dice) # x_dice_special_combos_dict = roll_to_dict(roll) x_dice_combos_dict = find_unique_combos(x_dice_combos) x_dice_combos_dict_w_scores = find_values_of_unique_combos(x_dice_combos_dict) all_combos_for_x_dice,all_c...
def log_death(self, reason): logger.info(f'"{self.name}" died from {reason}') def change_status(self, new_status): if self.status != new_status: self.status = new_status self.sub_status = None self.log_status() def work(self, time): self.change_status('resting...
The code updates an entity's state by managing hunger, status transitions (sleeping, eating, working), and short-term memory. It checks survival conditions, adjusts hunger over time, and triggers state changes based on hunger levels and time-of-day. If hunger depletes, the entity dies. The function handles status-speci...
def update(self, time): if not self.is_alive: return self.short_memory_reset_timer -= 1 if self.short_memory_reset_timer <= 0: self.short_memory.clear() self.short_memory_reset_timer = 100 if self.hunger <= 0: self.log_death('hunger') ...
def check_python_version(): """ Makes sure that the script is run with Python 3.6 or newer. """ if sys.version_info.major == 3 and sys.version_info.minor >= 6: return version = "{}.{}".format(sys.version_info.major, sys.version_info.minor) raise RuntimeError("Unsupported Python version {...
The main task of the code is to install GPU drivers and the CUDA Toolkit on a Linux system. It checks prerequisites like Python version and root privileges, verifies system compatibility, ensures no existing installation (unless forced), detects GPU presence, installs dependencies, and executes driver installation and ...
def install(args: argparse.Namespace): # Prerequisites check_python_version() if os.geteuid() != 0: print("This script needs to be run with root privileges!") sys.exit(1) # Set up the log directory. Logger.setup_log_dir() if check_driver_installed() and not args.force: ...
def parse_args(): parser = argparse.ArgumentParser(description='Install or verify GPU drivers.') parser.add_argument("action", choices=['install', 'verify'], default="install", nargs="?") parser.add_argument("--force", help="Forces driver installation, even if there is no GPU detected.", ...
The main task of the code is to execute an installation script based on user-specified actions. It parses command-line arguments, verifies NVIDIA driver installation status by checking system details, or triggers the installation process if the action is 'install'. The script provides feedback on driver status and dire...
def main(): """ Main function of the installation script. """ args = parse_args() if args.action == 'verify': if not check_driver_installed(): print("The driver is not installed.") else: print("The driver seems to be installed. Run `nvidia-smi` to check detai...
def initialize_parameters(self, num_nodes_in_layers): print("Initialization function") L = len(num_nodes_in_layers) # parameters is a dictionary from where we'll extract all our parameters W and b parameters = {} # Convention: W1 is the weight matrix of first hidden layer. b2 ...
This code trains a neural network using binary cross-entropy loss via gradient descent. It initializes parameters, iteratively performs forward propagation, computes predictions, calculates loss, executes backpropagation to derive gradients, updates parameters, and tracks costs. After training, it plots the cost histor...
def fit(self, X, Y, num_nodes_in_layers): print("Training in progres............") costs = np.zeros(self.num_iterations) parameters = self.initialize_parameters(num_nodes_in_layers) for i in range(self.num_iterations): print("Iteration ", i+1) A_L, cache = sel...
def checkIfIndexed(column): """Checks if the collectionName.column exists in either hashedKeys or bTreedKeys Parameters ---------- column : str The key to check in the dictionary """ if column in hashedKeys or column in bTreedKeys: return True else: return False def ...
This function performs a left join between two collections (left and right) based on specified conditions. It processes conditions to identify left/right columns, checks for indexed columns for optimization, renames fields to avoid conflicts, and merges matching rows from the right collection with each row from the lef...
def join(outputCollection, leftCollection, rightCollection, conditions, operator): """Left Joins two collections based on specified conditions Parameters ---------- outputCollection : str The collection name we store the final result as leftCollection : str The collection name w...
def _check_expired(self): self.now = datetime.datetime.now() self.expired = self.expires < self.now if self.expired: self.renew_token() def pause_track(self): self._check_expired() response = requests.put(self.pasue_url, headers=self.auth_header) valid_respo...
This function records a single audio track by pausing the current playback, preparing Audacity for recording, playing the specified track, capturing the audio, trimming silence, and exporting the processed track as an MP3 file while updating metadata.
def record_single_track(self, idx): self._check_expired() # Pause currently playing track self.pause_track() # Get track duration track_data = self.tracks[idx]['track'] track_duration = track_data['duration_ms']/1000. # --- Set up Audacity for recording --- ...
def clean_string(string): string = re.sub(r'[^0-9a-zA-Z\[\]() ,-]+', '', string) string = re.sub(r'\.', '', string) return string def list_artist_names(self, artists_data): artists = [] for artist in artists_data: artists.append(artist['name']) return artists ...
The main task of the code is to write metadata (title, artist, album, genre, and artwork) to an audio file using data from a track dictionary and a Spotify image URL. It downloads the album artwork, embeds it into the audio file's metadata, saves the changes, and deletes the temporary image file afterward.
def write_metadata_new(self, track, filepath): try: audiofile = eyed3.load(filepath) except FileNotFoundError: print('Audiofile not found.') track_data = track['track'] track_name = track_data['name'] track_name = self.clean_string(track_name) al...
def get_playlist_tracks(self): self._check_expired() playlist_url = f'https://api.spotify.com/v1/playlists/{self.playlist_id}/tracks' header = { 'Authorization': f'Bearer {self.token}' } n_tracks_returned = 100 n_tracks = 0 self.tracks = [] w...
The function retrieves a playlist's tracks, searches YouTube for each track, and downloads the audio if available. It first fetches the playlist tracks, then iterates through them, performing a YouTube search for each. If a download is required and a valid video is found, it triggers the audio download process. The tas...
def _rip_playlist(self): if self.playlist_id is not None: # Get playlist tracks self.get_playlist_tracks() # Loop through the tracks, search on Youtube and download. for _idx in range(len(self.tracks)): track = self.tracks[_idx] pr...
def populates_unseen_movies_to_user(self): user_dic = self.finding_movieIds() films = self.get_all_movies() new_dict = {} for film in films: if film in user_dic: new_dict[film] = user_dic[film] else: new_dict[film] = np.nan...
This function generates a DataFrame for a new user by populating unseen movies, imputing missing values using a pre-trained imputer, and returning the transformed DataFrame with movie ratings. It initializes a user dictionary, converts it to a DataFrame, applies mean imputation on missing entries, and ensures the outpu...
def df_user(self): '''This function creates a dataframe from user entries.''' user_dict = self.populates_unseen_movies_to_user() user_df = pd.DataFrame(user_dict, index=[0]) user_df.index = ["new_user"] #Fill-in missing values as before(with mean) ratings, ratings...
def populates_unseen_movies_to_user(self): user_dic = self.finding_movieIds() films = self.get_all_movies() new_dict = {} for film in films: if film in user_dic: new_dict[film] = user_dic[film] else: new_dict[film] = np.nan...
This function generates a DataFrame for a new user by populating unseen movies, imputing missing ratings with mean values from existing data, and returning the completed user profile for further processing like recommendations.
def df_user(self): '''This function creates a dataframe from user entries.''' user_dict = self.populates_unseen_movies_to_user() user_df = pd.DataFrame(user_dict, index=[0]) user_df.index = ["new_user"] #Fill-in missing values as before(with mean) ratings, ratings...
def populates_unseen_movies_to_user(self): user_dic = self.finding_movieIds() films = self.get_all_movies() new_dict = {} for film in films: if film in user_dic: new_dict[film] = user_dic[film] else: new_dict[film] = np.nan...
The main task of the code is to generate a DataFrame representing a new user's movie ratings, filling missing values with mean imputation. It first populates unseen movies, creates a DataFrame, applies an imputer to handle missing data using pre-trained models, and returns the completed user profile with predicted rati...
def df_user(self): user_dict = self.populates_unseen_movies_to_user() user_df = pd.DataFrame(user_dict, index=[0]) user_df.index = ["new_user"] #Fill-in missing values as before(with mean) ratings, ratings_imp, movies, imputer = self.prepare_data() films = self.ge...
def n_movie(self): n_recom = list(self.user_ratings.items())[-1] n = n_recom[1] # print(type(n)) return int(n) def prepare_data(self): ratings= pd.read_csv('./data/ml-latest-small/ratings.csv', index_col=0) ratings= pd.pivot_table(ratings, index='userI...
The code recommends movies using collaborative filtering by predicting ratings for unseen movies. It calculates user similarity via cosine similarity, computes weighted average ratings, and returns top N movies with highest predicted scores based on user preferences.
def recommend_movies(self): n = self.n_movie() ratings, ratings_imp, movies, imputer = self.prepare_data() user_dict = self.finding_movieIds() seen_movies = list(user_dict.keys()) films = self.get_all_movies() unseen_movies = set(films).difference(set(seen_movies)) ...
def n_movie(self): '''This function extracts the last user entry which is the number of movies that he/she wants to get as recommendation.''' n_recom = list(self.user_ratings.items())[-1] n = n_recom[1] return n def prepare_data(self): ratings= pd.read_csv('./data/ml-latest-small...
The code implements a collaborative filtering movie recommendation system. It calculates predicted ratings for unseen movies by averaging weighted ratings of similar users, using cosine similarity. The top N movies with highest predicted scores are selected and their titles are returned as recommendations.
def recommend_movies(self): n = self.n_movie() ratings, ratings_imp, movies, imputer = self.prepare_data() user_dict = self.finding_movieIds() seen_movies = list(user_dict.keys()) films = self.get_all_movies() unseen_movies = set(films).difference(set(seen_movies)) ...
def n_movie(self): '''This function extracts the last user entry which is the number of movies that he/she wants to get as recommendation.''' n_recom = list(self.user_ratings.items())[-1] n = n_recom[1] # print(type(n)) return int(n) def prepare_data(self): '''Th...
The code recommends movies by predicting ratings for unseen films using cosine similarity between user preferences and existing ratings, then returning the top N highest-rated movies based on these predictions.
def recommend_movies(self): n = self.n_movie() ratings, ratings_imp, movies, imputer = self.prepare_data() user_dict = self.finding_movieIds() seen_movies = list(user_dict.keys()) films = self.get_all_movies() unseen_movies = set(films).difference(set(seen_movies)) ...
def add(self, commands): command_to_add = commands[2] if self.find_command(command_to_add.lower()) is not None: self.ANSWER = f"@{self.CONTEXT.author.name}, command {command_to_add} already exists." return self.SAVED_CONTEXT.append({ "name": command_to_add, ...
This code processes user commands by parsing the action from the input event and invoking corresponding methods like add, delete, edit, or help. If an unknown action is detected, it returns an error message.
def execute_command(self, event): commands = event.split(' ') action = commands[1].lower() if action == 'add': self.add(commands) elif action == 'remove' or action == 'delete': self.delete(commands) elif action == 'edit': self.edit(commands) ...
def challenge_chatter(self, commands): duel_user_name = '' challenged = commands[1][1:] for user in self.CONTEXT.channel.chatters: if user.name == challenged: duel_user_name = user.name if challenged == self.CONTEXT.channel.name: duel_user_...
This function processes user commands in a game context, handling challenges, accepting/rejecting duels, shooting, and providing help. It checks the command type and game state to determine actions, responding with appropriate messages or triggering game logic.
def execute_command(self, event): commands = event.split(' ') game = self.find_game(self.GAME_NAME) action = commands[1].lower() if commands[1][:1] == '@' and game is None: self.challenge_chatter(commands) elif commands[1][:1] == '@' and game is not None: ...
def _letting_enter_closest_person_waiting(self) -> None: closest_person, closest_person_index = self.get_closest_person_waiting() print(f'Closest person waiting is : {closest_person}') self._go_to_closest_person(person=closest_person) self._someone_enters(index=closest_person_index, pers...
The code simulates an elevator's operation by repeatedly allowing the closest waiting person to enter, calculating target floors based on the first passenger's direction, moving to each floor, checking for new entries/exits, and stopping if no passengers remain. It handles sequential floor visits, door openings for exi...
def go(self) -> None: while len(self.persons_outside) != 0: self._letting_enter_closest_person_waiting() levels = self._compute_levels_until_extremities(direction=self.persons_inside[0].get_direction()) for next_level in levels: print(f"Going to level... {nex...
def get_apod_date(): """Gets the APOD date The APOD date is taken from the first command line parameter. Validates that the command line parameter specifies a valid APOD date. Prints an error message and exits script if the date is invalid. Uses today's date if no date is provided on the comma...
The main task of the code is to fetch an Astronomy Picture of the Day (APOD) for a specified date, cache it in a local directory, retrieve its file path from a database, and set it as the desktop background. The script handles date input, cache initialization, image storage, and desktop configuration, with error handli...
def main(): ## DO NOT CHANGE THIS FUNCTION ## # Get the APOD date from the command line apod_date = get_apod_date() # Get the path of the directory in which this script resides script_dir = get_script_dir() # Initialize the image cache init_apod_cache(script_dir) # Add the APOD fo...
def key_hit(self): """Process the current position of the blocks relatively to the ones underneath when user hit the switch, then decide if the user will win, lose or go to the next level of the tower. """ sound = pygame.mixer.Sound("effect.wav") sound.play() if s...
This code implements a game loop that handles different game states (intro, playing, win, lose, score screens), processes user input (keyboard events), transitions between states based on game outcomes, updates game mechanics, and renders the screen. It includes features like state initialization, score calculation, re...
def main_loop(self, loop=True): """The main loop.""" while loop: if self.game_state == self.INTRO: for event in pygame.event.get(): if event.type == pygame.QUIT: loop = False elif event.type == pygame.KEYDOWN: ...
def is_all_out(self): return self._bottles == 0 def buy_new_beer(self): return 'Go to the store and buy some more' def drink_beer(self): return f"Take {self.it_or_one()} down and pass it around"
The function manages beer bottle count logic: if all bottles are out, it restocks to 99 and triggers buying new beer; otherwise, it decrements the count and returns lyrics from drinking a bottle.
def go_to_the_store_or_take_one_down(self): if self.is_all_out(): self._bottles = 99 return self.buy_new_beer() else: lyrics = self.drink_beer() self._bottles -= 1 return lyrics
def go_to_the_store_or_take_one_down(self): if self.is_all_out(): self._bottles = 99 return self.buy_new_beer() else: lyrics = self.drink_beer() self._bottles -= 1 return lyrics def bottles_of_beer(self): return self.anglicized_bottle_c...
The code generates a line of the "99 Bottles of Beer on the Wall" song by concatenating three method calls: `go_to_the_store_or_take_one_down()` (action), `bottles_of_beer()` (quantity), and `on_wall()` (location), formatting them into a lyrical sentence with a newline.
def response(self): return self.go_to_the_store_or_take_one_down() + ", " + self.bottles_of_beer() + " " + self.on_wall() + ".\n"
def get_mtime(output_dir, action_type, action_id, compressed=True): path = get_path( output_dir, 'output', action_type, action_id, compressed=compressed, ) if os.path.exists(path): return os.path.getmtime(path) return None def get_path(output_dir, path_t...
This function checks if output files are up-to-date by comparing modification times (mtime) of the latest action in an action sequence with its dependencies. For 'aggregate' actions, it recursively checks all grid subdirectories. If any dependency is newer (stale), it returns (1, exists) indicating rebuild needed. Othe...
def check_deps( output_dir, action_sequence, compressed=True ): if not len(action_sequence): return None, False action = action_sequence[-1] # Iterate from end action_type, action_id = action['type'], action['id'] mtime = get_mtime(output_dir, action_type, action_id, com...
def aggregate( output_dir, action_sequence, grid_params, aggregation_id=None, evaluation_id=None, labeling_id=None, subnetwork_id=1, kernel_radius=5, eps=1e-3, compress_outputs=None, dump_kwargs=True, indent=0 ): assert ...
The function `parcellate` executes a sequence of actions (e.g., sampling, alignment, labeling) to generate parcellated data outputs. It supports grid search over parameters, recursively processing each configuration, and aggregates results. It checks for existing outputs to avoid redundant work, using overwrite flags t...
def parcellate( output_dir, action_sequence, grid_params=None, eps=1e-3, compress_outputs=True, overwrite=False, dump_kwargs=True, indent=0 ): assert isinstance(output_dir, str), 'output_dir is required, must be given as a str' assert isinstance(ac...
def read_map(file: str): with open(file) as f: data = f.read().split('\n\n') seeds = [int(x) for x in data[0].split()[1:]] mappers = {make_map(mapper)[0]: make_map(mapper)[1:] for mapper in data[1:]} return seeds, mappers def part1(seeds, mappers): print("Part 1:", min([translate(mappers, '...
The main task of the code is to execute two processing stages (part1 and part2) on seed and mapper data from two input files: 'input_test.txt' and 'input.txt'. It first processes the test input, then the actual input, printing separators before and after each processing phase.
def main(): print("----") seeds, mappers = read_map('input_test.txt') part1(seeds, mappers) part2(seeds, mappers) print("----") seeds, mappers = read_map('input.txt') part1(seeds, mappers) part2(seeds, mappers)
def create_random_layout(self) -> dict: self.pos = nx.random_layout(self.graph, dim=3) def sample_sphere( G: nx.Graph, layout: list[float, float, float], *args: tuple, **kwargs: dict ) -> dict[str, list[float, float, float]]: """Samples a sphere around the given layout for as many nodes as provided with...
The main task of the code is to apply a specified cartoGRAPH layout algorithm to position nodes in a graph's 3D space. It selects the appropriate algorithm (e.g., TSNE, UMAP, functional) based on the input, handles unimplemented algorithms by raising errors, and places nodes without features/links on a spherical shell ...
def create_cartoGRAPH_layout( self, ) -> dict: """Will pick the correct cartoGRAPHs layout algorithm and apply it to the graph. If cartoGRAPH is not installed an ImportError is raised. In link based algorithms all nodes without a link will be placed on a sphere around the center of the graph. In fun...
def makeProjectFolders(self) -> None: """Creates the project folders and writes empty pfile and names file.""" self.project.create_all_directories() rel_path = self.project.location.find("static") rel_path = self.project.location[rel_path:] log.debug(f"Successfully created direc...
The function generates and uploads network textures and layouts, creating 2D node/link layouts and STRING evidence-based edge textures. It processes nodes/links (parallel or sequential), cleans data, sorts layouts, updates project files, and returns a status message.
def upload_files( self, parallel: bool = True, ) -> str: """Generates textures and upload the needed network files. If created_2d_layout is True, it will create 2d layouts of the network one based on the cytoscape coordinates and one based on the new coordinated that come from the 3D layout ...
def create_cartoGRAPH_layout( self, ) -> dict: """Will pick the correct cartoGRAPHs layout algorithm and apply it to the graph. If cartoGRAPH is not installed an ImportError is raised. In link based algorithms all nodes without a link will be placed on a sphere around the center of the graph. In fun...
The code determines the layout algorithm type stored in `self.algo` and executes the corresponding layout generation method (e.g., `create_cartoGRAPH_layout`, `create_spring_layout`, or `create_kamada_kawai_layout`) to compute a graph layout. It acts as a dispatcher, selecting the appropriate layout strategy based on t...
def calculate_layout(self): if LA.cartoGRAPH in self.algo: self.create_cartoGRAPH_layout() elif LA.spring == self.algo: self.create_spring_layout() elif LA.kamada_kawai == self.algo: self.create_kamada_kawai_layout()
def table_by_symbol(df: Cols("symbol amount amount_usd"), sufix=""): table = Table(title=f"Grouped by symbol{sufix}") table.add_column("Symbol", justify="left", style="white", no_wrap=True) table.add_column("Amount", justify="right", style="green bold", no_wrap=True) table.add_column("USD", justify="rig...
The code's main task is to display aggregated blockchain data by generating a grid table that combines four grouped views of a DataFrame (symbol, symbol group, chain, wallet) alongside a block IDs table and a main summary. It structures and prints multi-dimensional insights from cryptocurrency transaction data in a tab...
def show_all(block_ids, df: Cols("chain wallet amount symbol price amount_usd")): grouped = Table.grid() grouped.add_row(table_by_symbol(df), table_by_symbol_group(df), table_by_chain(df), table_by_wallet(df)) print(block_ids_table(block_ids), main(df), grouped)
def shiftImage(image, x, y): rows, cols = image.shape[:2] newImage = np.zeros((rows, cols, 3), np.uint8) for i in range(rows): for j in range(cols): if i+y >= rows or j-x >= cols or i+y < 0 or j-x < 0: continue newImage[i, j] = image[i+y, j-x] return newIm...
The code performs three image processing tasks: shifting an image, applying a Gaussian blur, and computing the difference of Gaussians. It measures the execution time for each operation, saves the processed images, and displays them using OpenCV.
def p2(): mImage = cv2.imread('downscaled8.jpg') print(f'Running Image Shift') start = time.time() mImageShifted = shiftImage(mImage, 100, 100) print(f'Time taken: {time.time() - start:.2f}s') func('shifted.jpg', mImageShifted) cv2.waitKey(0) cv2.destroyAllWindows() print(f'Running...
def eye_aspect_ratio(eye): A = distance.euclidean(eye[1], eye[5]) B = distance.euclidean(eye[2], eye[4]) C = distance.euclidean(eye[0], eye[3]) ear = (A + B) / (2.0 * C) return ear def mouth_aspect_ratio(mouth): A = distance.euclidean(mouth[14], mouth[18]) C = distance.euclidean(mouth[12], mouth[16]) m...
The main task of the code is to perform real-time drowsiness detection using a webcam or phone camera. It captures video, detects faces, extracts facial landmarks, computes features like eye aspect ratio (EAR) and mouth aspect ratio (MAR), and classifies the subject as "Drowsy" or "Alert" based on a model. Results are ...
def live(device, url): if device == 'CAMERA_LAPTOP': cap = cv2.VideoCapture(0) elif device == 'CAMERA_PHONE': try: cap = cv2.VideoCapture(url) except: print('wrong url') return data = [] cnt = 0 while True: # Getting out image by w...
def ls_index(start_date, long, short, resolution): """ Returns dataframe of returns data of index start_date - string of start date ex. "2022-04-01" long - name of market to long short - name of market to short resolution - resolution of candlestick ex. "1h" returns: DataFrame of returns """ try: ...
The function `index_chart` generates a visual representation of the performance of a long/short trading strategy between two assets (`long` and `short`) starting from a specified date (`start_date`). It calculates and displays key metrics such as maximum drawdown, maximum return, current return, and the percentage diff...
def index_chart(long, short, start_date): """ Plots the long/short index via matplotlib long - ticker to long short - ticker to short start_date - string of start date ex. "2022-04-01" """ fxs_waves = ls_index(start_date, long, short, "1h") plt.plot(fxs_waves['time'],fxs_waves['returns']) a,b,c = anal...
def forward_delta(p, x, rate=0.1): return match(thardlim(p), x) * rate def backward_delta(p, x, rate=0.1): return (x - thardlim(p)) * rate def compare(p, x): return "bin > %s <=> %s" % (thardlim(p), x)
The code updates parameter 'p' by sequentially adding forward and backward deltas derived from 'x', then compares the result with 'x'. It prints 'p' states before and after each adjustment, returning the final updated 'p'.
def train(p, x, rate=0.1): print("before > %s" % p) p += forward_delta(p, x) print("forward> %s" % p) p += backward_delta(p, x) print("back > %s" % p) print(compare(p, x)) return p
def get_table_for_variable_code(variable_code, site_id=None, start_date=None, end_date=None): var_id = get_id('Variable', {'VariableCode': variable_code}) table_name = 'datavalues' sql = """SELECT * FROM {} WHERE VariableID={};""".format(table_name, var_id) if start_date or end_date: if not star...
The function associates maximum rain event times with daily maximum tides by resampling tide data, extracting rain event timestamps, and aligning them to compute daily tide peaks. It processes rain data columns, generates unique identifiers for tide values, and concatenates results into a sorted DataFrame linking rain ...
def tide_when_rain_max(rn_mx_time_df): td_df = get_table_for_variable_code('six_min_tide') try: td_df = pivot_dv_df(td_df) except: td_df = remove_duplicates(td_df) td_df = pivot_dv_df(td_df) td_df = td_df.resample('15T').mean() rn_mx_time_rnd = cln_n_rnd_times(rn_mx_time_df) ...
def get_table_for_variable_code(variable_code, site_id=None, start_date=None, end_date=None): var_id = get_id('Variable', {'VariableCode': variable_code}) table_name = 'datavalues' sql = """SELECT * FROM {} WHERE VariableID={};""".format(table_name, var_id) if start_date or end_date: if not star...
The main task of the code is to generate a daily aggregated pivot table from a dataset. It retrieves data for a given variable code, attempts to pivot the data, handles potential errors by removing duplicates, resamples the pivoted data to daily intervals, applies a specified aggregation function, and renames columns u...
def daily_pivot_table(var_code, agg_function, abbreviation): df = get_table_for_variable_code(var_code) try: dfp = pivot_dv_df(df) except ValueError: df = remove_duplicates(df) dfp = pivot_dv_df(df) dfd = dfp.resample('D') aggrd = dfd.agg(agg_function) rnmed = rename_...
def read_number(self): number = [] while self.current_char.isdigit() and not self.is_EOF(): number.append(self.current_char) self.read_next_char() return int("".join(number)) def read_symbol(self): symbol = [] while not self.current_char.isdigit() and not ...
This function identifies the type of the next token based on the current character: digits trigger number reading, letters trigger symbol reading, and other characters trigger operator reading, returning the result of the corresponding method.
def read_next_token(self): if self.current_char.isdigit(): return self.read_number() if self.current_char.isalpha(): return self.read_symbol() else: return self.read_operator()
def ddx(a): return fullSimplify(derivative(a)) def evalExpr(c, val, a): # plug in val for c in a a_c = plugIn(c, val, a) return evalExprC(a_c) def fullSimplify(expr): last = Const(0) while not equal(expr,last): last = expr expr = simplify(expr) return expr
The code processes mathematical expressions based on a keyword. It tokenizes the input expression, executes it to obtain a function `e`, then applies operations: differentiation (`der`), evaluation (`eval`), or simplification (`simp`). The result depends on the keyword, returning computed values or errors for invalid c...
def run(fn, expr): tokens, keyword, eva = tokenize(expr) expr_str = build_expr(tokens) kw = {} exec(expr_str) in kw # derive if keyword == 'der': return ddx(kw['e']), None elif keyword == 'eval': c = eva[0] val = eva[1] return evalExpr(c, val, kw['e'...
def _swap_buttons(self, first_button, second_button): ''' Sets property Enabled = False to all squares on a board (until the animations end), creates animation objects (QPropertyAnimation) which stand for swapping two marked squares. It also updates squares' attributes x-inde...
This function swaps two marked squares by updating their colors, creates an animation sequence to visually represent the swap, grow sequences, nullify them, and animate squares falling down. It disables the swap button during execution, connects to a post-animation check for game state updates, and initiates the animat...
def swap_sequences(self): ''' Creates and starts animation group for: swapping marked squares, grow up the sequences, nullify them and bring down squares from above. ''' self.window_parent.button_swap_buttons.setEnabled(False) first_button = self.buttons[clicked_...
def _reloadBoard(self): ''' Called when player ranks up. The function nullifies all squares on a board, creates new squares with another colors, sets them over the screen and brigns the entire new board donw on the widget. ''' self.potential_colors = random.sa...
This function checks if the player has leveled up by comparing their points to level requirements. If so, it updates the level, displays a congratulatory message, refreshes the game board, and unlocks buttons. It then checks for remaining playable sequences; if none exist, it triggers a loss state. If no loss occurs, b...
def _check_the_promotion_and_loss(self): ''' Called after sequence of animations ends. It checks whether player ranks up, and afterwards - whether he losses. If not - unlocks all button and lets player play. ''' if points_for_levels[self.level] <= self.points:...
def init_data(self): # Load data from CSV files try: self.df_companies = pd.read_csv('company_ref.csv') self.df_contracts = pd.read_csv('Construction_Contracts.csv') except Exception as e: # Log errors if loading fails logging.error(f"Error loading...
This code initializes a GUI application's main window, setting its title, size, and background color. It calls methods to initialize data, configure styles, and create UI components, establishing the application's foundational structure and visual elements.
def __init__(self): super().__init__() # Setting up the main window self.title("GroupPay") self.geometry("800x600") self.configure(bg="#f4f4f4") # Initialize data and UI components self.init_data() self.configure_styles() self.create_widgets()
def _entropy(self, ids): if len(ids) == 0: return 0 count_y = 0 count_n = 0 freq = [] for element in ids: if self.target[element] == "yes" or self.target[element] == True or self.target[element] == 1: count_y += 1 ...
This code builds a decision tree by recursively splitting nodes based on entropy and depth constraints. It initializes tree parameters, creates a root node, and processes nodes in a queue. Each node is split if depth allows or entropy is sufficient, with labels set for leaf nodes or default labels otherwise, constructi...
def fit(self, data, target): self.Ntrain = data.count()[0] self.data = data self.attributes = list(data) self.target = target self.labels = target.unique() ids = range(self.Ntrain) self.root = TreeNode(ids = ids, entropy = self._entropy(ids), dep...
def _entropy(self, ids): if len(ids) == 0: return 0 count_y = 0 count_n = 0 freq = [] for element in ids: if self.target[element] == "yes" or self.target[element] == True or self.target[element] == 1: count_y += 1 ...
The code implements a decision tree classifier's `fit` method by recursively splitting data nodes based on entropy and depth constraints. It initializes tree structure, calculates node entropy, splits nodes into children if depth/gain conditions are met, assigns labels to leaf nodes, and uses BFS traversal to process n...
def fit(self, data, target): self.Ntrain = data.count()[0] self.data = data self.attributes = list(data) self.target = target self.labels = target.unique() ids = range(self.Ntrain) self.root = TreeNode(ids = ids, entropy = self._entropy(ids), dep...
def populate_pairs_by_id(self): ''' Populates a dict with all pairs avaiable on zkswap. Useful to do because this list doesn't change very often. Adds the pairs in a dictionary with the keys being the ids of the pairs as specified by zkswap, together with some ...
This function retrieves comprehensive details for all zkSwap pairs by calling multiple endpoints. It updates or retrieves token/pair data based on `update_info`, then merges price data (amounts, price, total supply) from `get_pairs_prices()` with existing pair info, returning a dictionary of all pairs with their detail...
def get_complete_info_all_pairs(self, update_info=False): ''' Calls multiple endpoints to gather comprehensive details on all the zkswap pairs. `update_info` - bool | whether to update the existing info in `self.tokens_by_id` & `self.pairs_by_id` or not Returns a ...
def generate_trigger(self, X_train, y_train, mode='CLASSIFICATION'): """Generate trigger data for watermark. Returns: ownership (dict): Watermark triggers information X_train (array): Modified input data y_train (array): Modified label data """ if s...
The main task of the code is to train a machine learning model on watermarked data by generating classification or regression triggers based on the model type, then returning encrypted or unencrypted ownership information containing trigger details and selected training samples.
def fit(self, X_train, y_train): """ Train the model on watermarked data Args: X_train (array): Input data y_train (array): Label data (0 / 1) Returns: ownership (dict): Watermark triggers information """ # Check type of the model if...
def find_cycle(N): memo = {} nsupport, nrocks = get_indices() for i in range(N): hrocks = hashable(nrocks) if hrocks in memo: return i + 1, memo[hrocks], nsupport, nrocks nsupport, nrocks = cycle(nsupport, nrocks) memo[hrocks] = i + 1 def cycle(support, rocks): ...
The code calculates the load after applying a determined number of cycles to initial values, based on parameters found by the find_cycle function, ultimately returning the computed load.
def solution(): N = 1000000000 p, b, nsupport, nrocks = find_cycle(N) ind = (N - b) % (p - b) for i in range(ind + 1): nsupport, nrocks = cycle(nsupport, nrocks) return calculate_load(nrocks)
def add_data_point(self, node, data_point): #add data points and update the the MBRS node.data_points.append(data_point) if data_point['x'] < node.MBR['x1']: node.MBR['x1'] = data_point['x'] if data_point['x'] > node.MBR['x2']: node.MBR['x2'] = data_point['x'] if ...
The code inserts a data point `p` into a node `u` (MBR) of a tree structure. If `u` is a leaf, it adds `p`, updates the MBR, and handles overflow. If `u` is not a leaf, it recursively inserts `p` into the chosen subtree to minimize perimeter sum, then updates the subtree's MBR. The main task is efficiently inserting da...
def insert(self, u, p): # insert p(data point) to u (MBR) if u.is_leaf(): self.add_data_point(u, p) #add the data point and update the corresponding MBR if u.is_overflow(): self.handle_overflow(u) #handel overflow for leaf nodes else: v = self.choose_...
def start_server(): try: global ping g.server = sock.socket(sock.AF_INET, sock.SOCK_STREAM) ping = sock.socket(sock.AF_INET, sock.SOCK_STREAM) g.server.bind((g.host, g.port)) pn_port = g.port+1 ping.bind((g.host, pn_port)) g.server.listen() ping.listen...
This code implements an interactive shell for managing network connections, allowing users to set listening parameters (host/port), start a listener server, handle client interactions, list/close connections, and exit gracefully or forcibly. It processes commands like 'set', 'listen', 'select', 'close', and provides he...
def shell(): global cmnd, output_buffer, listen_thread, isShell isShell = True while not g.till: try: print() cmnd = input(f"{g.bl}┌[{g.e}FishShell{g.bl}]\n└───↠{g.y}>>> {g.e}") if cmnd == 'help': help_menu(command='help') elif 'help' i...
def _show(self, title="MULTIBOOT", text="", note=""): splash = displayio.Group(max_size=10) if title and len(title): lbl_title = label.Label(terminalio.FONT, text=title, color=0xFFFF00, x=0, y=3) splash.append(lbl_title) if text and len(text): lbl_text = label...
This code runs a multiboot menu interface, displaying paginated program listings with navigation controls. It continuously checks for key presses to execute selections, update the display, or navigate pages, maintaining an interactive loop for user interaction with loaded programs.
def run(self): self._show("MULTIBOOT", "Loading...", _version) self._load_programs() current_press = set() updated = True while True: if updated: self._clear() page, has_previous, has_next = self._show_programs() self._s...
def goals_by_week_component(task_list: TaskList) -> None: date_format = "%b %d" max_weeks = 8 goals_by_week = get_goals_by_week(task_list) goals_table_cols = [[], [], []] i = 1 for _, row in sorted(goals_by_week.items(), key=lambda p: p[0])[(-1 * max_weeks) :]: table_week_str = ( ...
This function generates a Streamlit dashboard displaying statistical breakdowns of goals and task completions. It shows weekly/monthly goal counts and task completions in two-column layouts, using separate components to visualize data trends over time.
def statistics_component( task_list: TaskList, previous_task_list: Optional[TaskList] ) -> None: st.header("Statistics") st.subheader("Goal Counts") col1, col2 = st.columns(2, gap="small") with col1: goals_by_week_component(task_list) with col2: goal_completions_by_month_compone...