dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def blast(db, query, evalue, max_target_seqs=50, cpus=-1, out='hits.hits'): outfmt_str = 'qaccver saccver pident evalue qcovs length staxid stitle ' \ 'sstart send' fasta = parse_fasta(query) if os.path.isfile(out): blasts = pd.read_csv(out, sep='\t', header=None, ...
The main task of the code is to perform taxonomic assignment of biological sequences using BLAST and phylogenetic analysis. It processes query sequences against a nucleotide database, filters high-identity hits, constructs phylogenetic trees, and assigns species-level identifications based on evolutionary relationships...
def main(email, query='all_samples.fasta', intended='intended.txt', db='nt', dbname='nt', evalue=1e-3, gaps=0.9, cpus=-1, ntop=3, sig_level=0.05, geneofinterest='COI', prefinquery='sq'): pref = query[:query.find('.fasta')] dbname = os.path.split(db)[-1] if dbname is None else dbname outbla...
def register_peer(self, addr): """ Adds a peer to the network of peers. """ with self.lock: self.peers[addr] = time.time() print(f"Registered a peer {addr} ") self.broadcast_peers() def update_heartbeat(self, addr): """ Updates the time of the ...
The code handles peer communication by listening for messages (JOIN, KEEPALIVE, LEAVE) from a client socket. It registers new peers on "JOIN", updates heartbeat data on "KEEPALIVE", and removes peers on "LEAVE". The loop processes incoming data until disconnection or errors, then closes the socket.
def handle_peer(self, client_socket, addr): """ The tracker listens for peers. Different message types have corresponding prefixes and are handled differently. Below is the message type it can receive. "JOIN" : A new peer requests a connection. "KEEPALIVE" : A peer requ...
def _setup_placeholder(self): with tf.name_scope('placeholder'): self.x_history = tf.placeholder(tf.float32, [None, self.hist_terms, *self.image_shape], name='x_history') self.x_future = tf.placeholder(tf.float32, [None, self.future_terms, *self.image_shape], name='x_future') ...
The main task of the code is to build a computational graph for a predictive model. It encodes historical and future image data into latent representations, generates an autoregressive context from the history, and computes a loss function (supervised or unsupervised) to predict future states. The graph includes placeh...
def _build_graph(self): self._setup_placeholder() x_history_flat = tf.reshape(self.x_history, [-1, *self.image_shape]) x_future_flat = tf.reshape(self.x_future, [-1, *self.image_shape]) z_history_flat = self._encode(x_history_flat) z_future_flat = self._encode(x_future_flat, reu...
def rotate_left(array, n): """ Array rotation """ return array[n:] + array[:n] def bin_to_array(number): """ Number -> Binary representation """ array = [0] * 20 for i in range(20): array[19-i] = number & 1 number = number >> 1 return array def test_solutions(t, z, M): """ ...
The code's main task is to recover a cryptographic key (Ezero) from a byte dump by solving a system of linear equations over GF(2). It generates transformation matrices (Pi) and carry matrices (Ci), iterates through possible values, computes Wi vectors, solves equations for each matrix, and checks if all eight systems ...
def main(): """ Main function """ # Reading the output values of our ffcsr from a file bytedump = open(DUMP_PATH + "dump", "rb") z = bytedump.read() bytedump.close() size_of_dump = len(z) # Initializing our vector and matrix spaces VS = VectorSpace(GF(2), 20) MS = MatrixSpac...
def pre_process(self, image): image = cv2.imread(image) height, width = image.shape[0:2] inp_height = (height | self.opt.pad) + 1 inp_width = (width | self.opt.pad) + 1 c = np.array([width // 2, height // 2], dtype=np.float32) s = np.array([inp_width, inp_height], dtype...
The code processes an input image through a detection model: it reads the image, preprocesses it, performs inference on a GPU, post-processes detections, merges results, and returns them. Debug mode saves results.
def run(self, image, meta=None): img = cv2.imread(image) image, meta = self.pre_process(image) image = image.to(self.opt.device) torch.cuda.synchronize() output, dets = self.process(image) torch.cuda.synchronize() ...
def _get_centroids(cent, gaussian=True): if gaussian: cent = filters.gaussian(cent, sigma=(0, 1, 1)) centroids = feature.peak_local_max(cent, threshold_abs=.04) return centroids def _get_mask(img, sigma=2): thresh = filters.threshold_otsu(filters.gaussian(img, sigma=sigma)) mask = img > thre...
The function `segment_output_image` performs image segmentation using a U-Net output. It extracts affinities, centroids, and a thresholding mask from specified channels, normalizes affinities, pads images, identifies centroids, generates a mask, removes unwanted objects, and applies affinity-based watershed segmentatio...
def segment_output_image( unet_output, affinities_channels, centroids_channel, thresholding_channel, scale=None, absolute_thresh=None, out=None, py_func=False, ): ''' Parameters ---------- unet_output: np.ndarray or dask.array.core....
def git(): run("git pull") def poetry(): run("poetry install") def migrate(): run("python manage.py makemigrations") run("python manage.py migrate") def npm(): run("npm i") run("npm run build") def collectstatic(): run("python manage.py collectstatic --noinput -v 3") def kill_prod(): run...
The code defines a deployment function for a web application, executing steps like pulling code via Git, installing Python dependencies with Poetry, running database migrations, handling frontend assets with NPM, collecting static files, stopping the production server, restarting it, and configuring Nginx to ensure the...
def deploy_prod(): git() poetry() migrate() npm() collectstatic() kill_prod() start_prod() nginx()
def get_picture_information(value): value = deepcopy(value) border_count = 12 picture_information = {} for _ in range(6): just_corners, unique_corners = get_unique_corners(value) picture_information[border_count] = {"c": {}, "e": {}, "a": []} for key in just_corners: ...
The code constructs a 12x12 grid of tiles by selecting and placing matching tiles from input data, then searches for a specific "dragon" pattern in the assembled image. If found, it calculates a count of '#' characters adjusted by the pattern's occurrences; otherwise, it rotates/flips the grid and repeats the check.
def part2(): value = data.INPUT picture_information = get_picture_information(value) first_four = picture_information[12] first_four_tiles = list(first_four["c"].keys()) first_id = first_four_tiles[3] grid = [[None for r in range(12)] for c in range(12)] grid[11][0] = {first_id: value[fi...
def layout_preprocessing(self, v, prev=None, n=1, lmost_sibling=None, lsibling=None): el = self._graph.node[v]["el"] el.layout_ancestor = prev el.layout_number = n el.layout_lmost_sibling = lmost_sibling el.layout_lsibling = lsibling el.layout_thread = None height...
This code computes the layout of a graph branch by finding a root node with zero in-degree, performing a post-order traversal, calculating node positions through preprocessing and two layout passes, adjusting coordinates to align the layout, and updating the branch's dimensions based on the computed extremes.
def layout(self): # Get first node v = None for vid, deg in self._graph.in_degree().items(): if deg == 0: v = vid break if v is None: logger.critical("Could not find parent node to layout branch %i: stopping", self.id) e...
def _draw_virtual_individual(self, sex, x, y): """Draws individual on drawing""" if sex == "M": self._image_layers["1:individuals"].append( self._svg.rect( (x, y), (self._symbol_size, self._symbol_size), fill="white"...
This function draws a family unit on a diagram by rendering father and mother (or virtual placeholders if absent), calculating positions, and connecting them with lines. It handles missing parents by creating virtual symbols, adjusts spacing based on text sizes, and uses helper methods for individual and connector rend...
def _draw_family(self, fid, x, y): """Draws family on drawing""" logger.debug("Drawing family %s at (%.1f, %.1f)", fid, x, y) family = self._pedigree.family(fid) # family.set_coordinates(x, y) father = family.father() mother = family.mother() if father is None: ...
def _draw_family(self, fid, x, y): """Draws family on drawing""" logger.debug("Drawing family %s at (%.1f, %.1f)", fid, x, y) family = self._pedigree.family(fid) # family.set_coordinates(x, y) father = family.father() mother = family.mother() if father is None: ...
The code generates a pedigree plot by rendering family and individual nodes with connections, using SVG. It initializes a FamilyGraph, calculates layout dimensions, draws nodes (families/individuals), creates connectors between parents/children, handles duplicates, and saves the SVG file. Key steps include node renderi...
def draw(self): """Draws pedigree plot based on specified parameters""" logger.info("Starting plot draw") draw_start = time.time() self._graph = FamilyGraph(self._pedigree, font_size=self._font_size, hmargin=self._hm...
def check_keydown_events(event, ai_settings, screen, ship, bullets): """Reaction on key's down""" if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: fire_bullets(ai_settings, screen, ...
This function processes user inputs by checking for events like quitting, key presses/releases, and mouse clicks. It handles game actions such as starting the game via the play button, ship movement, and shooting bullets, delegating specific tasks to helper functions based on detected events.
def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets): """Processing key's pressing and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event,...
def check_fleet_edges(ai_settings, aliens): """Reacts on achieving the edge of the screen by alien""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets): ...
This function updates alien movement by checking fleet edges and updating positions. It detects collisions between the ship and aliens, triggering a ship-hit response, and checks if aliens reach the screen's bottom to handle game-over logic.
def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets): """Checks if fleet achieved edge of the screen then it updates position of all aliens if the fleet""" check_fleet_edges(ai_settings, aliens) aliens.update() # Checking collisions "ship-alien" if pygame.sprite.spritecollideany...
def make_dictionary(): file = open("data.txt", 'r') lines = file.readlines() count = 0 dictionary = dict() new = [] for i in lines: line = i.strip('\n') if line != '': new.append(line) while count < len(new): date = new[count] text = new[count + 1]...
The code manages a dictionary stored in "data.txt" by allowing user interactions: read, write, lookup, append, or check yesterday's data. It repeatedly prompts for actions until 'q' is entered, updating the dictionary after write/append operations.
def main(): str = "r for read, w for write, l for lookup, a for append, y for yesterday, q for quit\n" whatdo=input(str) file=open("data.txt") file.close() dictionary=make_dictionary() while whatdo != 'q': dictionary = make_dictionary() if whatdo == "r": print() ...
def _get_start_time(self, message): self.message = message if "start_time" in self._user_data: self.bot.send_message( self.message.chat.id, "What is the end time (YYYY-MM-DD) ?") self.bot.register_next_step_handler( self.message, self._get_end_tim...
This function validates the end date from a user message. If invalid, it notifies the user and requests the start time. If valid, it checks if the start date precedes the end date; if not, it alerts the user and requests the asset name. Otherwise, it proceeds to perform analytical analysis.
def _get_end_time(self, message): self.message = message end_time = self.message.text try: super().is_valid_date(end_time) except ValueError as err: self.bot.send_message( self.message.chat.id, err) self._get_start_time(self.message) ...
def normalize(self, dataSet,means=[],stds=[]): normalized = dataSet.copy(True) attributes = dataSet.shape[1] - 1 if len(means) != attributes: newMeans = [] newStds = [] for i in range(attributes): mean = dataSet[i].mean() newMea...
The code performs k-fold cross-validation for logistic regression, evaluating model accuracy, precision, and recall on both training and test sets per fold. It normalizes data, trains the model, and stores metrics. After all folds, it calculates and prints mean and standard deviation of the metrics to assess model perf...
def validate(self): trainAccuracies = [] trainPrecisions = [] trainRecalls = [] testAccuracies = [] testPrecisions = [] testRecalls = [] fold = 1 plotFold = random.randint(1, self.kFold + 1) print( "Fold\tTrained Accuracy\tTr...
def deal_with_cookie_modal(self) -> None: try: self.web_driver.find_element( By.CSS_SELECTOR, "[id='exponea-cookie-compliance'] a[class~=close]" ).click() except NoSuchElementException: pass def _single_selector_reader(self, css_selector: str, attribut...
The main task of the code is to extract product information from a webpage, including name, description, brand, and prices (if enabled), by navigating to the product page, handling modals, and parsing HTML elements using specific selectors. The result is returned as a `ProductInfo` dictionary with dynamic price inclusi...
def fetch_product_info( self, product_name: str, get_prices: bool = True ) -> ProductInfo: """ Extracts a list of information on a product. Args: product_name: The name of the product to put in the search bar. get_prices: Whether the prices should be retrieve...
def create_groups(self): '''Create the groups in the h5 file.''' for target in self.targets: self.file.create_group(f"{SpecialKey.Targets}/{target}") for object in self.input_features.keys(): self.file.create_group(f"{SpecialKey.Inputs}/{object}") for group in sel...
This code saves a dataset (train/test) to an HDF5 file, creating groups and datasets for targets, classifications, inputs, and weights. It validates the dataset type, constructs the output filename, writes data into the HDF5 structure, and ensures proper file closure.
def save_h5(self, dataset_type): '''Save the h5 file.''' assert dataset_type in ["train", "test"], f"Dataset type `{dataset_type}` not recognized." df = getattr(self.dataset, dataset_type) output_file = self.output_file.replace(".h5", f"_{dataset_type}_{len(df)}.h5") pr...
def get_fintness(chromosome): """ get individual student fitness similarity visibility distance compute overall fitness return overall fitness of the given chromosome """ indivial_student_fitness = [student_fitness(chromosome[i]...
This code implements a genetic algorithm to evolve a population of chromosomes over multiple generations. It initializes a population, selects top-performing chromosomes based on fitness, applies crossover and mutation to generate new offspring, and iterates through epochs to optimize solutions. The algorithm aims to i...
def genetic(length_of_chromosome,initial_chromosome,population_size,epochs): population=[] population.append(initial_chromosome) for i in range(population_size-1): #print("len of population ",len(population)," ") #chromosome_to_generate_random = random.randint(0,len(population)-1) ...
def visibility_factor(s1,s2): angle= angle_between_students(s1,s2) vis_fact=gaussian(angle,0,1) return float(vis_fact) def euclidean_distance(s1,s2): dst = distance.euclidean(s1, s2) return float(dst) def subject_similarity(s1,s2): subj_sim=subject_subject_dictionary_constant[s1][s2] return ...
The function calculates a fitness value between two points (s1 and s2) by combining visibility, distance, and subject dissimilarity factors. It computes visibility and Euclidean distance coefficients, derives subject dissimilarity from similarity, applies non-linear transformations (exponents), and multiplies the weigh...
def fitness_value(s1,s2): ### THIS IS THE FUNCTION TO CALL s1->[row,column,subject] s2->[row,column,subject] visibility_coefficient=visibility_factor([s1[0],s1[1]],[s2[0],s2[1]]) #print("visibility_coefficient ",visibility_coefficient) distance_coefficient=euclidean_distance([s1[0],s1[1]],[s2[0],s2[1]]...
def send_hash(self, message, sock, secret_key): message = self.format_message(message) message = self.encrypt_symmetric(message, secret_key) sock.sendall(message) def recv_hash(self, sock, secret_key): message = sock.recv(4096) message = self.decrypt_symmetric(message, secret_key...
The code authenticates a user by sending hashed credentials (username and password) to a server via a socket, using a secret key for hashing. It checks server responses after each transmission; if both steps return 'true', the login succeeds. The function returns True on successful authentication, otherwise False.
def user_login_client(self, usuario, senha, secret_key): self.send_hash(usuario, self.sock, secret_key) ok = self.recv_hash(self.sock, secret_key) self.send_password(senha, self.sock, secret_key) ok = self.recv_hash(self.sock, secret_key) if ok == 'true': return True...
def send_hash(self, message, sock, secret_key): message = self.format_message(message) message = self.encrypt_symmetric(message, secret_key) sock.sendall(message) def recv_hash(self, sock, secret_key): message = sock.recv(4096) message = self.decrypt_symmetric(message, secret_key...
This code registers a user by sending a username and two passwords to a server via a socket, using a secret key for hashing. It checks the server's response to determine if the registration was successful, returning a boolean and the server's message.
def cadastro_client(self, usuario, senha, senha2, secret_key): self.send_hash(usuario, self.sock, secret_key) ok = self.recv_hash(self.sock, secret_key) self.send_password(senha, self.sock, secret_key) ok = self.recv_hash(self.sock, secret_key) self.send_password(senha2, self.s...
def recv_hash(self, sock, secret_key): message = sock.recv(4096) message = self.decrypt_symmetric(message, secret_key) #essa func da erro aqui as vezes message = eval(message) if not self.compare_message(message): print('servidor nao confiavel') self.close...
The code creates a voting session by receiving a session name and options from a client, checking if the session already exists, and initializing it if not. It sends 'ok' or 'false' based on existence, stores session data, and returns True/False accordingly.
def server_create_session(self, client, secret_key): name = self.recv_hash(client, secret_key) ok = 'ok' self.send_hash(ok, client, secret_key) options = self.recv_hash(client, secret_key) options = eval(options) if name in self.voting_sessions: message = 'f...
def recv_hash(self, sock, secret_key): message = sock.recv(4096) message = self.decrypt_symmetric(message, secret_key) #essa func da erro aqui as vezes message = eval(message) if not self.compare_message(message): print('servidor nao confiavel') self.close...
(The code handles a user login process by receiving an encrypted username and password, verifying the credentials, and sending a 'true' or 'false' response to the client based on the verification result. It returns a tuple containing the verification status and the username.)
def user_login_server(self, client, secret_key): usuario = self.recv_hash(client, secret_key) message = 'ok' self.send_hash(message, client, secret_key) senha = self.recv_password(client, secret_key) ret = self.checa_login(usuario, senha) if ret == False: me...
def recv_hash(self, sock, secret_key): message = sock.recv(4096) message = self.decrypt_symmetric(message, secret_key) #essa func da erro aqui as vezes message = eval(message) if not self.compare_message(message): print('servidor nao confiavel') self.close...
The main task of the code is to register a new user by receiving a username and two passwords. It checks if the passwords match and if the username already exists. If valid, it stores the user in a dictionary; otherwise, it returns False with error messages.
def cadastro_server(self, client, secret_key): usuario = self.recv_hash(client, secret_key) ok = 'ok' self.send_hash(ok, client, secret_key) senha = self.recv_password(client, secret_key) ok = 'ok' self.send_hash(ok, client, secret_key) senha2 = self.recv_passwo...
def recv_hash(self, sock, secret_key): message = sock.recv(4096) message = self.decrypt_symmetric(message, secret_key) #essa func da erro aqui as vezes message = eval(message) if not self.compare_message(message): print('servidor nao confiavel') self.close...
The main task of the code is to handle client authentication via login/registration and provide voting-related functionalities. It loops to receive client choices, authenticates users, and allows actions like viewing voting sessions, casting votes, checking results, or creating sessions. If invalid choices are made, th...
def server_login(self, client, secret_key): saiu = False ret = False usuario = '' while not ret: choice = self.recv_hash(client, secret_key) if choice == '1': ok = False while not ok: ok, user = self.user_login_...
def create_cipher(self, public_key): #cifrar com a chave publica do outro return PKCS1_OAEP.new(key=public_key) def decrypt_message(self, message): return self.decipher.decrypt(message) def encrypt_message(self, message, cipher): return cipher.encrypt(message) def generate_secret_key(sel...
The function establishes secure client-server communication via RSA encryption. It exchanges public keys, decrypts client messages with its private key, re-encrypts them with the client's public key, generates a secret key, encrypts and shares it, then authenticates the client using the secret key.
def server_connection(self, client): #self.n_clients = self.n_clients + 1 #if self.n_clients > 5: #self.cond = False client.sendall(self.public_key_str) client_public_key = client.recv(4096) client_public_key = RSA.importKey(client_public_key) cipher = self...
def forward(self): input_A = self.input_A.clone() input_B = self.input_B.clone() self.real_A = self.input_A self.real_B = self.input_B size = self.opt.crop_size if self.opt.geometry == 'rot': self.real_gc_A = self.rot90(input_A, 0) self.real_gc_...
This code optimizes a generative adversarial network (GAN) by first performing a forward pass, then updating the generator (G_AB) via backpropagation and gradient descent. It subsequently optimizes the discriminators (D_B and D_gc_B) by computing their gradients and applying updates. The process alternates between mini...
def optimize_parameters(self): # forward self.forward() # G_AB self.optimizer_G.zero_grad() self.backward_G() self.optimizer_G.step() # D_B and D_gc_B self.optimizer_D_B.zero_grad() self.backward_D_B() self.optimizer_D_B.step()
def network_running(self): return is_apache_configured()\ or self.is_click_running()\ or self.is_tc_configured() def stop_network(self): logging.getLogger(__name__).info('Stopping simulated network...') # stop apache instances logging.getLogger(__name__).info('Stopping apache...') try: reset_apache(...
The main task of the code is to initialize a simulated network environment by creating virtual network interfaces, configuring traffic shaping, and launching Apache instances. It checks if the network is already running, stops it if necessary, generates Click configuration files, applies traffic control policies, and s...
def start_network(self): if self.network_running(): logging.getLogger(__name__).info('Some network components already running...') self.stop_network() logging.getLogger(__name__).info('Starting simulated network...') # Create fake NICs logging.getLogger(__name__).info('Creating network interfaces...') ...
def getCSVHeaders(df: pd.DataFrame): global lengthOfHeaders, valueOfCheckList, buttonsAndChecksList, valueOfComboList valueOfCheckList.clear() valueOfComboList.clear() lengthOfHeaders = 0 for chcb in buttonsAndChecksList: chcb.destroy() for h in df.head(0): lengthOfHeaders += 1 ...
This function allows users to select a CSV file, loads it into a DataFrame, displays time conversion and graph generation buttons, and sets default time settings.
def getCSVFile(): global df root.filename = filedialog.askopenfilename(title="Select A CSV File", filetypes=[("CSV Files", "*.csv")]) # catch if user doesn't select a file if root.filename == "": return df = pd.read_csv(root.filename) getCSVHeaders(df) placeButtons(69) tb =...
def getElectrictyUsageInfo(startDate, endDate): """ Gets half hourly usage for the specified interval Args: startDate: start date endDate: end date Return: Dict: dict containing metrics Raises: GetElectricityUsageRequestError """ try: # Get login coo...
The function retrieves electricity usage data between specified dates, generates a notification message from the data, and sends it via Pushover. It handles errors by logging failures, notifying users of internal errors, and raising a custom exception.
def getElectricityBillThreaded(startDate, endDate): """ fetches electricity bill data and sends pushover notificaton Args: startDate: start date of the interval endDate: end date of the interval Raises: GetElectricityBillError """ try: metrics = getElectrictyUsa...
def Stage2_Generator(): input_embedding = tf.keras.Input(shape=(1024,)) input_images = tf.keras.Input(shape=(64, 64, 3)) # Conditioning Augmentation ca = tf.keras.layers.Dense(256)(input_embedding) ca = tf.keras.layers.LeakyReLU(alpha=0.2)(ca) c = tf.keras.layers.Lambda(conditional_augmentation)(ca) # Dow...
This code initializes a Stage 2 GAN model for image generation, configuring parameters, optimizers, and pre-trained components. It sets up a generator, discriminator, and adversarial model with custom loss functions, loads a Stage 1 generator, and prepares an embedding compressor. The checkpoint saves model weights and...
def __init__(self, train_ds, epochs=400, z_dim=100, batch_size=64, gen_lr=0.001, dis_lr=0.001): self.epochs=epochs self.z_dim=z_dim self.batch_size=batch_size self.gen_lr=gen_lr self.dis_lr=dis_lr self.img_size=256 # Training dataset self.train_ds=train_ds # Optimizers to the models...
def newSessionId (self) -> str: ''' Generates a new random and unique session id from ns timestamp. [Return] Session id as string. ''' # generate unique chat identifier from ns timestamp while True: id = str(time_ns()) if not id ...
The main task of the code is to create an interactive text-based chat loop that maintains context across conversations. It initializes a chat session with configurable parameters (username, character traits, scenario), processes user inputs through a model inference pipeline, and outputs responses with optional timing ...
def chat (self, username: str='human', char_tags: list[str]=['helpful'], scenario: str=None, show_duration: bool=True, **pipe_twargs) -> None: ''' A text-to-text chat loop with context aggregator. Will initialize a new chat with identifier in context. Helpful to interfere with the model...
def _create_cells(self) -> typing.List[typing.List[Cell]]: return [[Cell(self._win) for _ in range(self._num_cols)] for _ in range(self._num_rows)] def _draw_cells(self): for row in range(self._num_rows): for col in range(self._num_cols): self._draw_cell(row, col) def _break_...
This code initializes a maze generator by setting up a grid with specified dimensions, cell sizes, and a window. It creates maze cells, draws them, breaks walls recursively to form paths, and sets entrance/exit points. The seed parameter ensures reproducible randomization during maze generation.
def __init__( self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win: typing.Union[Window, None] = None, seed=None, ) -> None: if seed is not None: random.seed(seed) s...
def check_folder_exists(self, fileName, u_parent_id): fileName = clean_name(fileName) # Create Search Query for API request. query = f"'{u_parent_id}' in parents and (name contains '{fileName}' and trashed=false)" response = self.__service.files().list(supportsTeamDrives=True, ...
This function synchronizes a Google Drive folder's contents to a local path by recursively cloning subfolders and copying files, while handling pagination, ignoring specified folders, and updating status with file/folder counts and transfer progress.
def cloneFolder(self, name, local_path, folder_id, parent_id, status, ignoreList=[]): page_token = None q = f"'{folder_id}' in parents" files = [] LOGGER.info(f"Syncing: {local_path}") while True: response = self.__service.files().list(supportsTeamDrives=True, ...
def getIdFromUrl(link: str): if len(link) in [33, 19]: return link if "folders" in link or "file" in link: regex = r"https:\/\/drive\.google\.com\/(?:drive(.*?)\/folders\/|file(.*?)?\/d\/)([-\w]+)" res = re.search(regex, link) if res is None: ...
This function clones a Google Drive file or folder from a given link, handling errors, checking for existing files/folders, copying content, and generating a summary message with metadata and download links. It updates status objects and returns formatted HTML text with file details.
def clone(self, link, status, ignoreList=[]): self.transferred_size = 0 self.total_files = 0 self.total_folders = 0 try: file_id = self.getIdFromUrl(link) except (KeyError, IndexError): msg = "Google drive ID could not be found in the provided link" ...
def check_imports(): """Checks whether all needed modules are imported""" if libvirt is None: raise LibvirtVmProcessingError("Python module 'libvirt' is missing") if BeautifulSoup is None: raise LibvirtVmProcessingError("Python module 'BeautifulSoup 4'" ...
The main task of the code is to monitor virtual machines (VMs) via libvirt, periodically listing all domains, processing each VM to check associated processes, counting successfully processed VMs, and outputting metrics (timestamp and count) to track active VMs. It handles connection errors and LibvirtVmProcessingError...
def main(): try: check_imports() conn = libvirt.openReadOnly(LIBVIRT_URI) if conn is None: utils.err("Failed to open connection to the hypervisor") return ERROR_CODE_DONT_RETRY while True: domains = conn.listAllDomains() random.shuffl...
def journey_planner(self, start:str, dest:str): ''' Function takes the start and destination stations as crs inputs and returns a list of stations in the journey from start to end ''' if not (isinstance(start, str) or isinstance(dest, str)): raise(TypeError('crs must be 3 letter string')...
This function calculates the fare for a railway journey between two stations based on the number of legs in the route. It determines costs by evaluating distances, regional differences, and hub stations. For 2-leg journeys, it directly computes fare using distance and region checks. For 3-4 leg journeys, it accounts fo...
def journey_fare(self, start:str, dest:str, summary=False): ''' Function takes start and destination as crs values and returns the cost of the journey. Summary is true to output more information and show the journey passage. ''' journey = self.journey_planner(start, dest) ...
def GetAttributeFlags(self): """Gets attributes passed in by the user via the command line. User inputs include the directory containing all the raw profile validation resource files, the directory to output the final bundle, and whether or not the user needs the global array with the ImplementationGui...
This method generates a FHIR transaction bundle containing profile validation resources by processing input resources from a source directory, applying validation rules based on flags, and outputting the resulting bundle to a target directory.
def CreateProfileValidationResourcesBundle(self): """Helps create a FHIR transaction bundle from a set of profile validation resources.""" source_dir, target_dir, do_construct_global_array = self.GetAttributeFlags() bundle = self.ProcessProfileValidationResourcesAt( source_dir, do_construct_global_a...
def getLog(logName): with open (logName, "rb") as f: log = pickle.load(f) return log def avgDay(log): index = log.timeToIndex("06:00", 0) timeLog = log.getLog() timeArr = np.array(timeLog[index:]) timeArr = np.append(timeArr, timeLog[:index]) timeArr = timeArr.reshape((7,-1)) ...
The main task of the code is to retrieve a log from "diaLog.db", compute average daily data using `avgDay(log)`, and compare daily metrics with `compDay(log)`, while also preparing for potential visualization of the log data and daily trends.
def main(): diaLogName = "diaLog.db" dayDict = {"mon":0, "tue":1, "wed":2, "thur":3, "fri":4, "sat":5, "sun":6} log = getLog(diaLogName) # plotLog(log) # plotDay(log, int(datetime.today().weekday())) avgDay(log) compDay(log)
def compute(self): needed = self.xs[self.xs.compute] for row in needed.itertuples(): try: fx = self.f([row.x1, row.x2, row.x3], self.ts) except Exception: print("Exception evaluating function at " + str(row) + ".") fx = [] ...
The code executes a cycle of operations `n` times: computing data, measuring focus metrics, and probing with specified parameters. It returns the shapes of the processed data arrays `xs` and `ys` after all cycles.
def cycle(self, n = 1, focus = 2, alpha = 1, maxdepth = _maxdepth): for i in range(n): self.compute() self.measure(focus = focus) self.probe(alpha = alpha, maxdepth = maxdepth) return (self.xs.shape, self.ys.shape)
def _get_entity(self, id): url = f"https://www.wikidata.org/wiki/Special:EntityData/{id}.json" response = requests.get(url) if self._valid_response(response): return response.json() def _id_to_label(self, id): response = self._get_entity(id) if response: ...
This function extracts triples (subject-predicate-object) and related QIDs from a Wikidata entity using its QID. It retrieves entity labels, descriptions, and claims, processes values and qualifiers, and constructs Triples with labels and qualifiers. It returns a list of triples and a dictionary mapping tail labels to ...
def _get_triples_from_qid(self, qid): response = self._get_entity(qid) if not response: return None, None triples = [] tail_qids = {} entity_info = response["entities"][qid] try: entity_label = entity_info["labels"]["en"]["value"] exce...
def _generate_apidocs_packages(executor: ThreadPoolExecutor) -> None: """Generate API docs for default packages.""" for component_type, default_package in DEFAULT_PACKAGES: public_id = PublicId.from_str(default_package) author = public_id.author name = public_id.name type_plural ...
The main task of the code is to generate API documentation by first deleting the existing API directory, then creating a new one, and concurrently generating API docs for packages, AEA modules, and plugins using multithreading.
def generate_api_docs() -> None: """Generate the api docs.""" shutil.rmtree(API_DIR, ignore_errors=True) API_DIR.mkdir() with ThreadPoolExecutor() as executor: _generate_apidocs_packages(executor) _generate_apidocs_aea_modules(executor) _generate_apidocs_plugins(executor)
def load_git_cache() -> None: """Load versions cache.""" if not _cache_file.exists(): return with _cache_file.open("r", encoding="utf-8") as stream: _version_cache.update(yaml_load(stream=stream)) def get_dependencies() -> t.Dict: """Get dependency->version mapping.""" dependencies =...
The main task of the code is to update dependency versions in Pipfile and pyproject.toml, bump package versions in tox.ini and source files, manage git cache, and synchronize packages if specified. It aggregates dependencies, updates project files, and uses a package manager to sync sources, ensuring version consistenc...
def main( extra: t.Tuple[Dependency, ...], sources: t.Tuple[str, ...], sync: bool, no_cache: bool, ) -> None: """Run the bump script.""" if not no_cache: load_git_cache() dependencies = {} dependencies.update(get_dependencies()) dependencies.update({dep.name: dep.version fo...
def rerun_notebook(orig_notebook: str, new_notebook: str = "cs-320-test.ipynb") -> Dict: """ rerun notebook and return parsed JSON :param orig_notebook: path to jupyter notebook :param new_notebook: path to re-run jupyter nb :return: JSON parsed ipynb """ # re-execute it from the beginning...
This function grades a Jupyter notebook by extracting answer cells marked with #q{number} headers, evaluating them against expected results, calculating a weighted score, and outputting a detailed JSON report with per-test results and an overall percentage score. It ensures proper directory setup, validates question nu...
def grade_notebook(nb_path: str): """ Grade a notebook using provided expected.json :param nb_path: Ipynb path """ # make sure directories are properly setup nb = rerun_notebook(nb_path) # extract cells that have answers answer_cells = {} for cell in nb["cells"]: q = extrac...
def descpension(self): return self.__sueldo*0.04 def descsalud(self): return self.__sueldo*0.04 def descuentoarl(self): return 5700 def descuentonomina(self): return self.descsalud()+self.descpension()+self.descuentoarl()+self.calculohe() def total(self): return self.__sueldo-sel...
The main task of the code is to display an employee's payroll details, including their salary, overtime hours, calculated deductions (pension, health, ARl), total deductions, and final total. It prints structured information about the employee's earnings and deductions using internal methods to compute values like pens...
def mostrar(self): print("*** Datos Empleados ***") print("Sueldo",self.__sueldo) print("Horas Extras",self.__he) print("******Descuentos Nomina***********") print("Pension: ",self.descpension()) print("Salud ",self.descsalud()) print("Arl ",self.descuentoarl()) ...
def userInDB(self, twitchUser): conn = self.getConnection() query = "SELECT id FROM streamers WHERE user_login = ?;" params = [twitchUser] cursor = conn.cursor() cursor.execute(query, params) row = cursor.fetchone() cursor.close() conn.close() if r...
The code adds a Twitch user to a database if not already present, inserts a server if not existing, and associates the user with the server's ID to link them in the system.
def addUser(self, twitchUser, author): if False == self.userInDB(twitchUser): query = "INSERT INTO streamers (user_login, online) VALUES (?,0);" params = [twitchUser] self.executeQuery(query, params) if False == self.serverInDB(author.guild): self.addServe...
def add_column(data, times): for i in range(1, times + 1): new = np.zeros((len(data), 1), dtype = float) data = np.append(data, new, axis = 1) return data def ema(data, alpha, lookback, close, position): alpha = alpha / (lookback + 1.0) beta = 1 - alpha ...
The function computes the MACD (Moving Average Convergence Divergence) indicator by calculating exponential moving averages (EMA) for given periods, subtracting short-term EMA from long-term EMA to generate the MACD line, then applying another EMA to the MACD line to create the signal line. It modifies the input data a...
def macd(data, close, long_ema, short_ema, signal_ema, position): data = add_column(data, 1) data = ema(data, 2, long_ema, close, position) data = ema(data, 2, short_ema, close, position + 1) data[:, position + 2] = data[:, position + 1] - data[:, position] data = delete_row(data, l...
def add_column(data, times): for i in range(1, times + 1): new = np.zeros((len(data), 1), dtype = float) data = np.append(data, new, axis = 1) return data def ema(data, alpha, lookback, close, position): alpha = alpha / (lookback + 1.0) beta = 1 - alpha ...
The function computes multiple Exponential Moving Averages (EMAs) with Fibonacci-like periods, combines them into a "High FMA" by averaging, then repeats the process with shifted positions, deleting intermediate columns. It processes financial/time-series data to generate composite moving average indicators for analysi...
def fma(data, position): data = add_column(data, 2) # Calculating Different Moving Averages data = ema(data, 2, 5, 1, position) data = ema(data, 2, 8, 1, position + 1) data = ema(data, 2, 13, 1, position + 2) data = ema(data, 2, 21, 1, position + 3) data = ema...
def add_column(data, times): for i in range(1, times + 1): new = np.zeros((len(data), 1), dtype = float) data = np.append(data, new, axis = 1) return data def smoothed_ma(data, alpha, lookback, close, position): lookback = (2 * lookback) - 1 alpha = alpha / ...
The code calculates the Average True Range (ATR) for financial data by determining the maximum of three volatility measures (high-low, high vs. previous close, low vs. previous close) over a lookback period. It then applies a smoothed moving average to the ATR values, removes temporary columns/rows, and returns the pro...
def atr(data, lookback, high, low, close, position): data = add_column(data, 1) for i in range(len(data)): try: data[i, position] = max(data[i, high] - data[i, low], abs(data[i, high] - data[i - 1, close]), abs(data[i, low] - data[i - 1, close])) ...
def add_column(data, times): for i in range(1, times + 1): new = np.zeros((len(data), 1), dtype = float) data = np.append(data, new, axis = 1) return data def smoothed_ma(data, alpha, lookback, close, position): lookback = (2 * lookback) - 1 alpha = alpha / ...
The code calculates the Relative Strength Index (RSI) for given financial data. It computes price changes, separates positive and negative changes, applies smoothed moving averages, calculates the RSI ratio, and returns the data with RSI values. The process involves modifying the data structure by adding/removing colum...
def rsi(data, lookback, close, position): data = add_column(data, 5) for i in range(len(data)): data[i, position] = data[i, close] - data[i - 1, close] for i in range(len(data)): if data[i, position] > 0: data[i, position + 1] = data...
def add_column(data, times): for i in range(1, times + 1): new = np.zeros((len(data), 1), dtype = float) data = np.append(data, new, axis = 1) return data def stochastic_oscillator(data, lookback, high, ...
The function applies the Fisher Transform to a stochastic oscillator value in the input data. It normalizes the oscillator (0-100 to -1 to 1), adjusts edge cases, computes the Fisher Transform using a logarithmic formula, then removes the original column, returning the transformed data for further analysis.
def fisher_transform(data, lookback, high, low, close, position): data = add_column(data, 1) data = stochastic_oscillator(data, lookback, high, low, close, position) data[:, position] = data[:, position] / 100 data[:, position] = (2 * data[:, position]) - 1 for i in range(len(data)):...
def volatility_adjusted_moving_average(data, lookback_volatility_short, lookback_volatility_long, close, position): data = add_column(data, 2) # Calculating Standard Deviations data = volatility(data, lookback_volatility_short, close, position) data = volatility(data, lookback_volatility_long,...
The function computes volatility-adjusted moving average bands by first applying a volatility-adjusted moving average (VAMA) to the input data. It then calculates volatility, adds columns for upper and lower bands using standard deviation multiplied by volatility values, and trims rows/columns to finalize the output. T...
def vama_bands(data, lookback_volatility_short, lookback_volatility_long, lookback_volatility, std, close, position): data = volatility_adjusted_moving_average(data, lookback_volatility_short, lookback_volatility_long, close, position) data = volatility(data, lookback_volatility, close, position + 1) ...
def macd(data, close, long_ema, short_ema, signal_ema, position): data = add_column(data, 1) data = ema(data, 2, long_ema, close, position) data = ema(data, 2, short_ema, close, position + 1) data[:, position + 2] = data[:, position + 1] - data[:, position] data = delete_row(data, l...
The function generates buy/sell signals using MACD and stochastic oscillators. It processes data by applying MACD, removing signal lines, calculating stochastic indicators, and adding columns. It identifies reversal points when MACD crosses zero with stochastic values <30 (buy) or >70 (sell), marking signals in the dat...
def rob_booker_reversal(data, high, low, close, position, buy, sell): # Calling the MACD function data = macd(data, close, 26, 12, 9, position) # Removing the MACD signal line data = delete_column(data, position + 1, 1) # Calling the stochastic function data = stochastic_oscillato...
def add_column(data, times): for i in range(1, times + 1): new = np.zeros((len(data), 1), dtype = float) data = np.append(data, new, axis = 1) return data def ema(data, alpha, lookback, close, position): alpha = alpha / (lookback + 1.0) beta = 1 - alpha ...
The code calculates the Keltner Channel technical indicator by computing an Exponential Moving Average (EMA) and Average True Range (ATR), then creating upper and lower bands using the EMA and ATR multiplied by a given multiplier. It modifies the input data array by adding these bands, removing temporary columns/rows, ...
def keltner_channel(data, lookback, multiplier, close, position): data = add_column(data, 2) data = ema(data, 2, lookback, close, position) data = atr(data, lookback, 2, 1, 3, position + 1) data[:, position + 2] = data[:, position] + (data[:, position + 1] * multiplier) data[:, p...
def rsi(data, lookback, close, position): data = add_column(data, 5) for i in range(len(data)): data[i, position] = data[i, close] - data[i - 1, close] for i in range(len(data)): if data[i, position] > 0: data[i, position + 1] = data...
The code computes the Stochastic RSI indicator by first calculating the RSI of the input data, then applying a Stochastic oscillator formula to normalize RSI values within a lookback period. It scales the result to 0–100, applies moving averages for smoothing, and returns the final smoothed Stochastic RSI values. This ...
def stochastic_rsi(data, lookback_rsi, lookback_stoch, close, position, slowing_period = 1, smoothing_period = 1): data = rsi(data, lookback_rsi, close, position) data = add_column(data, 1) for i in range(len(data)): try: data[i, p...
def rsi(data, lookback, close, position): data = add_column(data, 5) for i in range(len(data)): data[i, position] = data[i, close] - data[i - 1, close] for i in range(len(data)): if data[i, position] > 0: data[i, position + 1] = data...
The code computes RSI and ATR indicators on financial data, calculates their ratio, generates a new RSI from this ratio, and modifies the data structure by adding/removing columns. It combines technical analysis metrics for potential trading signals, adjusting the dataset's column layout to focus on derived indicators.
def rsi_atr(data, lookback_rsi, lookback_atr, lookback_rsi_atr, high, low, close, position): data = rsi(data, lookback_rsi, close, position) data = atr(data, lookback_atr, high, low, close, position + 1) data = add_column(data, 1) data[:, position + 2] = data[:, position] / data[:, p...
def winter(): for _ in range(6): winter_border_color((0, 0, 255), (0, 255, 255)) def mud_map(): color_this = set() water_set = get_water_border() for tup in water_set: r, c = tup[0], tup[1] if pixel[r, c] == (0, 0, 255): this_elevation = data_matrix[r, c, 0] ...
The main task of the code is to adjust the map settings based on the current season by calling specific functions: `winter()` for winter, `mud_map()` for spring, and `fall()` for fall.
def alter_map(current_season): if current_season == "winter": winter() elif current_season == "spring": mud_map() elif current_season == "fall": fall()
def populate_matrix(): result_matrix = np.zeros([height, width, 2]) for rows in range(height): # horizontal for columns in range(width): # vertical result_matrix[rows, columns, 0] = elevations[rows, columns] # elevation result_matrix[rows, columns, 1] = color_map[pixel[rows, c...
The code processes a terrain image and elevation data to compute paths between specified checkpoints using the A* algorithm. It marks these paths on the image, calculates the total distance of all paths, and saves the modified image. The season parameter influences the terrain conditions, affecting pathfinding. The scr...
def main(): img_file = "terrain.png" # sys.argv[1] elev_file = "elevations.txt" # sys.argv[2] node_file = "check_points.txt" # sys.argv[3] season = "spring" # sys.argv[4] op_img_file = "result" # sys.argv[5] global elevations elevations = np.loadtxt(elev_file).transpose() checkpoint...
def pure_leaves(D): if len(np.unique(D[:, -1])) == 1: return True else: return False def classify_data(D): classes, counts = np.unique(D[:, -1], return_counts=True) classified_class = classes[counts.argmax()] return classified_class def choose_best_attribute(D): best = None b...
The code constructs a decision tree by recursively splitting data based on selected attributes, handling different attribute types (binary, boolean, categorical) with varying node increments. It checks termination conditions (pure leaves, height limits, node counts) and returns classification results or sub-trees, mana...
def decision_tree(D, step, redundant=False, height=0): global nodes if pure_leaves(D) or redundant or height > h or nodes > x: return classify_data(D) else: height += 1 attr = choose_best_attribute(D) step += 1 if step % 20 == 0: node_arr.append(nodes) ...
def can_prune(node): for i in node.values(): for j in i: if isinstance(j, dict): return True return False def is_accuracy_improved(new_tree): D = np.asarray(df_val[1:], dtype=float) preprocess() a1 = accuracy(D, tree) a2 = accuracy(D, new_tree) if a1 > a2:...
The main task of the code is to recursively prune subtrees in a tree structure by checking if they can be pruned using the `can_prune` function and if their removal improves accuracy via `is_accuracy_improved`. It iterates through nodes in reverse order, deletes qualifying subtrees via hash-based identification, and mo...
def prune_tree(t): for i in tree.values(): #print(tree.keys()) for j in reversed(i): if isinstance(j, dict): prune_tree(j) if can_prune(j): if is_accuracy_improved(tree): del t[hash(str(j))]
def get_ws(): """ get workspace root and name """ if "WORKSPACE_ROOT" not in os.environ: ws_dir = os.path.join(Path(__file__).parents[0],'workspaces') else: ws_dir = os.environ['WORKSPACE_ROOT'] if len(ws_dir)==0: ws_dir = os.path.join(Path(__file__).paren...
This function updates the workspace environment by modifying the .env file with specified root and name parameters, defaulting to the current workspace root and 'main' if unspecified. It replaces WORKSPACE_ROOT and WORKSPACE_NAME entries, reloads environment variables, and ensures local directories are set up.
def set_workspace(root='',name=''): """ sets the workspace environment .env file and environment variables using specified root and name params. If root is not specified then this uses the current workspace's root. """ if root=='': root, _ = get_ws() # root = os.path.jo...
def get_database(): """ retrieves the CURRENT_SCHEMA property of DB_SETTINGS object """ return DB_SETTINGS['CURRENT_DATABASE'] def get_schema(): """ retrieves the CURRENT_SCHEMA property of DB_SETTINGS object """ return DB_SETTINGS['CURRENT_SCHEMA'] def py_connect_db(warehouse = ...
The main task of the code is to execute an SQL query against a database (using DuckDB for CSV files or a connection for other formats), process the resulting data by converting date columns to datetime objects, handle caching of results if enabled, and return the processed DataFrame while validating data existence and ...
def run(self, database='', schema=''): # print(DB_SETTINGS) if database=='': database=get_database() if schema=='': schema=get_schema() # print('schema is', schema) if '.csv' in self.sql.text: df = duckdb.sql(self.sql.text).df() else:...
def compile(template='total_aggs.sql',*args,**kwargs): """ creates sql queries by injecting into template or takes a string query and substitues params """ environment = Environment(loader=FileSystemLoader([ get_user_template_dir(), get_user_tests_template_dir(), get_global_...
This code initializes an object to handle SQL query processing, determining if the query is a template or ad-hoc, compiling it, and managing caching logic. It disables caching if the template references CSV files or if the query is ad-hoc. It sets up attributes for SQL text, templates, cache status, and CSV files, ensu...
def __init__(self, query='aggregate_user_data.sql', cache=True, **kwargs) -> None: self.query = query # query can be sql command string or template file name self.sql=None self.template=None self.cache = cache self.df = None self.tests = {} self.core_attributes =...
def is_cached(self): if self.cache: if (os.path.exists(self.get_cache_files()[0])): return True else: return False else: if not self.template: return False else: return def cache_is_s...
The main task of the code is to load data by checking if it exists in a cache. If cached, it verifies synchronization with the current SQL; if synced, it reads the cached CSV file into a DataFrame. If not synced or no cache exists, it executes `.run()` to generate the data. The result is stored in `self.df` and returne...
def load(self): """ loads from cache if present, otherwise call .run() """ if self.is_cached(): cache_file=self.csv if self.cache_is_synced(): # check data.sql matches current compiled sql - if it doesn't then rerun df = pd.read_csv...
def escape_url(url): return html.escape(url, quote=True) def escape_str(s): assert s is not None return html.escape(s) def do_feed_entry(entry, logf): global API_KEY rnd = secrets.SystemRandom() title, summary = entry.title, entry.summary prompts = [f'{title} {summary}'] for what in [title, summary]:...
This code generates HTML content from RSS feed entries by creating clickable image links for each entry. It logs processing details, generates images via do_feed_entry, resizes them, and creates individual HTML files with entry metadata and images. The main output is a combined HTML string with formatted entry links an...
def do_feed(entries : list[Entry], logf): global requests_rss body = [] for i, entry in enumerate(tqdm.tqdm(entries)): title = entry.title url = entry.url summary = entry.summary logf.flush() logf.write(f'\tENTRY {i}. "{title}" | "{summary}" | {url}\n') body.append(f'<a href="{escape_url...
def install_caches(): global requests_rss, requests_stability_ai hour_session = requests_cache.CachedSession('http_cache_hour', expire_after=3600, allowable_methods=('GET', 'POST')) month_session = requests_cache.CachedSe...
The main task of the code is to generate an HTML page from randomly selected feed entries. It copies a style sheet to the output directory, retrieves and samples feed entries, reads an API key from a file, processes the entries into HTML content, and writes the result to an index.html file along with a log.txt file.
def main(_): global API_KEY assert os.path.isdir(FLAGS.outdir) install_caches() shutil.copy2('style.css', FLAGS.outdir) entries = get_all_feed_entries() entries = secrets.SystemRandom().sample(entries, FLAGS.max_entries) # requests_cache.install_cache(expire_after=3600, allowable_methods=('GET', 'POST'...
def import_dataset(csv_file): tweets = pd.read_csv(csv_file, sep=';', encoding = 'ISO-8859-1') print(tweets.head()) return tweets def preprocess(tweets): tokenized_tweets = [] # prepare stopwords stop_words = stopwords.words('english') # removing URLS tweets.text = tweets.text.apply(lambda x: re.sub(u'http\S+'...
The code's main task is to open a CSV file containing tweets, load and preprocess the text data, then apply Latent Dirichlet Allocation (LDA) for topic modeling. It uses a file dialog to select the input file, processes the dataset, and performs LDA to identify underlying topics in the tweets.
def open_file(): filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("csv files","*.csv"),("all files","*.*"))) tweets = import_dataset(filename) data_lemmatized = preprocess(tweets) lda(data_lemmatized)
def import_dataset(csv_file): try: tweets = pd.read_csv(csv_file, sep=';', encoding = 'ISO-8859-1') print(tweets.head()) return tweets except Exception as e: # raise e print("error2") def preprocess(tweets): tokenized_tweets = [] # prepare stopwords stop_words = stopwords.words('english') # removing UR...
The main task of the code is to process a dataset for LDA topic modeling. It imports data from a file, preprocesses text (e.g., lemmatization), applies LDA, and handles errors by displaying the StartPage frame. The code uses a controller to navigate UI states and includes exception handling to log errors and revert to ...
def logic(self, controller): try: # print(StartPage.file) print(FILENAME) tweets = import_dataset(FILENAME) data_lemmatized = preprocess(tweets) lda(data_lemmatized) except Exception as e: print(FILENAME) raise e print("error") controller.show_frame(StartPage)
def import_dataset(csv_file): try: tweets = pd.read_csv(csv_file, sep=';', encoding = 'ISO-8859-1') print(tweets.head()) return tweets except Exception as e: # raise e print("error2") def preprocess(tweets): tokenized_tweets = [] # prepare stopwords stop_words = stopwords.words('english') # removing UR...
The code processes a text dataset by importing, preprocessing (lemmatization), and applying LDA topic modeling. It handles exceptions by printing "error" without re-raising them.
def logic(filename): try: tweets = import_dataset(filename) data_lemmatized = preprocess(tweets) lda(data_lemmatized) except Exception as e: # raise e print("error")
def one(puzzle: list) -> int: passports = list_to_passports(puzzle) valid = 0 for p in passports: if has_required_fields(p): valid += 1 return valid def list_to_passports(puzzle: list) -> list: passports = [] p = "" for line in puzzle: if line != "": ...
The code tests the validity of passport data entries according to specific rules. It verifies that the `one()` function correctly counts valid passports in the first example list, then checks that `is_valid()` correctly identifies invalid passports in the `invalid_examples` list and valid ones in the `valid_examples` l...
def test(): example = [ "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd", "byr:1937 iyr:2017 cid:147 hgt:183cm", "", "iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884", "hcl:#cfa07d byr:1929", "", "hcl:#ae17e1 iyr:2013", "eyr:2024", "ecl:brn pid:760...
def flowerSignature(adj): counts = sorted(sum(row) for row in adj) petalRank = counts[0] return petalRank, petalRank >= 2 and counts[-1] == len(adj) - 1 and all(petalRank == c for c in counts[:-1]) def isSelfConnecting(adj): return any(adj[i][i] for i in range(len(adj))) def getNPetals(adj): remove...
The code validates if a graph meets specific structural conditions: it checks if the graph isn't self-connected, if the product of petal count and petal rank equals the number of edges minus one, and if the solution signature is valid. It returns True only if all these conditions are satisfied.
def solution(adj): petalRank, solutionSignature = flowerSignature(adj) return solutionSignature and not isSelfConnecting(adj) and getNPetals(adj) * petalRank == len(adj) - 1
def test_sp(arr): #for x in range(len(arr)): for x in arr: sp = find_split_point(arr, 0, 16, x) print(f'{x} is at {sp}') print(f'\tEND test_sp') def test_pmergeaux(arr) : a2 = [ 5, 15, 7, 9, 13, 13, 13, 19, 14, 8, 5, 11, 2, 9, 9, 4] a2 = np.sort(a2) combined = np.concatenate((arr, a2), axis=None) print(co...
The code's main task is to test and compare a parallel merge sort implementation against standard sorting. It initializes and sorts an array, then tests functions like `test_sp`, `test_pmergeaux`, and `test_pmerge` for parallel merge logic. Finally, it verifies if a custom `my_api_pms` function correctly sorts a large ...
def main(): #arr_num = np.random.randint(20, size=16) arr_num = [17, 19, 7, 2, 8, 5, 13, 9, 11, 19, 18, 11, 6, 0, 12, 6] print(arr_num) arr_num = np.sort(arr_num) print(arr_num) #sp = find_split_point(arr_num, 0, 16, 7) #print(sp) test_sp(arr_num); test_pmergeaux(arr_num) test_pmerge(arr_num) #...
def mu(SL): return mu_l + (1+alpha*(SL-SL0)*100)*mu_nl def b(SL): return mu_l / mu(SL) def int1_(SL, k): return si.quad(int1, Z(SL, k), np.inf, args=(SL, k))[0] def int2_(SL, k): return si.quad(int2, 0, Z(SL, k), args=(SL, k))[0]
This function calculates the net profit $ R $ by combining revenue and cost terms. It uses $ p_r \times (\mu(SL) - (1 - b(SL)) \times \text{int1}(SL, k)) $ for revenue, subtracts $ b(SL) \times c_b \times \text{int1}(SL, k) $ for cost, and further subtracts $ c_h \times \text{int2}(SL, k) $ for holding costs, where $ \...
def profit_r(SL, k): return p_r * (mu(SL) - (1-b(SL)) * int1_(SL, k)) - b(SL)*c_b*int1_(SL, k) - c_h * int2_(SL, k)
def mu(SL): return mu_l + (1+alpha*(SL-SL0)*100)*mu_nl def b(SL): return mu_l / mu(SL) def int1_(SL, k): return si.quad(int1, Z(SL, k), np.inf, args=(SL, k))[0] def int2_(SL, k): return si.quad(int2, 0, Z(SL, k), args=(SL, k))[0]
This function calculates the profit for a given SL (stock level) and parameters k and buyback_percent, incorporating terms for revenue, holding costs, buyback costs, and buyback revenue. It combines these factors using integrals (int1_, int2_) and variables like mu(SL), b(SL), p_r, c_b, c_h, and p_b to determine the ne...
def profit_r1(SL, k, buyback_percent): return p_r * (mu(SL) - (1-b(SL)) * int1_(SL, k)) - b(SL)*c_b*int1_(SL, k) - (1-buyback_percent)*c_h * int2_(SL, k) + buyback_percent * p_b * int2_(SL, k)
def mu(SL): return mu_l + (1+alpha*(SL-SL0)*100)*mu_nl def b(SL): return mu_l / mu(SL) def int1_(SL, k): return si.quad(int1, Z(SL, k), np.inf, args=(SL, k))[0] def int2_(SL, k): return si.quad(int2, 0, Z(SL, k), args=(SL, k))[0]
The code calculates a profit metric based on parameters SL, k, and buyback_percent. It combines terms involving p_m, mu(SL), b(SL), and integrals int1_ and int2_ to compute a value that subtracts a buyback cost component. The function likely models financial or economic profit, incorporating adjustments for buyback per...
def profit_m(SL, k, buyback_percent): return p_m * (mu(SL) - (1-b(SL)) * int1_(SL, k)) - buyback_percent * p_b * int2_(SL, k)
def count_vectorize_fit_transform(x_list): vectorizer_binary = CountVectorizer(lowercase=True, preprocessor=None, binary=True, stop_words=None, tokenizer=preProcessAndTokenize) X = vectorizer_binary.fit_transform(x_list) print(" count vectorized with dimension : ",len(vectorizer_binary.get_feature_n...
This function generates text embeddings using specified methods (CountVectorizer, Word2Vec, or self-trained Word2Vec) on input text data. It trains the embedding model, saves it as a joblib file with a filename derived from parameters like embedding type, class group, and test size, then returns the transformed feature...
def embedding_fit_transform(x_list, embedding, class_group, sampling, test_size, masking): print("processing preprocessing.embedding_fit_transform ...") if embedding == 'cv': trained_embedding, X = count_vectorize_fit_transform(x_list) elif embedding == 'w2v': trained_embedding, X = pr...
def handle_sending_Packet(self,packet): pkt_type = packet [0] if pkt_type == Packet.UNICAST: pkt_type,seq,ttl,src,dst = Packet.read_header(packet) nextHop = self.get_nextHop(dst) if nextHop != None: s = socket (AF_INET, SOCK_DGRAM) pr...
This code sends packets via UDP, handling unicast, multicast, or tunneling based on destination count and user input. It creates packets, sends them, manages acknowledgments, and processes received packets for retransmission or handling.
def send_packet(self): s = socket (AF_INET, SOCK_DGRAM) s.bind((self.ip, self.port)) print("[x] Sender Reciving Packet on ",s.getsockname(),"\n") seq_num = 0 sent = False # if 1 dst send unicast if len(self.dst) == 1: dst = self.dst[0] pa...
def check_valid_input(s_expression): """ returns True if a single layer S_Expression is valid, else - False""" if s_expression[0] != '(' and s_expression[len(s_expression) - 1] != ')': temp = get_data_type(s_expression) if temp not in variable_types and temp not in variables: return...
This function simplifies nested expressions by recursively evaluating the innermost layers first. It identifies sub-expressions enclosed in parentheses, checks for complex numbers, validates the expression, and replaces each layer with its simplified value. The process continues until no nested layers remain, returning...
def simplify_layers(expression): """ receives an expression and simplifies all the layers in it """ if expression.startswith(';'): return if expression.startswith('(') and expression.endswith(')'): # until one layer is left while expression.startswith('(') and expression.endswith(')'...
def clean_input(inserted): """ cleans the input """ return inserted.strip().upper() def check_valid_input(s_expression): """ returns True if a single layer S_Expression is valid, else - False""" if s_expression[0] != '(' and s_expression[len(s_expression) - 1] != ')': temp = get_data_type(s_exp...
The function `run_a_list_of_code` executes a list of code lines, validating each line with `check_valid_input` and processing it with `simplify_layers`. It cleans input, reports errors for invalid lines, and prints simplified results for valid ones, iterating sequentially through the list.
def run_a_list_of_code(lst_of_code): """Executes a list of code. Necessary for Text-Editor and File mode. Perhaps for looping too.""" index = 1 for line in lst_of_code: line = clean_input(line) if not check_valid_input(line): print(f'Error in line {index}') break ...
def clean_input(inserted): """ cleans the input """ return inserted.strip().upper() def simplify_layers(expression): """ receives an expression and simplifies all the layers in it """ if expression.startswith(';'): return if expression.startswith('(') and expression.endswith(')'): # ...
The function `eval_lisp` evaluates a Lisp expression provided as a string. It first cleans the input using `clean_input`, then simplifies the expression's layers with `simplify_layers`, and finally matches and returns the appropriate type of the result via `match_types`. The core task is to parse, process, and return t...
def eval_lisp(lisp_code: str): """ The method receives a string that represents a lisp expression and evaluates it. The result is returned """ clean_code = clean_input(lisp_code) result = simplify_layers(clean_code) typed_result = match_types(result) return typed_result
def clean_input(inserted): """ cleans the input """ return inserted.strip().upper() def receive_expression(): expression = clean_input(input('>>> ')) while expression.count('(') != expression.count(')'): expression += ' ' + clean_input(input('... ')) return expression def simplify_layers(exp...
The code's main task is to provide a Lisp interpreter with three modes: REPL for real-time input, TEXT EDITOR for manual line entry, and FILE for importing code from a file. It processes user input, executes commands, collects results, and exports them, handling interruptions gracefully.
def run(): """ The main method.""" intro_font = Figlet(font='standard') print(intro_font.renderText('LISPER '), end='') print('Version 1.0.3') try: user_choice = clean_input( input('Choose your mode: REPL, FILE, OR TEXT EDITOR ')) if user_choice == 'REPL' or user_choic...
def find_min_player(self): return min(self.player_role_count, key=self.player_role_count.get) def find_min_role(self): return min(self.role_player_count, key=self.role_player_count.get) def remove_player(self, player): for k, v in self.players_per_role.items(): if player in v: ...
The main task of the code is to sort players into roles by iteratively assigning players to roles until at least 10 roles are filled. It checks for errors like insufficient players per role or invalid assignments, removes invalid players/roles, and uses different sorting strategies (single-role, instant, or value-based...
def main_sort(self): while sum((len(v) for v in self.resultant_roles.values())) < 10: lowest_role_player = self.find_min_player() lowest_player_role = self.find_min_role() if self.player_role_count[lowest_role_player] == 0: self.error_detected = True ...
def makeFactor(self, v, e, bn): #get probs out = {} node = bn.getNode(v) for child in [v] + node.children: var = [] par_val = [] factors = {} c_node = bn.getNode(child) if c_node.prob == {}: continue ...
The code performs variable elimination on a Bayesian network to compute the posterior probabilities of a query variable given evidence. It iterates over variables in reverse order, creating factors and summing out hidden variables not in the query or evidence. The result is normalized and returned as a probability dist...
def variableElimination(self, query, evidence, bn): if query in evidence.keys(): print("NOPE") quit() factors = {} #3d dict [v][string of parents][v.domain val] # instead of reversed do we need a heuristic for ordering for v in reversed(bn.variables): ...
def create_users(self): user_list = [] # generate data for i in range(self.agent_count): user = self.create_user(is_agent = True) user_list.append(user) for i in range(self.customer_count): user = self.create_user(is_agent = False) user_lis...
The main task of the code is to generate a synthetic database by creating randomized tables/entities such as users, agents, customers, policies, options, and policy-options relationships. It initializes a reproducible random seed and sequentially populates database structures with predefined data through multiple creat...
def generate_database(self): random.seed(self.random_state) self.create_users() self.create_agents() self.create_customers() self.create_policies() self.create_options() self.create_policy_options() self.create_claims()
def Set_WindmillHeight(self,value): self.height = value def Set_WindmillRadius(self, value): self.radius = value def InitializeWindMarkers(self): self.clear_marker_event() #Reset the markers every time this is called self.UpdateWindmillParams() for i in range(0, city_latlong.shap...
This function initializes a UI for configuring wind turbine parameters and displaying a map. It clears existing widgets, sets default height/radius values, creates a left panel with input controls and a segmented button for renewable type, and a right panel with a map widget. The map is centered on Lebanon, Kansas, wit...
def WindStartMap(self): for i in self.master.winfo_children(): i.destroy() self.marker_list = [] try: #This checks if height has been defined at all self.height = self.height #This allows app to keep values once changed by user except Exception as ex: ...
def Set_PanelArea(self,value): self.Area = value def Set_PVEfficiency(self, value): self.Efficiency = value def InitializeSolarMarkers(self): for i in range(0, city_latlong.shape[0]): self.UpdateSolarParams() self.marker_list.append( self.map_widget.set_ma...
This code initializes a solar energy mapping interface by clearing existing widgets, setting default parameters for panel area and efficiency, creating a UI with input controls, and embedding a map widget with solar markers. It configures a left panel for parameter adjustment and a right panel for map visualization, en...
def SolarStartMap(self): for i in self.master.winfo_children(): i.destroy() self.marker_list = [] try: #This checks if parameters has been defined at all self.Area = self.Area #This allows app to keep values once changed by user except Exception as ex: ...
def _lock(self, name: str): try: self.pabotlib.acquire_lock(name) yield finally: self.pabotlib.release_lock(name) def _open_cache_file(self) -> CacheContents: shared_cache = self.pabotlib.get_parallel_value_for_key(self.parallel_value_key) # If not set...
The main task of the code is to store a JSON-serializable value in a cache with an expiration time. It uses a lock for thread safety, creates a cache entry with the value and expiration timestamp, updates the cache dictionary, and persists it to a JSON file. The function supports common data types and allows custom exp...
def cache_store_value(self, key: CacheKey, value: CacheValue, expire_in_seconds=3600) -> None: """ Store a value in the cache. The value to be stored must be able to be stored in JSON. Supported values include (but are not limited to): - String - Integer - Float...
def _lock(self, name: str): try: self.pabotlib.acquire_lock(name) yield finally: self.pabotlib.release_lock(name) def _open_cache_file(self) -> CacheContents: shared_cache = self.pabotlib.get_parallel_value_for_key(self.parallel_value_key) # If not set...
This function removes a specified key from a cache, ensuring thread safety via a lock. It opens the cache file, checks if the key exists, deletes it if present, updates parallel value tracking, and persists the modified cache to a JSON file.
def cache_remove_value(self, key: CacheKey) -> None: """ Remove a value from the cache. | `key` | Name of the stored value | = Examples = Remove a value from the cache | Cache Remove Value user-session """ with self._lock("cachelib-edit"): ...
def _open_cache_file(self) -> CacheContents: shared_cache = self.pabotlib.get_parallel_value_for_key(self.parallel_value_key) # If not set, `shared_cache` will be an empty string. if isinstance(shared_cache, dict): return shared_cache cache_file_contents = self._read_json_fi...
The function retrieves a value from the cache using the provided key. If the key does not exist or the cached entry is expired, it returns `None`. Otherwise, it returns the stored value. It first checks the key's presence, verifies expiration, and removes expired entries before returning the result.
def cache_retrieve_value(self, key: CacheKey) -> CacheValue: """ Retrieve a value from the cache. Will return the value stored in the cache, or `None` if it does not exist. | `key` | Name of the stored value | = Examples = == Basic usage == Retrieve a value f...
def createLabelBar(self): frame_labels, bbox_labels=self.labelset.getLabelNames() self.labelBar=QToolBar("labeling") self.labelBar.addWidget(QLabel("Frame Labels: ")) self.frame_label_selection=QComboBox() self.frame_label_selection.addItems(frame_labels) self.labelBar.a...
The code initializes a video player application with label annotation capabilities. It sets up data handling, label color mapping, UI components (window, timers, docks), and integrates a video frame display with interaction features for managing bounding boxes, including cycling through labels, removal, and rendering f...
def __init__(self, data, labels, *args, **kwargs): super(Player, self).__init__(*args, **kwargs) self.data=Dataset(data) self.file_list=[] for f in self.data.get_files(): self.file_list.append(f.split("/")[-1]) self.labelset=LabelSet(self.file_list, labels[0], label...
def get(self, x, y): """Get the value of one square.""" return self.Matrix[x, y] def shift(self, row, direction): """Shift one row left (direction == 0) or right (direction == 1), combining if required.""" length = len(row) assert length == self.size #assert direction == ...
The main task of the code is to perform a single game move in a specified direction (up, right, down, left) by shifting and combining tiles, calculating the resulting score, and updating the game state if changes occur. It logs the direction (if not a trial), processes rows/columns based on the direction, shifts tiles ...
def move(self, direction, trial=False): """Perform one move of the game. Shift things to one side then, combine. directions 0, 1, 2, 3 are up, right, down, left. Returns the score that [would have] got.""" if not trial: if direction == 0: logging.debug("Up") ...
def move(self, direction, trial=False): """Perform one move of the game. Shift things to one side then, combine. directions 0, 1, 2, 3 are up, right, down, left. Returns the score that [would have] got.""" if not trial: if direction == 0: logging.debug("Up") ...
This method executes one game step by applying a move, updating the score, adding a new tile, and checking game end. It returns the updated board state, reward (based on move score), a done flag, and info including the highest tile. Illegal moves trigger no reward and a 'done' status of False.
def step(self, action): """Perform one step of the game. This involves moving and adding a new tile.""" logging.debug("Action {}".format(action)) score = 0 done = None try: score = float(self.move(action)) self.score += score assert score <= 2*...
def get_archived_contents(): archived_contents = [] archived_files = os.listdir('./archived') for file in archived_files: content = '' with open('./archived/' + file, mode='r', encoding='utf-8') as f: content = f.read() archived_contents.append(content) return archive...
The main task of the code is to scrape programming language data (including 'java', 'python', etc.) and generate markdown files comparing scraped results with pre-archived contents. The function iterates through a list of languages, executes scraping for each, and writes output using archived data as a reference.
def job(): ''' Get archived contents ''' archived_contents = get_archived_contents() ''' Start the scrape job ''' languages = ['', 'java', 'python', 'javascript', 'go', 'c', 'c++', 'c#', 'html', 'css', 'unknown'] for lang in languages: results = scrape_lang(lang) write_markd...
def success_dialog(self): dialog = QMessageBox(self) dialog.setText("Success!") dialog.show() button_ok = dialog.buttons()[0] button_ok.clicked.connect(self.reset_state) def radio_btn_interact(self): # self.reset_state() self.open_file_btn.setEnabled(True) ...
The main task of the code is to execute PDF operations based on user-selected mode. If "split" is chosen, it splits the selected PDF using customized pages and shows a success dialog. If "merge" is chosen, it counts pages of selected files and opens a file name form for merging. The method interacts with UI elements to...
def execute_operation(self): if self.split_radio_btn.isChecked(): pdf_splitter(self, self.selected_files[0], self.customized_pages) self.success_dialog() self.radio_btn_interact() elif self.merge_radio_btn.isChecked(): self.pages = count_pdf_pages(self.se...
def get_cookie(url): home = os.environ['HOME'] data = yaml.load(open(f"{home}/.flyrc")) for target in data["targets"]: api = data["targets"][target]["api"] if api == url: cookie = "\"Bearer " + data["targets"][target]["token"]["value"] + "\"" return cookie return ...
This code retrieves build data from a CI/CD system using authentication cookies, filters completed builds (failed/succeeded), aggregates failure details from specified builds, and outputs results including failure URLs. It processes build summaries, identifies relevant runs, and compiles failure information for analysi...
def main(url, team, pipeline, job, number_of_builds, authorization_cookie, threaded): cookie = get_cookie(url) authorization_cookie = {u'skymarshal_auth0': cookie} builds = get_builds_summary_sheet(url, team, pipeline, job, number_of_builds+10, authorization_cookie) build_to_examine = get_builds_to_ex...
def reset(self) -> np.ndarray: self.bar = self.lag self.data_ = deepcopy(self.data) self.day_price = self.init_price = self._get_current_price() self.initial_account__reset = self.initial_account # reset() self.account = self.initial_account__reset self.units = 0.0 ...
The code visualizes cumulative returns of a trading agent (using a given model) versus a buy-and-hold strategy over time. It simulates the agent's performance by iterating through steps, calculating total assets, and plotting both strategies' returns on a graph to compare their effectiveness in a financial environment.
def draw_cumulative_return(self, model) -> list: state = self.reset() state = np.reshape(state, [1, self.lag, self.n_features]) episode_returns = list() episode_returns.append(1) buy_hold_returns = list() for i in range(self.max_step): adj = self....
def testCreatePhonebook(): print("Testing createPhonebook()...", end="") assert(createPhonebook(["Kelly", "Margaret", "Kelly"], ["0000", "1234", "9876"]) == { "Kelly" : "0000", "Margaret" : "1234" }) assert(createPhonebook(["Rebecca", "Ellie", "Gayatri", "Rishab"], ["5", "3", "7", "1"]) == { "Rebecca" : "5"...
The code defines a function `testAll()` that sequentially executes four test functions: `testCreatePhonebook()`, `testCreateAuthorMap()`, `testGetStartingTeams()`, and `testEvaluateExpression()`. Its main task is to run a suite of tests to validate the correctness of functionalities related to creating phonebooks, auth...
def testAll(): testCreatePhonebook() testCreateAuthorMap() testGetStartingTeams() testEvaluateExpression()
def parseExpr(expr): parsed = {"value" : "", "children" : [], "powered" : False } expr = expr.strip() if expr[0] == "(" and findMatchingParen(expr, 0) == len(expr) - 1: parsed = parseExpr(expr[1:-1]) elif " " not in expr: parsed["value"] = expr elif expr[...
The main task of the code is to parse, validate, and generate a truth table for a user-input boolean expression. It prompts the user for an expression, attempts to parse and validate it, and if successful, outputs a truth table. Errors during parsing or validation trigger appropriate error messages. The parsed expressi...
def runProgram(): print("Enter a boolean expression:") expr = input() try: parsedExpr = parseExpr(expr) try: worked = validateExpr(parsedExpr) print("Valid Expression Succesfully Parsed :)") #print(parsedExpr) makeTruthTable(parsedExpr) ...
def parseExpr(expr): parsed = {"value" : "", "children" : [], "powered" : False } expr = expr.strip() if expr[0] == "(" and findMatchingParen(expr, 0) == len(expr) - 1: parsed = parseExpr(expr[1:-1]) elif " " not in expr: parsed["value"] = expr elif expr[...
This function handles keyboard inputs to manipulate a logical expression. It deletes the last character with BackSpace, evaluates the expression with Enter, generates a truth table with Tab, and appends other characters to the expression. It uses parsing and circuit execution for evaluation, with error handling for inv...
def keyPressed(data, event): if event.keysym == "BackSpace": if len(data["expression"]) > 0: data["expression"] = data["expression"][:-1] elif event.keysym == "Return": try: data["tree"] = parseExpr(data["expression"]) runInitialCircuit(data) except: ...