dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def char_create(player: Player) -> None: print("Please create your character.") player.name = input("Name: ").title() while True: player.p_class = input("Pick Mage or Knight: ").title() if player.p_class == "Mage" or player.p_class == "Knight": break else: pri...
This code runs a game loop where the player navigates locations, interacts with environments (e.g., opening chests, using magic circles), fights random enemies, uses inventory/potions, and saves progress. It loads a saved player or creates a new one, handles combat mechanics, and triggers location-specific events like ...
def main(): try: with open('save.pickle', 'rb') as f: player = pickle.load(f) f.close() except FileNotFoundError: player = Player("", 100, 100, 100, 100, "", 1, 0, "Rusted Sword", 0, 0) char_create(player) goblin_moves = ["Move1", "Move2", "Move 3"] ...
def get_spray_height_at_intersection_with_measurement_line(self, point): if x_0 := self.get_x_projected_to_measurement_line(point): return self._get_basic_spray_height(x_0) return 0 def adjust_for_distance(self, h_0, y): try: relative_y = self.get_relative_y(y) ex...
The main task of the code is to calculate the adjusted spray height at a specific point by first determining the initial height at the intersection with a measurement line, then adjusting it for distance using the point's y-coordinate, and finally adjusting for angular effects based on the point's position. The functio...
def _get_spray_height_for_point(self, point): h_0 = self.get_spray_height_at_intersection_with_measurement_line(point) h_distance_adjusted = self.adjust_for_distance(h_0, point.y) h_distance_and_angle_adjusted = self.adjust_for_angle(h_distance_adjusted, point) return h_distance_and_angl...
def handle_events(self): for e in pg.event.get(): if e.type == pg.QUIT: if self.playing: sys.exit() if e.type == pg.KEYDOWN: if e.key == pg.K_SPACE or e.key == pg.K_UP: self.mainCharater.jump() if e.type ...
The code runs a game loop that handles events, updates game state, renders frames at a fixed FPS, and displays the game over screen when the loop ends.
def run(self): self.playing = True while self.playing: self.clock.tick(FPS) self.window.blit(background, (0, 0)) self.handle_events() self.update() self.draw() self.show_game_over()
def display_welcome(self): print("Welcome to Robots vs Dinosaurs!") def battle(self): self.robots_alive = True self.dinos_alive = True while len(self.fleet.robots) > 0 and len(self.herd.dinosaurs) > 0: if len(self.fleet.robots) != 0: ...
The code's main task is to execute a game sequence: display a welcome message, conduct the battle phase, and then show the winners. It orchestrates the game flow by sequentially calling methods to introduce the game, handle gameplay mechanics, and present results, ensuring a complete player experience from start to con...
def run_game(self): self.display_welcome() self.battle() self.display_winners()
def nsinfo_done(self): # Make sure we have nsinfo cnt = 300 while self.nsinfo is None and cnt > 0: # Warn after a couple seconds if cnt < 298: msg = f'Unable to test webooks nsinfo={self.nsinfo} not initialized yet cnt={cnt}' LOGGER.warning...
The main task of the code is to test connectivity to a webhook endpoint by sending a POST request with a JSON payload to a specific URL constructed from `uuid` and `profileNum` values. It verifies the response status (200 OK) and checks if the returned content is "success" to confirm successful connectivity. If success...
def test_webhook(self): if not self.nsinfo_done(): return False host = 'my.isy.io' port = 443 # # All good, start the test # msg = "Unknown Error" try: if 'uuid' in self.nsinfo and 'profileNum' in self.nsinfo: conn...
def nsinfo_done(self): # Make sure we have nsinfo cnt = 300 while self.nsinfo is None and cnt > 0: # Warn after a couple seconds if cnt < 298: msg = f'Unable to test webooks nsinfo={self.nsinfo} not initialized yet cnt={cnt}' LOGGER.warning...
The main task of the code is to configure or update a webhook for a specified device by ensuring the correct URL and event types are set, handling existing webhooks, and creating a new one if none exists, returning success/failure status.
def configure_webhook(self, WS_deviceID): if not self.nsinfo_done(): return False # All good unless we have a problem res = True # Use portal for webhooks _url = f"https://my.isy.io/api/eisy/pg3/webhook/response/{self.nsinfo['uuid']}/{self.nsinfo['profileNum']}" ...
def test_webhook(self): if not self.nsinfo_done(): return False host = 'my.isy.io' port = 443 # # All good, start the test # msg = "Unknown Error" try: if 'uuid' in self.nsinfo and 'profileNum' in self.nsinfo: conn...
The code discovers Rachio devices via API, checks webhook functionality, retrieves device data, adds controllers to the ISY system, and configures webhooks. It logs errors and returns success/failure status based on API interactions and device registration.
def discover(self, command=None): LOGGER.info('Starting discovery on %s api_key=%s', self.name, self.api_key) self.discover_st = None if not self.test_webhook(): self.inc_error('Unable to discover until webooks are working properly',name='discover') self.discover_st = Fa...
def discover(self, command=None): LOGGER.info('Starting discovery on %s api_key=%s', self.name, self.api_key) self.discover_st = None if not self.test_webhook(): self.inc_error('Unable to discover until webooks are working properly',name='discover') self.discover_st = Fa...
(The main task of the code is to handle a long polling process by checking if discovery needs retrying, testing webhooks for portal compatibility, updating node information, and handling errors. If 'longPoll' is specified, it ensures discovery is successful, validates webhooks, iterates through nodes to update their da...
def poll(self, polltype): if 'longPoll' in polltype: # If previous discover failed, try again if self.discover_st is False: if not self.discover(): return False else: # Make sure webooks are passing thru the portal ...
def gather_files(self) -> None: """Gather audio files recursively from the root path.""" print_bold(f"Getting audio files from {get_color(str(self.root), color=Color.cyan)}") file_list: list[Track] = [] for file in self.root.rglob("*"): if file.suffix.lower() in self.file_fo...
The code's main task is to gather and process supported audio files. It first collects files using `gather_files()`, then processes them with `process_files()`. If interrupted by a keyboard command, it prints a cancellation message. Finally, it displays processing statistics via `print_stats()`, ensuring structured han...
def run(self): """Gather and process supported audio files.""" try: self.gather_files() self.process_files() except KeyboardInterrupt: print_yellow("\ncancelled...") self.print_stats()
def showHead(): led.plot(px, py) snakeList.unshift(px) snakeList.unshift(py) def hideTail(): if len(snakeList) > 6: led.unplot(snakeList.pop(), snakeList.pop()) def moveHead(): global px, dx, py, dy if direction == HORIZONTAL: px += dx if outOfScreen(px) == 1: ...
The code's main task is to repeatedly perform a sequence of actions: displaying a head, pausing, hiding a tail, moving the head, and escaping an outer corner. This loop likely animates a moving object (e.g., a sprite or robot) by managing its visual components and navigation, ensuring smooth motion and collision avoida...
def on_forever(): showHead() basic.pause(200) hideTail() moveHead() escapeOuterCorner()
def get_writing_time( ds, fpath, chunks=None, # Use current chunking compressor=None, consolidated=True, n_repetitions=5, remove_last=True, ): """Return the writing time of a Dataset.""" times = [] for i in range(1, n_repetitions): t_i = time.time() write_zarr( ...
The function profiles Zarr I/O operations by measuring writing time, reading time, reading throughput, and compression ratio for a given dataset. It executes repeated tests, aggregates results, and returns a dictionary with performance metrics, while cleaning up the temporary file path after execution.
def profile_zarr_io( ds, fpath, chunks=None, # Use current chunking compressor=None, isel_dict={}, consolidated=True, n_repetitions=5, ): """Profile reading and writing of a Dataset.""" io_dict = {} io_dict["writing"] = get_writing_time( ds=ds, fpath=fpath, ...
def check_compressor_name(compressor_name): valid_compressors = get_valid_compressors() if compressor_name not in valid_compressors: raise ValueError(f"Invalid compressor name. Valid names are {valid_compressors}") def _get_blosc(algorithm="lz4", clevel=1, shuffle=1, blocksize=0): """Get BLOSC compr...
The function `get_compressor` acts as a factory to instantiate specific compression algorithms based on the provided `compressor_name`. It validates the name, maps it to the corresponding internal implementation (e.g., `blosc`, `gzip`, `zlib`), and returns the configured compressor object using helper functions. If the...
def get_compressor(compressor_name, **kwargs): check_compressor_name(compressor_name) if compressor_name == "blosc": return _get_blosc(**kwargs) elif compressor_name == "b2": return _get_bz2(**kwargs) elif compressor_name == "gzip": return _get_gzip(**kwargs) elif compressor_...
def _is_chunk_dict_per_variable(chunks_dict, ds): """Return True if chunks dictionary is defined per variable.""" variable_names = list(ds.data_vars.keys()) return _contains_all_keys(chunks_dict, variable_names) def _is_chunk_dict_per_dims(chunks_dict, ds): """Return True if chunks dictionary is defined...
This function validates and normalizes a chunks dictionary for a dataset. It checks if chunks are specified per variable or per dimension, ensuring compatibility with the dataset's structure. If invalid, it raises an error. If per-variable chunks are provided, it validates them; otherwise, it converts dimension-based c...
def _check_chunks_dict(chunks, ds): """Check chunks dictionaries validity. Return a 'per variable' chunks dictionary. """ is_chunks_per_variable = _is_chunk_dict_per_variable(chunks, ds) is_chunks_per_dims = _is_chunk_dict_per_dims(chunks, ds) if not is_chunks_per_variable and not is_chunks_per...
def _checks_chunks_type(chunks): """Check chunks input type.""" # Check chunks if not isinstance(chunks, (str, dict, type(None))): raise TypeError("'chunks' must be a dictionary, 'auto' or None.") if isinstance(chunks, str): if not chunks == "auto": raise ValueError("If 'chun...
The function `check_chunks` validates and processes chunk specifications for an xarray Dataset. It handles `None`, `"auto"`, or dictionary inputs, converting "per dimension" chunks to "per variable" format. It uses default chunks if specified, sanitizes values (replacing -1/None with dimension lengths), and ensures the...
def check_chunks(ds, chunks, default_chunks=None): """ Check chunks validity. The default_chunks argument is used only if chunks="auto". Chunk values -1 and None are equivalent to the entire dimension length !!! Parameters ---------- ds : xr.Dataset xarray Dataset. chunks : (N...
def start_match(self): print('\nMatch begins!') self.__qm(1, msg_args=(MSG.MATCH_BEGINS, 1)) self.__qm(2, msg_args=(MSG.MATCH_BEGINS, 2)) self.bat_player = self.perform_toss() print(f'\nPlayer {self.bat_player} bats:') args = (MSG.INNINGS1_BEGIN, self.bat_player) ...
This code sets up a server to handle two client connections for a cricket game. It collects game parameters (overs, wickets), initiates matches, manages rematches, and terminates the game by disconnecting players and closing the server.
def server_client_comm(self): self.players = ['', None, None] print('\nWaiting for players...') self.players[1] = self.server.accept() print('Player 1 connected!') self.players[2] = self.server.accept() print('Player 2 connected!') print('\nHow many overs?') ...
def _initialize_recording(self) -> None: """Initialize the recorded track with the data from the last beat buffer. Moreover, note the times of the first frame of the recorded track and the START recording event. If the old recording was not finished yet, discard it and initialize a new one. ...
This callback function handles real-time audio processing by managing input/output buffers, detecting output underflow (filling with zeros), processing user recording events (start/stop), recording audio data, and mixing input signals for output. It initializes/recording tracks, truncates beats on stop events, updates ...
def callback(indata: npt.NDArray[DTYPE], outdata: npt.NDArray[DTYPE], frames: int, time: Any, status: sd.CallbackFlags) -> None: """The callback method, which is called by the stream every time it needs audio data. This function contains the core logic of the audio manipula...
def __initialize_image(self): image = np.full((len(self.maze) * self.block_size, len(self.maze[0]) * self.block_size, 3), self.BACKGROUND_COLOR_INT, dtype=np.uint8) return image def __draw_path(self, image, path): for path_node in path: min_x = path_node[1] * self.block_size ...
The main task of the code is to generate a visual representation of a maze by initializing an image, drawing paths, selected blocks, start/end points, and walls, then removing adjacent walls between connected cells to accurately reflect the maze's structure.
def generate_image(self): if self.maze is None: raise ValueError('Maze is not initialized') # First, draw the background # image = self.__initialize_image() # The order of the drawing is important - otherwise, we can get weird graphical artifacts # i...
def initialize(self): assert self.warmup_batch_num[0] > 0 self.workload_forward_comp[0].append(self.device_forward_comp_time[0]) def print_init_status(self): print("NUM DEVICES: "+str(self.num_device)) print("FORWARD_COMPUTE_TIME "+str(self.device_forward_comp_time)) print("FORWA...
The code's main task is to execute a sequence of operations: initialize the system, print initial status, perform a warmup phase, execute a 1f1b task, cooldown, and return the total time (timer + cooldown duration). It orchestrates initialization, execution, and cleanup phases with status updates and timing tracking.
def run(self): self.initialize() self.print_init_status() self.warmup() print("WARMUP FINISHED") self.do_1f1b() time = self.cooldown() print("FINISHED!!") return self.timer + time
def calculate_clusters(x_axis, y_axis, x_axis_centroid, y_axis_centroid, number_of_clusters): return list( map(lambda x, y: min( list( map(lambda xc, yc, c: (euclidian_distance(x, y, xc, yc), c) ...
The function clusters 2D data points into specified clusters using either k-means or k-medoids. It validates cluster count (2-10), initializes centroids randomly, iteratively assigns data points to clusters, updates centroids, and stops when centroids stabilize or time expires. Returns final centroids, clustering error...
def clusterizer(x_axis, y_axis, number_of_clusters=2, method="kmeans"): if number_of_clusters < 2 or number_of_clusters > 10: return False min_x_axis = min(x_axis) max_x_axis = max(x_axis) min_y_axis = min(y_axis) max_y_axis = max(y_axis) if(method == "kmeans"): x_axis_centro...
def get_parent_dir(path): split_path = path.split('/') length = len(split_path) if split_path[length - 1] == '': return split_path[len(split_path) - 2] else: return split_path[len(split_path) - 1] def backup_files(files): for file in files: if is_file(file, "ftp"): ...
The main task of the code is to perform an FTP backup by connecting to a host, authenticating with credentials, downloading files from a specified remote directory, storing them in a timestamped local directory, zipping the backup, and cleaning up. It handles connection/login errors by retrying, ensures the local backu...
def main(): global ftp profile_data = start() try: ftp = FTP(profile_data['host']) except: print(" Unable to connect to host. \n") main() password = getpass.getpass(prompt="Enter password: ") try: ftp.login(profile_data['username'], password) except: ...
def GetNodeName(name): name = ' '.join(name.split('_')[1:]) return name def QueryNodeInfo(t,term2pid, DATA_DIR): if t not in term2pid: return '','','' return ReadAbst(term2pid[t], t, DATA_DIR) def ExtractSnippt(term, abst, lookahead = 20): term = term.lower() abst = abst.lower() nword = len(term.split(' ')) t...
The function `query_node` processes a given term to retrieve and format node information (e.g., gene, protein) from biomedical databases. It extracts relevant snippets, truncates descriptions, appends URLs, and standardizes titles with source identifiers (e.g., NCBI, MeSH). The output includes formatted titles, descrip...
def query_node(term, info, term2pid, node2tp, DATA_DIR, ind = 0): term = GetNodeName(term) t1s,t2s,t3s = QueryNodeInfo(term, term2pid, DATA_DIR) tmp = [] for ii in range(len(t3s)): t3s[ii] = ExtractSnippt(term, t3s[ii]) t2s[ii] = ExtractSnippt(term, t2s[ii], lookahead=8) if len(t2s[ii])>140: t2s[ii] = t2s[...
def prelu(_x, scope='prelu/'): # code from https://stackoverflow.com/questions/39975676/how-to-implement-prelu-activation-in-tensorflow alphas = tf.get_variable(scope+'alpha', _x.get_shape()[-1], initializer=tf.constant_initializer(0.0), dtype=tf.float32) pos = tf.nn.relu(_x) neg = ...
This code generates an image from latent vectors (z_s, z_r) and conditions (y) by concatenating inputs, applying batch normalization, and using multiple gated deconvolutional layers to upsample features. It incorporates skip connections from encoder outputs (down_outputs) and applies sigmoid activation for final pixel ...
def generator(down_outputs, z_s, z_r, y, batch_size): cond = tf.concat([z_r, y], 1) z = tf.concat([cond, z_s], 1) output = tf.contrib.layers.fully_connected(z, 1024*4*4, scope='fully1', activation_fn=None, normalizer_fn=tf.contrib.layers.batch_norm, normalizer_params={'scale': True}) pri...
def parse(self): self.log.info(f"Parsing demo: \"{self.demo_file}\"") demo_parser = DemoParser( demofile=os.path.join(self.directory, self.demo_file), demo_id=self.demo_file[:-4], parse_rate=self.parse_rate, trade_time=self.trade_time, buy_styl...
The main task of the code is to perform an ETL (Extract, Transform, Load) process: it connects to a database, parses data, creates necessary tables, saves processed data to the database, handles errors by invalidating the match if exceptions occur, and finally returns the match ID as an integer after cleaning up the da...
def etl(self): self.log.info(f"Openning connection to database: \"{self.db_con_str}\"") self.db_con = create_engine(self.db_con_str) self.parse() try: self.make_tables() self.save_to_db() except Exception as e: self.invalidate_match() ...
def get_keypoints(): """Get descriptors directly from images.""" keypoints_list = [] for i in range(1, N_POKEMONS + 1): for filename in os.listdir('dataset/{i}/'.format(i=i)): image_path = IMAGE_PATH_OS.format(index=i, img=filename) test_image = cv2.imread(image_path) ...
The main task of the code is to match a given Pokémon image against a dataset of keypoints using SIFT descriptors. It parses command-line arguments to load or regenerate the dataset, reads the input image, performs feature matching, and outputs the results from a CSV file. The code either loads precomputed keypoints fr...
def main(): """Execute.""" parser = argparse.ArgumentParser('pokedex using sift descriptor') parser.add_argument('-f', help='path to pokemon image', required=True) parser.add_argument('-n', help='reload dataset from images', action='store_true') args =...
def _sign(self, method, path, ts, params=None): self._method = method # create signature: if params is None: params = {} params['SignatureMethod'] = 'HmacSHA256' params['SignatureVersion'] = '2' params['AccessKeyId'] = self._accessKeyId params['Timesta...
The main task of the code is to send a signed HTTP GET request to a specified path with parameters, construct the request URL by appending a signed query string, and return the resulting JSON response from the server. The method uses internal helper functions to generate the request signature and execute the HTTP call,...
def get(self, path, **params): ''' Send a http get request and return json object. ''' qs = self._sign('GET', path, self._utc(), params) return self._call('GET', '%s?%s' % (path, qs))
def _sign(self, method, path, ts, params=None): self._method = method # create signature: if params is None: params = {} params['SignatureMethod'] = 'HmacSHA256' params['SignatureVersion'] = '2' params['AccessKeyId'] = self._accessKeyId params['Timesta...
This function sends an HTTP POST request to a specified path, optionally including JSON-encoded data. It first generates a query string for signing using `self._sign`, then constructs the request URL with the signature. If an object is provided, it serializes it to JSON and sends it in the request body. The method ulti...
def post(self, path, obj=None): ''' Send a http post request and return json object. ''' qs = self._sign('POST', path, self._utc()) data = None if obj is not None: data = json.dumps(obj).encode('utf-8') return self._call('POST', '%s?%s' % (path, qs), d...
def get_fields(filtering): path = 'field' params = { 'expand': 'names' } # Make the HTTP request fields = make_authenticated_get(path, params) if filtering: return [f for f in fields if re.search(filtering, f.get('name', ''), re.IGNORECASE)] else: return fields def cal...
The code analyzes an epic by calculating its 30-day velocity, fetching its changelog, retrieving child issues, filtering recent changelogs/comments post-last-checked-date, and identifying child issues stuck in "In Progress" for over 10 days. It returns velocity, epic changelog, filtered child issue data, and long-runni...
def analyze_epic(epic_key, last_checked_date): # Initialize the result dictionary result = {} # Step 1: Compute the 30-day velocity for issues with that epic as a parent jql = f'parent = {epic_key}' points_fields = get_fields(r'point') # Assuming this returns the fields used for story points ...
def remark_delete(self, task): self.remarks.controls.remove(task) self.update_dropdown() self.update() def update_dropdown(self): unique_ids = set([r.ticket_id for r in self.remarks.controls]) options = [dropdown.Option('all')] for r in sorted(list(unique_ids)): ...
This function removes all completed tasks from the UI by iterating through a list of tasks, deleting each marked-as-complete task, then updating the dropdown and UI to reflect the changes.
def clear_clicked(self, e): for task in self.remarks.controls[:]: if task.completed: self.remark_delete(task) self.update_dropdown() self.update()
def inputDataMenu(): global colourBackground global colourText global typeFont global colourHighlight layout = [ [sg.Text("", size=(20, 1), font=(typeFont, 10), key="date_display", justification="left", background_color=colourBackground, text_color=colourText)], [sg.Text("", size=(20...
The main task of the code is to create a GUI-based parking database application using PySimpleGUI. It initializes a main menu with buttons for adding/viewing data, settings, debugging, and exiting. The interface displays real-time date/time, handles user interactions, and delegates tasks to other functions like `inputD...
def main(): global colourBackground global colourText global typeFont global colourHighlight layout = [ [sg.Text("", size=(20, 1), font=(typeFont, 10), key="date_display", justification="left", background_color=colourBackground, text_color=colourText)], [sg.Text("", size=(20, 1), fo...
def download_voc2007(root): path_devkit = os.path.join(root, 'VOCdevkit') path_images = os.path.join(root, 'VOCdevkit', 'VOC2007', 'JPEGImages') tmpdir = os.path.join(root, 'tmp') # create directory if not os.path.exists(root): os.makedirs(root) if not os.path.exists(path_devkit): ...
The code initializes a VOC2007 dataset loader, handling data paths, downloading the dataset, generating CSV files for image-label mappings, applying label noise to training data, and splitting datasets. It prepares images, true labels, and noisy labels, supporting transformations and splits for training/validation, wit...
def __init__(self, root, set_name, transform=None, target_transform=None, noise_type = 'symmetric', noise_rate=0.3, split_per=0.9, nb_classes=20 ,random_seed=1): self.root = root self.path_devkit = os.path.join(root, 'VOCdevkit') self.path_images = os.path.join(root, 'VOCdevkit', 'VOC2007', 'JPE...
def download_voc2012(root): path_devkit = os.path.join(root, 'VOCdevkit') path_images = os.path.join(root, 'VOCdevkit', 'VOC2012', 'JPEGImages') tmpdir = os.path.join(root, 'tmp') # create directory if not os.path.exists(root): os.makedirs(root) if not os.path.exists(path_devkit): ...
This code initializes a VOC2012 dataset loader for classification, handling training/validation splits, label noise injection, and data splitting. It downloads the dataset if missing, generates CSV files for image-label mappings, applies symmetric noise to training labels (if specified), and prepares image/label arrays...
def __init__(self, root, set_name, transform=None, target_transform=None, noise_type = 'symmetric', noise_rate=0.3, split_per=0.9, nb_classes=20 ,random_seed=1): self.root = root self.path_devkit = os.path.join(root, 'VOCdevkit') self.path_images = os.path.join(root, 'VOCdevkit', 'VOC2012', 'JPE...
def load_data(args): #np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) train_transform = transforms.Compose([ MultiScaleCrop(args.image_size, scales=(1.0, 0.875, 0.75, 0.66, 0.5), max_distort=2), transforms.RandomHorizontalFlip(), ...
The main task of the code is to train a graph convolutional network (GCN) model for classification tasks. It loads datasets, initializes the model with DataParallel, and trains it using Adam optimization. The training alternates between standard and correction-based phases, adjusting parameters like delta over epochs. ...
def main(args): # Data Loader (Input Pipeline) print(args) # Data Loader (Input Pipeline) print('loading dataset...') train_dataset, val_dataset, test_dataset = load_data(args) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batc...
def get_anno(self): list_path = os.path.join(self.root, 'data', '{}_anno.json'.format(self.phase)) self.img_list = json.load(open(list_path, 'r')) self.cat2idx = json.load(open(os.path.join(self.root, 'data', 'category.json'), 'r')) def get_true_labels(self): list_path = os.path.join(sel...
This code initializes a dataset class for image processing, handling annotations and label generation. It loads image data, retrieves true labels, and applies noisy labels during training (controlled by 'noise_type' and 'noise_rate') while using true labels for testing. The class supports customization via transforms, ...
def __init__(self, root, transform=None, phase='train', noise_type = 'symmetric', noise_rate=0.3, split_per=0.9, nb_classes =80, random_seed=1): self.root = root self.phase = phase self.img_list = [] self.transform = transform # download_coco2014(root, phase) self.get_ann...
def get_zillow_data(): ''' This function reads in zillow data from Codeup database, writes data to a csv file if a local file does not exist, and returns a df. ''' if os.path.isfile('zillow.csv'): # If csv file exists, read in data from csv file. df = pd.read_csv('zillow.csv...
The function `wrangle_zillow` automates data preprocessing for Zillow data by cleaning, removing outliers, splitting into train/validate/test sets, applying MinMax scaling, and separating features (X) and target (y) variables for modeling. It returns the cleaned DataFrame and scaled feature-target splits for analysis o...
def wrangle_zillow(): """ Automates all functions contained within module (Unscaled) """ df = get_zillow_data() df = clean_zillow(df) df = remove_outliers(df) train, validate, test = split_data(df) #imp_train, imp_validate, imp_test = imp_mean(train, validate, test) ...
def get_telco_data(): ''' This function reads in telco data from Codeup database, writes data to a csv file if a local file does not exist, and returns a df. ''' if os.path.isfile('telco_df.csv'): # If csv file exists, read in data from csv file. df = pd.read_csv('telco_df.c...
The function `wrangle_telco` loads telco data, preprocesses it, splits it into training, validation, and test sets using a specified target variable ('churn'), applies MinMax scaling to each split, and returns the scaled datasets for modeling.
def wrangle_telco(): """ Initiates all functions with scaling """ df = get_telco_data() df = prep_data(df) train, validate, test = train_validate_test_split(df, target='churn', seed=123) minmax_train, minmax_validate, minmax_test = minmax_scaler(train, validate, test) return minmax_trai...
def get_telco_data(): ''' This function reads in telco data from Codeup database, writes data to a csv file if a local file does not exist, and returns a df. ''' if os.path.isfile('telco_df.csv'): # If csv file exists, read in data from csv file. df = pd.read_csv('telco_df.c...
The main task of the code is to load, prepare, and split the Telco churn dataset into training, validation, and test sets without applying any scaling. It retrieves the data, preprocesses it, and divides it into stratified subsets using a specified target variable 'churn' and random seed for reproducibility.
def wrangle_unscaled_telco(): """ Initiates all functions without scaling """ df = get_telco_data() df = prep_data(df) train, validate, test = train_validate_test_split(df, target='churn', seed=123) return train, validate, test
def gen_blank_matrix(self): self.matrix = [] for rows in range(tiles_y): row = [] for columns in range((tiles_x * 2) + 1): row.append(2) self.matrix.append(row) row = [] for columns in range(tiles_x): row.append(...
The code initializes a maze level by generating a blank matrix, creating a random maze from a specified starting coordinate, expanding the maze to a larger size, and loading the resulting structure for use in a game or simulation.
def init_level(self): self.gen_blank_matrix() self.gen_rand_maze(self.start_coord[0], self.start_coord[1]) self.extend_maze(extend_size) self.load()
def action(self): keys = pygame.key.get_pressed() if keys[pygame.K_w] or keys[pygame.K_UP]: self.frames = self.up_frames self.facing('up') self.move(0, (-1 * player_vel)) # subtract y to move up elif keys[pygame.K_s] or keys[pygame.K_DOWN]: self....
This method updates object behavior based on input function: 'update' triggers action and border updates, 'animation' runs animation logic, 'go_to_rel' calculates relative screen positioning relative to hero's absolute position, and 'go_to_abs' sets direct absolute coordinates for the object's rectangle.
def update(self, function='update'): if function == 'update': self.action() self.update_rel_borders() if function == 'animation': self.animation() if function == 'go_to_rel': if hero.abs_pos_x <= screen_width: self.rel_pos_x = in...
def get_user_id(raw_data: Update): try: res = raw_data['callback_query']['message']['chat']['id'] except: res = raw_data['message']['chat']['id'] return res def update_user_stat(self, update: Update, context:CallbackContext): query = update.callback_query query.answer() ...
This function handles Telegram bot button interactions by processing callback queries. It deletes messages, updates user audio data, and modifies message replies based on the button status ('drop_audio', 'drop', 'correct', 'again'). It also updates user statistics, sends audio, and saves changes to the user's audio tab...
def Button_tracker(self, update: Updater, context: CallbackContext): query = update.callback_query query.answer() user_id = get_user_id(update) id_sound = self.user_audiotable[user_id][0:1] status = query.data audio_id = self.last_messages[user_id]['audi...
def get_image(image_path): image = Image.open(image_path).convert('RGB') image = np.array(image) return image def get_mask_yolov8(model,image_path): results = model(image_path) height,width,channels =get_image(image_path).shape polygon = results[0].masks.xy[0] # Replace with actual valu...
This function processes a DataFrame of image data by analyzing each image to calculate model lengths (in meters and pixels) and region-of-interest (ROI) pixels. It uses YOLO models for segmentation and keypoint detection, computes pixel curves, converts them to real-world lengths using altitude/focal-length ratios, and...
def analyse_csv(df,base_folder,sensor_width,key_point_model,yolo_seg_model,mask_predictor,save_folder): df["model_length_meters"] = 0 df["model_length_pixel"] = 0 df["pixels_roi"] = 0 df["bai"]=0 for idx,row in df.iterrows(): image_path = os.path.join(base_folder,row["image...
def get_image(image_path): image = Image.open(image_path).convert('RGB') image = np.array(image) return image def get_alt(image_path): image_name = image_path.split('/')[-1] alt = image_name.split('_000_')[-1] alt = alt.split('.')[0] alt = alt.split('_') try : alt = fl...
The function processes a DataFrame of image data by analyzing each image to estimate whale length in meters and pixels. It uses keypoint detection, segmentation models, and altitude data to calculate metrics like arc length, area, and BAI. Results are saved in the DataFrame, including image details, computed lengths, a...
def analyse_csv(df,base_folder,sensor_width,key_point_model,yolo_seg_model,sam_mask_predictor,save_folder,start,end): for idx,row in df.iterrows(): image_path = row["image_path"] if not os.path.exists(image_path): continue image = get_image(i...
def read_img(self,uploaded_file): image = Image.open(uploaded_file).convert('RGB') image = np.array(image) return image def detection_op(self,yolo_results, yolo_keypoints_results,image): st.write(yolo_results.pandas().xyxy[0]) st.write(yolo_keypoints_results.pandas().xyxy[0]) ...
The code processes an uploaded image to detect objects and key points using YOLO models, generates a Bezier curve from detected centers, calculates curve metrics (length, area), applies a mask to isolate regions, and computes a Body Area Index (BAI) ratio for display.
def render(self): st.title("XtraX") uploaded_file = st.file_uploader("Choose a file") if uploaded_file: alt = uploaded_file.name.split("_")[3:5] try : alt = float(alt[0])+float(alt[1])/(10*len(alt[1])) except: alt = 50 ...
def load_models(seg_model_wt_paths = 'yolov8l-seg-ko.pt',CHECKPOINT_PATH = 'sam_vit_h_4b8939.pth'): # segement anything model DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') MODEL_TYPE = "vit_h" sam = sam_model_registry[MODEL_TYPE](checkpoint=CHECKPOINT_PATH) sam.to(devi...
The code creates a Streamlit app for analyzing video frames to calculate body condition using YOLO and SAM models. It takes user inputs for sensor parameters, launch height, and body region ranges, processes the frames, generates analysis results, and saves them as a CSV file in the specified output folder.
def your_streamlit_app(lightning_app_state): st.title("XtraX") st.text("To reselect the folders, close the app and restart it") st.text('Give the page a few seconds to load') frames_folders_path = lightning_app_state.frames_folders_path results_folder_path = lightning_app_state.results_folder_...
def add_movie(): name = input('Enter name:') director = input('Enter director:') year = input('Year') movies.append({ 'name': name, 'director': director, 'year': year }) def show_movies(movies_list): for movie in movies_list: show_movie_details(movie) def find_mo...
The code defines a menu-driven interface allowing users to interact with a movie management system by selecting options to add movies, display all movies, search for movies, or exit. It continuously prompts for input until 'q' is entered, executing corresponding functions based on user choices like 'a', 's', or 'f'
def menu(): user_input = input("Choose an option:") while user_input != 'q': if user_input == 'a': add_movie() elif user_input == 's': show_movies(movies) elif user_input == 'f': find_movies() else: print('Unknown command...') ...
def read_dbt_manifest(self): local_filepath = f"{self.project_root}/.meltano/transformers/dbt/target/manifest.json" with open(local_filepath) as f: return json.load(f) def create_dbt_selection_cache(self): selections = {} dags = self.read_dag_definitions() for dag_nam...
The code's main task is to analyze a dbt project by reading its manifest file, generating a selection cache, and identifying models that are referenced but missing from the manifest, ensuring consistency between selected models and available resources.
def analyze(self): dbt_manifest = self.read_dbt_manifest() dbt_selections = self.create_dbt_selection_cache() return self.find_missing_models(dbt_manifest, dbt_selections)
def show(_state): bot, top = _state _C = Counter() for c in top: _C[c] += 1 for k, v in bot.items(): for c in v: _C[c] += 1 def done(_state): bot, top = _state for k, v in bot.items(): for vv in v: if vv != k: return False retur...
The code calculates the minimum cost to transition a given state to a "done" state using dynamic programming (DP). It explores valid moves (shifting pieces between top and bottom layers) while avoiding obstacles, computes movement costs based on distance and predefined values, and recursively evaluates paths. Memoizati...
def main(_state): global final_state # given a state, what is the cost to get to "done"? show(_state) # move top -> L or R # move L or R -> # always move to destination ASAP bottom, top = _state key = (tuple((k, tuple(v)) for k, v in bottom.items()), tuple(top)) if done(_state): ...
def get_tile_at(self, x, y): return self.board[y][x] def get_ruling(self, subject, predicate, complement): rule = self.get_rule(subject, predicate) if rule is None: return False return complement in rule def vector_sum(vector_a, vector_b): return tuple(a + b for a, b in...
The code handles player movement in a grid-based game by identifying "you" entities, calculating displacement based on direction, checking for obstacles, and pushing entities if possible. It updates the game state and returns whether any changes occurred.
def handle_motion(self, direction_key): print("\thandle_motion(%s)" % direction_key) yous = [] for y in range(self.height): for x in range(self.width): for entity in self.get_tile_at(x, y): if self.get_ruling(entity, Verbs.IS, Adjectives.YOU): ...
def get_initialized_screen(screen_width_px, screen_height_px): new_screen = pygame.display.set_mode((screen_width_px, screen_height_px), pygame.RESIZABLE) new_screen.fill(SCREEN_BACKGROUND_COLOR) return new_screen def get_viewport_rect(screen_width_px, screen_height_px, level_width_tiles, level_height_tiles...
The code initializes a game screen and viewport for a given level, processes user input (keyboard events), handles screen resizing, updates the game state, and checks for a win condition. It runs a main loop that maintains the target FPS, processes key presses for level interaction, and renders the level accordingly. I...
def play_level(level): # initialize screen screen = get_initialized_screen(STARTING_SCREEN_WIDTH, STARTING_SCREEN_HEIGHT) pygame.display.update() # initialize viewport viewport_rect = get_viewport_rect(STARTING_SCREEN_WIDTH, STARTING_SCREEN_HEIGHT, level.width, level.height) update_screen(scree...
def parse_rules_from_board(self): print("\tparse_rules_from_board()") self.rules_dict.clear() self.add_implicit_rules() # horizontal scan for x in range(self.width - 2): for y in range(self.height): tiles = [self.get_tile_at(x + offset, y) for offset...
This code processes user input to update a game board state, handling undo, restart, and movement actions. It maintains a history of board states for undo/restart functionality, applies motion and proactive rules when the board changes, and re-parses rules only if the state changes. Reactive rules are applied afterward...
def process_input(self, key): print("\nprocess_input(%s)" % key) board_state_changed = False if key == Level.UNDO: if len(self.board_history) > 0: self.board = self.board_history.pop() self.parse_rules_from_board() elif key == Level.RESTART: ...
def populate_all_tables(self): """ method for populating/ refreshing all the tables in the gui. Use when app is first loaded or when large changes are made that affect all tables. """ self.populate_customer_table() self.populate_active_customers_table() self.popul...
This method handles the checkout process by creating an invoice with customer and purchase details, updating the database, adjusting product stock, and resetting UI elements. It validates customer selection and invoice items, then generates an invoice, records line items, updates stock levels, and clears input fields u...
def btn_pos_checkout_click_handler(self): """ method for checking out when all the desired products have been added to the invoice. creates an invoice to add into the database containing all the customers information and information related to the invoice like time of purchase and items ...
def populate_all_combo_boxes(self): """ method for refreshing all combo boxes in the gui. use when app is first loaded or when an update is performed on data being used in the combo box. """ self.populate_update_customers_cmb_box() self.populate_inventory_vendor_combo_box...
This method handles customer deletion via a confirmation dialog. It checks if a customer is selected, prompts for confirmation, deletes the customer by ID if confirmed, clears input fields, and refreshes UI elements like combo boxes and tables. Exceptions are caught and displayed.
def btn_customers_delete_customer_clicked_handler(self): """ method called when the btn_customers_delete_customer is clicked. using the customer id store in the QLineEdit will delete the customer from the database. """ if self.cmb_customers_update_customer.currentData() in ['sele...
def populate_all_combo_boxes(self): """ method for refreshing all combo boxes in the gui. use when app is first loaded or when an update is performed on data being used in the combo box. """ self.populate_update_customers_cmb_box() self.populate_inventory_vendor_combo_box...
This method updates a selected customer's information in the database by retrieving data from input fields, validating selection, executing the update operation, and refreshing UI components upon success, while displaying error messages for invalid selections or exceptions.
def btn_customers_update_customer_clicked_handler(self): """ method called when the btn_customers_update_customer is clicked. using the customer id and the info from the QLineEdits will update the customers information in the database. """ if self.cmb_customers_update_customer.cu...
def solve_word(): real_word = input("Enter a word to solve: ").lower() length = len(real_word) dictionary = get_words(length) # real_word = 'apply' # random.choice(dictionary) known = {char: 'u' * length for char in ALPHABET} round_count = 0 won = False while not won: round_coun...
The code provides a menu-driven interface for solving Wordle puzzles, offering options to solve a word, get help with a specific word length, tackle Quordle (multiple simultaneous Wordles), or resume an in-progress game. User input directs the program to execute corresponding functions like `solve_word()`, `help_solve(...
def main(): print("Enter 'solve' to enter a word and have the program solve") print("Enter 'help' to have the program help you solve the wordle") print("Enter 'quordle' to have the program help you solve a multiple simultaneous wordle") print("Enter 'saveme' to have the program help you with an in-progr...
def verifyCredentials(username, password): if not userExists(username): return generateReturnDictionary(301, 'Invalid Username'), True correct_pw = verifyPw(username, password) if not correct_pw: return generateReturnDictionary(302, 'Incorrect Password'), True return None, Fal...
The main task of the code is to handle a POST request for adding money to a user's account. It verifies user credentials, checks if the amount is positive, deducts a $1 service charge, transfers the fee to the bank, updates the user's balance with the remaining amount, and returns a success or error response.
def post(self): postedData = request.get_json() username = postedData['username'] password = postedData['password'] money = postedData['amount'] retJson, error = verifyCredentials(username, password) if error: return jsonify(retJson) ...
def verifyCredentials(username, password): if not userExists(username): return generateReturnDictionary(301, 'Invalid Username'), True correct_pw = verifyPw(username, password) if not correct_pw: return generateReturnDictionary(302, 'Incorrect Password'), True return None, Fal...
This code handles a money transfer request between users. It verifies credentials, checks sender's balance, validates the receiver's existence, deducts the amount from the sender, adds it to the receiver, and transfers 1 unit to the bank as a fee. It returns appropriate JSON responses for success or errors like insuffi...
def post(self): postedData = request.get_json() username = postedData['username'] password = postedData['password'] to = postedData['to'] money = postedData['amount'] retJson, error = verifyCredentials(username, password) if error: return jsonify(re...
def verifyCredentials(username, password): if not userExists(username): return generateReturnDictionary(301, 'Invalid Username'), True correct_pw = verifyPw(username, password) if not correct_pw: return generateReturnDictionary(302, 'Incorrect Password'), True return None, Fal...
This code handles a POST request to add a loan to a user's account. It verifies the user's credentials, retrieves their current cash and debt, updates their account by adding the specified amount to both, and returns a success message if valid.
def post(self): postedData = request.get_json() username = postedData['username'] password = postedData['password'] money = postedData['amount'] retJson, error = verifyCredentials(username, password) if error: return jsonify(retJson) cash = cashWit...
def verifyCredentials(username, password): if not userExists(username): return generateReturnDictionary(301, 'Invalid Username'), True correct_pw = verifyPw(username, password) if not correct_pw: return generateReturnDictionary(302, 'Incorrect Password'), True return None, Fal...
The code processes a loan payment request by verifying user credentials, checking if the user has sufficient cash, updating their account balance and debt, and returning a JSON response indicating success or error messages.
def post(self): postedData = request.get_json() username = postedData['username'] password = postedData['password'] money = postedData['amount'] retJson, error = verifyCredentials(username, password) if error: return jsonify(retJson) cash ...
def NNForward(x, y, alpha, beta): a = LinearForward(x,alpha) #print("Value of a (before sigmoid)",a) z = SigmoidForward(a) #print("this is z",z) b = LinearForward(z,beta) #print("Value of b (before softmax):",b) yhat = SoftmaxForward(b) #print("Value of y_hat (after softmax):",yhat) ...
The function `SGD` trains a neural network using a variant of stochastic gradient descent with adaptive learning rates (similar to RMSProp) to minimize cross-entropy loss for classification. It updates parameters `alpha` and `beta` by dividing gradients by the square root of accumulated squared gradients (plus a small ...
def SGD(train_data,train_label,test_data,test_label,alpha, beta ,learning_rate,num_epoch): nalpha=np.zeros((hidden_units, M+1)) nbeta=np.zeros((K,hidden_units+1)) train_sum,train_loss_plot,test_sum,test_loss_plot = 0, 0,0,0 tr_s,tr_l_p,te_s, te_l_p=0,0,0,0 len_train, len_test = 0,0 Ce_v=[] ...
def player_paddle_object(self): self.player_paddle = Turtle() self.player_paddle.color("white") self.player_paddle.shape("square") self.player_paddle.shapesize(stretch_len=int(self.paddle_size[0] / 20), stretch_wid=int(self.paddle_size[1] / 20)) ...
This code initializes a Pong game with configurable settings, including screen dimensions, paddle/ ball physics, and scoring. It sets up player/computer paddles, game boundaries, score tracking, and a ball object. The class checks for single-player or multiplayer mode, creates game elements, and prepares the game envir...
def __init__(self, screen_size=(800, 600), paddle_shift=0.85, time_delay=0.1, paddle_size=(20, 80), paddle_speed=50, ball_speed=100, point_limit=20): self.point_limit = point_limit self.player_2_score = 0 self.player_1_score = 0 self.score_board_2 = None self.sco...
def settleToBlack(): while True: spi.writebytes2(leddat(0, 0, 0, 0, 0, 0)) lux = sensor.lux if lux == 0: break def getLux(rvalue, gvalue, bvalue, rgain, ggain, bgain, settleTime): lux = 0 # wait until everything is completely dark settleToBlack() while True: ...
The code initializes a sensor interface, configures gain and integration time, and collects light intensity data (lux) across three gain levels (high, medium, low). It iterates through ADC values, computes RGB lux values using predefined functions, and logs results to a text file with timestamps and calibrated outputs ...
def main(): spi.open(0,0) spi.bits_per_word = 8 spi.max_speed_hz = 4000000 sensor.gain = 0x00 settleToBlack() rgain = 31 ggain = 31 bgain = 31 f = open("hd108data_g{}i{}rg{}gg{}bg{}.txt".format(sensor.gain>>4,sensor.integration_time,rgain,ggain,bgain), "w") if True: ...
def __createRegressionLearningData(self, data_set, used_days, keys): learning_data_X = [] learning_data_y = [] for i in range(used_days, len(data_set)): self.__addLearningElements(i, learning_data_X, data_set, used_days, keys) learning_data_y.append(data_set[i][keys.index...
The main task of the code is to generate training and validation datasets for machine learning based on the specified type (regression or classification). It processes raw data by selecting relevant features, creates feature-label pairs using private methods, and splits the data into training and validation sets. The f...
def getDataSets(self, type): data = self.DATA keys = list(data.keys().get_values()) data = data.values print('keys:' + str(keys)) if type == 'regr': data_X, data_y = self.__createRegressionLearningData(data, self.USED_DAYS, keys) elif type == 'high_class': ...
def get_disparity_map(img_1, img_2, down_sample=0): # Downsample each image if required img_1_downsampled = downsample_image(img_1, down_sample) img_2_downsampled = downsample_image(img_2, down_sample) # Set disparity parameters win_size = 3 min_disp = -1 max_disp = 31 num_disp = max_d...
The code estimates object poses (location and rotation) from two images and a disparity map by generating 3D points, applying masks to isolate objects, and calculating rotations using axis points. It optionally visualizes detected points, axes, and real-world locations on the image, returning a list of pose dictionarie...
def get_pose(img_1, img_2, disparity_map_matrix, draw_line=False, draw_points=False, real_locations=None): object_masks = get_object_masks(img_1, k_1=15, k_2=3) disparity_map = get_disparity_map(img_1, img_2) location_map, lambda_map, disparity_map_matrix = get_3d_points(disparity_map, disparity_map_matri...
def create_valid_passport_request_payload() -> Dict[str, Union[str, List[str]]]: """ Create a test passport request message payload Uses the details for a test passport that a test DCS instance will accept as valid. """ return { # This creates a JSON structure that the DCS can understand. "...
The main task of the code is to securely communicate with a DCS service by wrapping a request payload with JSON Web Signature (JWS) and Encryption (JWE), sending it via HTTPS, and unwrapping the encrypted response. It parses command-line arguments, constructs a passport request, applies cryptographic wrapping, transmit...
def main() -> None: """ This is the main entry point for the application. The diagram below explains the operations that are carried out in the `wrap_request_payload` method. The reverse of this operation is carried out by the `unwrap_response` method. +-------------+ 1 +-------------+ 2 ...
def pack_numbers(self): """ 1000/player_num = number of cards per person if number of cards is not whole number: cut to nearest whole number take leftover cards, and randomly give them to players write message at end saying "you received an extra card(s)" ...
This method checks if all players have completed their picks. If so, it either rotates packs, ends the draft by notifying players, or starts new packs based on the current pack and pick counts.
def checkPacks(self): #Checks if every player has picked. pack_nums = self.pack_numbers() if len([player for player in self.players if not player.hasPicked()]) == 0: if self.currentPick < int(pack_nums[self.currentPack - 1]): self.rotatePacks() elif self.c...
def pack_numbers(self): """ 1000/player_num = number of cards per person if number of cards is not whole number: cut to nearest whole number take leftover cards, and randomly give them to players write message at end saying "you received an extra card(s)" ...
This function resumes a draft process by checking the current state. If the draft isn't complete, it clears player picks, rotates packs, or starts anew. If finished, it notifies players and handles leftover cards. It ensures proper reset of player data and pack management based on draft progress.
def resume_draft(self): pack_nums = self.pack_numbers() if self.currentPick < int(pack_nums[self.currentPack - 1]): # for player in self.players: player.picks = [] # clear picks player.has_picked = False self.rotatePacks() elif self.curre...
def pack_numbers(self): """ 1000/player_num = number of cards per person if number of cards is not whole number: cut to nearest whole number take leftover cards, and randomly give them to players write message at end saying "you received an extra card(s)" ...
This function manages a draft process by checking if all players have made their picks, validating selections, saving progress, rotating to new packs when necessary, and handling draft completion by notifying players and distributing leftover cards.
def checkPacks(self): # Checks if every player has picked. pack_nums = self.pack_numbers() if len([player for player in self.players if not player.has_picked]) == 0: # rotating to new packs # validate all player picks for player in self.players: player.va...
def roundNumber(self, number): if number % 1 != 0: logging.warning("please provide integers as coordinates in move_to functions to prevent unexpected behavior.") return int(number) else: return number def init_variables(self, webdriver): x_start, y_start = get...
This code initializes a class to handle mouse movement by validating target coordinates (x, y) against the browser viewport dimensions, raising an error if out-of-bounds. It calculates movement path parameters, generates sample points for smooth motion, and prepares actions for execution. The core tasks involve coordin...
def __init__(self, x, y, webdriver, actions): x = self.roundNumber(x) y = self.roundNumber(y) windowWidth = webdriver.execute_script("return window.innerWidth;") windowHeight = webdriver.execute_script("return window.innerHeight;") if (x > windowWidth or y > windowHeight...
def click(self, element=None, addDelayAfter=True): if element is not None: self.move_to_element(element) self.actions.click_and_hold() self.actions.pause(np.random.normal(0.092, 0.018)) self.actions.release() if addDelayAfter: self.addDelayAfterAction() ...
This function sends text in sentences with pauses between them, clicking an element if provided. It splits input text into sentences, writes each with delays, adds punctuation, and applies a final delay if specified.
def send_keys(self, keys_to_send, element=None, addDelayAfter=True): if element is not None: self.click(element) sentences = keys_to_send.split(". ") for i in range(len(sentences)-1): self.write_sentence(sentences[i]) self.actions.pause(std_positive(1.7, 0.7, ...
def q_posterior_logits( self, x_start, x_t, t, x_start_format: Literal["logits", "labels"] ): # logits for q(x_{t-1} | x_t, x_start) if x_start_format == "logits": chex.assert_shape(x_start, (*x_t.shape, self.num_classes)) elif x_start_format == "labels": che...
This function computes the variational loss for a diffusion model by calculating the KL divergence between the true posterior and model logits, and the decoder's negative log likelihood of the initial data. It returns the weighted combination of these losses, using KL divergence for t>0 and decoder NLL for t=0, normali...
def variational_loss(self, model_fn, x_start, x_t, t): chex.assert_shape(t, (x_start.shape[0],)) true_logits = self.q_posterior_logits(x_start, x_t, t, x_start_format="labels") model_logits, pred_x_start_logits = self.p_logits(model_fn, x_t, t) kl = self._categorical_kl_logits(true_log...
def q_sample(self, x_start, t, rng): # sample from q(x_t | x_start) logits = jnp.log(self.q_probs(x_start, t) + self.eps) noise = jrnd.uniform( rng, (*x_start.shape, self.num_classes), dtype=logits.dtype, minval=jnp.finfo(logits.dtype).tiny, ...
The code computes the training loss for a diffusion model by combining variational and cross-entropy losses. It generates random time steps, applies noise to input data (x_start) to create x_t, calculates variational loss via the model's predictions, and computes cross-entropy loss between true and predicted x_start lo...
def training_losses(self, model_fn, x_start, rng): sample_rng, time_rng = jrnd.split(rng) t = jrnd.randint( time_rng, (x_start.shape[0],), minval=0, maxval=self.num_timesteps, dtype=jnp.int32, ) x_t = self.q_sample(x_start, t, s...
def connectdb() -> sqlite3.Connection: assert db_file_name is not None debug(f'calling _connectdb to connect to dbfilename "{db_file_name}"') conn = _connectdb(db_file_name) debug(f'_connectdb for dbfilename "{db_file_name}" returned {conn=}') return conn def debug(msg: str) -> None: f = inspe...
This function checks if a file's MD5 hash exists in an SQLite database table by querying the table for a matching filename. It connects to the database, executes a SELECT query with the provided filename, and returns True if the result contains exactly one entry, indicating the MD5 hash is present. It handles exception...
def is_file_in_table(fname: str, hits: list = None) -> bool: """Checks if md5 hash tag exists in the SQLite DB""" conn = connectdb() result = False try: query = f"SELECT fname, md5 FROM {table_name} WHERE fname = ?" debug(f"{query=}") args = (fname,) debug(f"{args=}") ...
def trace(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"TRACE : {f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def connectdb() -> sqlite3.Connection: assert db_file_name is not None debug(f'calling _connectdb to connect to dbfilename "{db_file_name}"') conn = _connectdb(d...
The function `runcmd` executes an SQLite database command with transaction handling, processes query results, and manages errors. It connects to the database, runs the provided SQL command (with optional arguments), fetches results, appends matching rows to a `hits` list, and handles exceptions like integrity or operat...
def runcmd(cmd: str, args: list = None, hits: list = None) -> bool: """Run a specific command on the SQLite DB""" trace(f"entry: {cmd=}") result = None conn = connectdb() debug(f"{conn=}, {type(conn)=}") debug(f"{cmd=}") debug(f"{args=}") debug(f"{hits=}") cursor = conn.cursor() ...
def trace(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"TRACE : {f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def connectdb() -> sqlite3.Connection: assert db_file_name is not None debug(f'calling _connectdb to connect to dbfilename "{db_file_name}"') conn = _connectdb(d...
This function checks if a specified SQLite database table exists by querying the sqlite_master metadata table. It uses parameterized SQL to safely check for the table name, returns True if found, False otherwise, and includes debugging logs.
def tableexists() -> bool: """Checks if a SQLite DB Table exists""" trace("enter") result = None try: conn = connectdb() query = ( # f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'" f"SELECT name FROM sqlite_master WHERE type='table'...
def trace(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"TRACE : {f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def debug(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"{f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def runcmd(cmd: str, args: list = No...
(The code creates a database table named `table_name` with columns for an integer ID, first name (text), MD5 hash (text), and modification date (integer) if it doesn't already exist. It executes a SQL `CREATE TABLE` command, checks the result, and logs errors or confirmation. The main task is to ensure the specified ta...
def createhashtable() -> None: """Creates the named table if it does not exist""" trace(f"enter") cmd = f"CREATE TABLE {table_name} (id integer primary key, fname text, md5 text, moddate integer)" debug(f"command = {cmd}") result = runcmd(cmd) debug(f"runcmd returned {result}") if not resul...
def trace(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"TRACE : {f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def debug(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"{f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def runcmd(cmd: str, args: list = No...
(The function creates a unique index on a specified column of a table using a predefined naming convention. It constructs and executes a SQL command to create the index, logs the command, checks the execution result, and reports success or a fatal error if the index creation fails. The task involves database schema mod...
def create_index(column_name): trace(f"enter: {column_name=}") index_name = f"idx_{table_name}_{column_name}" cmd = f"CREATE UNIQUE INDEX {index_name} ON {table_name} ({column_name})" debug(f"command = {cmd}") result = runcmd(cmd) debug(f"runcmd returned {result}") ...
def getmoddate(fname: str) -> int: """Get file modified date""" try: debug(f"{fname=}") mtime = os.path.getmtime(fname) debug(f"{type(mtime)=}, {mtime=}") return mtime except FileNotFoundError as ex: debug(f'no such file: "{fname}"') except Exception as ex: ...
(The function inserts a file's name, MD5 hash, and modification date into an SQLite database table, returning a boolean indicating success. It uses parameterized SQL to avoid injection, logs debug info, and relies on external functions for date retrieval and command execution.)
def inserthashtable(fname: str, md5: str) -> bool: """Insert into the SQLite File Table""" cmd = f"INSERT INTO {table_name} (fname, md5, moddate) VALUES (?, ?, ?)" args = (fname, md5, int(getmoddate(fname))) debug(f"QQRXQ running SQL INSERT command for {md5=} {fname=}") hits = list() result = ...
def getmoddate(fname: str) -> int: """Get file modified date""" try: debug(f"{fname=}") mtime = os.path.getmtime(fname) debug(f"{type(mtime)=}, {mtime=}") return mtime except FileNotFoundError as ex: debug(f'no such file: "{fname}"') except Exception as ex: ...
The function `updatehashtable` updates an SQLite table by modifying the `md5` and `moddate` fields for a record matching the given `fname`. It constructs an SQL `UPDATE` command, logs it for debugging, executes the command using `runcmd`, and returns the result of the operation. The function ensures the database entry ...
def updatehashtable(fname: str, md5: str) -> bool: """Update the SQLite File Table""" cmd = f"UPDATE {table_name} SET md5='{md5}', moddate={int(getmoddate(fname))} WHERE fname = '{fname}'" debug(f"update command = {cmd}") hits = list() result = runcmd(cmd, hits=hits) # , args) debug(f"QQRXQ r...
def trace(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"TRACE : {f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def debug(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"{f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def getfileext(fname: str) -> str: ...
The function `checkfilechanges` scans files in a specified folder, excluding certain extensions, to detect changes. It calculates each file's MD5 hash, compares it with stored values in a database/table, and updates records if discrepancies are found. It tracks statistics (folders checked, files skipped/changed) and re...
def checkfilechanges(folder: str, excludes: list, ws: object) -> bool: """Checks for files changes""" trace(f"enter: {folder=}, {excludes=}") global counters changed = False debug("=" * 100) debug(f'checking dir "{folder}"') counters["folders"] += 1 for subdir, dirs, files in os.walk(...
def trace(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"TRACE : {f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def debug(msg: str) -> None: f = inspect.currentframe() _logging_.debug(f"{f.f_back.f_code.co_name}[{f.f_back.f_lineno}]: {msg}") def loadflds() -> tuple: trace(f...
The function `runfilechanges` scans specified directories for file changes, ignoring predefined extensions, and tracks results using counters (folders, checked, skipped, changed, unchanged). It loads configuration data (`flds` for directories, `exts` for ignored extensions), iterates through each directory, and invokes...
def runfilechanges(ws: object = None) -> bool: trace(f"enter: {ws=}") global counters counters = { "folders": 0, "checked": 0, "skipped": 0, "changed": 0, "unchanged": 0, } # # read in and parse the config file # debug("getting list of dirs to be...
def read_pgm(filename, byteorder='>'): # code from stackoverflow user cgohlke at https://stackoverflow.com/questions/7368739/numpy-and-16-bit-pgm """Return image data from a raw PGM file as numpy array. Format specification: http://netpbm.sourceforge.net/doc/pgm.html """ with open(filename, 'rb') ...
The code's main task is to load a map from a PGM file, crop it, generate a configuration space (c_space) from the processed map, and return the c_space. It processes the input map file to prepare it for further analysis or navigation tasks.
def load_map(filename): workspace = read_pgm(filename) workspace = crop_map(workspace) c_space = generate_c_space(workspace, filename) return c_space
def read_pgm(filename, byteorder='>'): # code from stackoverflow user cgohlke at https://stackoverflow.com/questions/7368739/numpy-and-16-bit-pgm """Return image data from a raw PGM file as numpy array. Format specification: http://netpbm.sourceforge.net/doc/pgm.html """ with open(filename, 'rb') ...
The code reads a PGM map, crops it, generates a configuration space (obstacle map) with resolution, creates a CSpace object, and visualizes the navigable/free space as a grayscale image with labeled axes, showing robot's operational area versus obstacles.
def main(): workspace = read_pgm('tb_map.pgm') workspace = crop_map(workspace) [resolution, configuration_space] = generate_c_space(workspace, 'tb_map.pgm') configuration_space = c_space.CSpace(configuration_space, [resolution], resolution) plt.imshow(configuration_space.c_space, cmap='gray', ...
def generate_goal_matrix(goals, filename, n_samples=10000, r=0.2, p_goal=0.05, eps=0.1): [resolution, configuration_space] = map_load.load_map(filename) configuration_space = c_space.CSpace(configuration_space, goals, resolution) n = len(goals) goal_matrix = np.zeros([n, n], dtype=np.ndarray) index ...
The code's main task is to generate a goal matrix from predefined coordinates on a map ('tb_map.pgm'), visualize the configuration space and goals, save the goal matrix as a NumPy file, and optionally execute a benchmark. It defines goals, creates a matrix using `generate_goal_matrix`, displays the results, and stores ...
def main(): # goal 1: 95, 65 # goal 2: 48, 75 # goal 3: 48, 55 # goal 4: 70, 55 # goal 5: 70, 75 # goal 6: 60, 30 # goal 7: 60, 100 # goal 8: 20, 60 goals = np.array([[3.25, 1], [2.7, 2.4], [3.8, 2.4], [3.8, 3.45], [2.7, 3.45], [3.25, 5.1], [5, 3], [1.5, 3]]) [configuration_space...
def First(X): global first_look first = [] first_look.append(X) if X in terminals: first.append(X) elif X in nonterminals: for prods in G[X]: if prods[0] in terminals and prods[0] not in first: first.append(prods[0]) else: for n...
This function prints a grammar's structure, including original and augmented grammars, terminals, non-terminals, symbols, First/Follow sets, parsing items, closure, and a parsing table. It formats and displays all components of a context-free grammar and its associated LL(1) parsing data for analysis or debugging.
def print_info(): print("\nGRAMMAR:") for head, tail in G.items(): if head==start: continue print(head, " ->", end=" ") for t in tail: for r in t: print(r, end=" ") if(t!=tail[len(tail)-1]): print(" |", end=" ") ...
def get_company_list(): #to fetch company data return pd.read_csv('companylist.csv') def display_welcome(): # displays welcome message for user print('\n =*=*=*=*=*=*=*Welcome to the Stock Predictor Application=*=*=*=*=*=*=*= ') def display_menu(): # printing the main menu for user print("\n======Main Menu...
The main task of the code is to orchestrate a user interaction workflow for managing company data. It retrieves a company list, displays a welcome message and menu, captures user input, and processes the selected action using the company data. The function serves as the entry point for executing menu-driven operations ...
def main(): # the main function company_list = get_company_list() display_welcome() display_menu() choice = get_choice() process_choice(choice, company_list)
def BollingerBands(Data, boll_lookback, standard_distance, what, where): # Calculating mean ma(Data, boll_lookback, what, where) # Calculating volatility volatility(Data, boll_lookback, what, where + 1) Data[:, where + 2] = Data[:, where] + (standard_distance ...
This function processes financial data to detect market squeezes by calculating technical indicators like Bollinger Bands, Keltner Channels, Donchian Channels, and moving averages. It computes price deltas, smooths them, and identifies squeeze conditions when specific column values cross, marking the event in a new col...
def squeeze(Data, boll_lookback, boll_vol, kelt_lookback, kelt_vol, close, where): # Adding Columns Data = np.append(Data,np.zeros((Data.shape[0],20)),axis=1) # Adding Bollinger Bands Data = BollingerBands(Data, boll_lookback, boll_vol, close, where) # Adding Keltner Channel Data = kel...
def pick_up(self, value:bool): if value: command = CMD_PICK_UP else: command = CMD_DROP self.__add_buffer_of_commands(command) def __create_gcode_for_go_to_coordinate(self, x=None, y=None, z=None, f=DEFAULT_FEED_RATE): command = BASE_GO_...
This code removes an object from a specified position by marking it as unoccupied, moving the robotic arm to the position, releasing the object, navigating to a safe height, then proceeding to an output position to drop the object, and finally updating the system state to indicate products need refreshing.
def remove_in_position(self, position): self._points_busy[position] = False self.pick_up(value=False) self.__create_gcode_for_go_to_coordinate(z=Z_STANDARD_ELEVATION) self.go_to_position(position) self.__create_gcode_for_go_to_coordinate(z=Z_TO_PICK_UP) self.pick_up(value...
def pick_up(self, value:bool): if value: command = CMD_PICK_UP else: command = CMD_DROP self.__add_buffer_of_commands(command) def __create_gcode_for_go_to_coordinate(self, x=None, y=None, z=None, f=DEFAULT_FEED_RATE): command = BASE_GO_...
This function handles robotic arm movements to insert an item into a specified position. It marks the position as busy, moves to a pickup point, lifts the item, navigates to the target position, lowers the item, releases it, and updates product status. G-code commands orchestrate precise z-axis movements for safe inser...
def insert_in_position(self, position): self._points_busy[position] = True self.pick_up(value=False) self.__create_gcode_for_go_to_coordinate(z=Z_STANDARD_ELEVATION) self.go_to_position(POSITION_IN) self.__create_gcode_for_go_to_coordinate(z=Z_TO_PICK_UP) self.pick_up(val...
def infoBox(data): infoSection = data.split("{{Infobox") litsOfWordinInfobox = [] if(len(infoSection) > 1): for line in range(1,len(infoSection)): eachWord = infoSection[line].split('\n') for word in eachWord: if( word == "}}"): break preProcessWord = cleanData(word) ...
The function `getAllsection` extracts and returns lists of words from different sections of structured data, including the title (after cleaning), infobox, category, external links, references, and body content. It aggregates these word lists for further processing or analysis.
def getAllsection(title,data): # get list of word belong to each section litsOfWordinInfobox = infoBox(data) listOfWordsinCategory = category(data) externalLinksWords = external(data) referenceListWords = reference(data) listOfBodyWords = body(data) listOfTitlsWords = [] for words in tit...
def getAllsection(title,data): # get list of word belong to each section litsOfWordinInfobox = infoBox(data) listOfWordsinCategory = category(data) externalLinksWords = external(data) referenceListWords = reference(data) listOfBodyWords = body(data) listOfTitlsWords = [] for words in tit...
The function processes a document by splitting its title and text into structured sections (titleMap, infoMap, categoryMap, etc.), then indexes each word in these sections into a global `indexTable` mapped to document IDs. Each word is associated with its section-specific data (e.g., "externalData," "referenceMap") and...
def saveAndPreprocess(title , text , docId ): title , infoMap , categoryMap , externalData , referenceMap , bodyMap= getAllsection(title , text) titleMap = getMap(title) categoryMap = getMap(categoryMap) bodyMap = getMap(bodyMap) infoMap = getMap(infoMap) referenceMap = getMap(referenceMap) externalDa...
def printImports(self): temp = '' for val in self.getImports(): temp+=val+'\n' self.returns.append(temp+'\n') def printRelations(self): temp = '' temp += 'class Relation:\n' # self.returns.append(temp) # print(self.tableStruct) for vals in self...
The main task of the code is to generate and output structured code components by sequentially printing imports, relationships, and module structure, then initiating the main function with the provided 'manage' parameter. The method returns the instance's 'returns' attribute, likely containing generated code or results...
def outputFile(self,manage): self.printImports() self.printRelations() self.printMFStructure() self.startMain(manage) return self.returns
def backpropagate(self, simulation_score): """ Backpropagates score and visit count to parents. """ self.node_total_score += simulation_score self.node_total_visits += 1 if self.parent is not None: self.parent.backpropagate(opponent...
This function performs one iteration of the MCTS algorithm by checking if the current node is terminal (then backpropagating), expandable (then expanding and simulating), or otherwise selecting the strongest child and recursively repeating the process, thus completing one full cycle of selection, expansion, simulation,...
def tree_single_run(self): """ A single iteration of the 4 stages of the MCTS algorithm. """ if self.is_terminal: self.backpropagate(self.terminal_score) return if self.is_expandable(): self.expand_and_simulate_c...
def get_patterns(cell): """ 2A1. This function gets the swarm and opponent's patterns of each axis of the cell. It calls the get_pattern function for each axis and concatenates the resulting lists.""" ne = get_pattern(cell["x"], lambda z : z + 1, cell["y"], lambda z : z - 1, conf.inarow) ...
The main task of the code is to evaluate a cell's strategic value in a game by analyzing its patterns, calculating points, and exploring its upper cells across multiple rows to determine its importance to players' strategies.
def evaluate_cell(cell): """ 1. Evaluate qualities of the cell in how valuable it is to each player's patterns """ cell = get_patterns(cell) cell = calculate_points(cell) for i in range(1, conf.rows): cell = explore_cell_above(cell, i) return cell
def is_terminal_node(grid, config): if list(grid[0, :]).count(0) == 0: return True for row in range(config.rows): for col in range(config.columns-(config.inarow-1)): window = list(grid[row, col:col+config.inarow]) if is_terminal_window(window, conf...
The code implements the minimax algorithm with alpha-beta pruning for a game, evaluating optimal moves by recursively exploring game states. It alternates between maximizing and minimizing players, selecting the best move based on heuristic values. Alpha-beta pruning optimizes search efficiency by discarding suboptimal...
def minimax(node, depth, maximizingPlayer, mark, alpha, beta, config): is_terminal = is_terminal_node(node, config) valid_moves = [c for c in range(config.columns) if node[0][c] == 0] if depth == 0 or is_terminal: return get_heuristic(node, mark, config), None if maximizingPl...
def is_terminal_node(grid, config): # Check for draw if list(grid[0, :]).count(0) == 0: return True # Check for win: horizontal, vertical, or diagonal # horizontal for row in range(config.rows): for col in range(config.columns-(config.inarow-1)): ...
The code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a game-playing agent. It evaluates game states recursively, maximizing the agent's score (when `maximizingPlayer=True`) or minimizing the opponent's score (when `maximizingPlayer=False`), while pruning suboptimal branche...
def minimax(node, depth, maximizingPlayer, mark, alpha, beta, config): is_terminal = is_terminal_node(node, config) valid_moves = [c for c in range(config.columns) if node[0][c] == 0] if depth == 0 or is_terminal: return get_heuristic(node, mark, config), None # Agent's turn ...
def parse_cgs(file_name): cgs = [] with open(file_name, mode="r") as file: for line in file: if len(line) == 0: break striped_line = line.strip() item_type = None nested_data = None if striped_line.startswith('ENTRY'): ...
The code processes command-line arguments to parse, compress, and export CGS data using a specified LZSS tool, converting input files to compressed output files at a defined path.
def main(): parser = argparse.ArgumentParser() parser.add_argument("--output", required=True, type=pathlib.Path) parser.add_argument("--input", required=True, type=pathlib.Path) parser.add_argument("--lzss_tool", required=True, type=pathlib.Path) option = parser.parse_args() cgs = parse_cgs(op...
def fit_enough(population: list): return fitness(best_individual(population)) == 10 def weighted_by(population: list, fitness: callable) -> list: weights = [] for individual in population: weights.append(fitness(individual)) return weights def weighted_random_choices(population: list, weights: list, a...
The code implements a genetic algorithm to evolve a population of individuals toward an optimal solution. It iteratively selects parents based on fitness, breeds them to create offspring, applies random mutations, and replaces the population until a fit individual is found. The process tracks generations and returns th...
def genetic_algorithm(population: list, fitness: callable) -> tuple: global MUTATION_RATE generation = 0 while not fit_enough(population): weights = weighted_by(population, fitness) # same as fitness proprety next_population = [] for i in range(0, len(population)): parent1, par...
def load_moves(file_name): with open(file_name, 'r') as seq_file: raw_seq = seq_file.readlines() clean_seq = list() for move in raw_seq: clean_seq.append(move.rstrip()) return clean_seq def new_moves_generator(moves_to_extend, variant): variants_and_moves = {"1": 0, "...
The code evolves a new generation of candidates by generating variants of their move sequences, applying mutations, and returning the next generation for further iterations in an evolutionary algorithm.
def evolve(candidates, generation): candidate = candidates[0] moves = load_moves(candidate["seq_file"]) next_generation = list() variants_and_moves = {"1": 0, "2": 1, "3": 2, "4": 4, "5": 5, "6": 3} new_generation = int(generation) + 1 for v in variants_and_moves.keys(): new_candidate =...
def load_moves(file_name): with open(file_name, 'r') as seq_file: raw_seq = seq_file.readlines() clean_seq = list() for move in raw_seq: clean_seq.append(move.rstrip()) return clean_seq def crossover(parent1_moves, parent2_moves): offspring_moves = parent1_moves.copy(...
The function `evolve_sokol` generates the next generation of Sokol sequences by performing crossover operations on the top three parent candidates and applying mutations to the resulting offspring. It creates six new candidates: three from pairwise parent crosses, three direct copies of parent moves, and applies mutati...
def evolve_sokol(candidates, generation): parent_1 = candidates[0] parent_1_moves = load_moves(parent_1["seq_file"]) parent_2 = candidates[1] parent_2_moves = load_moves(parent_2["seq_file"]) parent_3 = candidates[2] parent_3_moves = load_moves(parent_3["seq_file"]) next_generation = list...
def load_moves(file_name): with open(file_name, 'r') as seq_file: raw_seq = seq_file.readlines() clean_seq = list() for move in raw_seq: clean_seq.append(move.rstrip()) return clean_seq def crossover(parent1_moves, parent2_moves): offspring_moves = parent1_moves.copy(...
The function `evolve_fixed_length` generates a new generation of candidates by selecting the top three parent candidates, performing crossover on their move sequences to create offspring, applying random mutations to these offspring, and appending the resulting mutated offspring as new candidates for the next generatio...
def evolve_fixed_length(candidates, generation): best_parent1 = candidates[0] best_parent1_moves = load_moves(best_parent1["seq_file"]) best_parent2 = candidates[1] best_parent2_moves = load_moves(best_parent2["seq_file"]) best_parent3 = candidates[2] best_parent3_moves = load_moves(best_paren...
def load_moves(file_name): with open(file_name, 'r') as seq_file: raw_seq = seq_file.readlines() clean_seq = list() for move in raw_seq: clean_seq.append(move.rstrip()) return clean_seq def crossover(parent1_moves, parent2_moves): offspring_moves = parent1_moves.copy(...
The function evolves a new generation of candidates using genetic operations. It selects top candidates, performs crossover on their move sequences, applies mutations, and generates new offspring. These are combined into a new generation, incrementing the generation count, to iteratively improve solutions through evolu...
def evolve_fixed_length_sroka(candidates, generation): best_parent1 = candidates[0] best_parent1_moves = load_moves(best_parent1["seq_file"]) best_parent2 = candidates[1] best_parent2_moves = load_moves(best_parent2["seq_file"]) best_parent3 = candidates[2] best_parent3_moves = load_moves(best...