dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _get_precise_code(self, params): """ Get precise code, i.e. progress code + recurency depth level """ return params.get('code') + '##' + str(params.get('recur_depth')) def _report_progress_do_percent(self, params): """ Progress reporting function At the moment...
This function marks progress as completed by updating parameters (100% progress, 'done' state) and handling reporting based on recursion depth. It stores data for main-level progress, immediately reports it, and cleans up tracking entries. For sub-level progress, it lazily reports. Finally, it removes the precise code'...
def _report_progress_done(self, params): """ Report progress as done. :param code: progress operation code :param total: total units :param msg: logging message :param recur_depth: recursion depth :param cancellable: indicates whether the operation is cancellable ...
def _get_recur_depth(self, code): """ Get current recursion depth :param code: web progress code :return: current recursion depth """ global recur_depths with lock: recur_depth = recur_depths.get(code, 0) return recur_depth def _get_precise_cod...
This function reports progress during iteration over a dataset, updating progress states (ongoing/done) and logging details. It handles cancellability, tracks recursion depth, and manages global progress tracking variables. It yields each element while maintaining concurrency safety via locks, ensuring proper cleanup a...
def _report_progress(self, data, msg='', total=None, cancellable=True, log_level="info"): """ Progress reporting generator :param data: collection / generator to iterate onto :param msg: msg to mass in progress report :param total: provide total directly to avoid calling len on d...
def drawSquare(win): for i in range(4): # create 3 white boxes with random coords bOriginX = random.randrange(0, W-50, 51) bOriginY = random.randrange(0, H-100, 51) bW = bOriginX + 50 # you have to include origin + width therefore 100-50 = 50 sBoxW bH = bOriginY + 50 square =...
The code creates a graphical window with randomly positioned, colored balls. It initializes balls with random velocities, ensuring none are stationary, then waits for a user click to start a simulation. The simulation likely animates the balls' movement based on their velocities.
def main(): win = GraphWin( "moving ball", W, H ) #--- define a ball position and velocity --- drawSquare(win) ballColor = ["red", "blue", "pink", "purple", "green"] for i in range(5): c = Circle( Point( random.randrange( 16, W-15, 20 ), random.randrange( H/3, 2*H/3, 20 ) ), 15 ) c.s...
def read_slope(): with open('input.txt', 'r') as f: lines = [parse_slope_line(line.strip()) for line in f] return lines def count_trees(slope, x_multiplier, y_multiplier): return len(get_tree_cords(slope, x_multiplier, y_multiplier)) def part_two(slope, part_one_answer): tree_counts = [ count_trees(slop...
The main task of the code is to process a slope data structure by counting trees encountered using specific movement parameters (3 right, 1 down) for part one, then calculating a second result using the first answer. It reads input, computes tree counts for part one, and prints both results.
def main(): slope = read_slope() part_one_answer = count_trees(slope, 3, 1) print('Part one:', part_one_answer) print('Part two:', part_two(slope, part_one_answer))
def generate_data(eps, eta, time_length_v1 = 20, time_length_v2 = 20, nfeat_v1 = 25, nfeat_v2 = 25, total_subjects = 200, ar_c1_v1 = [1, 0.5], ar_c1_v2 = [1, 0.5], ma_c1_v1 = [1, 0.6], ma_c1_v2 = [1, 0.6], ar_common_v1 = [1, 0.5], ar_common_v2 = [1, 0.5], ma_common_v1 = [1, 0.5], ma_...
The function `synthetic_data` generates a synthetic multiview longitudinal dataset with two views, simulating temporal dependencies using ARMA models. It creates data for two classes with controlled differences in covariance structure (via `eps`) and ARMA parameters (via `eta`). The dataset includes longitudinal measur...
def synthetic_data(eps, eta, time_length_v1 = 20, time_length_v2 = 20, nfeat_v1 = 25, nfeat_v2 = 25, total_subjects = 200, ar_c1_v1 = [1, 0.5], ar_c1_v2 = [1, 0.5], ma_c1_v1 = [1, 0.6], ma_c1_v2 = [1, 0.6], ar_common_v1 = [1, 0.5], ar_common_v2 = [1, 0.5], ma_common_v1 = [1, 0.5], ma...
def variable_selection_DGB(data, y, top_features = 'default', nboots=50, n_epoch_boot=50, structuresNN = None, structureGRU = None, LR=0.001, n_epochs=50, split_seed = 1234): ''' -data- : Input multiview data in a list where the (d-1)-th item of the list corresponds to the d-th view and has that view'...
The function `variable_selection` selects relevant variables from multiview data using specified methods (LMM, DGB, JPTA, or 'nothing'). It processes input data with views in (N,p_d,t_d) or (N,p_d) formats, applies the chosen method to identify top features per view (default: 25% per view), and returns pruned data with...
def variable_selection(data, y, method = 'nothing', top_features = 'default', nboots=50, n_epoch_boot=50, structuresNN = None, structureGRU = None, LR=0.001, n_epochs=50, split_seed = 1234): ''' ---Returns variables selected for any choice of the following methods: LMM, DGB, JPTA and nothing--- -data- : Inp...
def _parse_dtype_restrictions( allowed_dtypes: Collection[PolarsDataType] | None = None, excluded_dtypes: Sequence[PolarsDataType] | None = None, ) -> tuple[list[PolarsDataType], list[PolarsDataType], list[DataType]]: """ Parse data type restrictions. Splits allowed data types into flat and nested ...
The function `dtypes` generates a strategy for creating Polars `DataType` objects with customizable constraints. It allows specifying allowed/excluded data types, enabling time zones in datetime types, and controlling nesting complexity. The strategy recursively constructs nested data types if permitted, otherwise gene...
def dtypes( *, allowed_dtypes: Collection[PolarsDataType] | None = None, excluded_dtypes: Sequence[PolarsDataType] | None = None, allow_time_zones: bool = True, nesting_level: int = 3, ) -> SearchStrategy[DataType]: """ Create a strategy for generating Polars :class:`DataType` objects. ...
def find_words_for_seed(grid: Grid, filtered_words: List[str], seed: Square) -> List[Shape]: seed = Shape([seed]) seed.potential_words = filtered_words shapes = [seed] all_shapes = [] for i in range(0, grid.maxSize - 1): x = [] for shape in shapes: new_shapes = getExpande...
The code solves a grid-based puzzle by finding valid word shapes that fit within size constraints and character mappings. It filters candidate words, maps starting characters to words, and identifies valid shapes for each square. Through deduplication and iterative elimination of non-viable shapes, it constructs a solu...
def solve(grid: Grid) -> Optional[List[Shape]]: square_mapping: Dict[Square, List[Shape]] = {} for square in grid.squares: square_mapping[square] = [] filtered_words = [] for word in global_word_list: word_len = len(word) if word_len >= grid.minSize and word_len <= grid.maxSize:...
def available(self): return self.port.in_waiting def read(self): return self.port.readline() def ProcessPacket(self, packet): self.logger.log("packet:", packet) print(packet) for i, p in enumerate(packet): if "CSQ:" in p: self.sq = int(p[5]) ...
The code continuously checks for available messages in a loop, reads and decodes them, then processes the received data packets. It runs indefinitely in a separate thread, logging the start of the listener and sleeping for 1 second between checks to handle incoming messages.
def CheckMessages(self): self.logger.log("Listener Started") # infinite loop running in second thread while 1: # print('reading') if self.available() > 0: r = [] print("Reading...") while self.available() > 0: ...
def diagnose_new_patient(self): name = input(name_prompt) diagnosis = self.assess_appearance() self.save_diagnosis(name, diagnosis) def view_patient_history(self): print('Loading patient history...\n\n') self.simulate_load() print('Patient - Diagnosis') print('---...
The code defines a method `start_service` that runs an infinite loop to handle user interactions for a medical service application. It prompts the user with `action_prompt`, processes their choice to either diagnose a new patient, view patient history, or exit the application. If the user selects '3', it prints a closi...
def start_service(self): while True: choice = input(action_prompt) if choice == '1': self.diagnose_new_patient() elif choice == '2': self.view_patient_history() elif choice == '3': print(closing_application) ...
def load_document(): with open(path_to_input) as f: lines = f.read().splitlines() return lines def get_special_positions_in_line(line): asterisks = [] for match in re.finditer("\*", line): asterisks.append((match.group(), match.start(), match.end())) return asterisks def process_...
The main task of the code is to calculate the total sum of numbers surrounding special characters in each line of a document. It loads the document, iterates through each line to identify special character positions, retrieves surrounding numbers, and accumulates their total. The result is printed at the end.
def main(): lines = load_document() total = 0 for (index, line) in enumerate(lines): # number_positions_in_line = get_numbers_positions_in_line(line) sepcial_positions_in_line = get_special_positions_in_line(line) surrounding_numbers = process_line(index, lines, sepcial_positions_in_...
def getLogger(): # create logger BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LOG_FILENAME = os.path.join(BASE_DIR, "mylog.log") logger = logging.getLogger('Thrive') logger.setLevel(logging.INFO) if logger.handlers: logger.handlers = [] # create formatter ...
This function handles group initiation and winner selection in a multi-round bidding system. It processes POST requests to update group status, checks for pending invitations, sets group dates, selects winners based on bids or rounds, and returns JSON data or redirects to appropriate URLs for group progression.
def sendNotficationToStartComity(request): logger = getLogger() milliseconds = getCurrentMilis() id = request.POST.get('g_id') print("group_id" , id) allWinners = group_table.objects.filter(g_id=id, winner=True) print("allWinners" , allWinners) # If someone starts thrive make the start_comi...
def changePitchHeight(midiFile: str, octave = 1, min: int = 0, max: int = 127): """ """ midiFile = MidiFile (midiFile) new = MidiFile(type=0, ticks_per_beat = midiFile.ticks_per_beat) track = MidiTrack() new.tracks.append(track) for i in range(len(midiFile.tracks)): for msg in midiFi...
The main task of the code is to transpose the pitch of a MIDI file by two octaves and synthesize it into an audio file. It loads the original MIDI, applies a pitch height change, saves the modified MIDI, and converts it to a WAV file.
def maniMIDI(midiFile, manipulation = "tempo", filename = "audio/test3.wav"): """ """ org = MidiFile(midiFile) new = changePitchHeight(org, octave = 2) file = "midi/test.mid" exportMIDI(new, filename = file) synthMIDI(file, filename = filename)
def simulate_scenario(self): logging.info(f"Running in simulation mode. Saving result to {self.cfg.simulate_output}") duration = 0 for scene in self.cfg.scenes: self.get_or_initialize_mechanism(scene) duration += parse_time(scene.duration).total_seconds() frame_co...
The code renders scenes based on a configuration, logs timestamps and durations, handles interpolation frames between scenes, generates/saves frames when needed, and manages state transitions. It simulates or processes scenes sequentially, adjusting for interpolation durations and maintaining context between consecutiv...
def run(self): logging.debug(f"Launching with config:\n{OmegaConf.to_yaml(self.cfg)}") if "simulate_output" in self.cfg: self.simulate_scenario() return # TODO: this is pretty stateful, when resuming a run the interpolation frames will not be used. # Must find an...
def create_folder(self, directory): """ Given a path, create the directory """ directory = os.path.dirname(directory) if not os.path.exists(directory): print(directory + ' does not exist...') os.makedirs(directory) print(directory + ' directory created...') de...
The code initializes a class with a predefined distance value, sets source and destination folder paths based on this distance, creates the destination folder, filters images from the source, and removes zero data from the destination folder. The main tasks involve directory setup, image filtering, and data cleanup.
def __init__(self): self.distance = 30000 # Filepath self.src_folder = "./raw_data/28_03_2022-12_11_52-filtered" self.dst_folder = self.src_folder + "-" + str(self.distance) + '/' self.src_folder = self.src_folder + '/' self.create_folder(self.dst_folder) self.f...
def _next(self) -> Optional[str]: self._index += 1 return self._current() def _lookahead(self) -> Optional[str]: return ( self._pattern[self._index + 1] if self._index + 1 < len(self._pattern) else None ) def _get_character_range(first: str, last: str)...
This function parses a character class definition, handling escape sequences, ranges (e.g., a-z), and quantifiers. It accumulates valid characters into a string, processes meta-tokens with proper escaping, and returns a CharacterSet object containing the parsed characters along with start and count values derived from ...
def _get_character_set(self) -> CharacterSet: chars = "" cnt = 1 start = 0 while True: char = self._next() if self._lookahead() == MINUS and not char == BSLASH: f = char self._next() # skip hyphen char = self._next...
def _next(self) -> Optional[str]: self._index += 1 return self._current() def _last(self) -> Optional[str]: return None if self._index == 0 else self._pattern[self._index - 1] def _get_literal(self) -> Literal: chars = "" char = self._current() while True: if ...
This method parses a sequence of tokens, handling nested structures, operators (like '|'), and literal/character set elements. It constructs a Sequence object with parsed components, ensuring proper syntax (e.g., balanced parentheses, valid operators) and combining operands using SequenceOR when encountering '|'. It ra...
def _get_sequence(self, level: int = 0) -> Sequence: seq = [] op = "" left_operand = None sequence_closed = False while True: char = self._next() if not char: break is_last_bslash = self._last() == BSLASH if char and...
def read_template(template_name, configs): """Return a list containing lines of template text after parsing the template file""" folder_path = configs['templates_folder'] templates_dir = os.path.abspath(folder_path) template_path = os.path.join(templates_dir, template_name) #TODO: verify file actua...
The main task of the code is to generate FSH (FHIR Shorthand) code for multiple resources by processing templates and associated data files. It iterates through job configurations, reads and parses templates, loads resource data using specified or generic parsers, handles additional input files, and generates FSH insta...
def run_jobs(context): configs = context['configs'] template_lookup = context['templateLookup'] resource_data_lookup = context['resourceDataLookup'] for job in configs['jobs']: resource_name = job['resource'] print('#######################################################################...
def read_yaml_file(path): """Return a JSON object after parsing the input file""" if debug: print('read_yaml_file: input file = ' + path) jsonobj = {} with open(path) as yaml_file: jsonobj = yaml.load(yaml_file) if debug: pprint(jsonobj) return jsonobj def process_co...
The main task of the code is to generate FSH code files by reading configuration data, processing templates, and executing jobs. It initializes context, loads a YAML config file, sets debug mode if enabled, processes config and templates, then runs jobs to produce output. The script handles global debug settings and or...
def main(): """Main entry point for the script.""" print ("Starting gen_fsh_code script.") print ("Running in Main...") global debug context = {'templateLookup':{}, 'resourceDataLookup':{}} # read config file config_dir = os.path.abspath(DEFAULT_CONFIG_DIR) config_path = os.path.join(...
def get_data(url: str) -> dict: ''' Sends http get request to any URL and returns the a dictionary representation of the response. if data doesnt exist it returns an empty list. Runs in O(1) time. ''' # with aiohttp.ClientSession() as session: # response = session.get(url, ssl=False)...
The main task of the code is to fetch data from a URL, process it, display results, measure execution time, and retrieve updates using the provided data and URL.
def main(): start = time.time() data_url = 'https://mapping-test.fra1.'\ 'digitaloceanspaces.com/data/list.json' article_data = get_data(data_url) process_data(article_data) display_result() end = time.time() print(f"Took {end - start} seconds to run") get_upd...
def __init__(self): self.__goal_state = False self.__agent_state_1 = [0, self.__GRID_HEIGHT - 1] self.__agent_state_2 = [self.__GRID_WIDTH - 1, self.__GRID_HEIGHT - 1] self.__cow_state = [2, self.__GRID_HEIGHT - 1] self.__cow_counter = 0 self.__grid = [[-1 if [i, j] in se...
The code simulates interactions between two agents in an environment, tracking their actions, positions, and the cow's position over a maximum number of movements. It uses Q-values to determine each agent's actions, executes them, and updates the simulation state. The process stops when the simulation finishes or reach...
def test(self, agent1, agent2, maximum_movement=200): moves = [] move1 = [] move2 = [] position_cowboy1 = [] position_cowboy2 = [] position_cow = [] print("WTF") self.__init__() for i in np.arange(maximum_movement): print(i) ...
def __go_loading(self, i, total, show): percentage = i * 100 / total p = percentage s = "[" k = 0 while percentage > 0: s += "*" percentage -= 2 k += 1 k_prime = k while k < 50: k += 1 s += " " if...
The code trains two agents using reinforcement learning to reach a goal state by updating their Q-values through exploration (epsilon-greedy) and exploitation (max Q-values). It runs multiple episodes, where each agent selects actions based on their Q-table, receives rewards, and updates their Q-values using a discount...
def train(self, agent1, agent2, episodes=2000, maximum_movements=200, random=0.98, discount=0.99999, gamma=0.99): epsilon = 1 lamda = 1 maxxx = 200 ans = [] x = [] save1 = [] save2 = [] pause = 'n' show = -1 for i in np.arange(episodes): ...
def getAPIKey(): sw = requests.get('https://youtube.com/sw.js') script = re.findall(r'ytcfg\.set\(({.+?}},)',sw.text)[0].replace(r'}},',r'}}}') jsParse = json.loads(script) API_KEY = jsParse["INNERTUBE_API_KEY"] return API_KEY def getCookies(): cookies = parseCookieFile("youtube.com_cookies.txt") return cooki...
The code scrapes YouTube watch history using an authentication token, processes paginated data via continuation tokens, and exports video data to a specified JSON file. It handles command-line arguments for authentication, page limits, and output destination, with optional debug logging.
def main(): parser = argparse.ArgumentParser(description='scrap full youtube history') parser.add_argument('-a','--auth', help='auth token, you can get it from here https://i.imgur.com/xf8gqgl.png in https://www.youtube.com/feed/history, if you can\'t find it scroll to the end of the page and try again') parser.add_...
def get_config(self): """ Read config.yml file and return key elements.""" if not self.working_directory: self.working_directory = os.path.dirname(__file__) with open(os.path.join(self.working_directory, self.path), "r") as config: cfg = yaml.load(config...
This code initializes a class instance by loading configuration data from a specified path, processes parameters like customer IDs and data sources, sets up BigQuery project/dataset details, extracts query configurations, and converts date fields. The main task is to configure and prepare data processing or analysis wo...
def __init__(self, path, working_directory=None): self.path = path self.working_directory = working_directory # TODO: duplicate fields for config self.config = self.get_config() self.customer_id = self._atomic_to_list(self.config.get("customer_id")) self.ads_data_from = s...
def select_next_evtol(self): failed_attempts = 0 if not self.current_evtol: self.current_evtol = self.all_evtols[0] new_evtol_index = 0 else: old_evtol_index = self.all_evtols.index(self.current_evtol) new_evtol_index = old_evtol_index + 1 ...
The code processes an action in a simulation environment for EVTOLs (electric vertical takeoff and landing vehicles), decoding it to update their status, position, and job details (e.g., landing, takeoff, hovering). It handles noise, battery management, and environment updates, calculates rewards, and returns observati...
def step(self, action): """One of 11 actions is decoded and applied to the simulation environment.""" start_time = time.time() self.select_next_evtol() if self.test == "FCFS": decoded_action, self.test_takeoff_queue, self.test_land_queue = self.action_manager.decode_action_...
def majority_vote(data): if len(data[(data[: , -1]) == 1]) >= len(data[(data[: , -1]) == 0]): vote = 1 else: vote = 0 return vote def cal_entropy(label_column): count = 0 neg_sum = 0 pos_sum = 0 entropy = 0 if len(label_column) == 0 : return 0 else: ...
This function recursively constructs a decision tree by splitting data based on attributes. It creates nodes, checks base cases (max depth, entropy zero, single sample, no split), and returns leaf nodes with majority votes or internal nodes with splits. The tree stops splitting when conditions like max depth, zero entr...
def build_tree(data, max_depth, parent_depth = -1): new_node = Node() new_node.depth = parent_depth + 1 #base case #1. reach user's specified max_depth #2. All labels are identical (entropy == 0 ) #3. No more data to split (only 1 sample in a node) #4. Stop when mutual information == 0 ...
def build_tree(data, max_depth, parent_depth = -1): new_node = Node() new_node.depth = parent_depth + 1 #base case #1. reach user's specified max_depth #2. All labels are identical (entropy == 0 ) #3. No more data to split (only 1 sample in a node) #4. Stop when mutual information == 0 ...
This function plots training and testing errors against decision tree depth by iterating through depths, building trees, predicting outputs, calculating errors, and visualizing results.
def plot_errors(train_data, test_data): max_depth = train_data.shape[1] - 1 depth = range(max_depth) train_error = [] test_error = [] for each_depth in range(len(depth)): trained_tree = build_tree(train_data, each_depth) train_y_hat_lst = predict_output(train_data, trained_tree) ...
def epoch(self): """returns block number Returns: int: block number """ return self.block.block_header.beacon.checkpoint def parent(self): """parent block hash Returns: string: parent block hash """ return self.block.block_header....
The code's main task is to convert a Witnet proto object into a simplified dictionary format suitable for a dashboard. It aggregates specific attributes like block number, parent hash, miner, and transaction fees, sets placeholder values for difficulty and total difficulty, and includes transaction data via `self.get_t...
def convert(self): """reduce the witnet proto object to the required data by dashboard Returns: dictionary: reduced block data """ return { "number": self.epoch(), "parentHash": self.parent(), "miner": self.miner(), "difficulty...
def is_p2p_valid(self): return (hasattr(self, 'connection') and not self.connection.is_closed()) def send_active_and_uptime(self, active): # if active is false # or there is state change # send active and uptime stats if active != self.active or not active: self.activ...
(The code defines a loop that continuously listens for and processes messages from a node, updating the blockchain and sending relevant data to the frontend. It handles various message types (Block, SuperBlockVote, LastBeacon, Peers), validates P2P connections, manages inactive states with retry logic, and schedules pe...
def start_listener_loop(self): while not self.terminate: # this returns serialized message from node and parses to python obj if self.is_p2p_valid() and self.sio.connected: # if the p2p connection is valid # update active and send the stats to frontend ...
def initUserJson(self): directory_list = os.listdir("json") logging.info("Checking if userinfo.json exist...") if "userinfo.json" not in directory_list: logging.info("Initializing userinfo.json") logging.info(f"Creating userinfo.json") with open(f"json\\userin...
The main task of the code is to initiate the controller by retrieving user credentials from a JSON file, attempting automatic login if credentials exist, or launching a login window if no user data is found. It logs progress and handles potential errors during the login process.
def start(self): """ This function start the main controller. """ self.initUserJson() userinfo = self.getIdPw() logging.info("Grabbing user id and password from userinfo.json in order to log in...") # try: # if userinfo: # logging.info...
def _initMenu(self): self._createActions() self._createMenuBar() def _initMainLayout(self): """ Only those objects that will be used afterwards will be the property of the class """ mainVlayoutwidget = QWidget() mainVlayoutwidget.setObjectName("mainWidget") ...
The main task of the code is to initialize the user interface (UI) of an application by setting up the menu, main layout, attendance-related widgets, and announcement-related widgets. This method orchestrates the UI components, ensuring the interface is structured and functional for features like attendance tracking an...
def _initUI(self): self._initMenu() self._initMainLayout() self._initAttendanceWidgets() self._initAnnouncementWidgets()
def add_function(self, button): button.destroy() func = simpledialog.askstring('Function prompt', 'Enter the function to add') function = Function(func, self.__xMin, self.__xMax, self.__yMin, self.__yMax, self.__screen) self.listFuncs.append(func) self.__funcs.append(function) ...
This code creates a Tkinter GUI window with buttons to perform actions like adding/removing functions, clearing text, adjusting bounds, toggling drawing mode, and closing the window. Each button triggers a corresponding method (e.g., add_function, remove_function) and uses lambda to pass the window instance. The mainlo...
def getChoice(self): options = tk.Tk() tk.Button(options, command = lambda: self.add_function(options), text='Add a new function', padx=10).grid(row=0, padx=(40,40), pady=(20,0)) tk.Button(options, command = lambda: self.remove_function(options), text='Remove a function').grid(row=1) tk....
def baseGrid(self): for i, func in enumerate(self.__funcs): print(func) xGrid, yGrid = func.changeInSignGrid(i+1) self.__points.append((xGrid, yGrid)) def plot(self, update, *func): if update: if func: count = len(self.__funcs)+1 ...
The code initializes a pygame-based interactive interface, continuously updating the display at 60 FPS. It handles mouse events: left-clicks trigger function selection or exit, right-clicks add user-input text, and quit events terminate the loop. The core task is to manage real-time user interaction, screen rendering, ...
def start(self): p = True update = True self.baseGrid() while p: self.plot(update) self.functionBox() self.crossBox() update = False for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: ...
def part_repulsive_force(i, j): """ calculates the force used in the repulsive_force function. As per chate 2008 """ if bound_cond == True: # calculate the distance between the points distance_x, distance_y = per_boun_distance(i, j) # calcualte the magnitude of the distance betwe...
This function calculates a particle's new acceleration by summing repulsive forces from other particles, contact forces from objects, alignment forces with other particles' velocities, and an error term, then normalizing by mass. It iterates through all particles and objects to compute these forces, combining them with...
def update_acceleration(position_particle, velocity_particle, position_particles, velocity_particles, positions_obj, polygons): """ Algorithm which updates the algorithm """ # define two inital forces dependent on the particles and on hte object force_object = np.array([0., 0.]) force_particles ...
def update_acceleration(position_particle, velocity_particle, position_particles, velocity_particles, com_objects): """ Algorithm which updates the algorithm """ # define two inital forces dependent on the particles and on hte object force_object = np.array([0., 0.]) force_particles = np.array([...
This function updates the positions and velocities of all particles in a physical system by calculating new acceleration values for each particle based on their current positions and velocities, then applying these accelerations to compute updated velocities and positions. It iterates through each particle, uses auxili...
def update_system(positions, velocities, accelerations, com): """ Updates the positons and velocities of ALL the particles in a system. """ # lists which will contain the updated values new_positions = [] new_vels = [] # loop through each index in the positions, vel, acc for i in range(...
def update_acceleration(position_particle, velocity_particle, position_particles, velocity_particles, positions_obj, polygons): """ Algorithm which updates the algorithm """ # define two inital forces dependent on the particles and on hte object force_object = np.array([0., 0.]) force_particles ...
This function updates the positions and velocities of all particles in a system by calculating acceleration for each particle based on interactions with other particles and objects. It iterates through each particle, computes new velocity using acceleration, updates position considering boundaries (polygons), and store...
def update_system(positions, velocities, positions_obj, polygons): """ Updates the positons and velocities of ALL the particles in a system. """ # lists which will contain the updated values new_positions = [] new_vels = [] # loop through each index in the positions, vel, acc for i in r...
def pop_box(): """ Function which creates one particle with a ramdom position and velocity in a square of dimensions L by L. """ # will hold each posi/vel/acc for each particle in the system positions = [] velocities = [] accelerations = [] for i in range(N): # lsit containi...
The main task of the code is to simulate a physical system by initializing particle positions, velocities, and accelerations, then iteratively updating their states over time. It tracks the positions and velocities at each step and visualizes the 2D trajectories of particles alongside a square's vertices and center of ...
def main(): # fill up a box with particles and objects positions, velocities, accelerations = pop_box() verticies, com = square() # append the positions to the positions over time pos_over_t = [positions] vel_over_t = [velocities] # update the position for 10 times for i in range(U): ...
def pop_box(): """ Funciton which populates the box with N particles in random locations and random velocities inside the box. """ global L, dimensions, N # initial positions of created particles init_positions = [] # initial velocities of created particles init_velocities = [] ...
The main task of the code is to simulate particle movement in a box by iteratively updating velocities and positions using neural network functions, while varying input noise parameters. It tracks positions and velocities over time, computes velocity alignment, and returns the alignment metric without generating plots.
def main_noise(): """ Execution of main program, wihtout any plots and with varying the paramenter of noise in the input. """ # all positions over time pos_over_t = [] # all velocities over time vel_over_t = [] # populate the box - returns initial poss and vels positions, veloci...
def update_ang_acceleration_object(polygon, position_obj, ang_vel_object, positions_obj, position_particles, velocity_particles): """ Algorithm which updates the acceleration of the com of the object """ # define two inital forces dependent on the particles and on hte object torque_particles = 0 ...
The function updates the positions and angular velocities of all objects in a system by calculating angular acceleration based on polygon geometry, object positions, and particle interactions. It iterates through each object, computes new angular velocities from acceleration, and updates polygon vertices' positions acc...
def update_system_object(polygons, positions_obj, ang_velocities_obj, position_particles, velocity_particles): """ Updates the positons and velocities of ALL the objects in a system. """ # lists which will contain the updated values new_ang_vels = [] new_polygons = [] # loop through each in...
def polygon(origin, a, angle_diff, spikes): """ Define the polygon from the points on the verticies. """ refvec = (0, 1) def clockwiseangle_and_distance(point): """ Finds angle between point and ref vector ffor sortinf points in rotor in order of angles """ ...
This function simulates a system's dynamics over U time steps, tracking particle/object positions, velocities, and angular velocities. It initializes polygon shapes, populates particles/objects, updates their states iteratively, records temporal data, and returns final velocity alignment. If 'plot=True', it visualizes ...
def one_run(plot = False): """ One simulation of a total run by the system. """ # produce the polygons (verticeies of the polygon) positions_polygons = [polygon([L/2, L/2], 0.629867564929, 4.84245309456, 7) for i in range(M)] # fill up a box with particles and objects positions, velocities...
def convert_to_highway_tunnel(self, rule: Rule, parent_rules=[], zoom_min=0): """ Find lines in the rules and make them dashed :param rule: :param parent_rules: :param zoom_min: """ # rember parent rules for parent_rules.append(rule) if rule.zoom_...
The main task of the code is to process XML elements based on predefined actions (e.g., converting sections to tunnels, bridges, or adding styles). It identifies input sections, extracts source data, applies transformation rules using XML parsing/serialization, modifies elements according to action types, updates the X...
def process_actions(self) -> BeautifulSoup: # find places where are required some actions and where results will be placed input_sections = [] for action_name in self.actions: input_sections.extend(self.soup.find_all(action='{}'.format(action_name))) for input_section in in...
def _get_render_theme_header(self) -> Rendertheme: """ Prepare the root element of mapsforge theme XML. Set also version, background color :rtype: Rendertheme """ render_theme = Rendertheme() render_theme.version = 4 render_theme.base_stroke_width = 0.8 re...
The function generates custom render themes for POI data by processing folder/subfolder configurations, inheriting zoom levels and themes, creating rules with tags/symbols, and organizing them into layer-specific themes (e.g., hike_bike, ski). It ensures icon visibility rules are applied and saves the structured themes...
def generate_render_themes(self): """ For every theme (defined in POI DB configuration XML) creates a custom render theme. Every layer (hike_bike, ski) has separated theme file with icon definition """ render_theme = self._get_render_theme_header() for folder in self.poi...
def _parse_requirements_file(self, path: str, filename: str) -> Iterable[Dependency]: if ("requirements" in filename and filename.endswith(".txt")) or path.split("/")[-1] == "requirements": yield from self._resolve_requirements(source=self.read_source(path, filename)) def _parse_pipfile(self, path: ...
The main task of the code is to parse dependency files (requirements.txt, Pipfile, Pipfile.lock) from a given path and filename, yielding collected dependencies as an iterable. It delegates parsing to three internal methods, aggregating results for dependency resolution or analysis.
def parse_file_for_dependencies(self, path: str, filename: str) -> Iterable[Dependency]: yield from self._parse_requirements_file(path, filename) yield from self._parse_pipfile(path, filename) yield from self._parse_pipfile_lock(path, filename)
def simulate(w, C, n, z): X = np.random.multivariate_normal(np.array([0]*C.shape[0]), C, size = n) X += np.dot(z.reshape(-1, 1), w.reshape(-1, 1).T) return X def gen_C(u, g): A = np.tile(u, (len(u), 1)) B = np.abs(np.multiply((A.T- A) , nx.adj_matrix(g).todense())) myfunc_vec = np.vectorize(f) ...
The code generates two synthetic datasets, X1 and X2, using specified parameters (e.g., covariance matrices, random seeds) and simulates data based on normal distributions. It then executes an analysis or comparison function `run` with these datasets, along with parameters `g`, `lambdas`, and scaled variables, to evalu...
def runner_(cnt_): print(g) np.random.seed(cnt_) z = np.random.normal(0, 1, n) v = np.zeros(p1) v[25:50] = 1 Cv = 0.1 * np.ones((p1, p1)) np.fill_diagonal(Cv, 1) v = c * v X1 ...
def q1(): print("\nQuestion 1:") print("User provides a choice of cuisine and zipcode, the query returns a list of \ntop 5 restaurant names with full address and rating with results sorted descending order based on rating.") print("\nEnter Zip code (example : CF243JH)") get_unique_values(rest, 'zipcode'...
The code provides a menu-driven interface for MongoDB data queries. It displays a welcome message, loops to accept user input (Q1-Q4 for specific queries or 'Q' to exit), and executes corresponding functions (`q1()` to `q4()`) based on the selection. The loop ensures repeated interaction until the user quits. Your retu...
def main(): print("##############################################################################") print("Welcome to MongoDB Data Query") print("##############################################################################") while (True) : print("\n\nPlease Select Question number (valid option...
def start_timer(self): self.start_time = time.time()*1000; def day_sum_gas_consumption(self, gas_type, days_ago): factor = self.get_factor(gas_type) recorded_url = 'recorded/?startTime=-{}d&endTime=-{}d'.format(days_ago, days_ago + 1) interpolation_url = 'interpolated/?startTime=-{}d&en...
The code aggregates total fuel consumption values (gas, pellets, coal+pellets) over a specified number of days by iterating through fuel type dictionaries, calling specialized calculation methods, and summing results. It returns these aggregated values for further processing, likely for energy or emissions analysis.
def sum_all_fuels(self, days_ago): global burner_name gas_value = 0 pellets_value = 0 coal_pellets_value = 0 for dict in self.all_fuels_dict: self.start_timer() for burner_name in self.all_fuels_dict[dict]: curr = 0 if dic...
def train_epoch(self, train_loader, epoch=None): """ Method for the training of one single epoch. :param train_loader: data loader for training data :param epoch: index of epoch :return: training loss value averaged across training batches and a dictionary containing useful info...
This method trains a machine learning model using provided data loaders, performing validation after each epoch to monitor performance via a specified metric. It implements early stopping if validation performance stagnates, logs training details with Weights & Biases (if enabled), and saves the best model to a specifi...
def train(self, train_loader, val_loader, val_metric=None, n_epochs=500, early=None, verbose=10, save_path=None): """ Method for the train of the model. :param train_loader: data loader for training data :param val_loader: data loader for validation data :param val_metric: valid...
def iter_transformed_unfoldings(unfolding, box): """ Take an unfolding and generate all possible transformed versions by rotation and transformation, folding cells into the box by wrapping them around to the opposite sides of the box. Yield all unique results. For each result, an unfolded and folde...
The function generates an exact covering matrix from all possible transformed versions of an unfolding. Each row represents a transformed unfolding, with 1s indicating cell positions in the given box. It returns the matrix and a list of transformed unfoldings corresponding to the matrix rows.
def generate_matrix(unfolding, box): """ Create exact covering matrix from all possible transformed versions of the unfolding. Returns the matrix and a list with the transformed unfoldings that correspond to the rows of the matrix. """ transformed_unfoldings = list(iter_transformed_unfoldings(un...
def load_ofac_sanction_list_as_dict(filename: str) -> Dict[str, Any]: with open(filename, "rb") as fp: data: Dict[str, Any] = xml_to_dict(fp.read(), array_tags=OFAC_XML_ARRAY_TAGS) return data def parse_ofac_date(v: str) -> date: st = strptime(v, "%m/%d/%Y") if not st: raise ValidationEr...
The function imports OFAC sanctions data from a file into a database, parsing publication dates, creating `SanctionEntity` records, and associating related members. It logs progress and duration, uses database transactions for integrity, and updates the source object with import metadata.
def import_ofac_sanctions(source: SanctionsListFile, verbose: bool = False): data = load_ofac_sanction_list_as_dict(source.full_path) source.generation_date = parse_ofac_date(data["publshInformation"]["Publish_Date"]) t0 = now() entities_list = data.get("sdnEntry", []) for se_data in entities_list:...
def init(self, data_shape: Union[list, tuple, np.ndarray]): self._shape = data_shape self._d = np.prod(data_shape) self.mu = np.zeros((self.k, self._d)) self.W = np.random.randn(self.k, self._d, self.q) self.phi = np.random.rand(self.k) + self.__prec self.__update_M() ...
The main task of the code is to train a probabilistic Principal Component Analysis with Mixture Models (pPCAMM) by iteratively updating model parameters—mixture weights (mix), cluster means (mu), transformation matrices (W), and variances (phi)—using the Expectation-Maximization (EM) algorithm. It optimizes the model t...
def fit(self, X: np.ndarray, iterations: int=10, verbose: bool=True, save_mem: bool=False): """ Fit a GMM to the given datapoints :param X: the data to fit to, as a numpy array with shape [# samples, ...] :param iterations: the number of iterations to fit the model to the data for ...
def edit_user(task_number): """ In this block, the user assigned a task in 'tasks.txt' can be edited to a different user. This user is chosen from the 'user.txt' file. """ new_user_num = 0 error_input = True lines = file_read_handling('tasks.txt', 'r') changed_username = False pr...
The function allows users to edit a task's username, due date, or both in 'tasks.txt'. It prompts for selection (u, d, or b), calls corresponding edit functions, updates task and user reports post-edit, and handles invalid inputs by re-prompting.
def task_edit(task_number): """ In this block, the user selects if they would like to edit the username, the due date of a task or both in the 'tasks.txt' file. """ test_val = True while test_val: print("Would you like to edit the username or the due date or both?") user...
def mark_completed(task_number): """ In this block, for the task selected, if the task is not completed, the task will be assigned "Yes" to mark as completed. """ lines = file_read_handling('tasks.txt', 'r') temp_file_info = open('tasks.txt', 'w') for pos, line in enumerate(lines): ...
This function handles user choices to either mark a task as completed or edit it. If the choice is 'm', it marks the task as completed and updates reports; if 'e', it allows editing the task. Invalid choices trigger an error message.
def choice_task_funct(choice_task, task_number): """ In this block, the correct function is called based on whether the user would like to mark the task specified in task number as completed or whether they would like to edit something in the specified task number. """ if choice_task == "m": ...
def load_models(config_path): config = OmegaConf.load(config_path) config = OmegaConf.to_container(config, resolve=True) device = config.get("device", "cuda") diffusion_extractor = DiffusionExtractor(config, device) dims = config.get("dims") if dims is None: dims = collect_dims(diffusion...
This code loads pre-trained models, initializes a WandB run for logging, configures an AdamW optimizer for specific layers of an aggregation network, and either trains the model using provided data or validates it with pre-loaded weights. It handles training/validation logic based on config flags, ensuring batch size c...
def main(args): config, diffusion_extractor, aggregation_network = load_models(args.config_path) wandb.init(project=config["wandb_project"], name=config["wandb_run"]) wandb.run.name = f"{str(wandb.run.id)}_{wandb.run.name}" parameter_groups = [ {"params": aggregation_network.mixing_weights, "lr"...
def get_course_home(): """ Returns the full path name of the base for courses (~home_dir/Vorlesungen/Eigene Unterlagen) """ return os.sep.join([get_userhome(), 'Vorlesungen', 'Eigene Unterlagen']) def change_module_name(new_name=None, old_name=None, verbose=False): if new_name is None: retur...
The main task of the code is to copy a chapter's content, including notebooks, slides, and associated files, from a source course to a destination course. It allows renaming chapters, adjusting file names, and institution-specific slide formatting (e.g., GSO/HSAA). The function handles directory copying, file renaming,...
def copy_chapter(from_course=None, to_course=None, chapter=None, new_chapter=None, old_name=None, new_name=None, institution=None, slide_title=None, overwrite_existing=False, log_level=logging.ERROR): """Copies all...
def getParameter(self, p_name, p_default=None): try: p_value = self.p_dict[p_name] except KeyError: p_value = p_default return p_value def setParameters(self, p_dict): for (k, v) in p_dict.items(): self.p_dict[k] = v def createAllOutputDirectories(sel...
The main task of the code is to create a new chapter by generating LaTeX files and copying notebooks. It sets up directories, processes chapter content and titles, and handles LaTeX generation and notebook duplication for Exercises and Examples sections, using parameters to control output and logging.
def createChapter(self, c_nr=1, c_content=None, c_title=None): self.logger.setLevel(self.getParameter('loglevel')) if c_title is not None: self.setParameters({'subtitle': c_title}) self.createAllOutputDirectories() try: source_chapter, tex_files = self.contents[c...
def load_portfolio(self) -> Tuple[List[Share], List[CashFlow], List[Dividend]]: ''' Loads units, price, sell_price, buy_date, sell_date and code as registered in the data csv ''' # First, work out when the portfolio starts data = pd.read_csv('./portfolios/'+self.filename+'.csv').dropna(how='all'...
The code initializes a portfolio class with attributes like name, filename, and loaded financial data (shares, cash flows, dividends). It filters active shares with non-zero units, calculates the portfolio's current value, and computes returns. The main tasks are: 1) Loading portfolio data, 2) Filtering active holdings...
def __init__(self, name: str, filename: str) -> None: self.name = name self.filename = filename self.shares, self.cash_flows, self.dividends = self.load_portfolio() self.curr_shares = [share for share in self.shares if share.timeline.iloc[-1]['units'] != 0] self.portfolio_value =...
def get_config(): """Gets the config object from disk.""" with open(CONFIG_PATH, mode="rt", encoding="utf-8") as file_handle: return yaml.safe_load(file_handle) def timeout_abort(label, url): """Abort this script and log it as a timeout error.""" config = get_config() state = get_state() ...
The main task of the code is to retrieve data from a specified URL with retry logic for handling timeouts and connection errors. It uses a configurable timeout duration and retry limit from a config file, retrying up to the defined limit before aborting. The function returns the response object after successful retriev...
def get_with_retry(url, label, api_auth=None): """Gets the specified URL and retries if there's a timeout.""" config = get_config() reqs_timeout = config["requests_timeout_seconds"] retry_limit = config["getreq_retry_limit"] tries = 0 while True: try: resp = requests.get(url,...
def fail_exit(): """Updates state yaml and exits with error exit code.""" state = get_state() state["last_failed_run"] = datetime.now().isoformat() write_state(state) sys.exit(1) def get_config(): """Gets the config object from disk.""" with open(CONFIG_PATH, mode="rt", encoding="utf-8") as ...
The main task of the code is to update a DNS record with the current WAN IP if it differs from the stored value, using a configuration file for settings. It checks the WAN IP, compares it to the existing record via an API, updates the DNS entry if necessary, handles errors, logs changes, and sends email notifications i...
def main(): """Main app execution code.""" if not exists(CONFIG_PATH): logger.error("Could not find %s", CONFIG_PATH) fail_exit() with open(CONFIG_PATH, encoding="utf-8") as file_handle: config = yaml.safe_load(file_handle) logging.basicConfig( format=config["log_forma...
def is_data_old() -> bool: return __get_data_age_seconds() > config.dataService_MAX_DATA_AGE def scrape_and_cache_data(): listings = scrapeService.do_scrape() geocode_all_data(listings) ioService.overwrite_listings_file(listings) ioService.overwrite_listings_metadata_file(__get_current_time_seconds(...
The main task of the code is to retrieve data efficiently by checking if cached data is recent. If the data is outdated, it performs a full scrape and updates the cache; otherwise, it returns the existing cached data. This approach minimizes redundant scraping and ensures up-to-date information is used when necessary.
def get_data(): # Return cached data if it's recent enough if is_data_old(): # Execute full scrape. return scrape_and_cache_data() else: return get_data_cache()
def encodeBatch(self, X, batch_size=256): use_cuda = torch.cuda.is_available() if use_cuda: self.cuda() encoded = [] num = X.shape[0] num_batch = int(math.ceil(1.0 * X.shape[0] / batch_size)) for batch_idx in range(num_batch): xbatch = X[batch_idx...
This code performs clustering on input data using a neural network model that combines clustering objectives with reconstruction and similarity losses. It initializes cluster centers via KMeans, trains the model with an optimizer, and iteratively updates cluster assignments while minimizing losses like clustering, ZINB...
def fit(self, X, X_raw, sf, ml_ind1=np.array([]), ml_ind2=np.array([]), cl_ind1=np.array([]), cl_ind2=np.array([]), ml_p=1., cl_p=1., y=None, lr=1., batch_size=256, num_epochs=10, update_interval=1, tol=1e-3, save_dir="" ): use_cuda = torch.cuda.is_available() ...
def _generate_reagent_worklists(instruction_set, path_to_worklists=""): """Convert worklist and save CSV files Save all worklists from experiment as .csv files in data/worklists/[experiment ID]. Saves a single .zip in data/worklists/[experiment ID]/[experiment ID]_all.zip. instructio...
The function `generate_experiment_files` creates and saves CSV worklists for reagent and inoculation dispenses based on an experiment's instruction set, plate layout, and inoculation volume. It organizes these files into a directory structure under `data/worklists/[experiment ID]`, generates a ZIP archive containing al...
def generate_experiment_files( instruction_set, layout, inoculation_volume, path_to_worklists="" ): """Create worklists for reagent and inculation dispenses and save CSV files Save all worklists from experiment as .csv files in data/worklists/[experiment ID]. Saves a single .zip in ...
def init_grid(self): machinegrid=[] for i in range(self.cellmax): bb=[] for j in range(self.cellmax): bb.append(0) machinegrid.append(bb) randbomb= [(i,j) for i in range(self.cellmax) for j in range(self.cellmax)] # random.seed(0) ...
This code initializes a Minesweeper game with Pygame, setting up grid parameters, reward structures, and visualization components. It configures game states, tracks progress, and loads assets for rendering cells, bombs, and UI elements, preparing the environment for gameplay or AI training with specified reward mechani...
def __init__(self, cellmax=16, bombnumber=40, # based on https://github.com/jakejhansen/minesweeper_solver rewards={'win':1, 'lose':-1, 'progress':0.3, 'guess':-0.3, 'no_progress' : -0.3}): self.cellmax=cellmax self.bombnumber = bombnumber self.grid = self.init_grid() # ...
def creatingmachinelist(cellmax,bombnumber): machinelist=[0 for i in range(cellmax*cellmax)] randbomb= [i for i in range(cellmax*cellmax)] random.seed(5) randbomb= random.sample(randbomb,bombnumber) for i in randbomb: machinelist[i]=-1 for idx,i in enumerate(machinelist): if(i==0...
This code initializes a Pygame game with a grid-based interface, creates a list of machines, processes player input for cell coordinates, and updates game elements in a loop. It sets up a window, handles events, maintains FPS, and uses functions to generate machine data and manage player interactions within a grid syst...
def main(): pygame.init() cellmax=16 width = 36*cellmax height = 36*cellmax FPS = 30 initialadd=100 fpsClock = pygame.time.Clock() screen = pygame.display.set_mode((width, height+initialadd),0,32) machinelist=creatingmachinelist(cellmax,40) for i in range(0,cellmax*cellmax,cellma...
def _check_na(self, result): if result.check_section: objs = self.parse.find_objects(result.check_section) if not objs: result.status_name = 'N/A' self.results.append(result) return True return False def _section(self, result: Resul...
This function processes an item against a rule to determine its status. It creates a Result object, checks for specific conditions (e.g., errors, sections, time formatting), and appends the result to a list. If no special cases apply, it evaluates the item's validity using parsing logic and records the outcome.
def _check_rules(self, item, rule): result = Result(**item, rule=rule) if self._check_na(result): return if 'error' in item: result.status_name = 'MANUAL' self.results.append(result) elif 'section' in item: self._section(result) eli...
def compute_error(points, m, c): totalError = 0 for i in range(0, len(points)): x = points[i, 0] y = points[i, 1] totalError += (y - linear_equation(m, x, c)) ** 2 return totalError / float(len(points)) def compute_rss(data, calculated_m, calculated_c): ssr = compute_ssr(data,cal...
This function performs linear regression using gradient descent to find optimal slope (m) and intercept (c) for given data. It iteratively updates parameters, tracks error metrics, visualizes the regression line, and returns final parameters along with error and RSS values.
def calculate_m_b_with_gradient_descent(data, learning_rate, num_iterations, starting_m, starting_c): m = starting_m c = starting_c error = compute_error(data, m , c) rss_error = compute_rss(data, m, c) for i in range(num_iterations): m, c = step_gradient(np.array(data), learning_rate, m, ...
def compute_error(points, m, c): totalError = 0 for i in range(0, len(points)): x = points[i, 0] y = points[i, 1] totalError += (y - linear_equation(m, x, c)) ** 2 return round(totalError / float(len(points)*100000000), 3) def compute_rss(data, calculated_m, calculated_c): ssr = ...
This function performs linear regression using gradient descent to find optimal parameters m (slope) and c (intercept) for a dataset. It iteratively updates these parameters to minimize the residual sum of squares (RSS) error, visualizing the gradient path, fit line, and error progression over iterations. The final par...
def calculate_m_b_with_gradient_descent(data, learning_rate, num_iterations, starting_m, starting_c): m = starting_m c = starting_c error = compute_error(data, m , c) error_array = np.array([]) rss_error = compute_rss(data, m, c) fig = plt.figure(figsize=(10,4)) ax = fig.add_subplot(131) ...
def getQuery(self): query = {} for i in self.__dict__: if "__" not in i and i not in Collection.nonQuerable and self.__dict__[i] != None: query[i] = self.__dict__[i] return query def get(self,query = {}): client = self.getClient() if client != None: ...
This code initializes an object's attributes by either retrieving existing data (via search or API mapping) or inserting/updating it if not found, based on the 'update' flag. It handles data mapping, attribute assignment, and database operations (insert/update) to ensure the object's state aligns with the data source.
def init(self,update = False): query = self.getQuery() search = [] if len(query) != 0: search = self.get(query) if len(search) == 0 or update: mapping = self.apiMethod.doLocalMapping()[0] for i in mapping: ...
def eval_centrality(g, edge_centrality_fn, node_centrality_fn, weight, _city_name, _centrality, inplace=False): if not inplace: g = g.copy() nodes_centrality = node_centrality_fn(g, weight=weight) edges_centrality = edge_centrality_fn(g, weight=weight) for (u, v, i), centrality in edges_central...
The function performs centrality analysis on a graph before and after removing specified roads. It calculates original and post-edit node/edge centrality using given metrics, visualizes results via maps, and computes/demonstrates the difference in centrality. The process includes graph modification, centrality evaluati...
def perform_centrality_analysis(G, roads_to_remove, centrality, city_name): node_centrality, edge_centrality = centrality_mapping[centrality] with st.spinner('Evaluating original centrality'): og_centrality = eval_centrality( G, edge_centrality_fn=edge_centrality, no...
def input_panel() -> InputData: return InputData( city_name=st.text_input(label='Area name'), intersection_tolerance=st.slider('Intersection consolidation tolerance (in meters)', min_value=1, max_value=100) ) def read_graph(city_name: str, tolerance: floa...
The code provides an interactive web interface to visualize and analyze urban road networks using centrality metrics. It allows users to select a city, graph properties, and centrality functions, then generates a map and performs analysis after removing specified roads.
def main(): with st.sidebar: """## Visualization parameters""" data = input_panel() G = read_graph(data.city_name, data.intersection_tolerance) attr = st.selectbox( label='Plotted property', options=['maxspeed', 'travel_time'] ) centrality = st...
def parse_data(filename): with open(filename, 'r') as f: vals = [parse_line(line) for line in f] (ys, xs) = ([v[0] for v in vals], [v[1] for v in vals]) return np.asarray([ys], dtype=np.float32).T, np.asarray(xs, dtype=np.float32).reshape(len(xs), ...
The code trains a neural network with one hidden layer using backpropagation. It parses command-line arguments for hyperparameters (iterations, learning rate, hidden dimension), data files, and weight initialization. The model is trained on provided data, validated (if enabled), and tested. It outputs test accuracy and...
def main(): import argparse import os parser = argparse.ArgumentParser( description='Neural network with one hidden layer, trainable with backpropagation.') parser.add_argument('--nodev', action='store_true', default=False, help='If provided, no dev data will be used.') parser.add_argument(...
def draw_maze(self, maze): self.canvas.create_rectangle(0,0,self.width * self.cell_size-1, self.height * self.cell_size-1, outline="black") # outline for i in range(self.height): for j in range(self.width): cell = maze[(i,j)] if cell[0]: self.canvas.create_line(j*self.cell_siz...
This function initializes a depth-first search (DFS) visualization for a maze, setting up the start and goal positions with distinct colors, initializing a stack for DFS traversal, and scheduling the next step of the algorithm to execute after a 50ms delay. It prepares the GUI environment for animating the DFS pathfind...
def dfs_visualizer(self, maze, start, goal): self.prev = {} self.draw_maze(maze) self.paint_cell(start[0], start[1], "red") self.paint_cell(goal[0], goal[1], "black") self.stack= [start] self.discovered = set([start]) self.visited = set() self.root.after(50, la...
def draw_maze(self, maze): self.canvas.create_rectangle(0,0,self.width * self.cell_size-1, self.height * self.cell_size-1, outline="black") # outline for i in range(self.height): for j in range(self.width): cell = maze[(i,j)] if cell[0]: self.canvas.create_line(j*self.cell_siz...
This code initializes a Breadth-First Search (BFS) visualization on a maze. It sets up the start and goal positions, initializes a queue for BFS traversal, and schedules the first step of the algorithm. The function prepares the maze display, marks the start (red) and goal (black) positions, and triggers the BFS proces...
def bfs_visualizer(self, maze, start, goal): self.prev = {} self.draw_maze(maze) self.paint_cell(start[0], start[1], "red") self.paint_cell(goal[0], goal[1], "black") self.queue = [start] self.discovered = set([start]) self.visited = set() self.root.after(50, l...
def make_maze(width, height): maze = make_empty_maze(width, height, walls = True) stack = [(0,0)] #for j in range (0, height): # for k in range(0, width): # stack.append([height-j, width - k]) i = 0 j = 0 visited = set() discovered = set() def get_all_neighbors(maze,height,width,i, j): ne...
The code generates a maze using `make_maze`, draws it on a canvas, performs a DFS-based pathfinding visualization from the top-left to bottom-right corner, and launches the GUI main loop to display the result.
def run(self): #maze = make_simple_maze(self.height, self.width, 80) #maze = make_empty_maze(self.height, self.width, walls = True) maze = make_maze(self.width, self.height) self.draw_maze(maze) self.dfs_visualizer(maze, (0,0), (self.height-1, self.width-1)) self.canvas.mainloop()
def __getCommand(sock, addr, length): try: length = int(length.decode("utf-8")) sock.settimeout(0.5) data, recv_addr = sock.recvfrom(length) if(recv_addr == addr and length == len(data)): data = data.decode("utf-8") return data raise Exception() ...
This function processes client commands by receiving data, sending an acknowledgment, executing the command, and transmitting the result in chunks. It handles errors related to instruction reception, file transmission, and unknown exceptions, ensuring robust communication with the client.
def __handleData(sock,addr,length): try: command = __getCommand(sock, addr, length) __sendACK(sock,addr) command_output = __handleCommand(command) __sendResponseByChunks(sock, addr, command_output) except CannotRecieveInstructions as e: print('Failed to receive i...
def method3(b,a,mu,C,M,Del): x = cp.Variable(M,nonneg=True) d = cp.entr(x) obj = (a*np.log(b/a))@x + a@cp.entr(x) objective = cp.Maximize(obj) constraints = [x <= b/a, sum(x/mu)<= Del] prob = cp.Problem(objective,constraints) prob.solve(solver='ECOS') if prob.status =='optimal': ...
This function evaluates and compares the performance of three methods (method1, method3, line_search) by generating random parameters, calculating profit ratios, validating results against thresholds, and outputting statistical metrics (min ratio, average ratio) and execution time for different parameter configurations...
def generate2(C,M,N,T): start_time = time.time() profit = np.empty((3,N)) for j in range(N): b = 0.5 + 9.5*np.random.rand(M) a = 0.1 + 4.9*np.random.rand(M) mu = 0.02 + 19.98*np.random.rand(M) try: outcome2 = method3(b,a,mu,C,M,C) profit[1,j] = outcome...
def simulate_result(state_variable): simulated_state = state() simulated_state = simulated_state.copy_state(state_variable) simulated_state.current_status = simulated_state.check_status() if (simulated_state.current_status != "draw" or simulated_state.round_number == 9): simulated_state.ex...
This code recursively simulates optimal game moves by evaluating possible states, selecting the path that matches the desired outcome, and printing the grid for the best move. It checks game status, generates possible next states, and prioritizes the move leading to the target result, continuing recursively until a ter...
def simulate_best_game(state_variable): simulated_state = state() simulated_state = simulated_state.copy_state(state_variable) simulated_state.current_status = simulated_state.check_status() if (simulated_state.current_status != "draw" or simulated_state.round_number == 9): return else: ...
def stop_and_exit(self, m): self.stop_signal = True buy_o = self.buy_order self.order_log('SELL {0} @{1}'.format( m['symbol'] , m['ltp'])) #self.ws_data.unsubscribe(symbol=[self.ce['n'], self.pe['n']]) self._proxy.unsubscribe([self.ce['n'], self.pe['n']]) self.order_log(...
This function processes incoming market messages to check stop conditions, track selected options, and trigger orders. It evaluates price differences against a threshold (Strategy4.step), updates the selected option if exceeded, and executes orders or exit actions based on time thresholds and stop signals.
def MsgReceived(self, m): if m is None: return if self.stop_signal == True: return cur_date = datetime.now() td = cur_date - self.stop_time if td.total_seconds() > 0: self.stop_and_exit() symb = m['symbol'] ...
def get_example_from_db(self): example = self.db.get_example_not_solved(self.signs) if not example: example = self.db.get_slow_example(self.signs) if not example: return False self.x = example['x'] self.y = example['y'] self.sign = exampl...
The code's main task is to generate or retrieve an example, insert it into a database if necessary, build the example, and print it. It checks if `num_example` is a multiple of 3: if so, it attempts to fetch an example from the database; if that fails, it generates a new one and saves it. Otherwise, it directly generat...
def print_example(self): self.start_ex_time = int(time()) if self.num_example % 3 == 0: if not self.get_example_from_db(): self.generate_example() self.db.insert_data(x=self.x, y=self.y, sign=self.sign, ans=self.ans) else: self.generate_ex...
def print_start_info(self): start_date = datetime.fromtimestamp(self.start_time).strftime("%d-%m-%Y %H:%M:%S") print("start time: {}".format(start_date)) print("x from {} to {}".format(self.min_x, self.max_x)) print("y from {} to {}".format(self.min_y, self.max_y)) print("Signs: ...
The code's main task is to process examples by repeatedly printing an example, obtaining user input, and checking the answer until the number of required examples to win is met. Once all examples are processed, it writes the total answer. The loop continues as long as `self.example_to_win` exceeds `self.num_example`, e...
def run(self): self.print_start_info() while self.example_to_win > self.num_example: self.print_example() ans = self.get_write_ans() self.check_example(ans) self.write_total_ans()
def TakeCommand(self): Query = ''; r = sr.Recognizer() with sr.Microphone() as source: print('Listening') r.pause_threshold = 0.7 audio = r.listen(source) try: print("recognizing") Query = r.recognize_google(audio, l...
The code continuously listens for voice commands. When it detects specific trigger phrases ("hey siri," etc.), it activates the assistant, greets the user, and processes subsequent queries. If already active, it directly handles incoming commands. The loop ensures persistent listening for voice interactions, enabling h...
def Start(self): active = False while(True): query = self.TakeCommand().lower() if query == "hey siri" or query == "siri" or query == "hi siri": active = True self.Hello() else: if active is True: sel...
def preprocess_data(self): # Isolating data relevant to a work non_work_keys = list(set(self.work_data.keys()) - set([c for c in CofkCollectWork.__dict__.keys()])) # Removing non-work data so that variable work_data_raw can be used to pass parameters # to create a CofkCollectWork object...
This method processes an Excel row to create a work entry in the database, handling location mappings, mentions, languages, resources, authors, and addressees. It updates work_data with IDs, preprocesses data, creates a CofkCollectWork object, commits it to the session, and logs progress.
def process_work(self, work_data): """ This method processes one row of data from the Excel sheet. :param work_data: :return: """ self.work_data = work_data self.work_data['upload_id'] = self.upload_id self.iwork_id = work_data['iwork_id'] self....
def parse_input(input_file): data = [] with open(input_file, 'r') as input: line = input.readline() while line: (signal,output) = line.rstrip().split(' | ') signal_list = signal.split(' ') output_list = output.split(' ') data.append(tuple((signal_l...
The code processes an input file containing signal and output pairs, counting digits with lengths 2, 3, 4, or 7 (unique to 1, 7, 4, 8). It then decodes outputs using brute-force permutations of eight segments, mapping signals to digits and summing decoded output values. The main tasks are: (1) count specific digits in ...
def main(): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-i', '--input', dest='infile', help='Input file') args = parser.parse_args() data = parse_input(args.infile) print(len([dig for (signal,output) in data for dig in output i...
def parse_input(input_file): # read in input as string and convert to a flatlist (number, depth) number_lines = list() with open(input_file, 'r') as input: line = input.readline().rstrip() while line: snailfishno = convert_to_flat_list(line) number_lines.append(snailf...
The code processes a list of numbers from an input file to compute a total sum and determine the maximum possible magnitude by evaluating all permutations of the numbers. It uses command-line arguments for input, parses data, applies reduction operations, and outputs the total and maximum magnitude values.
def main(): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-i', '--input', dest='infile', help='Input file') args = parser.parse_args() data = parse_input(args.infile) total = reduce(add_sfish_nos,data) print("TOTAL:",total) ...
def maxi(self, a, b): return a if self.compare(a, b) >= 0 else b def mini(self, a, b): return b if self.compare(a, b) > 0 else a def compare(self, a, b): time_a = self.length(a) time_b = self.length(b) return 1 if time_a > time_b else (0 if time_a == time_b else -1)
The main task of the code is to compute the overlapping interval between two time ranges [a and b]. It calculates the later start time (from_time) and earlier end time (to_time). If to_time is not after from_time, it returns None (no overlap); otherwise, it returns the overlapping interval [from_time, to_time].
def reconc(self, a, b): from_time = self.maxi(a[0], b[0]) to_time = self.mini(a[1], b[1]) if self.compare(to_time, from_time) != 1: return None return [from_time, to_time]
def free_at(self, sched, bound, i): if i == 0: if self.compare(sched[i][0], bound[0]) == 1: return [bound[0], sched[i][0]] return None if len(sched) <= i: from_time = sched[len(sched) - 1][1] to_time = bound[1] if self.compare(...
The code identifies overlapping free time intervals between two schedules (sched_a and sched_b) by iterating through each schedule's free slots, comparing them, and collecting non-overlapping intervals where both schedules are free. It uses `free_at` to find free slots and `reconc` to merge compatible intervals, append...
def meeting(self, sched_a, bound_a, sched_b, bound_b): free_times = [] a_i = 0 b_i = 0 while True: # get free time of a # compare availablility with b # if yes, add to free_times, move forward free_a_slot = self.free_at(sched_a, bound_a, a...
def shift_edge_weights(E, gamma=0.05): max_weight = 0 for key in E: for edge in E[key]: # TODO: fix shift (remove 100 *) if key < edge: E[key][edge] = 100 * max(E[key][edge] + (np.random.uniform(-gamma, gamma)) * E[key][edge], 0) max_weight = max(E...
(The main task of the code is to generate and analyze Minimum Spanning Trees (MSTs) for clustering datasets, with options to apply noise, bucketing, and multiple runs. It processes input data, configures parameters, and evaluates clustering results by comparing MSTs across different configurations, saving outputs and v...
def main(): parser = ArgumentParser() parser.add_argument('--epsilon', help='epsilon [default=1/8]', type=float, default=1 / 8) parser.add_argument('--machines', help='Number of machines [default=1]', type=int, default=1) parser.add_argument('--buckets', help='Use buckets [default=False]', action='store...
def get_clustering_data(): """ Retrieves all toy datasets from sklearn :return: circles, moons, blobs datasets. """ n_samples = 1500 noisy_circles = make_circles(n_samples=n_samples, factor=.5, noise=0.05) noisy_moons = make_moons(n_samples=n_samples, noise=0...
The main task of the code is to generate Minimum Spanning Trees (MSTs) for multiple datasets, visualize the MSTs, and perform clustering analysis. It processes input datasets, computes distance matrices, constructs MSTs with specified parameters (e.g., epsilon), and plots results using 2D/3D visualizations. Additional ...
def main(): """ For every dataset, it creates the mst and plots the clustering """ parser = ArgumentParser() parser.add_argument('--test', help='Used for smaller dataset and testing', action='store_true') parser.add_argument('--epsilon', help='epsilon [default=1/8]', type=float, default=1 / 8) ...
def buildMap(): # first need to define the list of generated points randomPoints = [(np.random.randint(10, map.shape[1]-10), np.random.randint(10, map.shape[0]-10)) for _ in range(numberOfNodes)] listOfVertix = [] # now, populate the map for i in range(0,numberOfNodes): v = point(x = randomP...
The code implements a Rapidly-exploring Random Tree (RRT) algorithm to generate a path from a start point to a randomly inserted goal point on a map. It iteratively connects nodes from an explored list to unexplored vertices, avoiding collisions, until reaching the goal. The final path is traced back from the goal to t...
def mainRead(start_x = 250, start_y = 250, finish_x = 15, finish_y = 15): # get the list of points listOfVertix = buildMap() # this is essentially our RRT list of nodes exploredVertexList = [] # RRT list to return to drive_to_goal rrt = [] # starting index will be the first index of ...
def check_balance(w): c0, c1, r0, r1 = summary(w) return r0 == r1, c0 == c1 def candidate(w): c0, c1, r0, r1 = summary(w) return 2 * (r0 > r1) + (c0 > c1) def extra(v): return 2 * min(v[0], v[3]) + 2 * min(v[1], v[2])
The code balances a matrix `w` by redistributing values from `v`, ensuring both row and column balances are met. It iteratively selects candidate cells, decrementing `v` and incrementing `w` until balance is achieved. If `v` runs out (a cell's value reaches zero), it returns -1. The total steps taken (`cnt`) plus an ad...
def balancing(v, w): cnt = 0 rowbal, colbal = check_balance(w) while not (rowbal and colbal): c = candidate(w) if v[c] == 0: return -1 else: v[c] -= 1 w[c] += 1 cnt += 1 rowbal, colbal = check_balance(w) return cnt + extra(v)
def _move_tail(self): for index in range(len(self.tail)-1,0,-1): x=self.tail[index-1].xcor() y=self.tail[index-1].ycor() self.tail[index].goto(x,y) def _move_snake(self): x, y = self.get_cell_by_direction(self.snake.xcor(), self.snake.ycor(), self.snake.direction) ...
The main task of the code is to execute a single step of a snake game, updating the snake's movement, checking for collisions with walls/tail, handling food acquisition, managing direction changes, and calculating a reward based on game events like collisions, food collection, or proximity to food. The function also up...
def run_step(self): self._move_tail() prev_loc = (self.snake.xcor(), self.snake.ycor()) #move the segment 0 to the head if len(self.tail) > 0: self.tail[0].goto(self.snake.xcor(),self.snake.ycor()) self._move_snake() next_loc = (self.snake.xcor(), self...
def _initialize_window(self): # settings of the screen self.window=turtle.Screen() self.window.colormode(255) self.current_score_title = turtle.Turtle(visible=False) self.current_score_title.speed(0) self.current_score_title.goto(-self.CELL_MAX, self.CELL_MAX - 10) ...
This code initializes a Snake game environment by configuring parameters, setting up rendering, initializing the snake and food, managing game state, and preparing the environment for either human or AI agents. It handles difficulty levels, randomization, and state space for machine learning, ensuring smooth gameplay a...
def __init__(self, conf: SnakeConfig): self.config = conf self.rng = np.random.default_rng(int(time.time())) self.episode = 0 self.move_lock = threading.Lock() self.debug = conf.debug if conf.difficulty in self.difficulties: self.sleep_time ...
def _turn(self, direction): self.move_lock.acquire() if self.can_turn: self._change_direction(direction) if self.is_human: self.can_turn = False elif self.is_human and self.snake.direction != OPPOSITES[direction]: self.buffered_direction = d...
The main task of the code is to execute a single step in an environment by processing an action. It updates the agent's direction, runs the step to calculate a reward, extracts current state features, and returns them along with a game-over status indicator based on the reward value.
def step(self, action): # needs to return self._turn(self.direction_mapping[action]) reward = self.run_step() state_features = self.get_state_features() return state_features, reward, reward == GAME_OVER_SCORE
def objective(self, specF): """ Q = 1/2 \\chi^2 - S considering the standard deviation or not. """ return 0.5*self.chiSquare(specF) - self.entropy(specF) def D_cal(self, specF): """ From the spectral function to find out the D: D = K * rho """ return dot(self.K, specF) * self.dw def F_inv_g(g): if (g...
The code implements Bryan's method (SLSQP) to iteratively minimize an objective function and compute a spectral function (specF) dependent on alpha. It updates coefficients (c_coef) via gradient calculations, adjusts specF based on entropy type (SJ, TK, L2SP), and converges when changes in the objective function fall b...
def getSpecF(self, printrecord=True): """ using SLSQP aka sequential least square quadratic programing or Bryan's method (R. K. Bryan, Eur. Biophys. J., 18 (1990) 165) to minimize the objective function to get the spectral function depending on alpha. """ if self.minimizer != 'Bryan': print('use Bryan minim...
def createKernel(self): """ The Convolution Kernel: K = w / pi / (wn^2 + w^2) """ self.dw = self.wmax/self.numW self.w = linspace(self.dw, self.wmax, self.numW) if not self.k_assigned: self.dk = self.kmax/self.numK self.k = linspace(self.dk, self.kmax, self.numK) self.K = zeros([self.numK, s...
The code initializes a model for entropy maximization by configuring parameters (e.g., `numW`, `wmax`, `tol`), setting up kernels/data structures (`createKernel`, `createSKernel`, `createData`), and preparing the default model (`sfunction` or `input`). It reads input files if `CreateNew` is false, loads data, and valid...
def __init__(self, folder, numW = 500, wmax = 20, numK = 100, kmax = 20, numS = 600, smax = 30, tol = 1e-8, alphamin = -4, alphamax = 0, numAlpha = 100, entropy_type = "SJ", defaultModel = "sfunction", minimizer = "Bryan", rank=0, mu=0.1, maxIteration=1e4, CreateNew=False, noise=1e-4): self.start_time = time.time() ...
def bubble_sort(self): """ Fill and color blocks according to bubble sort :return: void """ #If sorted elements is filled then reset self.sorted_elements = {} for i in range(self.len_lst - 1): for j in range(0, self.len_lst - i - 1): s...
The main task of the code is to select and return a specified sorting algorithm from a predefined dictionary of sorting methods based on the input `algo_name`. If `algo_name` is "reset", it resets counters and applies a built-in sort. The function maps algorithm names to their corresponding methods, executes them, and ...
def choose_sort(self, algo_name): self.algos = { "bubble_sort": self.bubble_sort(), "insertion_sort": self.insertion_sort(), "selection_sort": self.selection_sort(), "merge_sort": self.merge_sort(), "quick_sort": self.quick_sort(), "heap_so...
def refresh_borrower(self): self.search_borrower(self.borrower_query['search_by'], self.borrower_query['argument']) def refresh_members(self): members = UserController.search_user(self.member_query) self.searchMembersCompleted.emit(members) def book_refresh(self): books = BookController....
This code deletes a user member by their ID, removes all associated borrower records, and refreshes the borrower, member, and book data lists to reflect the changes.
def delete_member(self, member_id): UserController.delete_user({'_id': member_id}) borrowers = BorrowerController.search_borrower({'user_id': member_id}) for borrower in borrowers: print(borrower['_id']) print('--------') BorrowerController.delete_borrower(...
def __loss_G__(self): criterion = nn.BCEWithLogitsLoss() sub_graph = self.__sub_graph__(my_sample_v=self.opt.sample_v_g) errorG = torch.zeros((1,)).to(self.device) sample_v = self.opt.sample_v_g for i in range(sample_v): v_i = sub_graph[i] for j in range...
The code computes and optimizes multiple loss components (G, D, E, E_pred, E_gan) using different optimizers, applies gradients with conditional steps based on flags like `use_g_encode` and `lambda_gan`, and returns a dictionary of loss values for monitoring.
def __optimize__(self): loss_value = dict() if not self.use_g_encode: self.loss_G = self.__loss_G__() if self.opt.lambda_gan != 0: self.loss_D = self.__loss_D__() self.loss_E, self.loss_E_pred, self.loss_E_gan = self.__loss_EF__() if not self.us...
def __set_input__(self, data, train=True): """ :param x_seq: Number of domain x Batch size x Data dim y_seq: Number of domain x Batch size x Predict Data dim one_hot_seq: Number of domain x Batch size x Number of vertices (domains) domain_seq: Number of d...
This code trains a neural network for one epoch using a given dataloader. It initializes loss tracking, processes each data batch through forward passes and optimization, averages accumulated losses, visualizes results with Visdom if enabled, prints loss values every 10 epochs, and updates learning rates via schedulers...
def learn(self, epoch, dataloader): self.train() if self.use_g_encode: self.netG.eval() self.epoch = epoch loss_values = {loss: 0 for loss in self.loss_names} count = 0 for data in dataloader: count += 1 self.__set_input__(data) ...
def printPlayers(self): print("PLAYER: BALANCE \n---------------") if len(self._players) == 0: print("-- no existing players --") for player in self._players: print(player.getPlayerName() + ": " + str(player.getPlayerBalance())) def playerSelection(self, name): fo...
The main task of the code is to initiate a game session by displaying available players, prompting the user to select or create a player, initializing a game table with the chosen player, starting the game, and updating the player data file. It handles user input, player selection, game setup, and data persistence in a...
def main(self): print("\u2665") self.printPlayers() playerName = input("\nPlease enter new or existing player name > ") player = self.playerSelection(playerName) table = Table(player) table.start() self.updatePlayerFile()
def affine_from_extent(extent, width=1024): x_min, x_max, y_min, y_max = extent x_res = 1.*(x_max - x_min) / width height = int((y_max - y_min) / x_res) transform = Affine.translation(x_min, y_min) * Affine.scale(x_res, x_res) return transform, height def heatmap_for_days(collection,product,start,en...
The main task is to generate and visualize a heatmap for a specified satellite data collection over a defined time period (start to end). It uses either an Australian-specific or global Lambert Conformal projection, loads or creates a heatmap via pickle file handling, and plots it with a dynamically generated title inc...
def main(collection, product, start, end, ausonly=True, heatmappickle=None, title=None, **kwargs): if ausonly: #Define Australian Extents and a suitable Affine Translation for the whole contintent proj='epsg:3577' projection = ccrs.epsg(3577) AOI_EXTENT=-2.69e6, 2.58e6, -5.1e6, -...