dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def grpPrep(varCount): g=list() for i in range(varCount+1): g.append([]) return g def decimalToBinary(n,varCount): t = bin(n).replace("0b", "") if len(t)<varCount: t= '0'*(varCount - len(t)) + t return t def pairing(col,varCount,i=0): col.append([]) col[i+1]=(grpPrep(varC...
The code implements the Quine-McCluskey algorithm to simplify Boolean expressions by determining minimal prime implicants. It processes minterms and don't-care terms, groups them by binary 1s, pairs terms to identify prime implicants, constructs a prime implicant chart, finds essential prime implicants (EPI), and handl...
def QMC(minterms , dontCareMint=[],varCount=4): col=[[],[]] col[0]=(grpPrep(varCount)) decMinterms= set(list(map(int,minterms.strip().split()))).union(set(dontCareMint)) for minterm in decMinterms: col[0][bin(minterm).count("1")].append([decimalToBinary(minterm,varCount),[minterm], 0,[]]) ...
def grpPrep(varCount): g=list() for i in range(varCount+1): g.append([]) return g def pairing(col,varCount,i=0): col.append([]) col[i+1]=(grpPrep(varCount)) p=[1,2,4,8,16,32,64,128] anyPairing = 0 for gc in range(varCount): if col[i][gc]: for termA in col[i][g...
The code implements the Quine-McCluskey algorithm to minimize Boolean functions by identifying essential prime implicants (EPIs) from given minterms and don't-care terms. It groups terms by binary 1s, pairs adjacent terms to find prime implicants, constructs a prime implicant chart, and iteratively reduces uncovered mi...
def MQMC(minterms , dontCareMint=[],varCount=4): col=[[],[]] col[0]=(grpPrep(varCount)) decMinterms= set(list(map(int,minterms.strip().split()))).union(set(dontCareMint)) for minterm in decMinterms: col[0][bin(minterm).count("1")].append( [ [minterm] , 0 , 0 ] ) pairing(col,varCount) P...
def group_selection(self) -> NumberGenerator: groups = self.get_groups() # print(f'groups: {groups}') if len(groups) <= 1: return self random_group = random.sample(groups, k=1)[0] print(f'selected group: {random_group}') for index, value in iter(self.basis_map...
The main task of the code is to validate and adjust traits based on "must" and "must-not" conditions in the configuration. It iteratively checks if required traits exist and ensures excluded traits are absent, adding/removing traits as needed with specific weights and probabilities until all conditions are satisfied.
def condition_correcting(self) -> NumberGenerator: print('in condition correcting') correct = False while not correct: self.group_selection() correct = True if "must" in self.config["conditions"]: for key, value in self.config["conditions"]["mu...
def check_correctness(month_range: MonthRange) -> None: time_entries = get_time_entries(month_range) try: check_if_empty(time_entries) check_reasonable_time(time_entries) check_if_overlapping(time_entries) except Exception as e: logging.warning(f"Raised exception {e} while ch...
The main task of the code is to download specific reports (SUM, DET in PDF/CSV) and an invoice (XLSX) for a given month and year, after validating the input parameters. It uses parsed arguments to determine the time frame, authenticates with fixed credentials, and triggers downloads for predefined report types and form...
def run(args: argparse.Namespace): month_range = MonthRange(args.month, args.year) check_correctness(month_range) download_report(USERNAME, PASSWORD, ReportType.SUM, FileExtension.PDF, month_range) download_report(USERNAME, PASSWORD, ReportType.DET, FileExtension.PDF, month_range) download_report(...
def fillcircle(centlist, vff): # fill possible additional circles if possible og = len(centlist) print("start", og) i = 0 while i < len(centlist): # overlap # tilt one degree if centlist[i][1] > 0.8 or centlist[i][1] < 0 or centlist[i][0] > 0.8 or centlist[i][0] < 0: ...
The function allows manual movement of selected circles in a graphical model, validating new positions within bounds and checking for overlaps. It handles user input for circle selection, adjusts coordinates, reverts invalid moves, and updates the display with filled circles or adjustments.
def movespaced(centlist, vff, tol, width, height): # manual moving of individual selected circles answer = input( f"type in the numbered circle (current max = {len(centlist)}) : ") while not answer.isnumeric(): answer = input( "invalid input, try again. Type in the numbered circl...
def modelprint(width, height, lw, vff, centlist): # plot function # generate model print(len(centlist)) print('FVF:', vff, '\n') # The final FVF fig = plt.figure() ax = fig.add_subplot(111) rectan = Rectangle((0, 0), width, height, linewidth=lw, edgecolor='red', facecolor='w', ...
The code recursively processes elements in 'centlist', adjusting each element using 'closein' and incrementing the index until all elements are processed. When the index reaches the list's end, it triggers 'modelprint' with parameters derived from 'centlist' and 'vff', likely generating a model or visualization. The re...
def recursion(index, centlist, possiblecircles, vff): if index == len(centlist): modelprint(width, height, 0.8, vff, centlist) else: centlist = closein(centlist[index], index, centlist, rmax*2+tol, tol) index = index + 1 recursion(index, centlist, possiblecircles, vff)
def plot_marginal_pdf(self, n_samples, ax): if self.n_dim not in [1, 2]: raise NotImplementedError pdf_samples = self.sample_pdf(n_samples) marginal = pdf_samples.mean(axis=0) if self.n_dim == 1: ax.plot(self.X.reshape(-1), marginal) ax.scatter(self.ob...
The main task of the code is to generate a visualization with three subplots: plotting the marginal probability density function (PDF), sampling from the PDF, and displaying unnormalized log PDF samples. It uses `matplotlib` to create a horizontal layout, calling three distinct methods to render each subplot, aiding in...
def plot(self): fig, axes = plt.subplots(ncols=3, figsize=(16, 4)) self.plot_marginal_pdf(1000, axes[0]) self.plot_pdf_samples(10, axes[1]) self.plot_unnormed_logpdf_samples(10, axes[2])
def use_sea_born_cal__(use_sea_born, tuple_len): if tuple_len == 1: return True return use_sea_born def plot_sub_scatter_plot(axes, data, i, j, k, l, tuple_len, use_sea_born_calculated): """ place sub scatter plot on main pair scatter plot :param axes: axes :param data: data list :pa...
The function `scatter_plot` generates a grid of pairwise scatter plots to visualize correlations between variables in the provided data. It accepts a list of data points and indexes to determine variables, using either seaborn or matplotlib (default). It creates a square grid of subplots, plotting each variable pair (x...
def scatter_plot(data: list, indexes: list, use_sea_born=False, title=None): """ Generate pair scatter plots against each item. Can be used to find correlation. Default seaborn only accept DataFrame. This has been customized single scatter plot which accepts list as x and y, to generate pair scatter plo...
def emitState(self): """ Thread-safe emit state changed signal """ # Assume the main thread owns the asyncio loop if threading.main_thread() == threading.currentThread(): self._emitState() else: self._main_loop.call_soon_threadsafe(self._emitState...
The code starts a live HLS preview stream without saving to a file by launching an FFmpeg process in a separate thread, ensuring the system is in the 'idle' state first. It constructs a command with input settings, HLS filters, and output parameters, then transitions the state to 'previewing' while executing the stream...
def start_preview(self): """ Start a preview HLS output stream, but don't save anything to file """ # Only permit starting preview from idle if self.state != STATE_IDLE: return False self.state = STATE_STARTING_PREVIEW self.emitState() self.p...
def emitState(self): """ Thread-safe emit state changed signal """ # Assume the main thread owns the asyncio loop if threading.main_thread() == threading.currentThread(): self._emitState() else: self._main_loop.call_soon_threadsafe(self._emitState...
The main task of the code is to initiate video recording to a file and generate an HLS output stream for real-time monitoring. It checks if the device is already in use, stops existing preview processes, prepares HLS settings, constructs an ffmpeg command with duration, output paths, and streaming parameters, then star...
def start_recording(self): """ Start a video capture to file and an generate an HLS output stream for monitoring """ if self.state == STATE_RECORDING or self.state == STATE_STARTING_RECORDING: # Already recording or starting to record return False # Previ...
def gen_passenger_threat_level(): """ Randomly spawn bad actors in passengers Set a threat level of high for dangerous ones (need arrest) Medium is for bad details (reject) None are all good passengers """ chance = rand(1, 100) if chance < 15: return "high" if...
This code initializes a passenger object by generating manifest (M_) and implant (I_) records with randomized or generated attributes like threat level, ticket tokens, cabin details, personal information, and biometrics. It duplicates M_ values into I_ fields, ensuring both records are synchronized. The task involves s...
def __init__(self): """ Init field data and generate field values where needed M_ are manifest records I_ are implant records """ self.threat_level = gen_passenger_threat_level() self.boarding_status = "" self.record_decrypted = False s...
def draw_box(line, col, width, height, fill, style, scr): """ Draw a window, takes starting position line & col. If fill is set True then insert spaces to fill window Width and height for size and style is curses color pairing. Also takes curses screen/pad we need to use """ ...
The code implements a game where the player decrypts a record by guessing an encryption key. The game generates a key of varying length (based on difficulty) and displays it among randomly placed fake keys. The player has 5 attempts to input the correct key, receiving real-time feedback on each character's accuracy. Su...
def decrypt_record_game(scr): """ Player gets 5 chances to work out the encryption key. Random key generated and displayed with mix of fakes. Player gets feedback on entered string """ c.DRG_ACT = True drgwin = curses.newwin(52, 81) for i in range(51): draw_box(51 - ...
def invalid_dt_bookid(): """Function which Displayes ID should be a integer between 1-5 when execption occer while assigning book ID""" print("\n***********************************\n ID should be a integer between 1-5\n***********************************\n") def invalid_dt(): """Function which Displayes whe...
The function `return_book` processes returning a book by validating user inputs for book ID and borrowed days, calculating potential fines, updating the book's quantity in the inventory (data_list) via `add_book`, and displaying the updated inventory. It handles input errors with exception handling and directs to error...
def return_book(data_list, display_book,name): """Function to take book ID. If valid ID is entered call other functions else call error function""" '''initializing boolean variables''' flag = True vld = True vld1 = True '''Exception handling''' while vld == True: try: boo...
def create_dataset_generator(datapath, datatype, batch_size=16, image_size=(512, 512), data_percentage=1.0, create_dist=False, four_channels=False, transform=False): heigth, width = image_size data_dir = os.path.join(datapath, datatype, "img_dir") print(data_dir) img_paths = [os.path.join(da...
This function generates a dataset by processing input images with a pre-trained model, applying transformations like softmax, dilation, and line detection, then saving processed images, annotations, masks, and gradients into structured directories. It checks for existing data, loads a model, processes each image batch,...
def create_dataset_from_model(dataset, dataset_type, args): base_path = os.path.join("data", args.load_model + "_large_building_area") print(args) if os.path.exists(base_path) and args.overwrite_dataset == False: print("Data already exists, and overwrite is False") return ...
def getWikiDataItemtifier(self): query = """ select ?wikicode { ?wikicode rdfs:label ?plabel . FILTER(?plabel = 'Wikidata QID'@en) . FILTER(lang(?plabel)='fr' || lang(?plabel)='en') } limit 1 """ self.sparql.setQuery(query) ...
This code reads a CSV file, processes each row to generate structured claims with properties and objects, handles qualifiers if present, and stores them in a dictionary. It skips invalid rows, logs errors, and uses Wikipedia data identifiers to create claims, primarily for knowledge graph or semantic data processing ta...
def read_file_and_process(self, file_url): claims_hash = {} self.getWikiDataItemtifier() with open(file_url) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if (line_count == 0): ...
def resunet_encoder(input_layer, model_size, reg_weight, name): x = tf.keras.layers.Conv2D(model_size[0], (3,3), padding='same', name = f'{name}_e0_conv_1')(input_layer) x = bn_relu(x, name = f'{name}_e0_bnrelu') x = tf.keras.layers.Conv2D(model_size[0], (3,3), padding='same', name = f'{name}_e0_conv_2')(x)...
The code defines a ResUNet model for image segmentation, constructing an encoder-decoder architecture with residual connections. It takes input data, processes it through an encoder to extract features, decodes these features to refine spatial resolution, and classifies outputs into `n_output` categories. The model inc...
def resunet(shape, model_size, n_output, reg_weight, name): input_layer = tf.keras.Input(shape, name=f'{name}_input') encoder_outs = resunet_encoder(input_layer, model_size, reg_weight, name = f'{name}_encoder') decoder_outs = resunet_decoder(encoder_outs, model_size, reg_weight, name = f'{name}_decoder') ...
def resunet_encoder(input_layer, model_size, reg_weight, name): x = tf.keras.layers.Conv2D(model_size[0], (3,3), padding='same', name = f'{name}_e0_conv_1')(input_layer) x = bn_relu(x, name = f'{name}_e0_bnrelu') x = tf.keras.layers.Conv2D(model_size[0], (3,3), padding='same', name = f'{name}_e0_conv_2')(x)...
This function creates a ResUNet model that fuses optical and SAR data early by concatenating encoder outputs from both modalities, then decodes and classifies the fused features. It takes two inputs, processes them through separate ResUNet encoders, combines their outputs, and uses a decoder/classifier to produce the f...
def early_fusion_resunet(shape_opt, shape_sar, model_size, n_output, reg_weight, name): #optical stream opt_input= tf.keras.Input(shape_opt, name=f'{name}_input') opt_encoder_outs = resunet_encoder(opt_input, model_size, reg_weight, name=f'{name}_opt_encoder') #sar encoder sar_input= tf.keras.Inp...
def resunet_encoder(input_layer, model_size, reg_weight, name): x = tf.keras.layers.Conv2D(model_size[0], (3,3), padding='same', name = f'{name}_e0_conv_1')(input_layer) x = bn_relu(x, name = f'{name}_e0_bnrelu') x = tf.keras.layers.Conv2D(model_size[0], (3,3), padding='same', name = f'{name}_e0_conv_2')(x)...
The function implements a late-fusion ResUNet model that processes optical and SAR imagery separately through encoder-decoder networks, concatenates their decoder outputs, and applies a classifier to generate multi-class outputs. It leverages dual-stream feature extraction followed by cross-modal fusion for tasks like ...
def late_fusion_resunet(shape_opt, shape_sar, model_size, n_output, reg_weight, name): #optical stream opt_input= tf.keras.Input(shape_opt, name=f'{name}_input') opt_encoder_outs = resunet_encoder(opt_input, model_size, reg_weight, name=f'{name}_opt_encoder') opt_decoder_outs = resunet_decoder(opt_enc...
def se_block(x, ch_size): sp_exc = tf.keras.layers.Conv2D(1, (1,1), padding='same', activation='sigmoid')(x) sp_out = tf.keras.layers.Multiply()([sp_exc , x]) ch_exc = tf.keras.layers.GlobalAvgPool2D()(x) ch_exc = tf.keras.layers.Dense(int(ch_size/2), use_bias=False)(ch_exc) ch_exc = tf.keras.laye...
This function constructs a neural network model that fuses features from two pre-trained models (model_1 and model_2) and a CMAP input. It freezes the pre-trained models, extracts penultimate layer outputs, concatenates them with the CMAP input, applies a 1×1 convolution and SE block for feature refinement. The fused f...
def opt_post_cmap_resunet(model_1, model_2, shape_cmap, model_size, n_output, reg_weight, name): input_1 = model_1.input input_2 = model_2.input input_3 = tf.keras.Input(shape_cmap, name = 'cmap_input') model_1.trainable = False model_2.trainable = False model_1_out = model_1.get_layer(index=-...
def Make_binary_image(self, x, y): #print(x, y) norm_x = np.array(x) - min(x) + 1 norm_y = np.array(y) - min(y) + 1 img = np.zeros((self.hull_width + 2, self.hull_height + 2)) for xx, yy in zip(norm_x, norm_y): img[xx, yy] = 1 return img def Make_image(self, x...
The code calculates key features for cluster classification, including energy statistics (volume, median, deciles), geometric properties (hull dimensions, area, occupancy), binary/image representations, skeletonization, and shape descriptors (radius, diameter, curvature). It processes track data to derive structural an...
def Calculate_features(self): # Extracts the features important for the classification of clusters x = list(map(int, self.track[0::3])) y = list(map(int, self.track[1::3])) energy = list(map(float, self.track[2::3])) points = list(zip(x, y)) self.volume = sum(energy) ...
def move_element_from_last_column(board, value_cell, empty_cell): """ After the value row is checked this function makes moves till the empty cell is not next to the target value, and if there is need makes extra moves while the empty cell is positioned to the right of the target value. """ value_r...
The function `last_columns_move_for_next_value` moves a value (`target_value + 1`) to its correct position on a board. It first checks if the value is in the last column, moving it out if needed. Then, it aligns the value to the `correct_cell` using row-specific or standard movement logic, repeatedly adjusting until th...
def last_columns_move_for_next_value(board, target_value, correct_cell): """ After increasing the target value with 1, we know what is the next value for order, before the current. Before the moves for order we have to check if the value is in the last column and move out it from there. Afte...
def set_the_empty_cell_right_to_the_target_value(board, value_cell, empty_cell): """ According to the target value coordinates and the empty cell coordinates, this function moves the empty cell in right of the target value. """ value_row, value_col = value_cell empty_row, empty_col = empty_cell...
This function moves a target value to its correct position on the board, ensuring it's not initially in the last column. It adjusts the empty cell's position, handles special column movements, and addresses cases where the last two elements on a row are misaligned after reordering. The process involves iterative moves ...
def last_columns_move_for_current_value(board, target_value, correct_cell): """ Before the moves for order the value on a correct cell we have to check if the value is in the last column and move out it from there. After that we can start moving the value according the coordinates of the value a...
def move_element_from_last_column(board, value_cell, empty_cell): """ After the value row is checked this function makes moves till the empty cell is not next to the target value, and if there is need makes extra moves while the empty cell is positioned to the right of the target value. """ value_r...
This function handles the movement of elements in the last two rows of a board game. It identifies the target value's and empty cell's positions, adjusts for the last column scenario, and uses specific helper functions to reposition the target value correctly based on its row and column relative to the empty cell and d...
def make_last_two_rows_moves(board, value_to_order, correct_cell_coordinates): """ Controls the last two rows moves. According to the current value coordinates call the correct function. """ value_coordinates = board.find_target_cell(value_to_order, board.board) value_row, value_col = value_coor...
def make_last_two_rows_moves(board, value_to_order, correct_cell_coordinates): """ Controls the last two rows moves. According to the current value coordinates call the correct function. """ value_coordinates = board.find_target_cell(value_to_order, board.board) value_row, value_col = value_coor...
This function arranges the last two rows of a puzzle by iteratively moving elements into their correct positions column-by-column. It compares current values with the target "winning board," executes moves to align elements, and swaps them into place. After processing all columns, it handles the final three cells to co...
def solve_the_last_two_rows_for_the_puzzle(board): """ Controls the ordering of the elements two by two until they are in correct positions in the 2 rows, same column. The last steps is to move the last 3 cells """ row = board.side - 2 for r in range(row, board.side-1): for c in ra...
def make_last_two_columns_moves(board, target_value, correct_cell): """ With the first function call we set the last correct value for the row in position [row][column-1] With the second function call we set the last-1 correct value for the row in position [row + 1][column-1] Then trey are prepared for ...
This function controls the movement of a specific value to its correct position on the board, handling special cases like last columns and rows. It checks if the target is in the last two columns, moves it if needed, and uses row-specific or standard move functions to position the value correctly, ensuring systematic p...
def ai_moves_control(board, value_to_order, value_cell_coordinates, correct_cell_coordinates): """ This is the main function that controls the steps for solving the puzzle from first to n-2 row. First we checked if the correct coordinates are for the last two columns order. If they are, after the move...
def get_doc_name(file_n,n): file_n[12]=str(n) doc_n="".join(file_n) return doc_n def orig(files, summary_doc): data = [] for file in files: data.extend(preprocess(file)) #preprocess file to create clean sentence, and reserve the original sentence word_probs = gen_word_prob(data) sent_probs = gen_sent_prob...
The main task of the code is to process three input documents using a specified method (e.g., 'orig', 'best-avg') and generate a summary. It reads three files, extracts a cluster identifier from the input filename, and writes the summary to a method-specific output file. The code routes processing to different function...
def main(): method_name = sys.argv[1] file_n = list(sys.argv[2]) doc_1=open(get_doc_name(file_n, 1), "r") doc_2=open(get_doc_name(file_n, 2), "r") doc_3=open(get_doc_name(file_n, 3), "r") f1 = doc_1.read() f2 = doc_2.read() f3 = doc_3.read() files = [f1,f2,f3] cluster = file_n[10] #print(cluster) summary_...
def get_activations(path_or_samples, model, batch_size, dims, device): if isinstance(path_or_samples, str): assert path_or_samples.endswith('.pt') or path_or_samples.endswith('.pth'), "path is not .pt or .pth!" act = torch.load(path_or_samples) else: assert isinstance(path_or_samples, to...
This function computes the Fréchet Inception Distance (FID), precision, and recall between real and generated data. It uses InceptionV3 to extract features from real/fake samples, calculates statistical metrics (mean, covariance), and computes FID via Frechet distance. Precision/recall are derived from feature similari...
def get_fid_PR(real_path_or_samples, fake_path_or_samples, device=torch.device('cuda'), batch_size=50, dims=2048, k=3, save_feats_path=None): block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] model = InceptionV3([block_idx]).to(device) # Real feat_r = get_activations(real_path_or_samples, ...
def __count_around(self, x, y, value): cells = [] count = 0 if x > 0: count, cells = self.__count(x - 1, y, value, count, cells) if x < self.__size - 1: count, cells = self.__count(x + 1, y, value, count, cells) if y > 0: count, cells = self.__...
The method `__naive_moves` identifies cells in a grid to either flag as mines or reveal as safe based on surrounding values. It iterates through each cell, checks adjacent flags and hidden cells, and applies simple logic: if a cell’s value exceeds surrounding flags, it flags hidden cells; otherwise, it reveals them. Th...
def __naive_moves(self): move_found = False for x in range(self.__size): for y in range(self.__size): if self.__grid[x][y] != None and self.__grid[x][y] > 0 and (x, y) not in self.__no_need_to_check_again: flags_around, cells = self.__count_around(x, y, -2...
def __place_bombs(self): for _ in range(self.__bombs_count): bomb_placed = False while not bomb_placed: x = random.randint(0, self.__size - 1) y = random.randint(0, self.__size - 1) if x != self.__cursor['x'] and y != self.__cursor['y'] and...
The main task of the code is to reveal the cell at the cursor's position when the game is active. It ensures bombs are placed if not already done, then triggers the cell revelation and redraws the game board to reflect the update.
def reveal_cell(self): if self.__status == 'in_game': if not self.__bombs_placed: self.__place_bombs() self.__reveal_cell(self.__cursor['x'], self.__cursor['y']) self.__draw()
def __place_bombs(self): for _ in range(self.__bombs_count): bomb_placed = False while not bomb_placed: x = random.randint(0, self.__size - 1) y = random.randint(0, self.__size - 1) if x != self.__cursor['x'] and y != self.__cursor['y'] and...
The method checks if the game is active, places bombs if not already done, reveals adjacent cells around a clicked position, and updates the game display.
def reveal_around(self): if self.__status == 'in_game': if not self.__bombs_placed: self.__place_bombs() self.__reveal_around() self.__draw()
def sigma_transform(rho): (m,) = rho.shape return np.log(np.ones(m) + np.exp(rho)) def show_selection(mu, rho, x_1, x_2, lines): plot_points(x_1, 'red') plot_points(x_2, 'blue') plt.xlim([-3, 6]) plt.ylim([-2, 7]) (_, m) = x_1.shape for _ in range(lines): epsilon = np.random.no...
The code generates synthetic data from two multivariate normal distributions, initializes parameters for a probabilistic model, and performs gradient descent to optimize these parameters by maximizing the ELBO (Evidence Lower Bound). It iteratively updates parameters (mu, rho) using gradients, evaluates the model's per...
def main(): n, m = 100, 3 mean_1 = np.array([1, 3, 1]) mean_2 = np.array([2, 1, 1]) cov_1 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]) cov_2 = cov_1 # x_1, y_1 = normal_sample(mean_1, cov_1, n) # x_2, y_2 = normal_sample(mean_2, cov_2, n) # plt.scatter(x_1, y_1, color='red') # plt...
def load_events(self): """ Loads the list of events from the 'events.txt' file. Filters events that occur in the future. """ try: with open('events.txt', 'r') as file: events_data = json.load(file) now = datetime.datetime.now() ...
The main task of the code is to start a program that loads event data, displays a menu, and processes user choices to view, add, edit, or delete events. The loop continues until the user selects "0" to exit, at which point events are saved and the program ends.
def run(self): """ Starts the program and executes the main loop. """ self.load_events() while True: self.display_menu() choice = input("Enter the action number:") if choice == '1': self.view_events() elif choice =...
def letterize(img, thresh=200): dat = np.array(img.convert(mode='L')) h, w = dat.shape dat = dat.mean(axis=1) plt.plot(dat*(dat>thresh)) vf = np.vectorize(num_to_bgw) return ''.join(vf(dat)) def get_intervals(letterized, px=45, pad=5): pattern = 'w{' + str(px) + ',}' brk = re.comp...
This function extracts musical score regions from an input image, processes them to isolate individual scores, and saves each extracted score as a separate image file in the specified output folder.
def extract_and_save_score(fn, score_fldr): img = Image.open(fn) letterized = letterize(img, thresh=200) intervals = get_intervals(letterized, px=45, pad=15) intervals = return_score_intervals(intervals, letterized) scores = return_score_images(img, intervals) for score in scores: save_s...
def load_data(path): with open(path, 'r') as document: doc = document.read().split('\n') doc = doc[:-1] # ignore last blank sentence # fil with ini and end tokens sentences = [] questions = [] answers = [] answersT1 = [] answersT0 = [] for idx, line in enumerate(doc): ...
The code performs three subtasks involving question-answering models. For SUBTASK 1, it trains a model to map questions to questions using reshaped data. For SUBTASK 2, it trains a model to generate answers from questions and targets. For SUBTASK 3, it initializes a third model (incomplete). The code loads embeddings, ...
def main(): embeddings, reverse_word_map, data, target, voc_size, questions, answers, answerst1, images = load_data(TRAIN_DATA) image_dict = loadImageFeatures() # dic["imageXXX"] =[features...] question_image_features = get_images_indexes(reverse_word_map,images, image_dict) print(question_image_featu...
def loadImageFeatures(): image_features = np.zeros((IMG_TOTAL,IMG_FEA_TOTAL)) with open(IMG_FEA_PATH, 'r', encoding="utf8") as csvfile: spamreader = csv.reader(csvfile, delimiter=',') for idx, row in enumerate(spamreader): image_features[idx] = row[1::] return image_features def...
The code executes two subtasks: for SUBTASK=1, it trains and tests a model to map questions to questions using reshaped data and embeddings; for SUBTASK=2, it trains and tests a model to map questions to answers, involving reshaped answer data and a distinct training process. The main task involves loading data, creati...
def main(): image_features = loadImageFeatures() embeddings, reverse_word_map, data, target, voc_size, questions, answers, answerst1 = load_data(TRAIN_DATA) if SUBTASK == 1: data = data.reshape(data.shape[0], MAX_WORDS_QUESTION) model = createModel(embeddings, voc_size) if (TRAIN)...
def initialize_logging(log_file_path): """ Initializes logging with the specified log file path. Ensures that the directory for the log file exists. Args: log_file_path: str. The path where the log file should be stored. """ # Extract the directory path from the log file path log_directory ...
The main task of the code is to continuously transcribe audio files from a specified directory using a model, with configurable parameters like language, file extensions, and deletion flags. It logs progress, processes files in a loop with 10-second intervals, and optionally executes a secondary "left_function" for bac...
def main(): log_file_path = r"Z:\fast_channels\OTERRA\!LOGS\whisper_logs.txt" initialize_logging(log_file_path) args = parse_arguments() args.extensions = args.extensions.split(',') while True: logging.info(f"Starting func transcribe_directory for {args.dir_path}.") transcribe_dire...
def split_features_outcome(data): features = data.drop(['decision'],axis=1) decision = data['decision'] return features,decision def buildTree(trainingSet,attributes,depth,maxDepth,minExamples): if depth==maxDepth or len(attributes)==0 or len(trainingSet)<minExamples: maxLabel = statistics.mode(...
The code trains a decision tree using `trainingSetRound` up to a specified depth, measures training time, and predicts outcomes on `trainingSet` using the built tree. It returns predicted labels and the tree structure.
def decisionTree(trainingSetRound,trainingSet,depth): features,decision = split_features_outcome(trainingSetRound) attributes = list(range(len(features.columns))) start = timeit.default_timer() trainingSetArray = trainingSetRound.to_numpy() root = buildTree(trainingSetArray,attributes,0,depth,50) ...
def decisionTree(trainingSetRound,trainingSet,depth): features,decision = split_features_outcome(trainingSetRound) attributes = list(range(len(features.columns))) start = timeit.default_timer() trainingSetArray = trainingSetRound.to_numpy() root = buildTree(trainingSetArray,attributes,0,depth,50) ...
The code implements the AdaBoost algorithm using decision stumps (depth-1 trees) to iteratively improve classification accuracy. It initializes equal weights for training samples, trains weak classifiers (decision trees) on weighted samples, computes error rates, updates classifier weights (alphas), and adjusts sample ...
def adaboost(trainingSet,testSet,noOfEstimators,learningRate): trainingSet['decision']=trainingSet['decision'].replace(0,-1) trainingSetArray = trainingSet.to_numpy() probSet = np.empty((trainingSetArray.shape[0],noOfEstimators+1)) predSet = np.empty((trainingSetArray.shape[0],noOfEstimators)) mis...
def enroll_step_1(self, u_id): self.__send_command(FPCconstants.CMD_ENROLL1, u_id) return self.__get_response(FPCconstants.CMD_ENROLL1) def enroll_step_2(self, u_id): self.__send_command(FPCconstants.CMD_ENROLL2, u_id) return self.__get_response(FPCconstants.CMD_ENROLL2) def enroll_step_...
The main task of the code is to enroll a user's fingerprint by performing three sequential steps: capturing the same finger three times with delays between each capture, verifying success at each step, and returning a response with the user ID if all steps succeed.
def enroll(self, u_id): response = self.enroll_step_1(u_id) if not response['success'] == True: return response print('Remove finger...') time.sleep(2) print('Waiting for same finger second time...') response = self.enroll_step_2(u_id) if not response['success'] ...
def make_frequency_dict(self, text): frequency = {} for character in text: if not character in frequency: frequency[character] = 0 frequency[character] += 1 self.freq_dict = frequency return frequency def make_heap(self, frequency): ...
The code compresses a file using Huffman coding. It handles `.txt` and `.bin` files by generating frequency dictionaries, building a priority heap, encoding data, padding it, and writing the compressed result to a new `.bin` file. The output path is stored and returned.
def compress(self): filename, file_extension = os.path.splitext(self.path) output_path = filename +"_Compressed"+".bin" if file_extension =='.txt': self.extension='.txt' with open(self.path, 'r+') as file, open(output_path, 'wb') as output: text = file.rea...
def remove_privous_sonar_fov(self): for (x,y), value in np.ndenumerate(self.board): if self.check_sonar_triangle(self.sonar_edges[0],self.sonar_edges[1],self.sonar_edges[2],self.sonar_edges[3],self.sonar_edges[4],self.sonar_edges[5],x,y) == True : #do some thing to element ...
The code advances a moving object's position by updating its coordinates based on velocity, manages sonar field-of-view (FOV) updates, decrements a duration counter, and handles velocity/duration array slicing when the duration reaches zero, returning None when motion stops.
def time_step(self): if self._duration[0] != 0 : #self.get_heading() if self.sonar_edges != [] : self.remove_privous_sonar_fov() self.current_positen[0] = self.current_positen[0]+self._velocity[0][0] self.current_positen[1] = self.current_positen[...
def time_step(self): if self._duration[0] != 0 : #self.get_heading() if self.sonar_edges != [] : self.remove_privous_sonar_fov() self.current_positen[0] = self.current_positen[0]+self._velocity[0][0] self.current_positen[1] = self.current_positen[...
The main task of the code is to simulate a sequence of time steps over a calculated duration. It sums elements in `self._duration` to determine the total steps, then iterates through each step to update the system's state via `time_step()`, detect mines with `get_mines()`, and calculate internal heading data using `get...
def start(self): #self.get_sonar_fov() counter=0 for i in self._duration: counter = counter + i for i in range(counter): self.time_step() #self.display_map() self.get_mines() self.get_heading_inner() #self.display_ma...
def inputs(argv): try: opts, args = getopt.getopt(argv,"hc:") for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt == "-c": global configfilename configfilename = arg except getopt.GetoptError as...
The code's main task is to process command-line arguments, parse a configuration, and generate output files. The `main` function initializes by handling inputs via `inputs(argv)`, then parses configuration settings with `parseconfiguration()`, and finally executes `writefiles()` to produce or save the resulting files. ...
def main(argv): inputs(argv) parseconfiguration() writefiles()
def inputs(argv): try: opts, args = getopt.getopt(argv,"hm:c:p:i:o:") for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt == "-m": global modelScript modelScript = importlib.import_module(arg) ...
The main task of the code is to process input parameters, parse matrix data, compute functional rates, build a model, and write results to a file. It sequentially executes input handling, parameter parsing, matrix parsing, functional rate calculation, model construction, and output writing to accomplish a computational...
def main(argv): inputs(argv) parseparameters() parsematrix() compute_functionalrates() model_builder() writefile()
def get_cnx() -> MySQLConnection: return connect(**config.dbparams) def find_account_number(id: int) -> list[dict]: ''' Helps in fetching account number of the investor who logged in to buy stocks [R] ''' db_cnx: MySQLConnection = get_cnx() cursor = db_cnx.cursor(dictionary=T...
The function updates an investor's portfolio by either deleting a stock entry if its quantity reaches zero or reducing the quantity when selling. It connects to the database, retrieves the account number, checks the stock's quantity, and executes a delete or update operation accordingly.
def update_portfolio(id: int, ticker_to_sell: str) -> None: ''' On clicking sell stock -> server checks the quantiy of the ticker for the particular investor -> either of these two actions take place, if quantity = 0 -> delete_portfolio() [D] else updates the row with th...
def getnextconditions(self, X, Y): self.iteration += 1 self.saveOpt(log=True) if self.mode == 'min': sign = 1 else: sign = -1 if int(self.nBatch.value()) < 2: xnext, _ = self.optimiser.multinextcondition(X, sign*Y) return xnext ...
The main task of the code is to handle user submission of experimental conditions and responses by collecting data from UI tables into numpy arrays, updating the model's training data (X and Y), generating next experimental conditions using the model, updating the UI with new conditions, adjusting response fields, and ...
def submit_click(self): # Firstly check response size matches conditions conditions = np.zeros((self.tConditions.rowCount(),self.tConditions.columnCount())) for i in range(self.tConditions.rowCount()): for j in range(self.tConditions.columnCount()): conditions[i,j] = ...
def compare_date(old_df, df, frequency): old_ts = old_df['timestamp'].iloc[0] old_timestamp = datetime.strptime(old_ts, '%Y-%m-%d %H:%M:%S:%f') # logger.info('Old ts %s' % old_timestamp) new_ts = df['timestamp'].iloc[0] new_timestamp = datetime.strptime(new_ts, '%Y-%m-%d %H:%M:%S:%f') # l...
The function `export_csv` exports a DataFrame (`df`) to a CSV file, appending new data to existing files while avoiding duplicates. It checks if the file exists, reads old data, merges and filters timestamps to remove overlaps, concatenates old and new data, sorts, processes NaN values, and writes the result. If errors...
def export_csv(df, date_from_str, output_dir,frequency): file_name = 'mtl1_' + date_from_str + '.csv' file_path = os.path.join(output_dir, file_name) if os.path.exists(file_path): try: logger.info('Found old file %s. Concatenating.' % file_path) old_df = pd.read_csv(file_path...
def get_fs(path): df = read_csv(path, 2, DATA_BEGINS) if len(df) == 0: logger.error('There are no data in file %s.' % path) return None, None if df is not []: df['$timestamp_dt'] = df.apply(lambda row: get_datetime(row['timestamp']), axis=1) df['$timestamp_fs'] = df['$timest...
The code parses time-series data from multiple files, converts timestamps to a specified timezone, filters data by date, groups by hour, fills NaN values, and exports processed CSVs to an output directory. It handles varying data frequencies, skips lines based on frequency, and ensures data consistency across files.
def parse(df, output_dir, output_tz): for file_name in df: path = file_name['path'] logger.info('Reading %s' % path) lines = DATA_BEGINS frequency, date_from = get_fs(path) if frequency is None: continue input_tz, sgn, hour_diff = get_tz(path) while ...
def get_date(match): d = match.groupdict() return d['year'] + '-' + d['month'] + '-' + d['day'] def verify(file_name): match = GENEACTIV_FILE_REGEX.match(file_name) if match: extension = match.group('extension') if extension == '.csv' or extension == '.csv.gz': return match ...
The code processes GENEActiv actigraphy files from a directory based on the specified extraction mode ('new', 'specific', or 'all'). It filters files by date, verifies their validity, and organizes them into dataframes. Depending on the mode, it selects files newer than existing outputs, within a specific date range, o...
def process(read_dir, output_dir, output_tz, ext_mode, ext_date): if ext_mode=='new': files2=[] for root_dir1, dirs1, files1 in os.walk(output_dir): for file in sorted(files1): if file.endswith('.csv'): files2 = file if files2==[]: ...
def check_input(read_dir): if os.path.exists(read_dir): return read_dir else: logger.error('%s does not exist.' % read_dir) return None def check_output(output_dir): if os.path.exists(output_dir): output_dir = os.path.join(output_dir, 'mtl1') if os.path.exists(output_...
The main task of the code is to process input data from a specified directory, validate input/output paths, configure logging, convert data to CSV format, and execute MATLAB scripts using provided parameters. It handles path expansion, sanity checks, logging setup, data processing, and MATLAB integration to complete th...
def main(args): # expand any ~/ in the directories read_dir = os.path.expanduser(args.read_dir) output_dir = os.path.expanduser(args.output_dir) # perform sanity checks for inputs read_dir = check_input(read_dir) output_dir = check_output(output_dir) if read_dir is None or output_dir is Non...
def connect( self, database=None, user=None, password=None, host=None, port=None, dsn=None, **kwargs, ): conn_params = self._conn_params.copy() new_params = { "database": database, "user": user, "pa...
(The code executes SQL statements in a database, handling both regular queries and special commands (via `pgspecial`). It splits multi-statement input, processes each query, and yields results as tuples with metadata (title, rows, headers, status, etc.). Error handling uses `exception_formatter` to format exceptions in...
def run( self, statement, pgspecial=None, exception_formatter=None, on_error_resume=False ): """Execute the sql in the database and return the results. :param statement: A string containing one or more sql statements :param pgspecial: PGSpecial object :param exception_format...
def azim_to_vec(az, el, degrees=True): if degrees: az = az / 180 * np.pi el = el / 180 * np.pi else: print('WARNING. azim_to_vec degrees=False') # deriv: https://math.stackexchange.com/questions/1150232/finding-the-unit-direction-vector-given-azimuth-and-elevation sina = np.sin(a...
The code generates a grid of camera parameter combinations (azimuth, elevation, etc.), computes 2D projections for each, adjusts for roll, and compiles results into a DataFrame. It iterates over all parameter permutations, calculates camera positions, handles exceptions, and returns structured projection data for visua...
def create_look_up_grid(ranges=None, no_roll=False): if ranges == None: ranges = {'azim': list(np.arange(-89, -1, 2)), 'elev': list(np.arange(-45, 1, 1)), 'dist': [1], 'fov': [20],#list(np.arange(1, 10, 2)), 'F': [1]#list(np.arange(1, 10, 2)) } N_opts = ...
def vp_to_azim_elev_roll(_df, target_v0, v_name='v0', plot_it=False, group_by='azim'): target_line_v0 = np.vstack((target_v0, [w/2,h/2])) target_line = target_line_v0 df_sel = _df g = df_sel.groupby([group_by, 'fov', 'F', 'dist']).groups.items() if plot_it: N = len(g) fig, axs...
This function computes camera parameters (azimuth, elevation, roll) to align projected lines with prototype lines by iteratively adjusting the view target. It minimizes projection offsets between 2D/3D points, calculates scale factors for athlete heights, and returns reconstructed data, camera settings, and scaling inf...
def azim_from_v0_proto_no_shift(df, proto_l0, proto_l1, v0, k=None, proj_indA=0, proj_indB=2, skel_store_dict={}, debug=False): proto0 = np.array([proto_l0[0], h-proto_l0[1], proto_l0[2], h-proto_l0[3]]) proto1 = np.array([proto_l1[0], h-proto_l1[1], proto_l1[2], h-proto_l1[3]]) ...
def first_time_start(): if "player1_bids" not in session: session["player1_bids"] = [] if "player2_bids" not in session: session["player2_bids"] = [] if "bottle_pos" not in session: session["bottle_pos"] = 5 if "draw_counts" not in session: session["draw_counts"] = 0 ...
This function handles a game's homepage logic, processing POST requests for player bids, updating game state, checking win conditions, and rendering the game interface with dynamic variables like balances, positions, and bid ranges. It restarts the game on a 'Restart' button click and validates bids, flashing errors fo...
def homepage(): flash("flash test!!!!") first_time_start() if request.method == 'POST': if request.form.get('start_button') == 'Restart': restart_game() return render_template('index.html',duration=0,p1_bal=100,p2_bal=100,new_pos = 5, min_bid = 1, max_bid = 100) playe...
def return_all_users(self): query = "SELECT * FROM users" cursor.execute(query) users = cursor.fetchall() if users: self.set_Response(200, users) else: self.set_Response(404, {'message': 'No users found'}) def return_profile_info(self): user = self...
This code handles HTTP GET requests by routing based on URL paths. It processes '/api/users', '/api/profile', and '/api/reservations' endpoints, returning user data, profile info, or reservation details. Sub-paths like '/due' trigger specific queries (e.g., due today). Unmatched paths return 404 errors.
def do_GET(self): paths = self.path.split('/') if len(paths) > 2 and paths[1] == 'api': if paths[2] == 'users': self.return_all_users() elif paths[2] == 'profile': self.return_profile_info() elif paths[2] == 'reservations':...
def authenticate_user(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) data = json.loads(post_data) email = data.get('username') password = data.get('password') if email and password: user = self....
This code handles POST requests by routing them to specific functions based on URL paths. If the path starts with '/api', it processes login, registration, or reservation creation. Otherwise, it returns a 404 error.
def do_POST(self): paths = self.path.split('/') if len(paths) > 2 and paths[1] == 'api': if paths[2] == 'login': self.authenticate_user() elif paths[2] == 'register': self.create_new_user() elif paths[2] == 'reservations': ...
def create_new_user(self): content_len = int(self.headers['Content-Length']) data_rec = self.rfile.read(content_len) data = json.loads(data_rec.decode()) user_type = data.get('type_id', '') fullname = data.get('fullname', '') contact = data.get('contact', '') ...
This code handles POST requests by routing them to specific methods based on the URL path. It splits the request path, checks the second segment (paths[1]), and calls corresponding functions like create_new_user, create_new_health_record, create_new_reminder, or create_new_healthcare_provider to process data for user r...
def do_POST(self): paths = self.path.split('/') if paths[1] == 'register': self.create_new_user() elif paths[1] == 'health_records': self.create_new_health_record() elif paths[1] == 'reminders': self.create_new_reminder() elif paths[1]...
def update_profile(self): content_len = int(self.headers['Content-Length']) data_rec = self.rfile.read(content_len) data = json.loads(data_rec.decode()) fullname = data.get('fullname', '') contact = data.get('contact', '') payload = self.verify_user() ...
This code handles PUT requests by routing them to specific update methods based on URL path segments. It splits the request path, checks the first segment to determine the resource type (profile, health records, reminders, permissions), and calls corresponding update functions, passing additional path segments as ident...
def do_PUT(self): paths = self.path.split('/') if paths[1] == 'profile': self.update_profile() elif paths[1] == 'health_records': record_id = paths[2] self.update_health_record(record_id) elif paths[1] == 'reminders': reminder_id =...
def delete_health_record(self, record_id): payload = self.verify_user() if payload: cursor.execute("SELECT type_id, user_id FROM users WHERE email = %s", (payload["email"],)) user = cursor.fetchone() if user: type_id, user_id = user ...
The code handles DELETE requests by routing based on URL paths. It splits the path into segments, identifies the resource type (health_records, reminders, users), extracts the ID from the path, and calls the corresponding deletion method (delete_health_record, delete_reminder, delete_user) to remove the specified resou...
def do_DELETE(self): paths = self.path.split('/') if paths[1] == 'health_records': record_id = paths[2] self.delete_health_record(record_id) elif paths[1] == 'reminders': reminder_id = paths[2] self.delete_reminder(reminder_id) eli...
def sample_conditional_query(self): random_draw = np.random.random() selected_query = self.valid_conditions[-1] for query_cdf_val, query_str in zip(self.queries_cdf, self.valid_conditions): if random_draw <= query_cdf_val: selected_query = query_str br...
This function generates a training example by sampling audio sources, creating synthetic mixtures with randomized parameters (overlap ratio, SNR, source order), extracting meta-features, and constructing conditional embeddings. It returns mixed audio tensors, a binary condition vector encoding task parameters, and a te...
def __getitem__(self, idx): if self.augment: seed = int(np.modf(time())[0] * 100000000) else: seed = idx np.random.seed(seed) sampled_conditional_query = self.sample_conditional_query() (target_source_file_path, interf_sampled_file_path, sampled...
def train_epoch(self, model, opt, loader, log_melspec, device, teacher=None): model.train() for i, (batch, labels) in tqdm(enumerate(loader), total=len(loader)): batch, labels = batch.to(device), labels.to(device) batch = log_melspec(batch).to(device) opt.zero_grad()...
The code trains a CRNN model for a specified number of epochs using Adam optimization, with optional knowledge distillation from a teacher model. It validates after each epoch, tracks metrics, and stops early if the validation metric meets a threshold. The trained model and training history are saved and returned.
def train(self, model_name, teacher_name=None): assert model_name in configs, f"Incorret model name. Choose one of {configs.keys()}" config = configs[model_name] model = CRNN(config).to(config.device) history = defaultdict(list) opt = torch.optim.Adam( model.paramete...
def eprint(msg: str): print(msg, file=sys.stderr) def split_var_name(name: str) -> tuple[str, int, str]: if "ins" in name or "del" in name: items = name.split("_") return items[3], int(items[0]), items[-1] items = re.match(r"([A-Z]+)([-\d]+)([A-Z/*]+)", name, re.I).groups() return items...
The code processes mutations from a file, validates them against a reference genome and GFF gene annotations, generates corresponding VCF files, and merges them into a final sorted, indexed VCF. It checks mutation positions, ensures sequence matches, applies strand-specific adjustments, and uses `bcftools` for normaliz...
def main(ref, gff, mutations, out_vcf): reference = "" chrom = "CHROM" with open(ref) as fp: for line in map(str.rstrip, fp): if line and line[0] == ">": chrom = line[1:].split()[0] reference += line features = dict() with open(gff) as fp: for...
def is_hom_ref(self) -> bool: """Is genotype homozygous reference?""" return self.is_hom() and (self.allele1 == 0 or self.allele2 == 0) def is_null(self) -> bool: """Is the genotype null. i.e. ./.""" return self.allele1 == -1 and self.allele2 == -1 def is_hom_alt(self) -> bool: "...
This function determines the index of the called allele in a genotype. It returns 0 for homozygous reference or null genotypes, alt_index()+1 for homozygous alternative genotypes, and raises an error for unexpected heterozygous genotypes.
def allele_index(self) -> Optional[int]: """The index of the called allele""" if self.is_hom_ref() or self.is_null(): return 0 elif self.is_hom_alt(): return self.alt_index() + 1 else: raise NotImplementedError(f"Het Genotype is unexpected: {self}")
def getDataFileNames(dataPath): #finds all data files dataPath = dataPath + 'fluidData*.npy' fileList = glob.glob(dataPath) fileNames = [] times = [] #creates a list of the filenames and corresponding times for fileName in fileList: dataFileName = fileName.split('/')[-1] file...
The main task of the code is to generate a GIF from a set of data files. It organizes data files, creates individual plot frames from them, compiles these frames into a GIF, and returns True upon successful completion. The function orchestrates data retrieval, frame generation, and GIF creation in a sequential workflow...
def makeGif(dataPath,framesPath): fileNames, times = getDataFileNames(dataPath) print("ordered files") makePlots(dataPath, framesPath, fileNames) print("created frames") print("creating GIF") makeGifFromFrames(framesPath) return True
def get_safe_input(input_data): """Check if input is safe.""" global aacs_client if not aacs_client: return input_data, 0 logger.info("Analyzing input...") result, severity = iterate(input_data) logger.info(f"Input analyzed, severity {severity}") return result, severity def get_reque...
The main task of the code is to generate text or chat completion responses using a preloaded model. It processes input data by checking safety thresholds, prepares query parameters, invokes the model's query method, formats the response based on task type (chat or text generation), logs results, and returns a structure...
def run(data): """Call the model to get the text generation or chat completion results.""" global model global task_type assert model is not None, "grpc client has not been setup when this model was created" try: # Check input content safety data, severity = get_safe_input(data) ...
def initiate(self, canvas, ax, canvas2, ax2): dir = 'Data/' + str(self.name.get()) + '/' self.seislist = glob.glob(dir + '/*PICKLE') print(self.seislist) self.resetCounter() # Create directory to dump data into self.dirdump = dir + 'Dump' if not os.path....
The code creates a GUI with buttons for initiating, accepting, rejecting, inverting data, and resetting, along with two matplotlib plots embedded in a Tkinter window. It binds arrow keys to data manipulation functions and updates labels to track events. The main task is to set up an interactive data visualization inter...
def createWidgets(self): ttk.Button(master=root, text="Start", command=lambda: self.initiate(canvas,ax,canvas2,ax2)).grid(row=1, column=3) ttk.Button(master=root, text="Accept", command=lambda: self.acceptData(canvas,ax,canvas2,ax2)).grid(row=1, column=4) ttk.Button(master=root, text="Re...
def validate_parent_items (dataKeys, data): dict_dataKeys = ["deviceId", "patientId", "patientName", "gender", "dob", "phoneNumber", "address", "measurements"] logging.info("Processing: validating json parent keys of {}".format(dict_dataKeys)) # Check if all primary keys are there, order does not matt...
The function validates a JSON file or input string by checking its structure and content, ensuring specific keys (parent, address, measurements) and their values meet defined criteria. It returns validation results: [True, success message, data] if all checks pass, or [False, error messages] if any validation fails.
def validate_json (inputFile:str): message:str = "" logging.info("Processing: validating json format") try: # Check to see if json file is passed in if (inputFile[-5:] == ".json"): with open (inputFile, "r") as f: if os.path.getsize(inputFile) == 0: ...
def time_dependent_implicit_solve(self, nx, nt): dx, dt = self.domain.getDelta(nx, nt) result = self._td_get_initial_value(nx) time = [0] for j in range(1, nt+2): A = np.zeros([nx, nx]) fv, u = np.zeros(nx), np.zeros(nx) for i in range(1, nx+1): # from...
The code solves partial differential equations (PDEs) by selecting appropriate numerical methods based on problem type. For time-dependent PDEs, it uses implicit or explicit time-stepping (depending on `nt`), while for spatial-only problems, it applies a spatial solver. Grid dimensions are defined by `nx` (x-axis point...
def solve(self, nx, ny = 1, nt = None): """ nx is the grid points number in x axis; ny is the symmetry of nx. The following grid has nx = 4, ny = 3 _ _ _ _ _ |_|_|_|_|_| |_|_|_|_|_| |_|_|_|_|_| |_|_|_|_|_| for 1d time-dependent problem, ny counts...
def countNumTreeNodes(self): ''' The number of tree nodes is inherent in the number of subformulas, which is given on the first line of a well-formed problem instance file. In this way, the given formula is considered to be the first subformula, where its main connective labels t...
The main task of the code is to parse a problem instance file by counting tree nodes, setting up a list of atoms with identical properties, and constructing a tree structure. It initializes key components for processing the problem instance, including node counts and atom groupings, while the commented-out methods sugg...
def parseProblemInstanceFile(self): self.countNumTreeNodes() #self.countNumTreeLeaves() #self.countNumAtoms() self.setUpSameAtomList() self.buildTree()
def makePathTreeVisible(self,path): node = {} nodeSons = os.listdir(path) for nodeSon in nodeSons : if self.nodeIsValid(nodeSon) : nodeSonPath = f'{path}{self.backSlash}{nodeSon}' try : node[nodeSon] = self.makePathTreeVisible(nodeS...
The main task of the code is to generate and store API path trees for each API in `self.apiNameList`, using `makePathTreeVisible` on their respective paths. Errors during processing are logged via `debug`, and if `printStatus` is enabled, the resulting tree is printed. The output is stored in `self.apisTree` as a dicti...
def makeApisAvaliable(self) : self.apisTree = {} for apiName in self.apiNameList : try : apiTree = self.makePathTreeVisible(self.getApiPath(apiName)) self.apisTree[apiName] = apiTree except Exception as exception : self.debug(f'Not ...
def resetValues(self,url,performerName): self.url = url self.performerName = performerName def accessPerformer(self): filteredPerformName = self.removeCharactere(self.performerName.strip().lower(),'`') filteredPerformName = self.removeCharactere(filteredPerformName,"'") filteredP...
The main task of the code is to scrape and organize song data from performer pages. It iterates through a set of performers, resets internal tracking values, accesses each performer's page, retrieves their song set, updates the performer set with these songs, and finally passes the updated set to a sequence-scraping fu...
def getItScraped(self,performerSet): songLyricList = [] songLineList = [] secondSongLineList = [] errorLineList = [] for performerName in performerSet.keys() : self.resetValues(None,performerName) performerPage = self.accessPerformer() performe...
def updateApplicationDependencies(self): try : if self.getApiSetting(AttributeKey.DEPENDENCY_UPDATE) : import subprocess moduleList = self.getApiSetting(AttributeKey.DEPENDENCY_LIST) if moduleList : subprocess.Popen(Globals.UPDATE_P...
The main task of the code is to update application dependencies, update a global class file, and make APIs available. The method sequentially executes these operations to ensure the application's dependencies are current, global class configurations are updated, and APIs are properly initialized for use.
def update(self) : self.updateApplicationDependencies() self.updateGlobalsClassFile() self.makeApisAvaliable()
def takeConfigs(): if len(sys.argv) < 2: print("Provide the config file as the 1st CLI argument please.") exit() conffile = understandconfigfile(sys.argv[1]) if conffile[:5] == 'cfgs/': conffile = conffile[5:] understandconfigfile(sys.argv[1]) if not os.path.exists("cfgs/{}"....
The main task of the code is to periodically capture screenshots of a desktop region, extract text using OCR, filter and clean chat messages containing stock ticker symbols via regex, compare them against existing database records to detect new unique messages, and store them in a PostgreSQL database during specified h...
def main(): conf = takeConfigs() logger = setUpLogging(conf) tickerregexes = setupregex(conf, logger) logger.info("Connecting to database initially") dbconnection = pg_sentiment_db.connectToDatabase_pg(conf, logger) while True: currhr = datetime.now().hour currmin = datetime.now(...
def add_all_security_zones(self): print(self.zones_list.count) for i in range(len(self.zones_list)): self.remove_box(self.zones_list[i]) del self.zones_list[:] # Adding the fixed box which protect the arm from the elevation system in steel self.add_box(0.0, 0.0, -0.1075, 1.0, (0.3...
The code processes a message to validate elevation parameters, selects a predefined scan position based on direction and shelf number, ensures successful initialization, navigates to the scan position, removes a curtain, and calls the elevation_controller_vision service to execute the elevation action, returning the se...
def elevationPositionCallback(self, msg): if msg.level.data < 0 or msg.level.data > 2: return ElevationVisionResponse(False) success = self.is_init_success # try: # rospy.delete_param("/kortex_examples_test_results/moveit_general_python") # except: # return ElevationVisionResponse...
def add_all_security_zones(self): print(self.zones_list.count) for i in range(len(self.zones_list)): self.remove_box(self.zones_list[i]) del self.zones_list[:] # Adding the fixed box which protect the arm from the elevation system in steel self.add_box(0.0, 0.0, -0.1075, 1.0, (0.3...
The code sets a robotic arm's Cartesian position based on input message parameters (level and searchPos), adjusts coordinates using predefined offsets, converts Euler angles to quaternions for orientation, and executes the movement with tolerance. It returns a success status after attempting to reach the calculated pos...
def armPositionCartesianCallback(self, msg): success = True self.add_all_security_zones() pose_msg = geometry_msgs.msg.Pose() if msg.level == 1: if msg.searchPos == 0: pose_msg.position.x = -0.12 - DISTANCE_SHELF_X pose_msg.position.y = -0.06 + DISTANCE_SH...
def add_all_security_zones(self): print(self.zones_list.count) for i in range(len(self.zones_list)): self.remove_box(self.zones_list[i]) del self.zones_list[:] # Adding the fixed box which protect the arm from the elevation system in steel self.add_box(0.0, 0.0, -0.1075, 1.0, (0.3...
The code's main task is to execute a sequence of joint angle movements for a robotic arm, first reaching specified angles to position the gripper, then adjusting joints again to complete a dropping action. It checks success at each step, ensuring all movements are achieved within tolerance before returning the overall ...
def drop_sequence(self): self.add_all_security_zones() success = self.reach_joint_angles(radians(-(360-272.01)),radians(-(360-285.38)), radians(100.14), radians(21.11), radians(-(360-340.58)), radians(-(360-303.13)), tolerance=0.01) if success: self.reach_gripper_position(0) suc...
def reach_gripper_position(self, relative_position): gripper_group = self.gripper_group # We only have to move this joint because all others are mimic! gripper_joint = self.robot.get_joint(self.gripper_joint_name) gripper_max_absolute_pos = gripper_joint.max_bound() gripper_min_absolute_po...
This callback function controls a robotic arm's gripper and Cartesian movements to grasp an object. It adjusts the gripper position based on input, navigates to a target pose, removes a shelf, repositions to grasp an article, closes the gripper, and re-adds a modified shelf. It returns a success status after executing ...
def armPositionGrabCallback(self, pose_msg): rospy.loginfo("Opening the gripper...") if pose_msg.grip > 0.7: print(pose_msg.grip) self.reach_gripper_position(0.2) else: self.reach_gripper_position(0) self.add_all_security_zones() rospy.loginfo("Reaching requested Z-Pose..." + st...
def GetInput(message, isCommand=False, inputType=str, date=False, searching=False): '''This function gets input from the user and briefly check the input Key arguments: - message: the output message (str) - isCommand: if the input is a command (bool) - inputType: used to check the type ...
The main task of the code is to save the current database to a file, handling user confirmation for overwriting existing files. If no file is open, it prompts for a filename, checks for duplicates, and allows overwrite confirmation. If a file is already open, it asks to confirm overwriting it. The database content is t...
def UpdateFile(): '''Save the current database to a file''' if currentFile is None: fileName = GetInput("Please enter the name of the file you want to save as: ") if fileName is None: # cancelling return while Open(fileName): # check if the file already exists i...
def init_CS_pin(self,CS_pin): self.set_CS_pin(CS_pin) def set_switches(self, switches_vector, bimms_sel=0): value = cstmux.cmd_shift * (cstmux.set_switch + bimms_sel) + switches_vector self.tx_2_STM32_MUX(value) def __init_default_config(self): self.config_mode("MANUAL") self.man...
This code initializes a hardware device by setting up communication interfaces, default switch configurations, and hardware components. It calls parent class constructors, configures a CS pin, applies default switch settings, initializes configuration parameters, and prepares variables for current injection/reception, ...
def __init__(self, bimms_id=None, serialnumber=None): BIMMS.__init__(self, bimms_id=bimms_id, serialnumber=serialnumber) EIT_class.__init__(self) self.init_CS_pin(cstmux.MUX_STM32_CS_p) self.sw_vector=cstmux.sw_default self.set_switches(0) #Dummy set (Bug?) self.__i...
def authentication(username, password): with psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) as conn: with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur: cur.execute("SELECT user_password FROM registeredvoter WHERE voter_id = %s;", [uuid.UUID(userna...
The code securely casts a vote by authenticating the user, generating a cryptographic key, blinding it with RSA, obtaining a signed token from an online verifier, verifying the signature, and registering the vote on Ethereum using the signed key and ballot ID.
def start(): user_id = input("Please enter your voter_id : ") passwd = getpass.getpass("Enter your password : ") ballot_id = int(input("Enter your ballot id : ")) authentication(user_id, passwd) key = int(secrets.token_hex(16), 16) public_ballot_key = serialization.load_pem_public_key(readPublic...
def make_vectors(data): vector = [] for line in data.splitlines(): vector.append(make_vector(line)) return vector def calculate_weights(training_data_vectors, alfa, classname, weight): weights_not_change = 0 old_weight = [] while weights_not_change < 1: for vector in training_dat...
The main task of the code is to implement a delta rule algorithm for classifying iris flower data using a perceptron model. It trains weights on "Iris-setosa" data, classifies test samples by calculating dot products, and evaluates accuracy by comparing predicted vs actual labels. The algorithm adjusts weights iterativ...
def delta_algorithm(training_data, testing_data, alfa): training_data_vectors = make_vectors(training_data) testing_data_vectors = make_vectors(testing_data) ## utworzenie wektorow weight = [] for i in training_data_vectors[0].keys(): for j in i: weight.append(random.uniform(-1,...
def make_vectors(dir): vector = [] for dir_in in os.listdir(dir): dirpath = dir+"/"+dir_in for file in os.listdir(dirpath): filepath = (dirpath+"/"+file) vector.append(make_vector(read_data(filepath),dir_in)) return vector def calculate_weights(training_data_vectors, ...
The code trains a single-layer perceptron for language classification using dot product comparisons. It initializes random weights, calculates language-specific weights with a given alpha, evaluates test vectors by selecting the language with the maximum dot product, and computes classification accuracy by comparing pr...
def layer_perceptron(alfa): training_data_vectors = make_vectors("data") testing_data_vectors = make_vectors("data_testing") random_weights = [] weights = {} for i in range(0,27): random_weights.append(random.uniform(-1, 1)) classifications = 1 data_rows = 1 for language in o...
def combinePairs(group, unmatched): l = len(group)-1 check_list = [] next_group = [[] for x in range(0,l)] for i in range(0,l): for e1 in group[i]: for e2 in group[i+1]: b, pos = compareBinary(e1, e2) if b == True: check_list.extend...
The code simplifies a Boolean function using the Quine-McCluskey algorithm. It processes input minterms, groups them by binary 1s, combines pairs to find prime implicants, removes redundancies, and constructs the minimal sum-of-products expression from the prime implicants.
def minFunc(numVar, stringIn): brack_minterms=stringIn.find(')') minterms=stringIn[1:brack_minterms] string = minterms.split(',') string = list(map(int, string)) length=len(string) group = [[] for x in range(numVar+1)] for i in range(length): string[i]= bin(string[i])[2:] if...
def deduce_targets(executions): targets = [] for e in executions: target = deduce_target(e) if target is not None: targets.append(target) return targets def remove_duplicates(targets): target_names = (target.name for target in targets) new_targets = {n: None for n in targ...
The code generates a CMakeLists.txt file by parsing an execution log, deducing unique targets, and writing CMake configuration entries for each target in a newly created 'gpu_mpi_project' directory.
def generate_cmake(): import json with open("execution_log.txt", "r") as f: executions = json.load(f) targets = deduce_targets(executions) targets = remove_duplicates(targets) Path("gpu_mpi_project").mkdir(parents=True, exist_ok=True) with open("gpu_mpi_project/CMakeLists.txt", "w") as...
def update_screen(board): row, col = board.shape size_w = WIDTH // col size_h = HEIGHT // row for i in range(row): for j in range(col): if board[i, j] == 1: screen.fill(BLACK, (j * size_w, i * size_h, (j + 1) * size_w, (i + 1) * siz...
The code runs a game loop that handles user input (exit via QUIT or 'Q' key), updates the game screen with the current board state, draws grid lines, and repeatedly computes the next board generation using find_next_generation, updating the board for the next iteration.
def play_game(board, screen): while(True): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN and event.key == K_q: pygame.quit() sys.exit() update_screen(board) draw_lin...
def extract(url, ticker, data_dir): page = requests.get(url + ticker.upper() + '/key-statistics?p=' + ticker.upper()).text gather = pickle_get(os.path.join(data_dir, 'ratios')) tables = pd.read_html(page) value_list = [] for each_data in gather: value = 'N/A' try: if...
The code predicts a stock's class (e.g., buy/sell/hold) using financial features extracted from a URL and ticker symbol. It constructs a DataFrame with 34 financial metrics, loads a pre-trained model, and outputs predicted class labels and probabilities for the input data.
def predict(url, ticker, data_dir): value_list = extract(url, ticker, data_dir) df = pd.DataFrame(columns=pickle_get(os.path.join(data_dir, 'useful_f'))) df = df.append({ 'DE Ratio': value_list[0], 'Trailing P/E': value_list[1], 'Price/Sales': valu...
def claim(self): claims = input("Example of usage: Brown Green FFL FL L\n").split() self.Log.append("{} > {}: {} > {} > {}\n".format(claims[0], claims[1], claims[2], claims[3], claims[4])) self.updateCards(claims[2], claims[3], claims[4]) self.updateScreen() def deleteLine(self): self.Log.pop(int(input("Enter...
The code defines an `execute` method that processes commands to perform actions: 'give' triggers `claim()`, 'del' invokes `deleteLine()`, and 'deck' updates the screen and prints deck statistics. The method handles user input to manipulate resources or display information about a deck's state, including constants and c...
def execute(self, command): if command == 'give': self.claim() elif command == "del": self.deleteLine() elif command == "deck": self.updateScreen() print("Deck: {}L, {}F\nCurrent deck: {}L, {}F".format(self.ConstL, self.ConstF, self.LibCards, self.FascCards))
def game_over(self, state): return wins(state, self.HUMAN) or wins(state, self.COMP) def evaluate(self, state): if wins(state, self.COMP): score = 10 elif wins(state, self.HUMAN): score = -10 else: score = 0 return score def available_spots(gam...
This function implements the minimax algorithm to determine the optimal move for a player in a game. It recursively evaluates all possible moves from the current state, alternating between maximizing (for the computer) and minimizing (for the human) scores. The function selects the best move based on depth, game state,...
def mini_max(self, state, depth, player): if player == self.COMP: best = [-1, -inf] else: best = [-1, inf] if depth == 0 or self.game_over(state): score = self.evaluate(state) return [-1, score] for spot in available_spots(state): ...
def game_field_coordinate(*coordinates_list): coordinate_list = [num for num in coordinates_list] if coordinate_list == ['1', '1']: return 6 elif coordinate_list == ['1', '2']: return 3 elif coordinate_list == ['1', '3']: return 0 elif coordinate_list == ['2', '1']: r...
The function handles the human player's turn in a game by validating user input coordinates, ensuring they are within the 1-3 range, checking if the target cell is unoccupied, and placing the human's move if valid. It repeatedly prompts until a valid move is made, handling errors like non-numeric inputs or out-of-bound...
def human_turn(self, c_choice, h_choice): make_move = False while make_move is False: print("Enter the coordinates: ") coordinates = input().split(" ", 1) try: bool_coordinates = [0 < int(n) < 4 for n in coordinates] if all(bool_coordin...
def confirm_account(user_acct_num): confirm = session.query(Account).filter(Account.number == user_acct_num).exists() return confirm def confirm_pin(user_acct, user_pin): all_accounts = session.query(Account).all() confirm = False for account in all_accounts: if account.number == user_acct a...
The main task of the code is to authenticate a user by verifying their card number and PIN. It prompts for input, checks account existence via `confirm_account`, validates the PIN with `confirm_pin`, and logs the user in if both are correct, otherwise displaying error messages.
def acct_log_in(): print('Enter your card number:') user_num = input() print('Enter your PIN: ') user_pin = input() if confirm_account(user_num) is False: print('Wrong card number or PIN!') elif confirm_pin(user_num, user_pin) is False: print('Wrong card number or PIN!') else...
def available_spots(game_field): available_spots = [] counter = 0 for spot in game_field: if spot == ' ': available_spots.append(counter) counter += 1 return available_spots def wins(state, player): win_state = win_options(state) if [player, player, player] in win_sta...
This function handles the AI's turn in a game, using either random selection (when the board is empty) or the mini-max algorithm (for optimal play) to determine the computer's move. It updates the game field with the AI's choice, prints a move confirmation, and renders the updated board state with the given player choi...
def ai_turn(self, c_choice, h_choice): depth = len(available_spots(self.game_field)) if depth == 0 or wins(self.game_field, self.COMP): return if depth == 9: spot = randint(0, 8) else: move = self.mini_max(self.game_field, depth, self.COMP) ...
def bank_menu(): print(''' 1. Create an account 2. Log into an account 0. Exit''') bank_choice = int(input()) return bank_choice def create_account(): account_num = acct_num() pin_list = [random.randint(0, 9) for x in range(4)] pin = ''.join(str(elem) for elem in pin_list) database_update(ac...
The code defines a banking system that continuously presents a menu to the user, allowing them to create an account, log in, or exit. It loops until the user selects the exit option (0), then closes the session.
def banking_system(): user = True while user is True: user_choice = bank_menu() if user_choice == 1: create_account() elif user_choice == 2: acct_log_in() elif user_choice == 0: print('Bye!') user = False session.close()
def available_spots(game_field): available_spots = [] counter = 0 for spot in game_field: if spot == ' ': available_spots.append(counter) counter += 1 return available_spots def game_over(self, state): return wins(state, self.HUMAN) or wins(state, self.COMP) def ai_tu...
The main task of the code is to manage a turn-based game loop where a human and AI player alternate turns (X/O) on a game field. It determines player roles (human vs. AI) based on predefined settings, alternates moves using a toggle variable, and ends the game when no spots remain or a win condition is met, returning t...
def game_play(self): h_choice = '' c_choice = '' choice = 0 if self.player1 == 'user': h_choice = 'X' elif self.player2 == 'user': h_choice = 'O' if self.player1 == 'hard': c_choice = 'X' elif self.player2 == 'hard': ...
def load_and_preprocess_data_multiple_files(file_paths): sentences = [] predicate_indices = [] labels = [] pos_tags = [] bio_tags = [] directed_distances = [] skipped_counts = [] taken_counts = [] for file_path in file_paths: result = load_and_preprocess_data(file_path) ...
This code initializes a dataset class by loading and preprocessing multiple text files, tokenizing the data using a specified tokenizer, and padding sentences to a uniform length. It stores tokenized inputs, labels, POS tags, BIO tags, and directed distances for batch processing in machine learning models.
def __init__(self, file_paths, tokenizer, max_length): self.sentences, self.predicate_indices, self.labels, self.pos_tags, self.bio_tags, self.directed_distances, _, _ = load_and_preprocess_data_multiple_files(file_paths) self.sentences, self.predicate_indices, self.labels, self.pos_tags, self.bio_tags,...
def load_and_preprocess_data_multiple_files(file_paths): sentences = [] predicate_indices = [] labels = [] pos_tags = [] bio_tags = [] directed_distances = [] skipped_counts = [] taken_counts = [] for file_path in file_paths: result = load_and_preprocess_data(file_path) ...
This code initializes a class to preprocess and tokenize multiple text files for a machine learning model. It loads data, tokenizes sentences, pads sequences, and stores labeled data (labels, POS tags, BIO tags, directed distances) for training or evaluation. The process involves loading, tokenizing, padding, and organ...
def __init__(self, file_paths, tokenizer, max_length): self.sentences, self.predicate_indices, self.labels, self.pos_tags, self.bio_tags, self.directed_distances, _, _ = load_and_preprocess_data_multiple_files(file_paths) self.sentences, self.predicate_indices, self.labels, self.pos_tags, self.bio_tags,...
def display_game_start(self): # person hand card person_card1_file = DECK_DIR + '/' + self._system.person.cards[0] + '.gif' person_card2_file = DECK_DIR + '/' + self._system.person.cards[1] + '.gif' self._person_card1 = ImageSprite(25, 550, person_card1_file) self._person_card2 =...
This function handles keyboard input for a game, triggering actions like restarting the game, initiating a new round, and controlling audio settings. It processes keys such as Enter (to restart after losing), L (raise), J (fold), K (check), and arrow keys (volume adjustment). It also resets game state elements like tex...
def key_up(self, key, event): # Press return, only trigger when a game is end if key == pygame.K_RETURN and self._start is False: # if ai or person lose all money if self._system.lose_all(): os.execl(sys.executable, sys.executable, *sys.argv) # shuffle...
def check_hand(five_cards): # get cards' num and color nums = [] colors = [] # color is the last char in string # num is the rest of for card in five_cards: nums.append(int(card[:-1])) colors.append(card[-1:]) # key is card num, value is the card num freq count cards_di...
The function `compare_hand` determines the winner between two poker hands by first comparing their hand types (e.g., straight, flush). If the types differ, the higher type wins. If types are equal, it uses specialized functions (e.g., `compare_straight`, `compare_non_straight`) to evaluate card values, returning `WIN`,...
def compare_hand(cards1, cards2): """ 1. compare hand kind first, cards1> cards2, return WIN; < , return lose, = return TIE 2. else compare the card list, use ten functions: compare_high_card() to compare_royal_flush 3. these ten functions, cards1 > cards2, return WIN """ cards1_type = check_...
def mouse_button_down(self, x, y): return def key_up(self, key, event): # Press return, only trigger when a game is end if key == pygame.K_RETURN and self._start is False: # if ai or person lose all money if self._system.lose_all(): os.execl(sys.executable...
This code runs a game loop using Pygame, handling events like quitting, mouse clicks, and key releases. It updates the game state, clears the screen with white, renders text, draws elements, updates the display, and maintains a consistent frame rate using a clock. The loop ensures continuous interaction, rendering, and...
def run(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: self.quit() elif event.type == pygame.MOUSEBUTTONDOWN: self.mouse_button_down(event.pos[0], event.pos[1]) elif event.type ...
def url_sine_qua_non(): if st.session_state.url == '': st.warning('You have not entered an URL yet. Please go to I. URL using the sidebar') closing_style() st.stop() else: pass def screen_one(): set_vars() rootUrl = st.session_state.url # * make default def_col, def_d...
The code defines a function `params()` that displays parameters in a Streamlit app. It creates two columns: the first shows content from `screen_one()`, while the second column includes a JSON viewer using a URL stored in `st.session_state.json_url`. The function also sets a title, adds separators, and organizes layout...
def params(): url_sine_qua_non() st.title('II. Parameters') st.write('-----------------') col_1, col_2 = st.columns(2) with col_1: screen_one() #col_2.write(stuff) with col_2: st.write('-----------------------------') st.subheader('JSON VIEWER') #st.write(stu...
def home(): st.title('I. URL') st.write('--------------------') st.header('A. URL Input') cola, colb = st.columns(2) with cola: with st.form('url_form'): url_input = st.text_input('To start, enter an url: ') #rootUrl submit_url = st.form_submit_button('SUBMIT UR...
The function `mode_director()` routes application flow based on the `st.session_state.mode` value, executing corresponding functions like `home()`, `params()`, or `mk_list()` for different modes (I-V), and defaulting to `extras()` if no match is found. It acts as a controller directing user interaction and UI transitio...
def mode_director(): if st.session_state.mode == 'I.URL': home() elif st.session_state.mode == 'II.Parameters': params() elif st.session_state.mode == 'III.Collections': mk_list('collections') elif st.session_state.mode == 'IV.Resources': mk_list('resources') elif st....