dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def run_game(self): self.input = input("Please Type 'on' to start game") if self.input != 'on': self.input if self.input == 'on': self.display_welcome() def battle(self): self.dinosaurs = herd() self.robots = fleet() self.input = input("Choose 'Din...
The code initializes and runs a game where dinosaurs and robots take alternating turns in battles, ultimately displaying the winners. The `__init__` method sequentially triggers game setup, combat logic, turn-based actions for both players, and result display.
def __init__(self): self.run_game() self.battle() self.dino_turn() self.robot_turn() self.display_winners()
def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.game_over = True if event.type == pygame.MOUSEBUTTONDOWN: mx, my = pygame.mouse.get_pos() if mx >= 0 and mx <= WIN_SIZE[0] \ ...
The code runs a game loop that continues until `game_over` is True. It maintains the frame rate using `clock.tick()`, processes events with `handle_events()`, updates game state via `update()`, and renders graphics with `draw()` to create an interactive game experience.
def run(self): while not self.game_over: self.clock.tick(self.fps) self.handle_events() self.draw() self.update()
def readSensors(): count = 0 sensor = "" for file in os.listdir("/sys/bus/w1/devices/"): if (file.startswith("28-")): readSensor(file) count+=1 if (count == 0): print("No sensor found! Check connection") def motor(status, direction): if status == 1: # run if direction == 1: GPIO.output(MotorPin_A, ...
The code continuously reads sensor data, checks temperature against a threshold, and controls a motor: activating it if temperature meets or exceeds the threshold, deactivating otherwise, while handling keyboard interrupts to stop operations.
def loop(): while True: readSensors() time.sleep(1) if temperature >= value: try: motor(1,1) except KeyboardInterrupt: totalStop() if temperature < value: motor(0,0)
def get_or_create_particle(p: Particle, i: int): name = f"Particle {i}" obj = bpy.data.objects.get(name) if not obj: bpy.ops.mesh.primitive_uv_sphere_add(radius=0.01, location=p.position) obj = bpy.context.object obj.name = name # Ensure the particle is visible starting at ...
This function simulates particle behavior over time, updating their positions and animation keyframes. It advances the simulation step-by-step, adjusts the scene frame rate, manages particle visibility based on state (alive/dirty), and configures animation settings. Finally, it sets the scene's end frame and updates ca...
def run_simulation(simulation: Simulation): FPS = 30 simulation.start() frame = 0 scene = bpy.context.scene while any(p.is_dirty for p in simulation.particles): # Advance the simulation by 1 step: simulation.step() # Current frame is the total time passed in sim * FPS ...
def Conv_BN(x, filters, kernel_size, strides, activation=True, dilation_rate=1): x = Conv2D(filters, kernel_size, strides=strides, padding='same', dilation_rate=dilation_rate)(x) x = BatchNormalization()(x) if activation: x = ReLU()(x) return x def sep_conv_block(x, filters, strides): if isi...
The code defines a neural network model with an entry flow (convolutional and separable convolution blocks), a middle flow (repeated separable identity blocks), and an exit flow (additional separable convolutions). It processes input tensors through progressively complex layers, ends with residual connections via the s...
def model(input_tensor): # entry flow x = Conv_BN(input_tensor, 32, kernel_size=3, strides=2) x = Conv_BN(x, 64, kernel_size=3, strides=1) x = sep_conv_block(x, filters=128, strides=2) x = sep_conv_block(x, filters=256, strides=2) shortcut = x x = sep_conv_block(x...
def _log(self, msg): print(self._name, msg) def _optimize(self): st = time.perf_counter() self._traverse(1, 0, len(self._loader)) if not self._use_cache: self._optimization_time = time.perf_counter() - st else: for m in self._exec_record: ...
The main task of the code is to perform optimization and execution, calculate query time based on cache usage, and return the result. It logs progress, invokes optimization and execution methods, computes total query time either directly or by aggregating model-specific times from execution records, then returns the pr...
def process(self): st = time.perf_counter() self._log("start optimization ...") self._optimize() self._log("start execution ...") self._execute() if not self._use_cache: self._query_time = time.perf_counter() - st else: for m in self._ex...
def image_mean_std(fits_data, samples=10000, mad_filter=5.0): test_data = 1.0 * fits_data.flatten() test_data = test_data[::int(len(test_data)/samples + 1)] quantiles = np.quantile(1.0 * test_data, [0.5 - 0.341, 0.5, 0.5 + 0.341]) if quantiles[0] == quantiles[1]: if quantile...
The function solves the plate (determines celestial coordinates of image pixels) by matching detected stars in a FITS image with Gaia catalog stars. It calculates image statistics, generates a default WCS, queries Gaia stars within the field of view (FOV), cross-matches detected and Gaia stars using an affine transform...
def image_plate_solve(fits_data, fits_header, ra, dec, mean=None, std=None, burn_limit=None, psf=None, stars=None, n=20, pixel=None, progress_window=None, verbose=False, gaia_engine=_get_gaia_stars): if verbose: print('\nAnalysing frame...') if mean is None ...
def planet_generator(): for color in colors: yield new_planet(color) def save(image, path=None): if path == None: i = 0 template = "sprites/planets/planet-{i}.png" path = template.format(i=i) while os.path.exists(path): i += 1 path = template.forma...
The code initializes Pygame, creates a 10x10 pixel display window, generates planets using a custom generator, saves each generated planet sprite, and creates a white "backing" planet sprite saved as a PNG file for later use in a game or visual project.
def main(): pg.init() pg.display.set_mode((10, 10), 0, 32) for p in planet_generator(): save(p) backing = new_planet((255, 255, 255), False) save(backing, "sprites/planets/planet-backing.png")
def edit_info(app_session, recipe): print_recipe_metadata(recipe) command = "" while command != "Exit": command = command_input(bcolors.BOLD + "Which Piece of Information Would You Like to Edit?" + bcolors.ENDC, ["Name", "Description", "Difficulty", "Servings", "Cook...
The code creates a new recipe, adds it to the user's recipe list, commits the session, then calls functions to edit the recipe's information, ingredients, and steps.
def create(app_session): print(bcolors.BOLD + bcolors.UNDERLINE + "Create a Recipe" + bcolors.ENDC) recipe = Recipe() app_session.user.Recipes.append(recipe) app_session.session.commit() edit_info(app_session, recipe) edit_ingredients(app_session, recipe) edit_steps(app_session,recipe)
def edit(app_session): recipes = get_users_recipes(app_session) print(bcolors.BOLD + bcolors.UNDERLINE + "Edit a Recipe" + bcolors.ENDC) print("Please Enter the Number of the Recipe you Would Like to Edit. (Or Type \"exit\" to leave this menu") for idx, r in enumerate(recipes): print(bcolors.B...
This code defines a RecipeController that manages recipe-related actions via a menu-driven interface. It allows users to Create, Edit, Delete, or Categorize recipes using functions like create(), edit(), and delete(), all within an app_session context. The loop continues until the user selects "Exit," at which point it...
def RecipeController(app_session): command = "" print(bcolors.HEADER + "Recipe Editor" + bcolors.ENDC) while command != "Exit": command = command_input(bcolors.BOLD + "What would you like todo?" + bcolors.ENDC, ["Create", "Edit", "Delete", "Categorize", "Exit"]) ...
def convert_fields(base_dict): """ Returns dictionary with the same keys and converted values <base_dict> : basic {key:value} dict containing only keys that are present in field_map """ field_map={'id':'int', 'lat':'float', 'lon':'float', 'user':'str', 'uid':'int', 'version':'int', 'cha...
The function `shape_element` converts XML elements representing map nodes or ways into structured Python dictionaries. It extracts specified attributes, processes tags, and handles nested node references for ways. It returns a dictionary with cleaned attributes and tags for nodes, or attributes, node references, and ta...
def shape_element(element, node_attr_fields=NODE_FIELDS, way_attr_fields=WAY_FIELDS, default_tag_type='regular'): """Clean and shape node or way XML element to Python dict""" node_attribs = {} way_attribs = {} way_nodes = [] tags = [] # Handle secondary tags the same way for both...
def get_element(osm_file, tags=('node', 'way', 'relation')): """Yield element if it is the right type of tag""" context = ET.iterparse(osm_file, events=('start', 'end')) _, root = next(context) for event, elem in context: if event == 'end' and elem.tag in tags: yield elem ...
This function processes XML elements from a file, validates them if specified, and writes structured data into separate CSV files for nodes, ways, and their associated tags. It uses UnicodeDictWriter to handle different element types, ensuring node and way data are split into distinct CSV outputs for organized storage.
def process_map(file_in, validate): """Iteratively process each XML element and write to csv(s)""" with codecs.open(NODES_PATH, 'w') as nodes_file, \ codecs.open(NODE_TAGS_PATH, 'w') as nodes_tags_file, \ codecs.open(WAYS_PATH, 'w') as ways_file, \ codecs.open(WAY_NODES_PATH, 'w') as...
def __stream(self): """Return a generator of outgoing gRPC messages. :return: a gRPC message generator """ while True: s = self.__queue.get() if s is not None: logger.info(f'{self.__player_id} - Sending {s}') yield s el...
(The main task of the code is to set up a gRPC client for a game, generating a unique player ID, establishing a connection to the server, initiating a game session, and sending a "join" request. It spawns a background thread to handle server responses asynchronously, ensuring the client is ready to participate in the g...
def join(self): """This method sets up the client for sending and receiving gRPC messages to the server. It then sends a join message to the game server to indicate we are ready to play a new game. """ self.__player_id = str(uuid.uuid4()) logger.info(f'New player: {self....
def recv(self): """Receive a gRPC message. :return: gRPC message that was received """ try: return next(self.__stream) except grpc.RpcError: logger.error('An RPC error occurred!') self.stop() except StopIteration: logger.wa...
This method initializes a server to handle player joining requests by establishing game connections, creating necessary threads for message subscription (Redis and gRPC), and managing game session lifecycle. It validates join messages, retrieves/creates game instances, and ensures proper thread coordination and cleanup...
def start(self, request_iterator, context): """Method that starts the actual server. :param request_iterator: iterator that provides message :param context: gRPC context object """ self.__stream = request_iterator self.__context = context while True: ...
def get_data(self): with tf.name_scope('Data'): train_dset, val_dset, test_dset, val_size, label_names = create_datasets(data_path=self.data_path, resize=self.size, augment=True, batch_size=self.batch_size, num_threads=16) # train_dset, val_dset = utils.get_mnist_dataset(self.batch_size) self.n_te...
The code defines a `build` method that separates tasks between CPU and GPU: it loads data on the CPU and performs model inference, loss calculation, optimization, evaluation, and summary generation on the GPU, leveraging parallelism for efficiency.
def build(self): with tf.device('/cpu:0'): self.get_data() with tf.device('/gpu:0'): self.inference() self.loss() self.optimize() self.eval() self.summary()
def generate_X_CPT_Gaussian(n_steps, n_perms, X, mean, cov): log_lik_mat = -1/2 * (X-mean) @ np.linalg.pinv(cov) @ (X-mean).T perm_mat = generate_X_CPT(n_steps, n_perms, log_lik_mat) return X[perm_mat] def reshape(array, d): for x in array: yield x.reshape(-1, d) def HSCIC(k_X, k_Y, k_Z, W): ...
This function performs a conditional independence test using kernel methods and permutation testing. It computes a test statistic (HSCIC) to assess independence between variables X and Y given Z, generating a null distribution via permutations to calculate a p-value. If the p-value is below a threshold (alpha), it reje...
def cond_indep_test(X, Y, Z_arr, lamb, alpha, n_perms, n_steps, make_K, pretest): if len(X.shape)==1: X = X.reshape(-1, 1) Y = Y.reshape(-1, 1) Z_arr = Z_arr.reshape(-1, 1) n_nodes, n_samples, n_obs = Z_arr.shape Z = np.zeros((n_samples, n_nodes*n_obs)) for node in range(n_node...
def marginal_indep_test(X, Y, n_perms, alpha, make_K, biased): """ Performs a marginal independence test with HSIC as a test statistic and returns an 'accept' (0) or 'reject' (1) statement for the null hypothesis of marginal independence Inputs: X: (n_samples, n_obs) array of function values of fir...
The function `test_power` calculates the statistical power of independence tests (marginal, conditional, or joint) by running multiple trials. It performs hypothesis testing on input data samples, using permutations to estimate p-values, and returns the percentage of null hypothesis rejections across trials. The test t...
def test_power(X, Y=None, Z=None, edges_dict=None, n_trials=200, n_perms=1000, alpha=0.05, K='K_ID', test='marginal', lamb_opt=1e-4, n_steps=50, biased=True): """ Computes the test power by conducting multiple independence tests in parallel and returning the percentage of null hypothesis reje...
def check_or_create_dir(path): if not os.path.exists(path): if not os.path.exists(os.path.dirname(path)): check_or_create_dir(os.path.dirname(path)) os.mkdir(path) def initial_config(self): self.config = configparser.ConfigParser() self.config_file = os.path.join(self.con...
The code initializes a configuration system by constructing a directory path in the user's local AppData folder. It checks if the directory exists, creating it if necessary. If the directory isn't a file (implying it's a new config), it initializes the config, adds a 'data' section, and saves it. If the config already ...
def __init__(self): self.config_folder = os.path.join(os.path.join(os.path.join(os.path.join('C:\\Users', os.getlogin()), 'AppData'), 'Local'), 'FOLIO-api') check_or_create_dir(self.config_folder) if not os.path.isfile(self.config_folder): self.initial_config() self.add_s...
def _update_ema(self, ema, input, reduce_fn=lambda x: x.abs().max()): """Update exponential moving average (EMA) of activations thresholds. the reduce_fn calculates the current threshold from the input tensor""" assert self._step >= self.start_step if self._step == self.start_step: ...
This function performs fake quantization on inputs and weights during training, using EMA to learn quantization ranges if enabled. It applies quantization to activations and weights, optionally requantizing outputs, to simulate low-precision training and prepare for deployment.
def training_quantized_forward(self, input): """fake quantized forward, fake quantizes weights and activations, learn quantization ranges if quantization mode is EMA. This function should only be used while training""" assert self.training, "should only be called when training" i...
def _get_input_scale(self, input=None): return self._get_activation_scale(input, self.input_thresh) def quantize(input, scale, bits): """Do linear quantization to input according to a scale and number of bits""" thresh = calc_max_quant_value(bits) return input.mul(scale).round().clamp(-thresh, thres...
This function performs quantized inference by converting input tensors to integer representations using a specified scale and bit-depth, executing linear computations with quantized weights and biases, and then dequantizing the output. It ensures operations use only integer arithmetic during inference, with optional ou...
def inference_quantized_forward(self, input): """Simulate quantized inference. quantize input and perform calculation with only integer numbers. This function should only be used while doing inference""" assert not self.training, "should only be called when not training" input_scale = se...
def valid_moves(board): result = [idx for idx, value in enumerate(board[0]) if value == 0] return np.array(result) def score_board(board, depth): player_score = score_player_board(board) score = player_score - depth/1000 if is_win(board): score = 4 if is_loss(board): score = -4 ...
This function implements alpha-beta pruning for game tree search, optimizing move selection by recursively evaluating nodes with depth-limited minimax. It alternates between maximizing and minimizing players, updating alpha/beta bounds to prune suboptimal branches. The 'history' dictionary tracks move efficacy by incre...
def alpha_beta_pruning(node, depth, alpha, beta, history=None, max_depth=DEPTH): if depth == max_depth: history = {move: 0 for move in valid_moves(node.board)} if depth == 0 or node.is_terminal(): return score_board(node.board, depth) if node.is_maximizing_player(): value = -math.i...
def generate_immigrant(self): examples = [] solutions = [] for i in range(self.n_examples): new_ex, sol = self.update_train_space() examples.append(new_ex) solutions.append(sol) return Candidate(pd.Series(examples), pd.Series(solutions), output_tokens=self.max_tokens, fit_func=self.fit_func, engine=se...
The function `reproduce_immigrate` generates new offspring by duplicating existing candidates, creates immigrants via `generate_immigrant`, performs PMX crossover between offspring and immigrants, applies mutation to offspring, and updates the population by combining original candidates, immigrants, and mutated offspri...
def reproduce_immigrate(self): # Create new offspring, one identical to each parent, to be crossed later # Note this only takes even numbers of candidates, which is guaranteed by the previous tournament selection new_candidates = [] for cand in self.candidates: new_cand = deepcopy(cand) new_cand.fitness =...
def calc_fitness(self, X_test, y_test, new_test_set=False): """ Update the fitness for each candidate. Args: X_test: pd.Series, the set of examples to evaluate y_test: pd.Series, labels of the X_test new_test_set: bool, whether to update the fitness of every candidate or just the unscored candidates. Use...
This function evolves a population in a genetic algorithm by updating member fitness, selecting candidates via tournament selection (or immigration-based selection), reproducing new members, re-evaluating their fitness, and updating the best candidate based on fitness scores. The 'immigrate' flag determines selection/r...
def next_generation(self, X_test, y_test, new_test_set=False, immigrate=True): # Check and update any new population members fitness self.calc_fitness(X_test, y_test, new_test_set) # Add new members of the population likely to have improved fitness if not immigrate: self.tournament_selection() self.repro...
def get_model(): style_layers = [ "block1_conv1", "block2_conv1", "block3_conv1", "block4_conv1", "block5_conv1" ] content_layers = ["block5_conv2"] vgg = vgg19.VGG19(include_top=False, weights='imagenet') vgg.trainable = False style_outputs = [vgg.get_lay...
The code performs neural style transfer by optimizing an image to blend the style of a given style image with the content of a target image. It freezes a pre-trained model's layers, extracts features, computes style (gram matrix) and content losses, and iteratively updates the generated image using gradient descent. Th...
def transfer(content, style_path, num_iters=1000, content_wt=1e3, style_wt=1e-2, vid=False): model = get_model() for layer in model.layers: layer.trainable = False style_feats, content_feats = get_features(model, content, style_path, vid=vid) gram_style_feats = [gram_matrix(style_feat) for styl...
def click_element(self, *locator): self.driver.find_element(*locator).click() def fill(self, text, *locator): self.driver.find_element(*locator).send_keys(text) def click_text(self, text): self.scroll_element(By.XPATH, '//*[contains(text(), "'+text+'")]') self.click_element(By.XPATH, '//...
This code automates entering payment details on a webpage: it clicks a 'Continue' button, fills in phone number, card number, expiry date, and CVV fields, then clicks 'Continue' and 'OK' buttons to complete the payment process.
def fillcc(self, phone, cardnumber, expire, cvv): self.click_element(*HomePageLocator.CONTINUE_BTN) self.fill(phone, *HomePageLocator.TEL) self.fill(cardnumber, *HomePageLocator.CARDNUMBER) self.fill(expire, *HomePageLocator.EXPIRY) self.fill(cvv, *HomePageLocator.CVV) se...
def _checkStraight(self): # get the tuple of the hand, which is already sorted based on card values hand = self._arrange() # get a list of values list_of_values = [a[0] for a in hand] # cycle first 4 cards. Does the value plusOne equal the next list element? If not, return fal...
The code initializes a poker hand evaluator by creating EvalCard instances from the input hand, then checks for straight, flush, royal/straight flush, and other combinations to determine the hand's properties.
def __init__(self, hand): # create and fill a list of EvalCard Class items self.evalHand = [EvalCard(value, suit) for value, suit in hand] # check and return if the hand has a straight self.is_there_straight = self._checkStraight() # check and return if the hand has a flush ...
def select_model(model_name): # load model class for a given model name if model_name.lower() == 'sgdregressor': from sklearn.linear_model import SGDRegressor return SGDRegressor elif model_name.lower() == 'linearregressor': from sklearn.linear_model import LinearRegression r...
This function tunes a regression model by first establishing a baseline with default parameters, then optimizing hyperparameters using a grid search. It scales training data, saves baseline and tuned models, and prints completion.
def tune_one_regression_model(args, X_train, y_train): ''' Tune a regression model and save the best parameters to a file. Both calculates a baseline from the standard parameters, and calls tune_regression_hyperparameters to find the best parameters. Data are scaled using StandardScaler before fitting...
def select_model(model_name): # load model class for a given model name if model_name.lower() == 'sgdregressor': from sklearn.linear_model import SGDRegressor return SGDRegressor elif model_name.lower() == 'linearregressor': from sklearn.linear_model import LinearRegression r...
This function tunes a classification model by first establishing a baseline with default parameters and then optimizing hyperparameters. It scales data using StandardScaler, trains the model, saves baseline results, generates a parameter grid, tunes hyperparameters via cross-validation, and stores the optimized model. ...
def tune_one_classification_model(args, X_train, y_train): ''' Tune a classification model and save the best parameters to a file. Both calculates a baseline from the standard parameters, and calls tune_classification_hyperparameters to find the best parameters. Data are scaled using StandardS...
def train_nn(arguments): results_dir = make_results_dir(arguments) X_train, X_test, y_train, y_test = make_datasets(arguments) save_data_to_results(X_train, X_test, y_train, y_test, results_dir) loaders = make_dataloaders(arguments, X_train, X_test, y_train, y_test) configs = get_configs(argume...
The main task of the code is to train a neural network, evaluate multiple configurations, identify the model with the lowest RMSE, visualize results (scatter/loss plots), and return the best RMSE value and corresponding configuration. It automates the process of model training, hyperparameter tuning, and performance an...
def train_and_evaluate_nn(arguments): results_dir, trained = train_nn(arguments) best_rmse, best_config = find_best_model(results_dir, range(arguments['nn_n_configs'])) evaluate_nn(best_config, results_dir, plot_scatter=True, plot_loss=True) print('Best RMSE:', best_rmse) print('Best config:', best_...
def get_model_type(model_name): # return the type of model for a given model name regressors = ['sgdregressor', 'decisiontreeregressor', 'randomforestregressor', 'gradientboostingregressor', 'svr', 'kernelridge', 'bayesianridge'] classifiers = ['logisticregression', 'decisiontreeclassifier', 'randomforestcl...
The code evaluates multiple machine learning models specified in the arguments. It iterates through each model, determines its type (regression or classification) using `get_model_type`, and applies the corresponding evaluation function (`evaluate_one_regression_model` or `evaluate_one_classification_model`) to assess ...
def do_evaluation(arguments): # evaluates models based on the arguments and model type for model in arguments['ml_model']: arguments['ml_model'] = model if get_model_type(model) == 'regression': evaluate_one_regression_model(arguments) elif get_model_type(model) == 'class...
def get_model_type(model_name): # return the type of model for a given model name regressors = ['sgdregressor', 'decisiontreeregressor', 'randomforestregressor', 'gradientboostingregressor', 'svr', 'kernelridge', 'bayesianridge'] classifiers = ['logisticregression', 'decisiontreeclassifier', 'randomforestcl...
The code trains machine learning models by iterating over specified models in the arguments, determining each model's type (regression, classification, or neural network), and invoking the corresponding training function (train_regression_model, train_classification_model, or train_and_evaluate_nn) to process each mode...
def do_training(arguments): # trains models based on the arguments and model type for model in arguments['ml_model']: arguments['ml_model'] = model if get_model_type(model) == 'regression': train_regression_model(arguments) elif get_model_type(model) == 'classification': ...
def get_all_links(links , limit): ''' This function takes in a list of links and a limit on the number of links to be visited. It then calls the functions to visit the links and collect the data. :param links: A list of links to be visited. :param limit: The number of links to be visited. :retur...
The main task of the code is to initiate an application by retrieving staff information through `get_all_links`, updating a file using `add_to_UNCC`, and saving the updated data with `save_UNCC`, ensuring data collection, modification, and storage in a structured workflow.
def start(): # Starting the application # get staff information get_all_links(staff_links, len(staff_links)) # update file add_to_UNCC() # save file save_UNCC()
def modificar(self) -> block.Juego: modal = ventana.Modif() self.juego = None modal.pushButton.clicked.connect(lambda: self.definirJuego(modal) ) modal.pushButton.clicked.connect(modal.close) modal.show() modal.exec_() def mostrarPieza(self, pieza, lab...
The main task of the code is to initialize a new game by closing existing windows, creating a new UI form, setting up game parameters, handling player turn logic, connecting UI interactions (like placing pieces and menu actions), and displaying the game state. It prepares the board, links button clicks to game actions,...
def nuevaPartida(self, app): app.closeAllWindows() self.form = ventana.Principal() """ juego = block.Juego(10, 10) definirTablero(form, 10,10) juego.definirJugador("hola", "blue") juego.definirJugador("a", "yellow") juego.cambioDeTurno() """ self...
def loadSampleNames(edf_source): return ['.'.join(item.split('.')[:-1]) for item in os.listdir(edf_source) if (os.path.isfile(os.path.join(edf_source, item)) and item.split('.')[-1].lower() == 'edf')] def printDec(msg): horizontal_border = '_' * 50 vertical_border = '|' l = len...
The code extracts and saves bad epochs from EEG data for each patient. It loads patient files, identifies bad epochs using a predefined bad events file, and writes the results to text files. Each patient's bad epochs are stored in a dedicated file within the specified output directory. The process involves iterating th...
def extractBadEpochs(): # -------------------------------------------------------------------------- # Set patient folder and bad events folder # -------------------------------------------------------------------------- eeg_folder = '/ddn/gs1/group/li3/DataFromLLI/SleepData_UNC/UNC_data/All_EDFs' ...
def on_press(key, socket): try: logger.debug('alphanumeric key {} pressed'.format(key.char)) message = pickle.dumps(('press', 'normal', key.char)) socket_send(message, socket) except AttributeError: logger.debug('special key {} pressed'.format(key.name)) message = pickle....
The code sets up a ZeroMQ publisher server to broadcast keyboard event status. It listens for key presses/releases, sends periodic "keyboard pulse" messages every 5 seconds, and handles exceptions. The server runs indefinitely, using a daemon thread for keyboard input detection and serializing messages with pickle for ...
def kb_server(): global keyboard_port try: context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind('tcp://*:'+keyboard_port) listener = kb.Listener( on_press=lambda key:on_press(key, socket), on_release=lambda key:on_release(key, socket), ...
def on_move(x, y, socket): global move_time, interval if time.time() - move_time < interval: return True move_time = time.time() logger.debug('move to {}'.format((x, y))) screen_width, screen_height = pyautogui.size() message = pickle.dumps(('move', x, y, screen_width, screen_height)) ...
The code creates a server that captures mouse movements, clicks, and scrolls using pynput, broadcasts events via ZeroMQ's PUB socket on a specified port, and periodically sends "mouse pulse" messages. It runs indefinitely, handling exceptions, for real-time remote mouse activity monitoring.
def mouse_server(): global mouse_port, move_time try: context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind('tcp://*:'+mouse_port) move_time = time.time() listener = mouse.Listener( on_move=lambda x,y:on_move(x,y,socket), on_click=la...
def firstwalk(v, distance=1.): if len(v.children) == 0: if v.lmost_sibling: v.x = v.lbrother().x + distance else: v.x = 0. else: default_ancestor = v.children[0] for w in v.children: firstwalk(w) default_ancestor = apportion(w, defa...
The code computes the horizontal coordinates for a tree layout using a three-step algorithm. First, it performs an initial traversal (firstwalk) to set preliminary positions. Then, it calculates the minimum offset (second_walk) to determine necessary adjustments. If the minimum is negative, it shifts nodes to prevent o...
def buchheim(tree): dt = firstwalk(DrawTree(tree)) min = second_walk(dt) if min < 0: third_walk(dt, -min) return dt
def _make_tree(self, node_id, et): # traverses _tree.Tree recursively, builds intermediate # "_reingold_tilford.Tree" object name = self.node_to_str(et, node_id, criterion='entropy') if (et.children_left[node_id] != et.children_right[node_id]): children = [self._make_tree(et....
This code visualizes a decision tree using matplotlib by applying the Buchheim layout algorithm to position nodes, rendering the tree structure recursively, adjusting plot limits based on annotations, and dynamically scaling font sizes to prevent text overlap while maintaining clarity.
def export(self, decision_tree, ax=None): import matplotlib.pyplot as plt from matplotlib.text import Annotation if ax is None: ax = plt.gca() ax.set_axis_off() my_tree = self._make_tree(0, decision_tree.tree_) dt = buchheim(my_tree) self._scalex = 1 ...
def broadcast(msg): try: message = msg.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER - len(send_length)) if msg[0] == "@": pass for client in CLIENTS: try: cl...
This function manages a votekick process by waiting for a specified delay, then checking if a subject received more than half the online clients' votes. If so, it broadcasts the result, kicks the subject, and sends a notification. If not, it announces the failure. It resets voting state variables and increments a vote ...
def votekick_timer(delay, initiator, Subject): global VOTES global VOTE_IN_PROGRESS global VOTE_ID VOTES = 0 time.sleep(delay) broadcast("#Votekick Over") broadcast(f"#{Subject} got {VOTES} votes against them") if VOTES > client_count() / 2: broadcast(f"#{VOTES} is greater than h...
def write(self, data: str): write_traceback(data) def raw_input(self, prompt: Any = '') -> str: if not isinstance(prompt, str): prompt = prompt.decode() if callable(getattr(prompt, 'decode', None)) else str(prompt) if self._auto_line: return self._auto_line.pop(0) ...
This code implements an interactive shell loop, displaying a customizable banner with version info, handling user input, and managing exceptions like KeyboardInterrupt and EOFError by raising appropriate errors with customizable exit messages.
def interact(self, banner=None, exitmsg=None): copyright_ = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: if 'py' not in self.__class__.__name__.casefold(): self.__class__.__name__ += ' Python' name_len = len(self.__cl...
def get_neighbors(self, node): ''' Get neighbors of a node with 8 connectivity ''' row = node.row col = node.col neighbors = [] # All the 8 neighbors for i in range(-1, 2): for j in range(-1, 2): # Check range if row + i < 0 or ...
The code detects new dynamic obstacles in the neighbors of a given node. If a neighbor is newly identified as a dynamic obstacle (is_dy_obs=True but is_obs=False), it updates the neighbor's status to an obstacle and adjusts the cost matrix using self.modify_cost. It also handles closed nodes by inserting them with infi...
def prepare_repair(self, node): ''' Sense the neighbors of the given node If any of the neighbor node is a dynamic obstacle the cost from the adjacent node to the dynamic obstacle node should be modified ''' #### TODO #### # Sense the neighbors to see if they are ...
def insert(self, node, new_h): ''' Insert node in the open list arguments: node - Node to be added new_h - The new path cost to the goal Update the k value of the node based on its tag Append the node t othe open_list ''' # Update k if node.tag =...
The main task of the code is to execute the D* algorithm for pathfinding. It first performs an initial search from the goal to the start node on a static grid, then dynamically replans the path when grid changes are detected. The algorithm iteratively checks for required repairs, updates costs, and visualizes the evolv...
def run(self): ''' Run D* algorithm Perform the first search from goal to start given the pre-known grid Check from start to goal to see if any change happens in the grid, modify the cost and replan in the new map ''' #### TODO #### # Search from goal...
def _init_atoms(self): """Generate all atoms and set certain featues accordingly""" # self.expression2meaning = dict() self.output_type2expression2meaning = dict( (output_type, dict()) for output_type in [bool, int, float, set] ) output_type2atoms = { int:...
The code generates all unique meaning sentences by recursively combining atoms and operators up to a specified maximum expression length. It builds expressions of increasing lengths (from 1 to max_expression_length) using unary and binary operators, ensuring uniqueness via the _ignore_or_add method. The result is a lis...
def generate_all_sentences(self, max_expression_length): """Generates all unique meaning sentences up go self.max_quantifier_length and self.max_model_size :returns: List with all unique sentences """ self._init_atoms() self.length2type2expressions = defaultdict(lambda: d...
def bossLevel(): global currLevel currLevel += 1 up, down, right, left = False, False, False, False if randint(0, 1): bossX = SCREEN_WIDTH//4 - 32 else: bossX = SCREEN_WIDTH - SCREEN_WIDTH//4 - 32 bossY = SCREEN_HEIGHT//2 - 32 boss = Boss(bossX, bossY) level_disp = pyg...
The function `nextLevel()` determines the next level based on the current level (`currLevel`). If `(currLevel + 1)` is divisible by 10, it returns `bossLevel()`. If divisible by 5 (but not 10), it returns `timeLevel()`. Otherwise, it returns `normalLevel()`, handling level progression with conditional logic.
def nextLevel(): if (currLevel + 1) % 10 == 0: return bossLevel() elif (currLevel + 1) % 5 == 0: return timeLevel() else: return normalLevel()
def nextLevel(): if (currLevel + 1) % 10 == 0: return bossLevel() elif (currLevel + 1) % 5 == 0: return timeLevel() else: return normalLevel() def goNextLevel(): ladder_exit = pygame.Rect(SCREEN_WIDTH//2 - 32, SCREEN_HEIGHT // 2 + 100, ladder_pic.get...
This code creates a game entry screen with "PLAY" and "CONTROLS" buttons. It handles mouse clicks to start gameplay, trigger controls info, or exit. When "PLAY" is selected, it runs game levels, processes results (continue, death, exit), and resets game states. The screen updates continuously at 60 FPS, displaying butt...
def entryScreen(): play_button = pygame.Rect(250, 106, 500, 150) controls_button = pygame.Rect(250, 306, 500, 150) running = True while running: screen.fill(BG_COLOUR) screen.fill(BLACK, play_button) text = myfont.render("PLAY", True, WHITE) disp_coords = (play_button.ce...
def discover(): raw_schemas = load_schemas() streams = [] for schema_name, schema in raw_schemas.items(): # create and add catalog entry catalog_entry = { 'stream': schema_name, 'tap_stream_id': schema_name, 'schema': schema, # TODO Events may...
The main task of the code is to handle command-line argument parsing, discover or load a catalog, configure context variables, initialize a Prometheus client, and execute data synchronization. If the 'discover' flag is set, it outputs the discovered catalog in JSON format. Otherwise, it sets up synchronization paramete...
def main(): # Parse command line arguments args = utils.parse_args(REQUIRED_CONFIG_KEYS) # If discover flag was passed, run discovery mode and dump output to stdout if args.discover: catalog = discover() print(json.dumps(catalog, indent=2)) else: Context.tap_start = utils.n...
def factorise(n): allfactors = [] for f in factorcache: if n % f == 0: n //= f allfactors.append(f) while n > 1: factors, n = call_yafu(n) allfactors.extend(factors) return sorted(allfactors) def product(ns): return functools.reduce(lambda a,b: a*b, ns...
This code proves primality of a number `p` using a combination of factorization and witness testing. It factors `p-1`, selects suitable primes, and verifies a witness `w` such that `w^(p-1) ≡ 1 mod p` and `w^((p-1)/q) ≡ 1 mod p` fails for all prime factors `q` of `p-1`, confirming `p` is prime via the Miller-Rabin test...
def proveprime(p, name=None): if p >> 32 == 0: smallprimes.add(p) return "{:d}".format(p) if name is None: name = next(names) print("{} = {:d}".format(name, p)) fs = factorise(p-1) fs.reverse() prod = product(fs) qs = [] for q in fs: newprod = prod // q ...
def get_possible_moves(self): moves = [] for r in range(len(self.board)): for c in range(len(self.board[r])): turn = self.board[r][c] if (turn[0] == 'w' and self.white_to_move) or (turn[0] == 'b' and not self.white_to_move): piece = turn[1]...
This function filters out invalid chess moves that result in the player's king being in check, determines if checkmate or stalemate conditions are met, and returns the list of valid moves. It iterates through possible moves, simulates each, checks for check status, and removes invalid moves. If no valid moves remain, i...
def get_valid_moves(self): moves = self.get_possible_moves() for i in range(len(moves)-1, -1, -1): self.make_move(moves[i]) self.white_to_move = not self.white_to_move if self.in_check(): moves.remove(moves[i]) self.white_to_move = not self...
def _open(self): self._logger.info("Opening device...") vendor_id = 0x04D9 product_id = 0xA052 self._device = hid.device() try: self._device.open(vendor_id, product_id) self._device.send_feature_report( [0x00, 0x00] ) # Don't u...
The code defines a worker thread that continuously runs a loop to open a connection, read data, and handle errors. It repeatedly attempts to read data until a stop event is triggered, logging errors and retrying after delays. Upon stopping, it exits gracefully.
def _worker_thread(self): while not self._stop_event.is_set(): try: self._open() while not self._stop_event.is_set(): self._read_loop() except ReadError as e: self._logger.error(e) time.sleep(3.0) ...
def flat(pool): if isinstance(pool, str): return [pool] res = [] for v in pool: if isinstance(v, str): res.append(v) else: res += flat(v) return res def read_timevector(self, function_name: str) -> np.ndarray: num_entries = int(self.hdf.attributes(...
This function converts function data from a FenicsStorage object into XDMF files for each subname, handling multiple time steps. It creates XDMF files, reads time vectors and function checkpoints, writes data to files incrementally, and ensures proper closure of files. The task involves exporting simulation data in a f...
def to_xdmf(self, funcname: str, subnames: Union[str, List[str]], directory=None): """FIXME: Rewrite as external function taking in a FenicsStorage object.""" if directory is None: directory = self.filepath.parent else: directory = Path(directory) directory.mk...
def get_fav_symbols(self): # Fetch the list of S&P 500 companies' symbols and names fav = ['spy','qqq','iwm','dia','cost','baba','aapl','wmt','msft','aapl','tsla','tlt','tgt','jpm','abnb','intc','riot','mara','coin','fivn','bac', 'dis','pfe','ai','pltr','googl','meta','nvda', 'dis','amc','...
The code scans financial symbols (either from a favorites list or S&P 500) for buy/sell signals. It iterates through each symbol, checks for trading signals using `scan()`, collects symbols with buy/sell signals into separate lists, handles errors during data fetching, and returns the lists of symbols with detected sig...
def scan_symbols(self,list='fav'): print("scanning ....") buy=[] sell=[] if list == 'fav': symbols = self.get_fav_symbols(); else: symbols = self.get_sp500_symbols(); for symbol in symbols: try: buy...
def find_generating_set(p, q): j = find_j(q) # Search for solutions to a_0^2 + a_1^2 + a_2^2 + a_3^2 = p # There are 8(p + 1) of them, restrict parity and signs to only get p + 1 s = [] for a0 in range(1, p, 2): acc0 = a0 * a0 if acc0 > p: break for a1 in range(0,...
The main task of the code is to generate a graph representation from input data by reading matrix tuples from a file, computing canonical forms of matrix products modulo q, and writing adjacency lists along with generating sets and inverse elements to an output file. It constructs a graph structure using group-theoreti...
def write_graph(p, q, pgl_file, filename): getNum = dict() pgl = [] fin = open(pgl_file, "r") for i in range(q * (q ** 2 - 1)): line = fin.readline() a = tuple(map(int, line.split())) getNum[a] = len(pgl) pgl.append(np.array(a).reshape((2, 2))) psl = list(map(int, fin...
def data_supplier(subject_uri): supply_list = [] if 'http://dbpedia.org/resource/' in subject_uri: supply_list = add_category_from_dbpeida(subject_uri) #elif 'http://dbpedia.org/class/yago/' in subject_uri: # supply_list = add_class_from_dbpedia(subject_uri) else: pass r...
The code parses an RDF file (in NT format) to extract objects, processes each object into a structured dictionary containing its original form, a compact version, and associated categories, then returns a list of these processed objects.
def form_object_doc_list(filepath): g = rdflib.Graph() g.load(filepath, format='nt') object_doc_list = [] for obj in g.objects(): object_dictionary = {'real':'', 'processed':'', 'categories':[]} object_dictionary['categories'] = data_supplier(str(obj)) obj = object_extract(obj...
def check_if_name_exists_in_container(self,object_name: str, object_parent: str,object_type: Object_Type): match object_type: case Object_Type.CLOUD: return False if object_name in [cloud.name for cloud in self.list_of_clouds] else True case Object_Type.H...
This code migrates selected objects (host, VM, or process) between locations in a cloud environment. It retrieves the object from its source, updates its parent reference to the destination, and ensures name uniqueness for hosts. The migration involves splitting paths, locating destination entities, removing the object...
def migrate_callback(self): if len(self.migrate_object_destination_combobox.currentText()) == 0: return if len(self.migrate_object_name_combobox.currentText()) == 0: return if len(self.migrate_object_type_combobox.currentText()) == 0: return i...
def read_settings_file(self, settings_file_name=None): settings_file_name = self.specified_or_default_settings_file(settings_file_name) if not os.path.exists(settings_file_name): self.error_and_exit(400, 'Cannot open the settings file (%s).\nPlease run pcs_configure.py to create a file, or s...
The main task of the code is to gather and validate application settings by prioritizing command-line arguments over a configuration file, normalize API URLs, handle the 'ca_bundle' boolean flag, and ensure required parameters (username, password, and at least one API endpoint) are present before returning a validated ...
def get_settings(self, args): settings = {} # Verify that there are enough command-line settings to continue, otherwise read the settings file. if (args.username is None or args.password is None) or (args.api == '' and args.api_compute == ''): settings = self.read_settings_file(args....
def read_settings_file(self, settings_file_name=None): settings_file_name = self.specified_or_default_settings_file(settings_file_name) if not os.path.exists(settings_file_name): self.error_and_exit(400, 'Cannot open the settings file (%s).\nPlease run pcs_configure.py to create a file, or s...
The main task of the code is to configure and manage CSPM (Cloud Security Platform Manager) settings by either displaying the current configuration from a file or saving new credentials (access key, secret key, API URL) to a specified configuration file, while handling user input validation and providing guidance for c...
def configure(self, args): print('Configuration File Name:') if args.config_file is None: print(self.DEFAULT_CONFIG_FILE) else: print(args.config_file) print() if args.username is None and args.password is None: settings = self.read_settings_fi...
def login_compute(self): if self.api: # Login via CSPM. self.login() elif self.api_compute: # Login via CWP. self.login('https://%s/api/v1/authenticate' % self.api_compute) else: self.error_and_exit(418, "Specify a Prisma Cloud API/UI B...
The function `execute_compute` performs authenticated API requests to a compute endpoint, handling pagination by querying in batches (up to 50 items per page) and accumulating results. It manages token authentication (CSPM/CWP), retries failed requests, processes responses, and returns aggregated data or errors, with o...
def execute_compute(self, action, endpoint, query_params=None, body_params=None, force=False, paginated=False): self.suppress_warnings_when_ca_bundle_false() if not self.token: self.login_compute() # Endpoints that return large numbers of results use a 'Total-Count' response header. ...
def initKeypad(): readKeypadInputThread = Thread(target = _readKeypadInput) readKeypadInputThread.start() def waitAndGetKeypadInputWithAudioPrompt(promptAudioName): userInput = '' while True: print(stringHelper.AUDIO + ' ' + audioOutput.audioTextDict[promptAudioName]) audioOutput.playAud...
The main task of the code is to test a system's keypad and audio functionalities by initializing components, playing a welcome message, capturing user input for a destination node ID, and terminating threads. It verifies the integration of audio prompts, keypad input handling, and resource cleanup in a test environment...
def _test(): initKeypad() audioOutput.initAudio() print(stringHelper.AUDIO + ' Welcome to IRIS.') audioOutput.playAudio('welcomeToIris') sleep(1) destNodeId = waitAndGetKeypadInputWithAudioPrompt( 'plsKeyInDestinationNodeIdFollowedByTheHashKey') print(stringHelper.INFO + ' ...
def superReader(nodeID,sensorID): if sensorID == "BME280": floatSum = 4 elif sensorID == "BME680": floatSum = 4 elif sensorID == "GPSGPGGA2": floatSum = 9 elif sensorID == "WIMDA": floatSum = 12 elif sensorID == "YXXDR": floatSum = 4 ...
The main task of the code is to preprocess and merge climate and sensor data for a specific node. It reads multiple datasets (GPS, climate sensor, WIMDA, YXXDR), combines them, crops the data spatially using GPS coordinates, removes GPS columns, and filters by a start date. The processed data is saved as pickle files f...
def climateDataPrep(nodeData,nodeID,climateSensor,WIMDA,YXXDR,mergedPklsFolder): dataCropDate = datetime.datetime.strptime(nodeData['climateSensorBegin'], '%Y-%m-%d') print("Reading Data for Node: " + nodeID) GPSGPGGA2 = superReader(nodeID,"GPSGPGGA2") climateSensor = superReader(nodeID,climate...
def getState(self,timeIn): # print("GET STATE") return (timeIn.second >= 45 or timeIn.second < 15); def changeState(self): # print("CHANGE STATE") if self.getValidity(): # print("IS VALID") self.getAverageAll() self.getTime() self.doCSV() ...
The main task of the code is to update the PM (Process Manager) state. It checks if the current state of `ctNowPM` differs from `zeroState`; if so, it triggers a state change via `changeState()`. Subsequently, it executes `currentUpdatePM()` to perform the update process, ensuring the PM's state remains consistent and ...
def pmUpdater(self): # print("PM UPDATER") if(self.getState(self.ctNowPM)!=self.zeroState): self.changeState() self.currentUpdatePM() return;
def getState(self,timeIn): # print("GET STATE") return (timeIn.second >= 45 or timeIn.second < 15); def changeState(self): # print("CHANGE STATE") if self.getValidity(): # print("IS VALID") self.getAverageAll() self.getTime() self.doCSV() ...
The code updates the climate state by checking if the current climate state (`ctNowClimate`) differs from a reference state (`zeroState`). If so, it triggers a state change via `changeState()`, then executes `currentUpdateClimate()` to apply the update. The function ensures climate state consistency and initiates neces...
def climateUpdater(self): # print("CLIMATE UPDATER") if(self.getState(self.ctNowClimate)!=self.zeroState): self.changeState() self.currentUpdateClimate() return;
def getState(self,timeIn): # print("GET STATE") return (timeIn.second >= 45 or timeIn.second < 15); def changeState(self): # print("CHANGE STATE") if self.getValidity(): # print("IS VALID") self.getAverageAll() self.getTime() self.doCSV() ...
The code's main task is to update the GPS state by checking if the current GPS state differs from a zero state, triggering a state change if needed, then executing a GPS update operation. It ensures the system's GPS state is current and applies necessary updates.
def gpsUpdater(self): # print("GPS UPDATER") if(self.getState(self.ctNowGPS)!=self.zeroState): self.changeState() self.currentUpdateGPS() return;
def pmUpdater(self): # print("PM UPDATER") if(self.getState(self.ctNowPM)!=self.zeroState): self.changeState() self.currentUpdatePM() return; def climateUpdater(self): # print("CLIMATE UPDATER") if(self.getState(self.ctNowClimate)!=self.zeroState): ...
The code reads latest sensor data (PM, climate, GPS) from MQTT via JSON, parses timestamps, checks for newer data compared to stored times, and triggers update methods if so. It handles three sensor types with error logging for failed reads.
def nodeReader(self): try: self.dataInPM = mL.readJSONLatestAllMQTT(self.nodeID,self.pmSensor)[0] self.ctNowPM = datetime.strptime(self.dataInPM['dateTime'],'%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=tz.tzutc()).astimezone(tz.gettz()) if (self.ctNowPM>self.lastPMDate...
def distanceFromBottom(board, column): d = 0 for i in range(5, -1, -1): if board[i][column] != '-': d += 1 else: break return d def isWin(board, x, y, player): directionPairs = [(1,0),(0,1),(1,1),(-1,1)] for dx,dy in directionPairs: firstDirection = 0 ...
The function determines the optimal column for an AI to place its 'X' piece in a Connect 4-like game. It prioritizes immediate winning moves for 'X', then blocks opponent ('O') wins, and uses recursive evaluation with limited iterations to select the best move based on future game states, returning the column index wit...
def pickAiSpot(board, iterations): for column in range(7): r,c = 5 - distanceFromBottom(board, column),column if board[r][c] == '-' and isWin(board, c, r, 'X'): return column for column in range(7): r,c = 5 - distanceFromBottom(board,column),column if board[r][c] == '...
def distanceFromBottom(board, column): d = 0 for i in range(5, -1, -1): if board[i][column] != '-': d += 1 else: break return d def isWin(board, x, y, player): directionPairs = [(1,0),(0,1),(1,1),(-1,1)] for dx,dy in directionPairs: firstDirection = 0 ...
The function determines the best column for the AI to play in a Connect Four-like game by prioritizing immediate winning moves, avoiding opponent wins, and recursively evaluating future moves to select the optimal strategy.
def pickAiSpot(board, iterations): for column in range(7): r,c = 5 - distanceFromBottom(board, column),column if board[r][c] == '-' and isWin(board, c, r, 'X'): return column for column in range(7): r,c = 5 - distanceFromBottom(board,column),column if board[r][c] == '...
def printBoard(board): for i in range(7): print(i,end=' ') print() for row in board: for i in row: print(i,end=' ') print() def distanceFromBottom(board, column): d = 0 for i in range(5, -1, -1): if board[i][column] != '-': d += 1 else:...
The main task of the code is to implement a Connect Four game where a human player and an AI alternate turns placing 'O' and 'X' tokens on a 6x7 grid. The game checks for a winning condition after each move, updates the board, and declares the winner once a player achieves four consecutive tokens in a row, column, or d...
def main(): board = [['-' for i in range(7)] for j in range(6)] winner = None while winner == None: printBoard(board) print('> ',end="") i = input() column = int(i[0]) r,c = 5 - distanceFromBottom(board, column),column if isWin(board,c,r,'O'): winn...
def _create_attribute_dict(params, dict_object, mapping_object=None): if mapping_object is not None: result = {k: _get_attribute_mapping(params.get(v), mapping_object) for k, v in dict_object.items()} else: result = {k: params.get(v) for k, v in dict_object.items()} return result def _get_ke...
This function constructs a dictionary representing a Global Secondary Index configuration for AWS DynamoDB based on the specified action (create, update, delete). It extracts parameters like index name, provisioned throughput, key schema, and projection, organizing them into the appropriate structure for DynamoDB opera...
def _get_global_secondary_index_attribute(params, action): if action == 'delete': delete = {'IndexName': params.get('indexName')} return {'Delete': delete} elif action == 'update': update = {'IndexName': params.get('indexName'), 'ProvisionedThroughput': _create_attribut...
def _get_attribute_definition(params): attrib_definition = {} if params.get('sortKey'): attrib_definition['AttributeDefinitions'] = [(_create_attribute_dict(params, item, DATA_TYPE_MAPPING)) for item in ATTRIBUTE_DEFINITIONS] else: attrib_...
The function constructs a payload dictionary for creating a table by aggregating parameters from the input. It initializes the payload with the table name, then incorporates attribute definitions, key schema, and billing mode settings from helper functions, ensuring all necessary configurations are included for table c...
def build_create_table_payload(params): payload = {'TableName': params.get('TableName')} payload.update(_get_attribute_definition(params)) payload.update(_get_key_schema(params)) payload.update(_get_billing_mode_attribute(params)) return payload
def _get_billing_mode_attribute(params): billing_mode = {} if params.get('billingMode') == 'Provisioned': billing_mode['BillingMode'] = _get_attribute_mapping(params.get('billingMode'), BILL_MODE_MAPPING) billing_mode['ProvisionedThroughput'] = _create_attribute_dict(params, PROVISIONED_THROUGHP...
The function constructs a payload dictionary for updating an AWS DynamoDB table based on the specified operation. It initializes the payload with the table name and conditionally adds attributes like billing mode, streams, or global secondary index updates by calling helper functions, depending on the 'updateOperation'...
def build_update_table_payload(params): payload = {'TableName': params.get('TableName')} if params.get('updateOperation') == 'Modify Provisioned Throughput': payload.update(_get_billing_mode_attribute(params)) elif params.get('updateOperation') == 'Enable or Disable DynamoDB Streams': payl...
def create_index(): indexDir = input("Index name: ") indexDir += '/' if os.path.exists(indexDir): print("Index in this folder already exists") return else: os.mkdir(indexDir) path = File(indexDir).toPath() indexDir = NIOFSDirectory(path) writerConfig = IndexWriterConf...
The code's main task is to create a Lucene index, allow user-driven searches with basic or advanced query options (including frequency-based statistics), and display results either by relevance score or frequency statistics. It handles index creation, searcher initialization, unit tests, and interactive query processin...
def main(): lucene.initVM() option = str(input("Create new index? y/n")).lower() index_dir = '' if option == "y": print("Creating index...") index_dir = create_index() print("Index has been created") search = str(input("Search? y/n ")).lower() if search == "y": if...
def is_game_over(): """ Determines if the game is over by checking if there are any valid moves left. :return: A boolean value indicating whether the game is over. """ game_status = get_game_status() return game_status == GAME_LOST or game_status == GAME_WON def add_2_or_4(): """ Add...
The function processes a game move by checking if the game is over, adding a new tile (2 or 4) if active, determining win/loss status, and updating the board display with the current state, score, and last move. It handles game state transitions, result evaluation, and visual refresh for a tile-merging game like 2048.
def process_game(last_move): """ Process the game state based on the last move made by the player. Checks if the game is over, updates the game state by adding a new number (2 or 4) to the board, determines the game result (won, lost, or no more moves), and updates the game board display. :param...
def load_S4_parameters(file_path): ''' Load S4 simulation parameters from S4_parameters.json file in main directory of code repository. Without this file, code will not run. Allows user to give the lua strings and values of all simulation constants, lua strings, guesses, and error bounds of simulati...
The function S4_args loads grating-specific simulation parameters from a JSON file, processes measured data from provided file paths, categorizes parameters into constants or variables based on measurement results, and prepares them for simulation. It handles error bounds, precision, and checks for 4-layer parameters, ...
def S4_args(parameters_path, file_paths, batch_name, grating_name): ''' Pull grating specific simulation arguments, constants and variables for a specific grating. Args: parameters_path: <string> path to parameters info json file_paths: <dict> file pat...
def ip(self, ip): alerts = [] result = self.otx.get_indicator_details_by_section(IndicatorTypes.IPv4, ip, 'general') validation = self.getValue(result, ['validation']) if not validation: pulses = self.getValue(result, ['pulse_info', 'pulses']) if pulses: ...
The code processes a query `q` by determining its type (IP, domain, URL, hash, or phrase) using regex checks, generates alerts via corresponding methods, inserts results into a PostgreSQL database with metadata, and logs completion.
def ask(self, q, askedBy, postgre_service): if re.search("^(\d{1,3}\.){0,3}\d{0,10}$", q): alerts = self.ip(q) query_type = "ip" elif re.search("^([A-Za-z0-9-]+)(\.[A-Za-z]+)+$", q): alerts = self.hostname(q) query_type = "domain" ...
def load(self, model_dir, depth, label_padding_index=None, *args): """ Loading model parameters """ fname = self.model_fname + "-depth=%d" % (depth) file_path = os.path.join(model_dir, fname+"_params.pkl") self.net.load_state_dict(torch.load(file_path)) ...
The main task of the code is to load a pre-trained model, prepare a dataset with specified normalization and feature/label parameters, and generate document embeddings using the model's depth node. It loads the model from `model_dir`, creates a test dataset from `data_dir` with `ts_feat_fname` features, processes data ...
def get_document(self, data_dir, model_dir, dataset, data=None, ts_feat_fname='tst_X_Xf.txt', batch_size=256, num_workers=6, keep_invalid=False, if_labels=False, feature_indices=None, label_indices=None, normalize_features=True, normali...
def _prep_dl(self, d, dataset, mode='test'): """ Creates dataloader for a given dataset Argument: ---------- d: int 0: module 1 and 2 1: module 4 dataset: Class object dataset mode: str ...
This function prepares a dataset (train/val/test) based on the specified depth. It handles module-specific data processing, predicts using lower-depth models if depth > 0, retrieves clustering information from the neural network, modifies the dataset structure for the given depth, and builds a shortlist of relevant dat...
def _prep_ds(self, depth, dataset): """ builds dataset [train|val|test] based on depth Arguments ---------- depth: int 0: module 1 and 2 1: module 4 dataset: Class object Returns ...
def _prep_ds(self, depth, dataset): """ builds dataset [train|val|test] based on depth Arguments ---------- depth: int 0: module 1 and 2 1: module 4 dataset: Class object Returns ...
The code predicts the most relevant items for each document in the input dataset using a neural network model. It iterates through each depth of the network, prepares the dataset and model configuration, loads pre-trained weights from the specified directory, and generates predictions. The final output is a compressed ...
def _predict(self, dataset, model_dir, **kwargs): """ Predicts most relevant items for each document in the dataset Arguments ---------- dataset: Class Object model_dir: string Model directory Returns: ...
def _prep_for_depth(self, depth, train_ds, valid_ds): """ Creates dataloader for train module 2 as well as module 4 and uses model 3 to initliaze module 2 and 4 Arguments ---------- depth: int 0: for module 2 ...
This function trains modules 1, 2, and 4 of a model using specified datasets, handling pre-trained models, adjusting learning rates, tracking training loss, and validating periodically. It prepares data loaders, trains for a set number of epochs, saves models, and performs validation based on depth and dataset size, en...
def _train_depth(self, train_ds, valid_ds, model_dir, depth, validate_after=5): """ training function for module 1,2, and 4 Arguments ---------- train_ds: Class object training dataset valid_ds: Class object ...
def _create_dataset(self, data_dir, fname_features, fname_labels=None, data=None, mode='predict', normalize_features=True, normalize_labels=False, feature_type="sparse", keep_invalid=False, feature_indices=None, label_indice...
The main task of the code is to perform prediction on a test dataset using a pre-trained model. It loads features and labels from specified files, prepares the dataset with normalization and parameters, runs the prediction via the model, and returns the predicted labels as a sparse matrix containing top-k elements per ...
def predict(self, data_dir, model_dir, dataset, data=None, ts_feat_fname='tst_X_Xf.txt', ts_label_fname='tst_X_Y.txt', batch_size=256, num_workers=6, keep_invalid=False, feature_indices=None, label_indices=None, normalize_features=True, normalize_labels=Fa...
def doubleAgentSet(self): global blueAgenNum self.doubleAgent = random.randint(0,1) if self.doubleAgent == 0: self.blueAgentNum = 9 self.redAgentNum = 8 return self.blueAgentNum, self.redAgentNum if self.doubleAgent == 1: self.blueAgentNum = 8 self.redAgentNum = 9 ret...
The code determines the initial game layout by checking the presence of a double agent. If no double agent exists (`self.doubleAgent == 0`), it sets up the blue team's turn layout. Otherwise, it initializes the red team's turn layout. The method orchestrates the game's starting configuration based on the double agent s...
def firstPick(self): self.doubleAgentSet() if self.doubleAgent == 0: self.turnLayoutBlueFirst() else: self.turnLayoutRedFirst()
def get_assignment(self, name): """Find the assignment id from its name, and get the assignment object from Quercus.""" assignment = self.find_assignments(name) return self.course.get_assignment(assignment.index.values[0]) def get_user(self, mid=None, name=None): """Find the use...
The code downloads a student's submission for a given assignment, handling group/user data, checking for existing submissions, and saving attachments if present. It returns the submission's identity and metadata, while avoiding duplicates via an ignore list. The function also prints debug info and processes submissions...
def download_submission( self, assignment_name, user_id, ignore_list=None, parent_directory="submission" ): """Download a single submission. Args: assignment_name : The assignment name user_id : The user id to download from Options ignore_list : A l...
def get_assignment(self, name): """Find the assignment id from its name, and get the assignment object from Quercus.""" assignment = self.find_assignments(name) return self.course.get_assignment(assignment.index.values[0]) def match_user(self, search, submission): found = False ...
This function downloads all submissions for a specified assignment, optionally filtered by a user ID or name. It retrieves submission data, checks for user matches, and collects submission details into a dictionary, returning the gathered information.
def download_submissions(self, name, user_id=None): """Downloads all submissions to this assignment. Args: name : The assignment name. user_id : user id or name to filter for. Side effect : Downloaded files. """ # Get the assigment object ...
def getO2(self): if self.o2 != "": return self.o2 o2candidates = self.lines.copy() for pos in range(0, self.bitLen): counts, lines = getCounts(o2candidates) check = "1" if lines - counts[pos] <= counts[pos] else "0" temp = [] for candidate in o2candidates: if check ==...
The code prints a formatted table displaying binary and integer representations of O2 and CO2 values, alongside the Life Support Rating (LSR). It retrieves these values using class methods, then outputs them with aligned columns for clarity, showing binary strings and their decimal equivalents.
def print(self): o2 = self.getO2() co2 = self.getCO2() lifeSupportRating = self.getLifeSupportRating() print(" ", "bin".ljust(len(o2), " "), " ", "int") print("O2 ", o2, " ", str(int(o2, 2))) print("CO2 ", co2, " ", str(int(co2, 2))) print("LSR ", "".ljust(len(o2), " "), " ", lif...
def submitFSquery(url,INparams): """ This function will send a spatial query to a web feature service and convert the results into a python structure. If the results from the service is an error due to an invalid token then a second attempt will be sent with using a newly generated arcgis t...
This function retrieves CLU geometry and attributes from a WFS service using an SQL query, inserts them into a feature class with formatted date fields, and handles errors. It sends a request to a REST endpoint, processes returned features, and uses an InsertCursor to populate the feature class with geometry and attrib...
def getCLUgeometryByTractQuery(sqlQuery,fc,RESTurl): """ This funciton will will retrieve CLU geometry from the CLU WFS and assemble into the CLU fc along with the attributes associated with it. It is intended to receive requests that will return records that are below the WFS record limit""...
def submitFSquery(url,INparams): """ This function will send a spatial query to a web feature service and convert the results into a python structure. If the results from the service is an error due to an invalid token then a second attempt will be sent with using a newly generated arcgis t...
The function splits an input feature class (FC) into smaller polygons if its CLU count exceeds a WFS limit. It repeatedly subdivides the FC using the subdivide polygon tool until each split's CLU count is under the limit. Each valid split generates a JSON extent and CLU count, stored in a dictionary. If splits fail or ...
def createListOfJSONextents(inFC,RESTurl): """ This function will deconstruct the input FC into JSON format and determine if the clu count within this extent exceeds the max record limit of the WFS. If the clu count exceeds the WFS limit then the incoming FC will continously be split until ...
def submitFSquery(url,INparams): """ This function will send a spatial query to a web feature service and convert the results into a python structure. If the results from the service is an error due to an invalid token then a second attempt will be sent with using a newly generated arcgis t...
This function splits an input feature class (FC) into smaller JSON extents to ensure each WFS request adheres to a maximum record limit. It checks the initial CLU count; if exceeding the limit, it recursively splits the FC using a fishnet and intersection, generating individual requests. Each split's JSON extent and CL...
def createListOfJSONextents_ArcMap(inFC,RESTurl): """ This function will deconstruct the input FC into JSON format and determine if the clu count within this extent exceeds the max record limit of the WFS. If the clu count exceeds the WFS limit then the incoming FC will continously be split ...
def AddMsgAndPrint(msg, severity=0): # prints message to screen if run as a python script # Adds tool message to the geoprocessor # #Split the message on \n first, so that if it's multiple lines, a GPMessage will be added for each line try: print(msg) #for string in msg.split('\n'):...
The code retrieves Common Land Units (CLU) data from a USDA-NRCS GeoPortal REST service based on administrative state, county, and tract number. It projects the queried CLU features to a user-defined or map-derived spatial reference, creates a feature class, and optionally adds the result to ArcGIS Pro or ArcMap. The m...
def start(state,county,trctNmbr,outSR,outWS,addCLUtoSoftware=False): try: # Use most of the cores on the machine where ever possible arcpy.env.parallelProcessingFactor = "75%" global bArcGISPro global adminState, adminCounty, tnum, outSpatialRef, outputWS global bUserDefine...
def produceSplits(current_node: TreeNode, minleaf: int, nfeat: int) -> List[Split]: """ Function that indentifies all possible splits randomly choosen nfeat attributes of a tree node. :param current_node: the tree node for which the splits are being calculated. :param minleaf: an integer that indicates ...
This function constructs a binary classification tree by recursively splitting nodes based on impurity. It starts with a root node, iteratively processes nodes, and applies splits if conditions (minimum observations, impurity) are met. Splits are generated using a subset of features, and the best split is selected to c...
def tree_grow(x: np.array, y: np.array, nmin: int, minleaf: int, nfeat: int)-> TreeNode: """ Function that creates a binary classification tree. :param x: a 2D numpy array that contains the instances of the data. :param y: a 1D numpy array that contains the true labels of the data. :param nmin: an i...
def produceSplits(current_node: TreeNode, minleaf: int, nfeat: int) -> List[Split]: """ Function that indentifies all possible splits randomly choosen nfeat attributes of a tree node. :param current_node: the tree node for which the splits are being calculated. :param minleaf: an integer that indicates ...
This function builds a binary classification tree with a limit on the number of splits. It uses breadth-first traversal to split nodes based on impurity, ensuring each split meets minimum observation requirements (nmin, minleaf) and feature constraints (nfeat). The process stops when the specified split limit is reache...
def tree_grow_limited(x: np.array, y: np.array, nmin: int, minleaf: int, nfeat: int, limit: int)-> TreeNode: """ Function that creates a binary classification tree. :param x: a 2D numpy array that contains the instances of the data. :param y: a 1D numpy array that contains the true labels of the data. ...
def produceSplits(current_node: TreeNode, minleaf: int, nfeat: int) -> List[Split]: """ Function that indentifies all possible splits randomly choosen nfeat attributes of a tree node. :param current_node: the tree node for which the splits are being calculated. :param minleaf: an integer that indicates ...
The function grows m decision trees using bootstrap sampling from input data (x, y). Each tree is built by recursively splitting nodes based on random subsets of features (nfeat), stopping when nodes have insufficient observations (nmin, minleaf). It returns a list of tree roots, where each tree is grown via impurity-b...
def tree_grow_b(x: np.array, y: np.array, nmin: int, minleaf: int, nfeat: int, m: int)-> List[TreeNode] : """ Function responsible for growing m trees, where every nodes is built based on nfeat random attributs :param x: a 2D numpy array that contains the instances of the data to be predicted. :param y:...
def get_ssh_pair(self): """ Read a pair of public and private key from files :return: """ try: with open(f"keys/{self.name}.pub", "r") as f: pub_key = VerifyingKey.from_pem(f.read()) with open(f"keys/{self.name}.priv", "r") as f: ...
This code initializes a blockchain node by setting up its name, address, and cryptographic keys, registering itself in the blockchain network, and initializing components like wallet, blockchain handler, message generator, and miner to participate in transaction processing, block mining, and peer communication within t...
def __init__(self, node_name, port): self.name = node_name self.address = "http://127.0.0.1:" + str(port) self.node_list: [] = [] self.transaction_pool: [] = [] random.seed(node_name) self.salt = str(random.random())[2:10].encode() self.pub_key, self.priv_key = se...
def getAllUniqueSubSeqs(seqs, length): """ Enumerates all unique substrings found within the sequences of the specified length. Parameters ---------- seqs : ndarray Array representing the set of sequences. length : int Length of the substrings to be enumerated. Returns ...
The function identifies the most probable subsequence from a set of sequences using a sampling approach, initializes a Position Weight Matrix (PWM) with this subsequence, and iteratively refines it via EM algorithm steps (E-step and M-step) to maximize likelihood. It returns the optimal PWM and its corresponding probab...
def memeInitPWM(seqs, motifL, motifProb, initSamplingSize=1): """ Search all the unique subsequences found throughout the sequences and select the subsequence that has the highest probability of occuring after on E/M step. This chosen subsequence is then used to initialize a PWM. Parameters ---...
def initPWMMatrix(motifL): """ Initializes an empty PWM to the correct shape based on the motif length. Parameters ---------- motifL : int Length of the motif to be considered. Returns ---------- All-zero ndarray representing the PWM. """ return np.zeros((4, motifL+1)) ...
The function `runGibbs` executes the Gibbs Sampling algorithm to identify motifs in a set of sequences. It initializes a position weight matrix (PWM) and random motif positions. Iteratively, it updates the PWM and motif locations by predicting probabilities and resampling positions, repeating until convergence or reach...
def runGibbs(seqs, motifL, minIters, maxIters): """ Runs the Gibbs Sampling algorithm on a set of sequences. Parameters ---------- seqs : ndarray Array representing the set of sequences. motifL : int Length of the planted motif. minIters : int Minimum number of itera...
def memeInitPWM(seqs, motifL, motifProb, initSamplingSize=1): """ Search all the unique subsequences found throughout the sequences and select the subsequence that has the highest probability of occuring after on E/M step. This chosen subsequence is then used to initialize a PWM. Parameters ---...
The function `runBasicMEME` executes the MEME algorithm to identify a motif in a set of sequences using an Expectation-Maximization (EM) approach. It initializes a Position Weight Matrix (PWM) and a Z matrix, iteratively refining them through E-step (computing sequence motif probabilities) and M-step (updating the PWM)...
def runBasicMEME(seqs, motifL, motifStartingProb, threshold, initSamplingSize=1): """ Runs the MEME algorithm on a set of sequences. Parameters ---------- seqs : ndarray Array representing the set of sequences. motifL : int Length of the planted motif. motifStartingProb : fl...
def get_samples_by_char(samples, labels, mapping): samples_by_char = defaultdict(list) for sample, label in zip(samples, labels.flatten()): samples_by_char[mapping[label]].append(sample) return samples_by_char def create_dataset_of_images(N, samples_by_char, sentence_generator, max_overlap): sam...
The main task of the code is to generate synthetic text image datasets for training/testing by combining EMNIST character samples into sequences, then saving them as compressed HDF5 files with 'x' (images) and 'y' (categorical labels) datasets. It uses SentenceGenerator to create character sequences, maps EMNIST labels...
def _generate_data(self, split): print('EmnistLinesDataset generating data...') from text_recognizer.datasets.sentence_generator import SentenceGenerator sentence_generator = SentenceGenerator(self.max_length) emnist = self.emnist emnist.load_or_generate_data() if split...
def speak(text): engine.say(text) engine.runAndWait() def wishMe(): if hour <=0 & hour > 12: speak("Good Morning SaiSaaketh") elif hour > 12 & hour < 15: speak("Good Afternon Saaketh") elif hour > 9 & hour < 15: speak("Good Evening Saaketh") else: speak("Good Ni...
The code initializes a voice assistant named "Hover," listens for wake words like "friday" to trigger task execution, and exits on commands like "shut up" or "goodbye." It continuously waits for user input, setting "hoverbusy" to "no" when no valid command is detected.
def wakeword(): speak('Inisialising Hover') wishMe() while True: command = getcommand() if 'friday' in command: Execution() elif 'shut up' in command or 'goodbye' in command: sys.exit() else: hove...
def backtranslate(text, source_lang, target_lang): translation = translate(text, source_lang, target_lang) back_translation = translate(translation, target_lang, source_lang) return back_translation def bleuscore_similarity_score(text1, text2): similarity_score = sentence_similarity(text1, text2, smoothin...
The function performs back-translation on two specified columns of a DataFrame using given language pairs, computes BLEU scores and cosine similarity between original and back-translated texts, and appends these metrics as new columns. It processes a subset of the data, iterates through rows, applies translation and si...
def single_language(df, cols_name, languages, size=1000): df_ = df[:size] src_bt = [] tgt_bt = [] src_bleu_score = [] tgt_bleu_score = [] src_cs_score = [] tgt_cs_score = [] for index, row in df_[:].iterrows(): row = row.astype(str) # back translating the first language bt_text = backtrans...
def sort_data(self): self.data = self.data.sort_values(by='age', ascending=False) def broken_turbines(self): cm = 0 for i in range(len(self.data)): if self.data.loc[i, 'age'] == 0: cm += 1 #print("CMs: ", cm) return cm def c_cm(self, cm): if cm...
The main task of the code is to handle corrective maintenance for broken turbines by updating their lifetimes, predicting next failures, and calculating maintenance costs. It sorts data, identifies broken turbines, resets their lifetimes, sets their age to 1, and subtracts the maintenance cost from the total cost. The ...
def corrective_maintenance(self): self.sort_data() cm = self.broken_turbines() #print("cms, ", cm) #print(self.data.tail(cm)) if cm > 0: for id, row in self.data.tail(n=cm).iterrows(): lt = self.data.at[id, 'lifetimes'] self.data.at[id,...
def raise_if_docker_py_and_an_incorrect_version_of_docker_exist(): docker_py_package = get_package('docker-py') docker_package = get_package('docker') if docker_py_package and docker_package and not docker_version_is_2_6_x(): message = os.linesep.join([ "Your local host has the 'docker-py' version {docker_py_ve...
The main task of the code is to ensure the correct installation of the `docker` Python package (docker-py) while validating compatibility with Docker's presence and version. It checks for conflicting or missing dependencies, raises errors for invalid states, and installs the specified version (`2.6.0` to `2.7`) of `doc...
def install_docker_py(): raise_if_docker_py_and_an_incorrect_version_of_docker_exist() raise_if_docker_py_does_not_exist_and_an_incorrect_version_of_docker_exists() raise_if_docker_py_and_docker_exist() raise_if_docker_py_exists_but_not_docker() if get_package('docker'): return # Install `docker` on behalf of...
def _checkNumeric(self, df): """Get only numeric data that can be plotted""" #x = df.convert_objects()._get_numeric_data() x = df.apply( lambda x: pd.to_numeric(x,errors='ignore') ) if x.empty==True: return False def showWarning(self, s='plot error', ax=None): """Sho...
This method generates 2D plots using pandas' plotting functionality, supporting multiple plot types (line, scatter, bar, etc.) with validated parameters. It handles grouped data via subplots, adjusts visual settings (color maps, legends, axes), and manages figure layout, warnings for invalid data, and annotations. The ...
def plot2D(self): """Plot method for current data. Relies on pandas plot functionality if possible. There is some temporary code here to make sure only the valid plot options are passed for each plot kind.""" if not hasattr(self, 'data'): return #this is a hack...
def which_day(): return dt.datetime.now().isoweekday() def is_sunday() -> bool: return is_day(7) def do_sunday_tasks(): pass def is_monday() -> bool: return is_day(1) def do_monday_tasks(): print("Monday") pass
The main task of the code is to serve as a CLI script entry point that identifies the current day and executes specific tasks: printing the day's name, then performing Sunday-specific or Monday-specific operations based on the day detected.
def main(): """ CLI script main entry point. """ print(which_day()) if is_sunday(): do_sunday_tasks() elif is_monday(): do_monday_tasks()