dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_nlp_cols_train(X_train, nlp_model,n_pca=5): word_features = spacy_word2vec_features(X_train["text"], nlp_model) ## c'est un pd dataframe pca = PCA() pca.fit(word_features) features_pca = pca.transform(word_features)[:, :n_pca] name_feats = ["word2vec_"+str(i) for i in range(n_pca)] text...
The function transforms training and test datasets by integrating text features extracted via an NLP model with PCA-reduced dimensions (n_pca=5) and additional transformations. It concatenates these features with transformed numerical data, returning combined datasets for training and testing, along with their labels, ...
def get_tranformed_dataset(X_train,y_train, X_test, y_test, nlp_model): pca = PCA() text_df_train, pca = get_nlp_cols_train(X_train, nlp_model, n_pca=5) X_tn, y_tn = transf(X_train, y_train) X_tn_final = pd.concat([X_tn,text_df_train], axis = 1) text_df_test = get_nlp_cols_test(X_test, nlp_model, pc...
def build_ae_e(self, bn, gap=True): ae_e_input = tf.keras.layers.Input(shape=self.generate_shape) x = ae_e_input for i in range(self.stride_index): x = self.conv2d(x, self.filters[i], 5, 2, activation='leaky', bn=bn) if gap: x = self.conv2d(x, self.latent_dim, 1, ...
The code constructs and returns multiple autoencoder models (ae, ae_e, ae_d, aae, aae_d) by building an encoder (ae_e), decoder (ae_d), and adversarial decoder (aae_d). It ensures input dimensions are multiples of 32, uses batch normalization and global average pooling, and connects components to form complete autoenco...
def build(self, ae_d=None, gap=True): assert self.generate_shape[0] % 32 == 0 and self.generate_shape[1] % 32 == 0 ae_e_input, ae_e_output = self.build_ae_e(bn=True, gap=gap) self.ae_e = tf.keras.models.Model(ae_e_input, ae_e_output) if ae_d is None: ae_d_input, ae_d_output =...
def print_loss(self, progress_str, reconstruction_loss, discriminator_loss, adversarial_loss): loss_str = f'\r{progress_str}' loss_str += f' reconstruction_loss: {reconstruction_loss:>8.4f}' loss_str += f' discriminator_loss: {discriminator_loss:>8.4f}' loss_str += f', generator_loss: {a...
This code trains a neural network model (likely a GAN variant) by iterating over image data, computing gradients for autoencoder, discriminator, and generator components using Adam optimizers. It tracks losses, adjusts learning rates, saves checkpoints periodically, generates visualizations, and exits after completing ...
def train(self): if len(self.train_image_paths) == 0: print(f'no images found in {self.train_image_path}') exit(0) self.model.summary() print(f'\ntrain on {len(self.train_image_paths)} samples.') print('start training') iteration_count = 0 compute...
def find_label_counts(data): """ Finds the labels in the data and counts each of them. Args: data (numpy.ndarray): (X, Y) numpy array of X rows of signals and classifications. The last column in Y is the classifications Returns: labels (numpy.ndarray): Room labels e.g. [1, 2, 3, 4] (can be...
This function recursively trains a decision tree by splitting the training dataset based on WiFi signal features, creating internal nodes for splits and leaf nodes when only one label remains. It returns the constructed tree structure and its maximum depth, using recursive calls to process left and right subsets of dat...
def decision_tree_learning(training_dataset, depth=0): """ Trains a decision tree recursively given a training dataset. Returns a trained tree and it's depth. NOTE depth variable must be zero at the beginning Nodes contain the following keys: {"attribute": wifi_split (int), ...
def on_launch(event, launch_request, session): print("on_launch requestId=" + launch_request['requestId'] + ", sessionId=" + session['sessionId']) # Dispatch to your skill's launch return get_welcome_response(session) def on_intent(intent_request, session): print("on_intent requestId=" + inten...
This Lambda function handles Alexa skill requests by routing events to specific handlers: LaunchRequest triggers on_launch, IntentRequest triggers on_intent, and SessionEndedRequest triggers on_session_ended. It uses the event's request type to determine the appropriate response, ensuring proper interaction flow for vo...
def lambda_handler(event, context): session = event['session'] if event['request']['type'] == "LaunchRequest": return on_launch(event, event['request'], event['session']) elif event['request']['type'] == "IntentRequest": return on_intent(event['request'], event['session']) elif event['r...
def report_dependency(self, instance): logger.debug('reporting') if '__cached_property_dep_stack' not in instance.__dict__: return if len(instance.__dict__['__cached_property_dep_stack']) > 0: instance.__dict__['__cached_property_dep_stack'][-1].dependency.update(self.dep...
This function handles cache misses by checking if the cache file exists. If not, it ensures the cache folder is valid, clears invalid cached files, tracks dependencies using a stack, computes the value via self.func(), updates dependencies, and serializes the result with pickle. If the cache exists but dependencies are...
def handle_cache_not_find(self, instance, owner=None): if not os.path.exists(self._cache_file): if os.path.exists(self._cache_folder): # cache folder while file not exist, clear cache folder for f in os.listdir(self._cache_folder): if os.path.isfil...
def extract_rms_chunk(x): return np.clip((10*np.log10(np.mean(x**2))), -100, 0) def track_pitch_nccf(x,blockSize,hopSize,fs, thresholdDb): [xb, timeInSec] = block_audio(x,blockSize,hopSize,fs) xb.T[xb.T == 0] = 0.00001 rmsDb = extract_rms(xb) f0 = np.zeros(len(timeInSec)) for idx, val...
This code tracks musical notes in an audio signal by analyzing chunks of the signal. It calculates the root mean square (RMS) of each chunk, and if it exceeds a threshold, it uses NCCF (Normalized Cross-Correlation Function) pitch tracking to determine the dominant frequency. The most frequent frequency in each valid c...
def onset_note_tracking(x, oInBlocks, fs, rmsThreshold): smallBlockSize = 1024 smallHopSize = 128 a0 = 440 nChunks = oInBlocks.shape[0] f0 = np.zeros(nChunks) for i in range(1, nChunks): initPos = oInBlocks[i-1] endPos = oInBlocks[i] xChunk = x[initPos:endPos] rms...
def extract_rms_chunk(x): return np.clip((10*np.log10(np.mean(x**2))), -100, 0) def track_pitch_nccf(x,blockSize,hopSize,fs): xb = block_audio(x,blockSize,hopSize,fs) f0 = np.zeros(xb.shape[0]) for idx, val in enumerate(xb): mod_val = mod_acf2(val) n = comp_FFTnccf(mod_val) ...
The function tracks pitch in audio segments defined by onset positions. It calculates RMS energy for each segment; if above a threshold, it uses NCCF with small block/hop sizes to estimate pitch, taking the median value. Frequencies are then converted to MIDI notes using A440 as reference, returning an array of MIDI no...
def onset_note_tracking(x, o, fs, rmsThreshold): smallBlockSize = 1024 smallHopSize = 512 a0 = 440 nChunks = o.shape[0] f0 = np.zeros(nChunks) for i in range(1, nChunks): initPos = o[i-1] endPos = o[i] rms = extract_rms_chunk(x[initPos:endPos]) if rms > rmsThresho...
def cross_over(self, pool, scores): soft_max_values = nn.Softmax(dim=0)(torch.FloatTensor(scores)/self.temperature) acc_values = [0.] for sv in soft_max_values: acc_values += [acc_values[-1]+float(sv)] new_pool = [] selected_parents = [] while len(new_pool) < len(pool): ...
The main task of the code is to perform a round of genetic algorithm operations: it conducts crossover to generate new solutions, applies mutation to introduce variations, and then reduces the population size while preserving key elements. The process iteratively refines the solution pool and associated scores to optim...
def round_search(self, pool, scores): new_pool, new_scores = self.cross_over(pool, scores) self.mutate(new_pool, new_scores) new_pool, new_scores = self.reduce(new_pool, pool, new_scores, scores) return new_pool, new_scores
def load_data(self, docs): self.sentences = [] for doc_id, doc_sents in docs: for si, sent in enumerate(doc_sents): entry = {'text': sent, 'doc_id': doc_id, 'sent_id':si, 'len':len(word_tokenize(sent))} self.sentences.append(entry) def init_pool(self, pop_size...
The main task of the code is to generate a summary by iteratively optimizing a pool of candidate summaries using a fitness function. It initializes a pool, evaluates their fitness, and refines the pool over multiple rounds to maximize fitness. Finally, it selects the highest-fitness candidate and constructs the summary...
def summarize(self, docs): self.load_data(docs) pool = self.init_pool(self.max_pop_size) scores = self.fitness_func(pool) for i in tqdm(range(self.max_round)): pool, scores = self.round_search(pool, scores) print('round {}, max fitness {:.3f}, median fitness {:....
def get_unet(self): inputs = Input((self.img_rows, self.img_cols, 1)) conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='glorot_uniform')(inputs) conv1 = BatchNormalization()(conv1) # print("conv1 shape:", conv1.shape) conv1 = Conv2D(64, 3, activation='...
The main task of the code is to train a U-Net model for image segmentation using a dataset specified by `data_path`, with options for stacking multiple models (`no_stacks`). It employs callbacks like early stopping, learning rate reduction, and model checkpointing to optimize training. The model is trained for a specif...
def train(self, data_path, checkpoint_file, models_path, epochs=50, factor=0.1, patience=5, min_lr=0.00001, steps_per_epoch=232, batch_size=1, no_stacks=1): model = self.get_unet() print("got unet") model_checkpoint = ModelCheckpoint(checkpoint_file, monitor='loss', verbose=1, ...
def record_audio_and_transcribe(audio_name, key): audio_name = f"{audio_name}.wav" record_audio(audio_file_name=audio_name) user_input = transcribe_audio(audio_name)["text"] st.write(f'You Recorded: {user_input}') st.session_state.responses[key] = user_input if st.button('Continue'): st...
The code defines a function `display_daily_form()` that guides users through a multi-step daily diary entry process in a Streamlit app. It captures mood (via emojis), activities (text/speech input), daily highlights (text/speech input), and submits entries with secure storage. Each step uses conditional logic based on ...
def display_daily_form(): hidden_response_capture = defaultdict(str) for i in range(1, 10): hidden_response_capture[i] = "" # Mood and Emotions if st.session_state.current_question == 1: print("STATE IS 1") st.subheader('Mood and Emotions') st.write("Select your...
def train_oil_model(oil_files=oil_files_list): print("Load oil data from: ", oil_files) oil = pd.concat((pd.read_csv(f) for f in oil_files)) print("Total {} oil samples was loaded".format(len(oil))) if len(oil) > max_oil_samples: oil = oil.sample(n=max_oil_samples) print("Size of oil da...
The main task of the code is to generate a training dataset by aggregating marker data from multiple files, each assigned unique labels, and combining them with oil data. It loads marker features, concatenates them with corresponding labels, adds oil data as an additional class, and returns the final feature matrix (X)...
def create_trainig_set(): print("load oil markers...") oil_clf, oil_data = train_oil_model(oil_files_list) joblib.dump(oil_clf, "oil_model.pkl") filenames, marker_names = load_training_set(training_set_path) print(filenames) X_df = load_markers(filenames[0], oil_clf) X = X_df.values ...
def __configure_window(self): self.title(WINDOW_TITLE + " - " + self.__state.get_word_to_guess()) self.geometry(f"{WINDOW_WIDTH}x{WINDOW_HEIGHT}") self.resizable(False, False) self.protocol("WM_DELETE_WINDOW", self.__on_closing) self.grid_columnconfigure(1, weight=1) sel...
The code initializes a GUI component by setting up state, guess, and feedback services, then configures the window layout, grid, and left/right frames to build the user interface.
def __init__(self, state: State, guess_service: BaseGuessService, feedback_service: BaseFeedbackService): super().__init__() self.__feedback_service = feedback_service self.__guess_service = guess_service self.__state = state self.__configure_window() ...
def init_pos(): for i, j in ti.ndrange(N + 1, N + 1): idx = i * (N + 1) + j pos[idx] = ti.Vector([i / N, 0.5, j / N]) inv_mass[idx] = 1.0 inv_mass[N] = 0.0 inv_mass[NV - 1] = 0.0 def init_tri(): for i, j in ti.ndrange(N, N): tri_idx = 6 * (i * N + j) pos_idx = i *...
The code initializes a Hierarchical PBD system by setting up particle positions, triangle/edge structures, neighbor relationships, and constraint restrictions. It marks all particles as coarse, prepares adjacency data, and generates constraint maps (c_l1, c_l1_rl) and weight mappings for hierarchical dynamics simulatio...
def init(): init_pos() init_tri() init_edge() # For Hierarchical PBD is_fine.fill(-1) # init all particles as coarse adj_vertices.fill(-1) init_neighbors() particle_restriction() init_particle_colors() c_l1, c_l1_rl, fine_coarse_index_map, find_coarse_weight_map = constraint_res...
def update_bulk_data(item_id_list, world): """Takes in a list of items stats and queries universalis, then updates each of the provided items""" item_data = req.get(f"https://universalis.app/api/{world.id}/{item_id_list}").json().get("items") items_to_requery = [] updated_items_stats = [] for item i...
The function updates item statistics for a specified world by synchronizing existing item stats, adding missing items, limiting bulk updates, filtering outdated stats based on a freshness threshold, and updating missing crafting costs, then returns the updated data as JSON.
def update_world_data(): # all this expects to take in is a world ID so like {"id": 62} for Diabolos data = request.get_json() world = World.query.get(data.get("id")) item_stats_list = ItemStats.query.filter_by(world_id=world.id).all() item_list = Item.query.all() if len(item_stats_list) < len(i...
def get_data(TableName, orderby="id",order="ASC",start=0,stop=0): con = lite.connect(PathToDatabase) con.row_factory = lite.Row try: cur = con.cursor() query = "SELECT * FROM %s" % TableName + " ORDER BY "+orderby+" "+order if stop > 0: query = "SELECT * FROM %s" % TableN...
The code initializes a camera system for real-time object detection using a TensorFlow model. It configures a Raspberry Pi camera with dual-resolution streaming, captures low-resolution frames, and triggers inference when activated. The system processes grayscale frames with a preloaded model, identifies objects via CO...
def main(): conf = get_data("config") label_file = "coco_labels.txt" model = conf[0]['detection_model'] picam2 = Picamera2() #picam2.start_preview(Preview.QTGL) config = picam2.create_preview_configuration(main={"size": normalSize}, lores={"size":...
def check_fleet_edges(settings,aliens): """Respond appropriately if any aliens have reached an edge.""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(settings,aliens) break def ship_hit(settings,stat,screen,shipObjet,aliens,bullets): """Respond...
This function updates alien positions, checks fleet edges, detects collisions between the ship and aliens, and triggers responses like ship damage or alien movement to the screen bottom, managing game state and interactions in an alien invasion game.
def update_aliens(settings,aliens,shipObject,screen,stats,bullets): """Update the position of all the alien in the fleet""" check_fleet_edges(settings,aliens) aliens.update() if pygame.sprite.spritecollideany(shipObject,aliens): ship_hit(settings,stats,screen,shipObject,aliens,bullets) check...
def check_play_button(stat,play_button,mouse_x,mouse_y,settings,screen,shipObject,aliens,bullets): """Start the New Game when Player clicks the play.""" button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y) if button_clicked and not stat.game_active: settings.initialise_dynamic_settings() ...
This function processes Pygame events to handle user inputs, including quitting the game, detecting mouse clicks on the play button to start gameplay, and responding to keyboard presses/releases for ship movement and shooting. It delegates specific actions to helper functions for keydown and keyup events, ensuring resp...
def check_events(shipObject,bullets,settings,screen,aliens,stat,play_button): """Respond to Mouse and Keyboard Events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.ge...
def get_perspective_transform(src, dst): r"""Calculates a perspective transform from four pairs of the corresponding points. The function calculates the matrix of a perspective transform so that: .. math :: \begin{bmatrix} t_{i}x_{i}^{'} \\ t_{i}y_{i}^{'} \\ t_{i} \\ ...
The main task of the code is to crop 2D image tensors (4D input) using source bounding boxes (src_box) and apply perspective transformations to fit the cropped regions into target bounding boxes (dst_box), returning the transformed patches. It computes a perspective transformation matrix between the boxes, applies it v...
def crop_by_boxes(tensor: paddle.Tensor, src_box: paddle.Tensor, dst_box: paddle.Tensor, interpolation: str = 'bilinear', align_corners: bool = False) -> paddle.Tensor: """Perform crop transform on 2D images (4D tensor) by bounding boxes. Given an input tensor, this function selected the inte...
def filterFrame(df, colpreds, colnames): return df[reduce(lambda x, y: x & y, colpreds)][colnames] def makeFilters(df, pairs): filters = [] for p in pairs: filters.append(p[1](df[p[0]])) return filters def makeIQROutlierPairs(df, cols): pairs = [] for col in cols: pairs.append...
Your return The function `removeIQROutliersFromDF` filters a DataFrame (`df`) by removing rows containing outliers identified via the Interquartile Range (IQR) method for specified columns (`cols`). It uses helper functions to detect IQR outliers, generate exclusion filters, and apply these filters to retain only non-o...
def removeIQROutliersFromDF(df, cols): return filterFrame( df, makeFilters(df, makeIQROutlierPairs(df, cols)), list(df.columns))
def generate_polynomial_features(self, X): """ Maps X to an mth degree feature vector e.g. [1, X, X^2, ..., X^m]. Parameters -------------------- X -- numpy array of shape (n,1), features Returns -------------------- Phi ...
The main task of the code is to fit a polynomial model to data using batch gradient descent (GD) to minimize least squares error. It iteratively updates model coefficients (self.coef_) by computing gradients of the cost function, with an optional decreasing learning rate. The algorithm stops when error changes fall bel...
def fit_GD(self, X, y, eta=None, eps=0, tmax=10000, verbose=True): """ Finds the coefficients of a {d-1}^th degree polynomial that fits the data using least squares batch gradient descent. Parameters -------------------- X -- numpy array of shape (n,d),...
def extract_dictionary(infile): """ Given a filename, reads the text file and builds a dictionary of unique words/punctuations. Parameters -------------------- infile -- string, filename Returns -------------------- word_list -- dictionary, (key, value) pairs are...
The code's main task is to evaluate a linear SVM classifier on a tweet classification dataset. It splits data into training (560 samples) and test sets (70 samples), performs 5-fold stratified cross-validation to select optimal hyperparameters (C) for SVM using accuracy, F1-score, and AUROC metrics, trains the SVM with...
def main() : np.random.seed(1234) # read the tweets and its labels dictionary = extract_dictionary('../data/tweets.txt') X = extract_feature_vectors('../data/tweets.txt', dictionary) y = read_vector_file('../data/labels.txt') metric_list = ["accuracy", "f1_score", "auroc"] ...
def hide_menu(self, menu_frame): menu_frame.pack_forget() def candidate_menu(self): self.root.title("CANDIDATE MENU") # Show candidate frame self.show_menu(self.candidate_frame) tk.Label(self.candidate_frame, text="*" * 54).pack() tk.Label(self.candidate...
The main task of the code is to toggle between hiding the vote frame and displaying the candidate menu, ensuring the candidate menu is created only once. It checks if the menu has been created; if not, it generates and shows it, then sets a flag to prevent re-creation. If already created, it directly displays the candi...
def show_candidate_menu(self): self.hide_menu(self.vote_frame) # Hide vote frame if not hasattr(self, 'candidate_menu_created'): self.candidate_menu() # Create and show candidate menu self.candidate_menu_created = True # Set the flag to indicate that the candidate menu has bee...
def get_issues(filter_name, tagged, start=0): """ Gets the set of Jira issues based on the relevant Jira filter. Only the issue data necessary for this application is returned (whether documentation is required, which documents should be affected, which documents have been updated, assignee, summary, an...
The function updates a team's documentation workbook by synchronizing existing issues with a Jira filter. It updates rows for issues already in the sheet, adds new rows for issues from the Jira filter not present in the sheet, and highlights rows containing issues no longer in the filter. It uses strike-through formatt...
def update_sheet(team): """ The main function for adding issues which should be documented to the Documentation workbook. Updates the information about each issue which is already in the sheet, adds new rows for issues which are tagged to affect documentation but are not in the sheet, and highlights any...
def get_command_help(self, name, command): return '{prefix}{name} {args} - {desc}\n'.format( prefix=self.config['command-prefix'], name=name, args=self.get_command_args_help(command), desc=self.get_command_description(command), ) def get_extension_help(self, name, extension): if len(extension.commands...
The main task of the code is to generate and display a help message listing available commands and extensions. It constructs a formatted string starting with a help header, adds the 'help' command's description, iterates through extensions to append their help information, and finally sends the compiled result as a rep...
def help_command(self, args, event): result = '\n== Help ==\n' result += self.get_command_help('help', { 'description': 'shows this help', }) for name, extension in zip(self.extension_names, self.extensions): result += self.get_extension_help(name, extension) self.reply(result)
def forward_prop(DeepNetwork, x_train): DeepNetwork.parameters['W1'] = DeepNetwork.parameters['W1']*DeepNetwork.mask1 DeepNetwork.parameters['W2'] = DeepNetwork.parameters['W2']*DeepNetwork.mask2 DeepNetwork.parameters['Wio'] = DeepNetwork.parameters['Wio']*DeepNetwork.maskio DeepNetwork.parameters_2['A0'] = ...
The code trains a deep neural network using mini-batch gradient descent with momentum. It iterates over epochs, processes data in batches, performs forward and backward propagation, updates weights, and tracks average cost and validation accuracy per epoch. The function returns the final cost and accuracy after trainin...
def train(DeepNetwork, x_train, y_train, x_val, y_val, epochs,l_rate, momentum, batch_size): start_time = time.time() n_examples = x_train.shape[1] iteration = 0 n_batches = round(n_examples/batch_size + 0.5) accuracy_epoch = 0 cost_epoch = 0 for iteration in range(epochs): costs_for_batch = [] accuraci...
def poll(s, sign = '?'): ''' Prints a question to the user ''' print_wrapped('[{0}] {1}'.format(sign, s), end_newline = False) def info(s, sign = '*'): ''' Print an informational message with '*' as a sign ''' print_wrapped('[{0}] {1}'.format(sign, s)) def fail(err = None): ''' C...
The main task of the code is to prompt the user to unload the IOFireWireIP kernel extension on macOS if present, execute the unloading via `kextunload`, and report success or failure. It warns about potential kernel panics, confirms user intent, and provides reload instructions if successful. Your return
def unload_fw_ip(): ''' Unloads IP over FireWire modules if present on OS X ''' poll('IOFireWireIP on OS X may cause kernel panics. Unload? [Y/n]: ') unload = input().lower() if unload in ['y', '']: status = call('kextunload /System/Library/Extensions/IOFireWireIP.kext', ...
def get_part_name_string(cnx, part, part_id): if not part_id: return '' with cnx.cursor() as cursor: cursor.execute(get_part_name(part, part_id)) s = "" for res in cursor.fetchall()[0]: s += f"{res} " return s def modification_menu(cnx, computer_name, part): m...
This function generates a curses-based menu for managing a computer build, displaying its components and options. It queries a database for the specified computer's parts, creates menu entries for each component, and links them to modification submenus. Additional options allow saving the build, viewing specs, and acce...
def computer_menu(cnx, computer_name): menu_entries = [] # Get the Field names and results for the current computer worked on with cnx.cursor() as cursor: cursor.execute( f"SELECT * FROM computer WHERE computer.name = \"{computer_name}\"" ) ids = cursor.fetchall()[0][1:] ...
def start(IP, PORT, username): global WAIT client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.settimeout(5) client_socket.connect((IP, PORT)) # received functionality will not be blocking client_socket.setblocking(0) ch = send_msg(username, client_socket, 'txt')...
The code establishes a client connection to a server at IP 127.0.0.1 on port 1234 using a specified username. It continuously receives messages via `receive_client()` in a loop and sends messages using `sending_messages()`, creating a basic client-server communication framework for real-time data exchange.
def main(): IP = "127.0.0.1" PORT = 1234 username = input('Username: ') client_socket = start(IP, PORT, username) header(username) while True: receive_client(client_socket) # Thread(target=sending_messages, args=(username, client_socket)).start() sending_messag...
def _send_available(self): self._mqttc.publish(self._make_evt_topic("avail"), self._make_evt_message_string(True), retain=True) def _send_version(self): value = { "serial": self._sharc_id, "sw": "DEV/FROZEN", "hw": "105", "fw": "ff00ff0", "model": "SHARC", "mfg": "Frenzy Engineering" } self._m...
This method handles MQTT client connection events by setting connection status, subscribing to a command topic, and sending device status updates including availability, version, reboot counts, network info, and MQTT status. It also triggers a user-defined callback if provided.
def _on_connect(self, client, userdata, flags, rc): self._is_connected = True if rc == 0 else False self._mqttc.subscribe(f"sharc/{self._sharc_id}/cmd/#") self._send_available() self._send_version() self._send_reboot_counts() self._send_network() self._send_mqtt() if self._cb_on_connect is not None: ...
def tryGettingMovie(self, i): resultTab = [] try: sourceCodeA = request.urlopen(self.urlMovieNorm + str(i), timeout=10).read() sourceCodeB = request.urlopen(self.urlMoviePro + str(i), timeout=10).read() infoMovieNorm = IMDbNormalMovie(sourceCodeA) infoMov...
The main task of the code is to process movie data by calling `tryGettingMovie`, then categorize and write the result to different files based on the return code: "good" file for code 0, "good without budget" for code 2, and "wrong" file otherwise. It also prints the input index `i` for tracking.
def getMovie(self, i): print(str(i)) result = self.tryGettingMovie(i) if result[0] == 0: self.printToGoodFile(result[1]) elif result[0] == 2: self.printToGoodWithoutBudgetFile(result[1]) else: self.printToWrongFile(result[1])
def _process_outputs(self) -> None: needed_data_gen_ids: set[str] = set() for output in self.output_list: if isinstance(output, SedMLPlot): if isinstance(output, SedMLPlot2D): for i in range(output.getNumCurves()): curve: SedMLCurve...
The main task of the code is to process a document by sequentially handling outputs, data generation, variables/parameters, and tasks. It orchestrates parsing and organizing these components to prepare models and simulations, ensuring necessary data is collected and structured for subsequent operations.
def _process_document(self) -> None: # Each call grabs the needed values for the next "call" # until we have parsed models and sims. self._process_outputs() self._process_data_gens() self._process_variables_and_params() self._process_tasks()
def eratos(n): bools = [] for i in range(n): bools.append(True) for i in range(2, n): if bools[i] == True: for j in range(i + i, n, i): bools[j] = False primes = [] for i in range(2, n): if bools[i] == True: primes.append(i) ...
The code tests RSA encryption/decryption by generating random prime pairs from a sieve, creating keys, encrypting an array, decrypting it, and verifying data integrity. It checks if the original array matches the decrypted result to ensure correctness.
def units(): arr = [] for i in range(80000, 80100): arr.append(i + 2) er = eratos(1000) for i in range(1000): ra = random.randint(len(er) // 4, len(er) - 1) rb = random.randint(len(er) // 4, len(er) - 1) while ra == rb: ra = random.randint(len(er) // 4, len(...
def int_arr_to_bits64(i_arr, action): extra = 0 if len(i_arr) % 8 != 0: extra = 8 - len(i_arr) % 8 for i in range(extra): i_arr.append(0) bits = [] bits_tmp = [] for i in range(len(i_arr) ): if i > 0 and i % 8 == 0: bits.append(bits_tmp) bi...
The code encrypts or decrypts a binary file using a key. It reads the file, converts it to bits, applies encryption/decryption with generated keys, and writes the result back as a binary file.
def work(fn, action): arr = int_arr_to_bits64(bytes_to_int_arr(read_bin_file(fn)), action) key = load_key(sys.argv[1]) keys = generate_keys(key) res = [] for a in arr: if action == "e": c = encrypt(a, keys) if action == "d": c = decrypt(a, keys) ...
def parse_headings(self) -> None: """ Finds using RegEx the headings in :instance_attribute:`self._input`. Add all these headings to the root of the contents tree, that is the :instance_attribute:`self._contents_tree`. :return: """ # find all headings by matching regex ...
The code processes input Markdown text to generate a table of contents (ToC), parsing headings, constructing a hierarchical structure, and creating ToC items with optional hyperlinks and navigation links. It excludes titles if specified, manages ToC placement, and builds a structured ToC for navigation.
def __init__(self, original: str, includes_title: bool = False, link: bool = True, back_to_toc_link: bool = True): """ :param original: Input Markdown text. :param includes_title: Whether a Title is included in the input text. If so, it'll be excluded from the ToC. :param link: Whether ...
def getinstance(): r = requests.get('http://localhost:8081/instance', headers=headers) return r def goto(row, column): r = getinstance() posx = int(r.json()['payload']['location']['x']) posy = int(r.json()['payload']['location']['y']) t_posx = int(column) t_posy = int(row) # === MOVE X ...
The code checks if the robot's location is within a threshold of the organic bin and if it holds many items or is the last task. If true, it navigates to each bin type (organic, recycle, garbage) in sequence, unloading collected items into them. The function uses location data, item counts, and a scan radius to decide ...
def checkBins(isLast): payload = getinstance().json()['payload'] instance = getinstance().json() bins = payload['constants']['BIN_LOCATION'] organicBin = bins['ORGANIC'] organicX = organicBin['X'] organicY = organicBin['Y'] recycleBin = bins['RECYCLE'] recycleX = recycleBin['X'] recy...
def scan(): r = requests.post('http://localhost:8081/scanArea', headers=headers) rj = r.json() return rj def goto(row, column): r = getinstance() posx = int(r.json()['payload']['location']['x']) posy = int(r.json()['payload']['location']['y']) t_posx = int(column) t_posy = int(row) ...
The function scans for located items, moves to each item's coordinates to collect them, and returns a boolean indicating if any collection action was required.
def scanSpot(): shouldReRun = False instanceInfo = scan() currentLoc = instanceInfo['payload']['location'] scannedInfo = instanceInfo['payload']['itemsLocated'] for elements in scannedInfo: shouldReRun = True goto(elements['y'], elements['x']) collect(elements['id']) retu...
def goto(row, column): r = getinstance() posx = int(r.json()['payload']['location']['x']) posy = int(r.json()['payload']['location']['y']) t_posx = int(column) t_posy = int(row) # === MOVE X === if (t_posx < posx): move('W', posx - t_posx) elif(t_posx > posx): move('E', ...
The main task of the code is to mark a specific grid cell (r,c) as cleaned (newone[r][c] = 1), navigate to its physical coordinates via goto(), repeatedly scan the spot until completion, check cleaning bins, and return the updated grid state. The function handles robotic cleaning operations by coordinating position tra...
def scanAndClean(r, c, xMin, yMin, newone): newone[r][c] = 1 print(r, c) goto(yMin+r, xMin+c) shouldReRun = scanSpot() while (shouldReRun): goto(yMin+r, xMin+c) shouldReRun = scanSpot() checkBins(False) return newone
def _count_func_call(self, node): if isinstance(node.func, ast.Name): self.call_count[node.func.id] = self.call_count.get(node.func.id, 0) + 1 if isinstance(node.func, ast.Attribute): self.call_count[node.func.attr] = self.call_count.get(node.func.attr, 0) + 1 def _cond_features(...
This method counts specific code elements in an AST: function calls, if statements, loops, breaks, continues, and variables. It also detects recursion by iterating through nodes and updating counters/flags for analysis.
def _countable_features(self): for node in self.node_list: # func call counts if isinstance(node, ast.Call): self._count_func_call(node) # if count if isinstance(node, ast.If): self.ifs_count += 1 self._cond_features...
def profile(Motifs): t = len(Motifs) k = len(Motifs[0]) profile = {} count = count(Motifs) for symbol, countArray in count.items(): profile[symbol] = [x / t for x in countArray] return profile def ProfileMostProbableKmer(text, k, profile): highestProbability = -1 mostProbablePatt...
(GreedyMotifSearch identifies the best set of k-length motifs (one per DNA string in Dna) with the lowest score using a greedy approach. It initializes motifs from the first k-mers of each DNA string, then iterates through all possible k-mers in the first DNA string. For each, it constructs a motif matrix by selecting ...
def GreedyMotifSearch(Dna, k, t): BestMotifs = [] # get the first k-mers from each DNA to form an intitial array of best motifs for index in range(0, t): BestMotifs.append(Dna[index][0:k]) # going trough all the possible k-mers in DNA[O] and forming motifs matrix from the rest dna strings # ...
def ProfileWithPseudocounts(Motifs, l): t = len(Motifs) k = len(Motifs[0]) profile = {} count = CountWithPseudocounts(Motifs) for symbol, countArray in count.items(): profile[symbol] = [x / (t + l) for x in countArray] return profile def ProfileMostProbableKmer(text, k, profile): hig...
(GreedyMotifSearchWithPseudocounts identifies the best set of k-length motifs from t DNA sequences using a greedy algorithm with pseudocounts. It initializes motifs from the first k-mer of each DNA string, iterates through all possible k-mers in the first DNA, constructs motifs for remaining sequences using profile-bas...
def GreedyMotifSearchWithPseudocounts(Dna, k, t): BestMotifs = [] # get the first k-mers from each DNA to form an intitial array of best motifs for index in range(0, t): BestMotifs.append(Dna[index][0:k]) # going trough all the possible k-mers in DNA[O] and forming motifs matrix from the rest dn...
def RandomMotifs(Dna, k, t): motifs = [] for index in range(0, t): dnaString = Dna[index] startMotifIndex = random.randint(1, k) endMotifIndex = startMotifIndex + k randomMotif = dnaString[startMotifIndex:endMotifIndex] motifs.append(randomMotif) return motifs def Pro...
The main task of the code is to perform randomized motif search in DNA sequences by iteratively generating motifs from a profile with pseudocounts, updating the best motifs when a lower score is achieved, and terminating when no further improvement is possible. It aims to identify optimal k-length motifs across t DNA s...
def RandomizedMotifSearch(Dna, k, t): motifs = RandomMotifs(Dna, k, t) BestMotifs = motifs count = 1 while True: profile = ProfileWithPseudocounts(motifs, count) motifs = Motifs(profile, Dna) if Score(motifs) < Score(BestMotifs): BestMotifs = motifs else: ...
def RandomMotifs(Dna, k, t): motifs = [] for index in range(0, t): dnaString = Dna[index] startMotifIndex = random.randint(1, k) endMotifIndex = startMotifIndex + k randomMotif = dnaString[startMotifIndex:endMotifIndex] motifs.append(randomMotif) return motifs def Pro...
The GibbsSampler function iteratively improves a set of random k-mers from DNA sequences by replacing each motif with a new k-mer generated from a profile matrix (with pseudocounts) of the remaining motifs. It runs N iterations, updating the best motifs if the current set has a lower score, aiming to find the optimal m...
def GibbsSampler(Dna, k, t, N): BestMotifs = [] random_motifs = RandomMotifs(Dna, k, t) BestMotifs = random_motifs for j in range(N): index = random.randint(0, t - 1) deleted_motif = random_motifs.pop(index) profile_matrix = ProfileWithPseudocounts(random_motifs, 4) kmer ...
def RandomMotifs(Dna, k, t): motifs = [] for index in range(0, t): dnaString = Dna[index] startMotifIndex = random.randint(1, k) endMotifIndex = startMotifIndex + k randomMotif = dnaString[startMotifIndex:endMotifIndex] motifs.append(randomMotif) return motifs def Ran...
The code performs repeated randomized motif search to find the best set of motifs in DNA sequences. It initializes with random motifs, iterates N times, each time generating new motifs via randomized search, and updates the best motifs if the current score is lower. The goal is to identify optimal k-mer motifs across t...
def RepeatedRandomizedMotifSearch(Dna, k, t, N): BestMotifs = RandomMotifs(Dna, k, t) for index in range(0, N): motifs = RandomizedMotifSearch(Dna, k, t) if Score(motifs) < Score(BestMotifs): BestMotifs = motifs return BestMotifs
def validValue(self, value): valid_values = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} val_str = str(value) if (len(val_str) != 1) or (val_str not in valid_values): return False else: return True def validCell(self, cell): valid_dims = {'0', '1', '...
The function `addValue` adds a value to a specified Sudoku cell, validating the input and checking for row, column, or box conflicts. It updates the grid (`sudoku_cells` or `solution`) and associated data structures (`row`, `col`, `box`) if valid. It returns `True` on success or `False` with error messages if invalid, ...
def addValue(self, value, cell, state, printing=0, validation=0): # adds value to cell # returns True if adding can be done according to Sudoku rules, otherwise False # state: 'normal' for sudoku_cells, 'solving' for solution # printing: 0 specifies not printing error messages, 1 specifi...
def addValue(self, value, cell, state, printing=0, validation=0): # adds value to cell # returns True if adding can be done according to Sudoku rules, otherwise False # state: 'normal' for sudoku_cells, 'solving' for solution # printing: 0 specifies not printing error messages, 1 specifi...
This recursive function implements backtracking to solve a puzzle by testing possible values (1-9) in a given cell. It adds a value, proceeds to the next blank cell, and recursively solves until no more cells remain (returns True on success). If a dead end is reached, it backtracks by removing the value and trying the ...
def helper(cell, path): values = [1,2,3,4,5,6,7,8,9] for guess in values: if self.addValue(guess, cell, 'solving', 0, 0): path.append((guess, cell)) #input('Guess worked: {}'.format(path)) next_cell = self.nextBlankCell(...
def extractTitle(pdf, titlePageNm): titlePageNm -= 1 tmp = fitz.open() title = '' try: tmp.insertPDF(pdf, from_page=titlePageNm, to_page=titlePageNm) # make a 1-page PDF of it tmp.save("Temp/paperTitle.pdf") completed_process = subprocess.run(['pdftitle', '-p', 'Temp/paperTitle....
This function extracts keywords and the paper title from a PDF page. It identifies the abstract section, locates keywords following 'keywords' or 'key words', processes them into a cleaned list, updates a keyword vector, and retrieves the paper title from the document or table of contents. It returns the extracted keyw...
def getPageKeywords(page, pageNm, pdf, pdfToc, catIdx, fileIdx): global insidePaper, paperText, GENERAL_PAPER_VECTOR, all_keywords#, zeroKeywords blocks = page.getText('blocks') textBlocks = [block[4].replace('-\n', '').replace('\xa0', ' ').replace('\n', ' ').strip() for block in blocks if not block[4].issp...
def populateVectors(catIdx, fileIdx): global paperText, nlp_arc, nlp_act, nlp_build, insidePaper, paperCount, paperIDcounter try: arcModelEnts = [ent.text for ent in nlp_arc(paperText).ents] actModelEnts = [ent.text for ent in nlp_act(paperText).ents] buildBlockModelEnts = [ent.text for ...
This function processes text lines to detect a 'references' section. If found, it updates entity vectors, writes them, and resets for the next paper. If not, it accumulates text for the current paper.
def tryMakeEntityVector(pageTextInLines, catIdx, fileIdx): global insidePaper, paperText, GENERAL_PAPER_VECTOR, all_keywords if insidePaper: for line in pageTextInLines: if line[0:10].lower() == 'references' or line[0:9].lower() == 'refrences': populateVectors(catIdx, fileIdx...
def getPageKeywords(page, pageNm, pdf, pdfToc, catIdx, fileIdx): global insidePaper, paperText, GENERAL_PAPER_VECTOR, all_keywords#, zeroKeywords blocks = page.getText('blocks') textBlocks = [block[4].replace('-\n', '').replace('\xa0', ' ').replace('\n', ' ').strip() for block in blocks if not block[4].issp...
The main task of the code is to extract keywords from a PDF document, build a keyword-based vector representation of the paper's content, and return the list of extracted keywords. It processes each page, identifies relevant sections (excluding references), updates keyword counts, and manages global state variables for...
def makeVectorForPDF(pdf, catIdx, fileIdx): global GENERAL_PAPER_VECTOR, paperText, insidePaper, all_keywords, paperIDcounter paperIDcounter = 1 pdfToc = pdf.getToC() # getting all the ToC titles, except the word References, because it is needed for finding the end of a research paper tocTitlesNoRef...
def preprocess_input(self, data): # move to GPU and change data types data['label'] = data['label'].long() if self.use_gpu(): data['label'] = data['label'] data['instance'] = data['instance'] data['image'] = data['image'] # create one-hot label map ...
The code defines an `execute` method that processes input data (`data`) and mode (`mode`) to perform different tasks in a neural network model. Depending on the mode, it preprocesses inputs, computes generator or discriminator losses, encodes inputs, or generates fake images. For 'generator' mode, it calculates loss an...
def execute(self, data, mode): input_semantics, real_image = self.preprocess_input(data) # print(input_semantics.size()) [1, 36, 256, 512] print(real_image.size()) [1, 3, 256, 512] # print(label_map.size()) [1, 1, 256, 512] if mode == 'generator': g_loss, generated, result_global, r...
def _get_pkgs_incl_deps(key, exs=set()): """ get package and its dependencies Parameter: pkg: key of package ex: set of keys of packages which should be excluded, including their dependencies Return: set set of keys """ global _packages if (key in exs) or (key not in _...
This code parses command-line arguments to determine packages for uninstallation or listing, considering dependencies and exclusions. It uses global variables to track top-level packages and protected items, processes exclusion lists, and outputs either pip uninstall commands or package details based on flags like --un...
def main(): global _tops global _protected psr = argparse.ArgumentParser(fromfile_prefix_chars='@') psr.add_argument('-u', '--uninstall', action='store_true', help=('List the packages and dependencies to uninstall,' ' but except those required by other pa...
def wrapAndSaveMarka(): soup = renewIPadress(basePath+"/tr/allbrands") brandLinks = soup.findAll("a", attrs={"class": "marki_blok"}) for bl in brandLinks: marka, created = Marka.get_or_create( Ad=bl.text.strip(), imgSrc=basePath + bl.next["src"], Link=basePath+bl[...
The main task of the code is to process and update records in a database through sequential steps: it retrieves all "Marka" entries, generates models for each, processes models to assign classes, updates class records to link generations, and finally checks each generation for missing technical details, creating them i...
def start(): wrapAndSaveMarka() allMarka = Marka.select() pbar = tqdm(allMarka,total=(len(allMarka))) for marka in pbar: pbar.set_description(marka.Ad); getModel(marka) pbar=None allModel = Model.select() pbar = tqdm(allModel,total=(len(allModel))) for m in pbar...
def is_second(self, second): return 0 <= second and second < 60 and isinstance(second, int) def is_minute(self, minute): return 0 <= minute and minute < 60 and isinstance(minute, int) def is_hour(self, hour): return 0 <= hour and hour < 24 and isinstance(hour, int) def is_day(self, day): ...
The code's main task is to validate time components (second, minute, hour, day, month, year) by checking each against specific validation methods (e.g., is_second, is_minute). It uses assert statements to ensure inputs conform to expected formats, raising errors with descriptive messages if any parameter fails validati...
def validate(self, second, minute, hour, day, month, year): assert self.is_second(second), 'Invalid format for "second" parameter.' assert self.is_minute(minute), 'Invalid format for "minute" parameter.' assert self.is_hour(hour), 'Invalid format for "hour" parameter.' assert self.is_day...
def add_second(self, second): self.second += int(second) while not self.is_second(self.second): self.second -= 60 self.minute += 1 def add_minute(self, minute): self.minute += int(minute) while not self.is_minute(self.minute): if minute >= 0: ...
This method adds specified time intervals to an object's current time by delegating each unit (seconds, minutes, hours, days, months, years) to corresponding individual methods, allowing incremental adjustments to the object's temporal value.
def add(self, second=0, minute=0, hour=0, day=0, month=0, year=0): self.add_second(second) self.add_minute(minute) self.add_hour(hour) self.add_day(day) self.add_month(month) self.add_year(year)
def subtract_second(self, second): self.second -= int(second) while not self.is_second(self.second): self.second += 60 self.minute -= 1 def subtract_minute(self, minute): self.minute -= int(minute) while not self.is_minute(self.minute): self.minute += ...
This code defines a method to subtract specified time intervals (seconds, minutes, hours, days, months, years) from a date/time object. It sequentially calls individual subtraction methods for each unit, using provided parameters or defaulting to 0 if unspecified. The primary task is to adjust the object's date/time by...
def subtract(self, second=0, minute=0, hour=0, day=0, month=0, year=0): self.subtract_second(second) self.subtract_minute(minute) self.subtract_hour(hour) self.subtract_day(day) self.subtract_month(month) self.subtract_year(year)
def pilihan(list_pilihan,block): ''' Fungsi untuk menerima jawaban nomor Melakukan check input apakah sesuai dengan nomor Input :(list->int) list_pilihan = List pilihan, paling akhir adalah exit Output :(int) pilihan = Bilangan integer ''' status = True print(block) while(status): ...
The function `menu_view()` displays a stock management menu allowing users to view all stock items, view specific items, or return to the main menu. It uses a loop to repeatedly prompt for input until the user selects "Kembali ke menu utama" (option 3). If the stock is empty, it shows an error. Otherwise, it calls `vie...
def menu_view(): '''Fungsi untuk menampilkan menu daftar''' menu=f''' {" Melihat Stock ":+^{50}} 1. Lihat semua 2. Lihat tertentu 3. Kembali ke menu utama ''' pil = pilihan([1,2,3],menu) while(pil!=3): if len(stock)==0: print('\n[ERROR] Tidak ada data') el...
def check_input(col, unique=False): ''' Fungsi untuk memeriksa input pada field Input :-(str) col = nama field -(bool) unique = apakah jika field nama harus unique atau tidak Output :Value yang telah tervalidasi ''' status = True acc_type = columns[col]['type'] limit_char = c...
The function creates a new stock item by copying a template, validates and ensures uniqueness of input fields, confirms addition with user input, generates a unique ID, and adds the item to the stock dictionary with the generated ID, printing a success message upon confirmation.
def create_stock(): ''' Funsgi untuk menambahkan stock baru Mengatasi duplikasi yang ada pada nama ''' global gen_pk, stock new_stock = template_stock.copy() for key in new_stock.keys(): new_stock[key] = check_input(key,unique=True) else: if confirmation(new_stock, 'T...
def get_stock(ID): ''' Fungsi untuk mengambil stock dari ID Input :(int) ID = ID dari produk (unique keys) Output :-(bool) status = True or False, ada atau tidak -(dict) stock = jika status True akan mengembalikan dict -(str) pesan = jika status False akan mengembalikan pesan ...
The function updates a product's stock information based on the provided ID. It retrieves the existing product data, prompts the user to select fields for modification, validates new inputs, and applies changes to the global stock dictionary after user confirmation. The process includes checking input uniqueness, displ...
def update_stock(ID): ''' Fungsi untuk memperbarui stock Memperbarui berdasarkan ID Input :(int) ID = ID dari stock yang ingin dihapus ''' global stock status, dump = get_stock(ID) if status: view_selected([ID]) if y_or_n(custom='Apakah anda ingin melanjutkan?[Y/N]\t:'): ...
def initialize(predata=False): ''' Fungsi inisialisasi Fungsi ini digunakan untuk menciptakan variabel dan generator. Input :(bool) predata -> Inisiasi dengan data awal Output :(None) Generate: - gen_pk = generator unique key - primary_keys = menyimpan unique key - st...
The main task of the code is to run a menu-driven application that initializes data, displays a main menu, and processes user choices (view, create, delete, update) through corresponding functions in a loop until the user selects the exit option (5).
def main(): '''Fungsi yang akan dijalankan''' initialize(predata=True) # Inisiasi pilihan = main_menu() # Menampilkan main menu dan menerima pilihan while pilihan != 5: if pilihan == 1: menu_view() elif pilihan == 2: menu_create() elif pilihan == 3: ...
def dropZeroColumns(reagents, uniqueChemicalNames=None): """ Version of dropZeroColumns that includes the uniqueChemicalNames corresponding to only nonzero columns in the reagent dictionary. Args: reagents: Dictionary defining the reagents. uniqueChemicalNames: (optional) Provide a list of uni...
The main task of the code is to generate all valid combinations of chemical concentrations and corresponding reagent volumes under specified constraints (e.g., max molarity, final volume). It processes reagent definitions and unique chemical names to compute achievable concentration grids, converts them to rounded volu...
def generateEnumerations(reagentDefs, uniqueChemicalNames, deltaV=10., maxMolarity=9., finalVolume=500., processValues='round'): """ Generates the enumerations for the defined reagents and unique chemical names supplied. Args: reagentDefs: Dictionary defining the reagents. uniqueChemicalNames...
def dropZeroColumns(reagents): """ Deletes any nonzero columns and reformats a dictionary of reagents. Args: reagents: Dictionary of reagents. Returns: Dictionary of reagents with only the non-zero columns returned. """ d_keys = list(reagents.keys()) array = np.array(list(re...
The function `generateExperiments` generates experimental concentration-volume combinations based on reagent definitions and constraints. It selects between 3D sampling or hit-and-run methods depending on the species dimensionality. When excluding reagents, it computes geometric hulls of allowed and excluded regions, s...
def generateExperiments(reagentDefs, excludedReagentsDef=None, nExpt=96, maxMolarity=9., finalVolume=500.): if excludedReagentsDef == None: """ This is the main interface that takes in the dictionary of reagent definitions, decides what experiment generation code to run, and returns the results. I...
def _get_map_db(self, deta_space_base_name: str): db = self._maps.get(deta_space_base_name) if db is None: db = self._deta.Base(deta_space_base_name) self._maps.update({deta_space_base_name: db}) return db def lookup_user_name_map(self, user_name: str, fetch_if_not_fou...
This function retrieves the list of user IDs that a specified Twitter user is following. It checks a database cache first; if `force_fetch` is True or data is missing, it fetches fresh data via API, updates the cache with timestamps, and maps usernames to IDs. The result is a list of user IDs representing the target us...
def get_following_of_user(self, user_name: str, force_fetch: bool = False) -> list : db = self._get_map_db(self.USER_ID_FOLLOWING_MAP) user_id = self.lookup_user_name_map(user_name, fetch_if_not_found=True) user_id_list = list() db_ret = db.get(user_id) if force_fetch or...
def lookup_user_name_map(self, user_name: str, fetch_if_not_found:bool = False) -> str: db = self._get_map_db(self.USER_NAME_MAP_BASE_NAME) db_ret = db.get(user_name) user_id = None try: user_id = db_ret['user_id'] except Exception as ex: print(f"username:{user...
This function checks if a user (by ID or name) is in a specified list, using a database lookup. If not found and `sync_if_not_found` is True, it triggers a sync and rechecks. Returns True if the user is in the list, False otherwise. Requires either `tgt_user_id` or `tgt_user_name`; raises an error if both or neither ar...
def lmtc_is_user_in_list(self, list_id: str, tgt_user_id: str = None, tgt_user_name: str = None, sync_if_not_found: bool = False) -> bool: ''' Check if the given user is in the list or not. Return True or False accordingly. If sync_if_not_found is set th...
def check_for_dotfiles_dir(): if os.path.exists(env.get_dotfiles_dir()): return True else: os.mkdir(env.get_dotfiles_dir()) def create_directory_structure(path): dirs = extract_list_of_directories(path) create_dirs(dirs) def extract_target_dir(path): dirs = path.split("/") del di...
This function adds a specified file to the user's dotfiles directory by creating necessary directory structures, navigating to the target directory, and copying the file to its designated destination within the dotfiles directory.
def add_file_to_dotfiles_dir(path): check_for_dotfiles_dir() os.chdir(env.get_dotfiles_dir()) create_directory_structure(fh.path_relative_to_home(path)) os.chdir(extract_target_dir(path)) fh.copy_file(path, generate_destination_path(path))
def buildPathLayer(self): self.sizeLayers() full_layer = [] for x in range(0, (self.x_len)): temp_col =[] for y in range(0, (self.y_len)): if x >= self.intersection_seed[0][1] and x < self.intersection_seed[0][1] + self.intersection_seed[1][0] \ ...
This code initializes a traffic intersection simulation environment. It sets up streets from input data, configures scoring features, prepares machine learning components (action space, layers for paths/cars/lights), and defines the observation space for an agent. The main task is to create a reinforcement learning env...
def __init__(self, intersection_seed: list): self.prev_action = None self.intersection_seed = intersection_seed #Streets self.streets = [] for street in self.intersection_seed: self.streets.append(Intersection.Street(*street, self)) #Scoring Features s...
def indexing(corpus, ram_limit=1024, d_test=True, stemmed=True): start_time = time.time() global stemming stemming = stemmed if stemming: analyzer = StemmingAnalyzer() else: analyzer = StandardAnalyzer() schema = Schema(doc_id=NUMERIC(stored=True), date=TEX...
The main task of the code is to index a corpus, measure indexing time and disk space, count indexed documents, and execute boolean and ranked queries (TF-IDF/BM25) for topic 104. It builds an inverted index, evaluates performance metrics, and retrieves results using specified retrieval models.
def main(): ix, ix_time, ix_space = indexing(corpus_dir, 2048, stemmed=True) # ix, ix_time, ix_space = indexing(corpus_dir, 2048, stemmed=False) # ix, ix_time, ix_space = open_dir(os.path.join("indexes", "docs")), 0, 0 # print("Whole index:"); print_index(ix) print(f"Time to build index: {round(ix_t...
def noise_interpolation(self, noise, noise_wavelengths): if type(noise) == int: noise_profile = noise * np.ones_like(self.wavelengths) elif type(noise) == float: noise_profile = noise * np.ones_like(self.wavelengths) else: noise_profile = np.interp(self.wavele...
The code performs Bayesian abundance retrieval of a test species from noisy spectra. It generates model and test spectra, computes posterior probability distributions via repeated noisy fittings, calculates mean and standard deviation of log10 abundances, and returns abundance values with their Bayesian likelihoods.
def perform_abundance_retrieval(self, test_species, noise, plot=True, signal_samples=111, repeats = 90, noise_wavelengths=None, min_abundance=-11): noise = self.noise_interpolation(noise, noise_wavelengths) self.background_spectrum, self.wavelengths = self.calculate_transmission_sp...
def compile_band_list(band_input_data, JWST_noise=True, spectral_resolution=1000, use_prism=True, auto_assign=True): # create dictionary of Spectral Band objects from band_input_data input file (e.g. prebiosignature.py) ...
The function `run_band` evaluates the detectability of atmospheric species in a specified spectral band using input data. It compiles band data, selects the target band, and assesses detection thresholds for all or a specified species. Parameters like spectral resolution, noise, and abundance limits guide the analysis,...
def run_band(band_name, atmosphere_input_data, band_input_data, spectral_resolution=1000, retrieved_species='All', JWST_noise=True, output_file='Results.txt', auto_assign=True, min_abundance=-6, use_pris...
def compile_band_list(band_input_data, JWST_noise=True, spectral_resolution=1000, use_prism=True, auto_assign=True): # create dictionary of Spectral Band objects from band_input_data input file (e.g. prebiosignature.py) ...
The code computes detection thresholds for atmospheric species across specified spectral bands. It processes input atmosphere and band data, iterates through bands and species, and assesses detectability using parameters like spectral resolution and noise models. Results are saved to a file. Your return
def run_atmosphere(atmosphere_input_data, band_input_data, spectral_resolution=1000, JWST_noise=True, output_file='Results.txt', auto_assign=True, min_abundance=-6, use_prism=True, ...
def init_parameters(): w1 = np.random.rand(30, 784) - 0.5 b1 = np.random.rand(30, 1) - 0.5 w2 = np.random.rand(10, 30) - 0.5 b2 = np.random.rand(10, 1) - 0.5 return w1, b1, w2, b2 def forward(x, w1, b1, w2, b2): z1 = np.dot(w1, x) + b1 a1 = ReLU(z1) z2 = np.dot(w2, a1) + b2 a2 =...
The code implements gradient descent for training a neural network with two layers. It initializes parameters, iteratively performs forward and backward propagation to compute gradients, updates weights and biases, and evaluates model performance on test data every 10 epochs by calculating loss and accuracy. The main t...
def gradient_descent(epochs, train_X, train_Y, test_X, test_Y): w1, b1, w2, b2 = init_parameters() for epoch in range(epochs): z1, a1, z2, a2 = forward(train_X, w1, b1, w2, b2) dw1, db1, dw2, db2 = backprop(train_X, train_Y, w1, b1, w2, b2, z1, a1, z2, a2) w1, b1, w2, b2 = upda...
def get_playlists(doVerify = False): ''' returns a dictionary of playlists with their titles as keys and their ids as values. ''' if (not doVerify): credentials = get_credentials() else: credentials = verified_credentials() yt = build('youtube', 'v3', credentials = credentials) print("Connected to Youtube") ...
This function retrieves all items from a YouTube playlist specified by name or ID, handling pagination, retries on API failures, and duplicate page detection. It uses YouTube API credentials, fetches playlist items in batches, and returns a consolidated list of all items while ensuring robustness against invalid inputs...
def get_playlist_items(playlist_name = None, playlist_id = None,doVerify = False): ''' Precondition: at least one of playlist_name, playlist_id is not None Returns a list of PlaylistItems inside a given playlist, specified by title or id Robust for duplicate pages being returned, page tokens being bad sometimes ''...
def deep_sha1_hash(s): orig_str = s s = type_convert(s) s = sha1(s).hexdigest().encode('ascii') for c in orig_str: s = sha1(s+type_convert(c)).hexdigest().encode('ascii') return sha1(type_convert(orig_str) + s).hexdigest()[:MAX_LENGTH] def sha1_hash(s): s = type_convert(s) return sha...
This code searches for hash collisions in SHA1 or a "deep" variant by generating strings with itertools.product, starting from a specified index. It compares each generated string's hash to a target hash, printing progress and displaying collisions when found. The function warns that high startnumbers cause long runtim...
def collide(startnumber, deep_sha1=True): ''' Search for collisions in the hash. Start with the possible match at index startnumber and look for collisions by searching upward from there. Note that this means if you choose a large value (e.g. 400000) this will not look for collisions...
def __need_download(self, path_in_repo, local_file): if path_in_repo and os.path.isfile(local_file): local_file_checksum = self.__get_sha1_of_local_file(local_file) remote_file_checksum = '' # noinspection PyBroadException try: remote_file_checksum...
The main task of the code is to download a file from a specified repository path to a local file, using the 'axel' command for accelerated downloads. It constructs the download URL, prints progress/status messages, validates the download, and retries if validation fails. The function ensures the file is correctly downl...
def download(self, path_in_repo: str, local_file: str, progress=""): path_in_repo = os.path.join(self.repo_path, path_in_repo) download_url = "{}/{}/{}".format(self.repo_url, self.repo_name, path_in_repo) star_count = 50 print("#" * star_count) print("# {} {}".format(progress, pa...
def load_component(args, component_path, component_uri): if not component_path.exists(): # Clone the repo if it does not exist already clone_command = f"git clone {component_uri} {str(component_path)}" clone_result = shell_run(clone_command) if clone_result.returncode != 0: ...
The main task of the code is to load and configure components based on a configuration file by merging component-specific and shared settings, creating a components directory if needed, and executing component scripts when enabled. It processes each component's URI, merges settings, and runs scripts to initialize or up...
def load_components(config, args): components = dict() config_components = config.get("_components") if not isinstance(config_components, dict): return components shared_settings = config.get("_shared", dict()) # Create components directory if it does not exist already Path("compo...
def load_config(config_file, test=False): config_data = config_file.read() config = jsto(config_data, verbose=True) if config is None and not test: exit(1) return config def load_components(config, args): components = dict() config_components = config.get("_components") if not ...
The main task of the code is to handle component termination based on command-line arguments. It checks if `kill_all` or `kill` flags are set, disables updates/scripts if so, loads configuration and components, and invokes `kill_components` to terminate them when killing is enabled.
def entry(args): killing = args.kill_all or args.kill if killing: args.no_updates = True args.no_scripts = True config = load_config(args.config) components = load_components(config, args) # DEBUG #pprint(components) if killing: kill_components(components, args)
def set_iface_if_not(self): self._write('') cursor = self._read_until('#') if 'config-if' not in cursor: self._write('interface gpon-olt_1/1/{}'.format(self.port)) self._wait() def _write(self, s: str): self.telnet.write(s.encode('ascii') + b'\n') def _read_until(...
The code scans for unconfigured GPON ONU devices on a specified port by sending a command, parsing output lines starting with 'gpon-onu', extracting serial numbers (SN), and storing them in a list with 'PASS' status. It clears prior data, checks interface settings, and optionally prints SNs during verbose mode. If no r...
def scan(self): self.data.clear() self.set_iface_if_not() self._write('show gpon onu uncfg gpon-olt_1/1/{}'.format(self.port)) cursor = self._read_until('#') if len(cursor) > 0: i = 0 for line in cursor.split('\n'): if line.startswith('gp...
def set_iface_if_not(self): self._write('') cursor = self._read_until('#') if 'config-if' not in cursor: self._write('interface gpon-olt_1/1/{}'.format(self.port)) self._wait() def _write(self, s: str): self.telnet.write(s.encode('ascii') + b'\n') def _wait(self):...
The main task of the code is to configure an ONU (Optical Network Unit) device by sending a series of network commands. It sets up the ONU's profile, assigns a GPON interface, configures hybrid switchport mode, and associates a VLAN service port. The function adds a profile for an ONU, ensuring it is properly integrate...
def add_profile(self, idx): if idx < len(self.data): self.set_iface_if_not() onu = self.data[idx] self._write('onu {} type ZTE-F608 sn {}'.format(idx + 1, onu['sn'])) self._wait() self._write('onu {} profile H4I0'.format(idx + 1)) self._wai...
def set_iface_if_not(self): self._write('') cursor = self._read_until('#') if 'config-if' not in cursor: self._write('interface gpon-olt_1/1/{}'.format(self.port)) self._wait() def _write(self, s: str): self.telnet.write(s.encode('ascii') + b'\n') def _read_until(...
This function checks PON power levels for ONUs on a GPON port by parsing device output. It sets power values, flags failures if power is below a threshold, and returns True only if all ONUs have valid (non-N/A) power readings. It also prints verbose results if enabled.
def check_pon_power(self): self.set_iface_if_not() self._write('show pon power onu-rx gpon-olt_1/1/{}'.format(self.port)) cursor = self._read_until('#') holder = True for x in self.data: x['pon'] = None if len(cursor) > 0: i = 0 for l...
def set_iface_if_not(self): self._write('') cursor = self._read_until('#') if 'config-if' not in cursor: self._write('interface gpon-olt_1/1/{}'.format(self.port)) self._wait() def _write(self, s: str): self.telnet.write(s.encode('ascii') + b'\n') def _wait(self):...
This function restores a specific Optical Network Unit (ONU) device to factory settings by accessing its management interface via a GPON port. It sends commands to exit current modes, navigate to the target ONU, execute the factory restore, and exit again. If verbose mode is enabled, it prints confirmation details incl...
def restore_factory(self, idx): self.set_iface_if_not() self._write('exit') self._wait() self._write('pon-onu-mng gpon-onu_1/1/{}:{}'.format(self.port, idx + 1)) self._wait() self._write('restore factory') self._wait() self._write('exit') self._wai...
def set_iface_if_not(self): self._write('') cursor = self._read_until('#') if 'config-if' not in cursor: self._write('interface gpon-olt_1/1/{}'.format(self.port)) self._wait() def _write(self, s: str): self.telnet.write(s.encode('ascii') + b'\n') def _read_until(...
The main task of the code is to retrieve and display PON power information for a specified ONU port on a GPON OLT device. It sends a command to query the power status, reads the response until the '#' prompt, and prints the result if data is received. This function likely supports network monitoring or device diagnosti...
def show_pon(self): self.set_iface_if_not() self._write('show pon power onu-rx gpon-olt_1/1/{}'.format(self.port)) cursor = self._read_until('#') if len(cursor) > 0: print(cursor)
def set_iface_if_not(self): self._write('') cursor = self._read_until('#') if 'config-if' not in cursor: self._write('interface gpon-olt_1/1/{}'.format(self.port)) self._wait() def _write(self, s: str): self.telnet.write(s.encode('ascii') + b'\n') def _wait(self):...
This method removes an ONU (Optical Network Unit) device by sending a command to disable it, using a 1-based index derived from the provided 'idx' parameter. It first ensures the interface is set, then executes the removal command with the adjusted index, followed by a wait to confirm the operation's completion.
def remove(self, idx): self.set_iface_if_not() self._write('no onu {}'.format(idx + 1)) self._wait()
def set_iface_if_not(self): self._write('') cursor = self._read_until('#') if 'config-if' not in cursor: self._write('interface gpon-olt_1/1/{}'.format(self.port)) self._wait() def _write(self, s: str): self.telnet.write(s.encode('ascii') + b'\n') def _read_until(...
The code collects MAC addresses from GPON OLT devices by sending a CLI command, parsing output lines containing 'gpon-onu', extracting MAC addresses, removing dots, and storing them in a data structure with serial numbers. It prints verbose results if enabled, iterating through captured data to map each entry's index, ...
def collect_mac(self): self.set_iface_if_not() self._write('show mac gpon olt gpon-olt_1/1/{}'.format(self.port)) cursor = self._read_until('#') if len(cursor) > 0: i = 0 for line in cursor.split('\n'): if 'gpon-onu': mac = [_ f...
def clear(self): self._write('auto-learn dis') self._wait() self._write('clear') self._wait() def _write(self, s: str): self.telnet.write(s.encode('ascii') + b'\n') def _wait(self): self._read_until('#')
The code's main task is to initiate an automatic learning process in English by first clearing any existing data, sending the command 'auto-learn en', and then waiting for the operation to complete. This method likely prepares the system for learning new content or configurations in English, ensuring a clean state befo...
def learn(self): self.clear() self._write('auto-learn en') self._wait()
def set_iface_if_not(self): self.write("") cursor = self.read_until("#") if "config-if" not in cursor: self.write("interface gpon-olt_1/1/{}".format(self.port)) self.wait() def write(self, s: str): self.telnet.write(s.encode("ascii") + b"\n") def wait(self): ...
This function restores a specific ONU (Optical Network Unit) to factory settings by sending commands through a network interface. It selects the target ONU using the provided index, checks for configuration mode errors, executes the factory restore command if no errors are detected, and outputs the operation's success/...
def restore_factory(self, idx): has_error = False self.set_iface_if_not() self.write("exit") self.wait() self.write("pon-onu-mng gpon-onu_1/1/{}:{}".format(self.port, idx + 1)) cursor = self.read_until("#") if "config" in cursor: has_error = True ...
def build_model(self): # num_channels: 1 or 3 self.model = Net(num_channels=1, base_filter=64, upscale_factor=self.upscale_factor).to(self.device) self.model.weight_init(mean=0.0, std=0.01) self.criterion = nn.MSELoss() torch.manual_seed(self.seed) if self.GPU_IN_USE: ...
This code trains a neural network model over multiple epochs, evaluates its performance using PSNR and SSIM metrics on a test set, and collects the top 5 generated images from the final epoch as PIL image objects. The primary task is image quality assessment and generation through iterative model training and validatio...
def run(self): self.build_model() contentPSNRTotal = []; contentSSIMTotal = [] PILImageSet = [] for epoch in range(1, self.nEpochs + 1): print("\n---> Epoch {} starts:".format(epoch)) self.train() contentPSNR, contentSSIM, prediction_total = self.tes...
def build_model(self): self.model = Net(num_channels=1, upscale_factor=self.upscale_factor).to(self.device) self.model.weight_init(mean=0.0, std=0.2) self.criterion = nn.MSELoss() torch.manual_seed(self.seed) if self.GPU_IN_USE: torch.cuda.manual_seed(self.seed) ...
The main task of the code is to train a machine learning model over multiple epochs, evaluate its performance using PSNR and SSIM metrics after each epoch, and collect these metrics for analysis. The code iteratively trains the model, tests it, updates the learning rate scheduler, and returns the accumulated PSNR and S...
def run(self): self.build_model() contentPSNRTotal = []; contentSSIMTotal = [] for epoch in range(1, self.nEpochs + 1): print("\n===> Epoch {} starts:".format(epoch)) self.train() contentPSNR, contentSSIM = self.test() contentPSNRTotal.append(co...
def multiply(num1, num2): """ This function multiplies two numbers via repeated addition. args: num1, num2 (the two numbers being multiplied) return: int """ result = 0 for i in range(num2): result += num1 return result def exponentiate(base, exponent): """ This function...
The main task of the code is to execute three mathematical operations—multiplication, exponentiation, and squaring—using defined functions, then print the results. It first multiplies 5 by 3, raises 5 to the power of -2, squares 11, and displays each outcome sequentially.
def main(): res = multiply(5, 3) print(res) res = exponentiate(5, -2) print(res) res = square(11) print(res)
def event_loop(self): '''handles events. Updates motor variables with axes of joysticks''' for event in pygame.event.get(): self.keys = pygame.key.get_pressed() if event.type == pygame.QUIT or self.keys[pygame.K_ESCAPE]: # handle quit self.done = True elif event.type == pygame.JOYAXISMOTION: # handle j...
The main task of the code is to implement a game loop that continuously processes events, updates the game state, renders graphics, and controls frame rate. It runs while `self.done` is False, calling `event_loop()` for input, `update()` for logic, `draw()` for rendering, `pygame.display.flip()` to update the screen, a...
def main_loop(self): '''main loop''' while not self.done: self.event_loop() self.update() self.draw() pygame.display.flip() pygame.time.wait(100)
def end_of_template(x, pos): open_templates = 1 while open_templates > 0: if line[pos] == '<': open_templates += 1 elif line[pos] == '>': open_templates -= 1 pos += 1 # exclude final '>' return pos - 1 def decompose_type_list(x, first, last): res = [] i = first n = next_element(x, ...
The function `decompose_typed_actor` extracts two type lists from a string `x` (input and output types) by locating `"caf::detail::type_list<"` markers, decomposes them, processes specific entries in the input list, and constructs a formatted string using `replies_to<...>::with<...>`. It returns this structured string,...
def decompose_typed_actor(x, first, last): needle = "caf::detail::type_list<" # first type list -> input types j = x.find(needle, first) + len(needle) k = end_of_template(x, j) inputs = decompose_type_list(x, j, k) # second type list -> outputs j = x.find(needle, k) + len(needle) k = end_of_template(x, ...
def generate_graph(*args): """Selector function for which graph generator to use""" f = generate_barabasi return f(*args) def initialize_graph(g, susceptible=True, exposed=False, infectious=False, recovered=False): p = { 'alive' : True, 'susceptible' : susceptible, ...
This code simulates an epidemic spread on a network. It initializes a graph with N nodes, infects a fraction (r0) of nodes, and iteratively propagates the infection over 'steps' time intervals. The simulation tracks infection dynamics, collecting debug data at each step into a history. It returns the final graph state ...
def simulate(r0, N=1000, steps=100): """Driver function to run a simulation for a given number of days with given input parameters""" g = generate_graph(N, 5) # g = generate_Watts(100000, 4, 0.01) # initialize the graph initialize_graph(g) N = len(g.nodes) initial_infected = choice(list(ran...
def generate_graph(*args): """Selector function for which graph generator to use""" f = generate_barabasi return f(*args) def initialize_graph(g, susceptible=True, exposed=False, infectious=False, recovered=False): p = { 'alive' : True, 'susceptible' : susceptible, ...
This code simulates an epidemic spreading on a network graph over a specified number of steps. It initializes a graph with N nodes, infects a proportion (r0) of nodes, then iteratively updates node states (exposed, infectious, recovered) and visualizes the changing status of each node using color-coded representations....
def simulate_graph(r0, N, steps=100): """Driver function to draw a simulation for a given number of days with given input parameters""" g = generate_graph(N, 5) # g = generate_Watts(100000, 4, 0.01) # initialize the graph initialize_graph(g) N = len(g.nodes) initial_infected = choice(list(r...
def check_full_lines(self): row = FIELD_H - 1 # define row to be able to determine what needs to be removed when you clear a row # called through update() below for y in range(FIELD_H - 1, -1, -1): # iterate through the array from bottom to top, left to right ...
This method updates game logic by checking for full lines, updating the tetromino's position, verifying if it has landed, calculating scores, and updating sprites. The 'trigger' variable determines if these actions occur, with speed-up logic based on 'self.speed_up' to control the timing of game updates.
def update(self): # method, method = Python function within Class trigger = [self.app.anim_trigger, self.app.fast_anim_trigger][self.speed_up] # time interval that game logic will be sped up by #if self.app.anim_trigger: # corresponds to set_timer i...
def keylog(self): keys = pg.key.get_pressed() if not self.dodging: # movement over the y direction if keys[pg.K_UP] and self.rect.top >= 0: self.direction.y = -1 elif keys[pg.K_DOWN] and self.rect.bottom <= SCREEN_HEIGHT: self.direc...
The code defines an `update` method that sequentially executes four actions: logging keyboard input (`keylog`), updating movement (`move`), triggering a dodgeroll animation (`dodgeroll`), and managing ability cooldowns (`cooldowns`). Its primary task is to handle real-time input, motion, evasive maneuvers, and ability ...
def update(self): self.keylog() self.move() self.dodgeroll() self.cooldowns()
def clear_terminal(): os.system('cls') return '' def landing_page(msg=''): msg = greetings(msg) msg = display_params(msg) msg = options(msg) print(msg) selection = input('\nSelect one of the options above: ') return selection def adjust_parameters(curr_params): # Initialize "GUI" for...
The main task of the code is to provide an interactive menu-driven interface for generating, adjusting, visualizing, and uploading custom waveforms (Gaussian and square) to a Moku device. It continuously loops through parameter adjustments, waveform formation, visualization, and device control based on user input, hand...
def page_selector(moku=None, wavegen=None): form_waves = True while True: clear_terminal() # Get values and save per, g_amp, l_amp, r_amp, l_w, r_w, sep, fwhm, g_pos = get_values() current_params = { 'period':per, 'gaussian amp':g_amp, 'l squa...
def unmount_ramdisk(self): """ Unmounts the ramdisk. Should be done after simulation is over to free memory. """ if os.path.exists(self.ramdisk_dir): shutil.rmtree(self.ramdisk_dir) return 1 def mount_ramdisk(self,verbose=False): """ Mounts a disk based in memory. Disk oper...
This function simulates a MACS scan by generating kidney angles and incident energy configurations, running parallel/sequential scans for specified A3 angles and energies, combining results into CSV files, and exporting data to ng0 format. It handles input validation, ramdisk management, and parallelization via threadi...
def script_scan(self, A3_list, Ei_list=False, num_threads=1, scan_title=False,verbose=False): """ Provided with a list of A3 angles, a kidney angle resolution, optionally a list of incident energies, simulates a MACS scan over the full range. :param A3_list: List of desired A3 angles for the scan. :t...
def mount_ramdisk(self,verbose=False): """ Mounts a disk based in memory. Disk operations are too slow, users are not intended to access the ramdisk.""" if os.path.exists(self.ramdisk_dir): return 1 else: os.mkdir(self.ramdisk_dir) if verbose is True: ...
The code simulates a scan using parameters from an input ng0 file (A3, Ei, Ef, beta1, beta2, kidney_angle, PTAI) by sequentially or parallelly executing mono and kidney scans. It combines results into a new ng0 file matching the original's data points, ensuring compatibility with tools like MSlice. The process mounts a...
def simulate_ng0(self, ng0_file, in_scan=False, n_threads=1): """ Provided an ng0 file or the path to an ng0 file, emulates a scan identically with the following parameters:\n A3, Ei, Ef, beta1, beta1, kidney_angle, PTAI\n Saves the result to its own ng0 file if not part of a larger scan. The result sho...
def validmoveinput(self, user_input) -> bool: if len(user_input) != 2: return False #check letter if user_input[0] < 'A' or user_input[0] > 'H': return False #check number if user_input[1] < '1' or user_input[1] > '8': return False ...
This function executes a piece move in a board game, validating inputs, checking if the move is legal, updating positions, handling captures, promoting pawns to queens upon reaching the end rank, and toggling turns. It ensures correct piece ownership, move validity, and updates internal game state tracking.
def move(self, start_loc, end_loc) -> bool: if not self.validmoveinput(start_loc) or not self.validmoveinput(end_loc): print('Invalid input') return False moves = self.get_moves(start_loc) piece = self.get_loc(start_loc) p_id = piece[0] p_color = piece[1...
def entropy_variational_posterior(self, logits:torch.tensor, temperature:float=1.0, MC_size:int=100, device='cuda')->float: #TODO: approximately calculate the entropy of the variational posterior #TODO: the true variational posterior (categorical) is approximated by a Gumbel-softmax distribution, contro...
The main task of the code is to compute the Monte Carlo estimate of the Evidence Lower Bound (ELBO) for variational inference. It involves sampling from a variational posterior distribution, calculating its entropy, updating mental state histories, and combining these with log-likelihood terms to form the ELBO. The res...
def ELBO(self, sample_ID_batch:list, temperature:float=1.0, device='cuda')->torch.tensor: #TODO: compute the ELBO. #TODO: Maximize the ELBO is equivalent to minimize the KL divergence between the variational posterior and the true posterior #NOTE: in order to compute the ELBO, we need to 1. be ...
def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() self.handle_key_events(event) def move(self, direction): x = self.head.x y = self.head.y if direction == Direction.RIGHT: ...
The main task of the code is to handle a single step in a game loop by processing events, moving the snake, checking for collisions, updating the score/UI, and maintaining game speed. It returns whether the game is over and the current score.
def play_step(self): self.handle_events() self.move(self.direction) self.snake.insert(0, self.head) game_over = False if self.is_collision(): game_over = True return game_over, self.score self.update_score_or_pop() self.update_ui() ...