dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def fileReader(filename): with open(filename, 'r') as file: next(file) reader = csv.reader(file) for row in reader: ####NEED TO TAKE IN STORAGE STILL vmObj = VirtualMachine(row[0], row[1], row[2], row[3], row[4], row[5]) # print(row) createVM(...
The main task of the code is to read deployment information from 'deploy_info.csv', process Docker-related data from 'dockerFile.csv', establish an SSH connection, and print a newline. The function orchestrates file reading, Docker configuration handling, and remote server connectivity setup for deployment tasks.
def main(): fileReader('deploy_info.csv') #listVM() fileReaderDocker('dockerFile.csv') sshConnection() print('\n')
def poscar_to(file_in): file = open(file_in) lines = file.readlines() file.close() name, basex, basey, basez, atoms_tot, positions = _parsing_poscar(lines) basex, basey, basez, positions = _rotating_positions(basex, basey, basez, positions) basex, basey, basez, positions = _positive_vectors(bas...
This function calculates the alpha parameters for a Gaussian process kernel method by constructing a covariance matrix from training data descriptors, performing Cholesky decomposition, and returning the covariance matrix, its inverse, and related parameters for model inference.
def _calc_alfa_pieces(fpath_training, training_set, sigma, l, se): training_set = np.sort(training_set) N = len(training_set) desc = [] atom_quant = [] Pn = [] file = open(fpath_training+'fe.dat') data = file.readlines()[1:] file.close() fe_samples = [d.split()[0] for d in ...
def poscar_to(file_in): file = open(file_in) lines = file.readlines() file.close() name, basex, basey, basez, atoms_tot, positions = _parsing_poscar(lines) basex, basey, basez, positions = _rotating_positions(basex, basey, basez, positions) basex, basey, basez, positions = _positive_vectors(bas...
The main task of the code is to predict free energy values for a set of materials by calculating kernel-based covariance between training and prediction data descriptors. It processes each entry in the prediction set, extracts structural and descriptor data, computes covariance matrices, and sums weighted contributions...
def calc_prediction(fpath_training, fpath_predication, prediction_set, alfa, desc, K, sigma, l): Fp = [] for ps in prediction_set: #reading data Pns = np.sum(poscar_to(fpath_predication + ps+'/POSCAR')[5]) _desc, shape, _atom_quant = desc_reader(fpath_predication + ps, fpath_training) ...
def temp(df): # df = set_periods(df) df = prepare_data(df) # df = df[df['adoption_date'] <= pd.to_datetime('2019-01-01')] df = df[~df['adoption_date'].isnull()] from matplotlib import dates unique_df = df.drop_duplicates(['repository_url']) unique_df = unique_df.sort_values('adoption_date')...
The code analyzes the impact of adding a Code of Conduct (CoC) on project diversity metrics and underrepresented developer ratios. It processes input data, assigns unique project IDs, and runs statistical tests to evaluate changes in contributor slopes, contribution residuals, and diversity indices over specified time ...
def run(df, interval='3M'): df = temp(df) df = prepare_data(df) projects = df['repository_url'].unique().tolist() projects = {projects[i]: i + 1 for i in range(len(projects))} df['project'] = [projects[p] for p in df['repository_url']] # test 1 # print('\n test effect of having CoC in projec...
def restore(settings): finfo = QFileInfo(settings.fileName()) if finfo.exists() and finfo.isFile(): for w in qApp.allWidgets(): mo = w.metaObject() if w.objectName() != "" and mo.className() not in not_saved_list: # skip to reload property for certain widget for ...
This code initializes a GUI component by setting up the UI, connecting widgets to controllers, and linking model events. It binds file type radio buttons to controller actions, directory changes to update handlers, and buttons to processing functions. The main task is to establish UI-controller-model interactions for f...
def __init__(self, model, main_controller): super().__init__() self._model = model self._main_controller = main_controller self._ui = Ui_MainWindow() self._ui.setupUi(self) # load saved settings restore(self.settings) self.default_model_value() p...
def cnf2qdimacs(self, fd): state = START extra_clause = False prefix = dict() min_level = None shown = None for line in fd: # START if state == START: match = re.match(r"p cnf (\d+) (\d+)", line) if match: ...
The main task of the code is to translate input data (`fd`) based on specified options. If the 'cnf' option is enabled, it converts to QDIMACS format; if 'interpret' is enabled, it interprets the input; otherwise, it uses the `smodels2smodels` method for translation. The function routes processing to different conversi...
def translate(self, fd): if self.options['cnf']: self.cnf2qdimacs(fd) elif self.options['interpret']: self.interpret(fd) else: self.smodels2smodels(fd)
def analyze_voice(url): y, sr = librosa.load(url, sr=None) # Extract Fundamental Frequency (F0) f0 = extract_fundamental_frequency(str(url)) # Extract Jitter, Shimmer, and HNR jitter, shimmer, hnr = extract_jitter_shimmer_hnr(str(url)) # Voice Quality Index (VQI) - example of com...
The main task of the code is to process user data from temporary files (video, audio, questionnaire, reaction time) by analyzing them with dedicated functions, generate ADHD subtype probabilities and corresponding tips, then render a test results HTML page with these analysis results and contextual data for display. Th...
def results(request): template = loader.get_template('test-results.html') # Feed data to DL model and retrieve the probabilities ip = request.META['REMOTE_ADDR'] # Extract IP to conduct analysis on files with this IP save_path_eye = Path('ADHD/temporary_files/' + str( request.META['REMOTE_ADDR'])+ "_re...
def activate_button(self, finished): self.finished = finished color = 'white' if self.finished else 'black' self.button_dropdown['state'] = 'normal' if self.finished else 'disabled' self.button_stop_video.configure(bg=color) self.pause_or_play(run=not self.finished) def show_imag...
The main task of the code is to process video frames in a loop by reading, displaying, and tracking progress. It initializes counters, activates a UI button, and continuously reads frames from a video stream while the `run` flag is active. Each frame is displayed, the frame counter is updated, and progress is visually ...
def run_frames(self): self.frame_list = list() self.frame_pass = 0 self.counter = 0 self.activate_button(finished=False) while self.__cap.isOpened(): if self.run: ret, frame = self.__cap.read() if ret: self.show_ima...
def ssh_config_params(): attempts = 0 max_attempts = 3 if device['address'] == None and device['username'] == None: mgmt_address = input('Insert management addres: ') device.update( {'address' : mgmt_address}) username = input('Insert username: ') device.update( {'username' :...
The code presents two SSH configuration options to the user: setting up SSH from scratch or using an existing setup. Based on the user's input (1 or 2), it calls either `ssh_config_params()` for new configurations or `make_ssh_connection()` for existing ones. If invalid input is provided, it prompts again after a 2-sec...
def main(): print('Configure SSH from scratch? [1]') print('SSH is already configured and set up [2]') config_ssh = input('Select an option: ') if config_ssh == '1': ssh_config_params() if config_ssh == '2': make_ssh_connection() else: print('please select an option [1] ...
def __build_declarator(self) -> c.FunctionDeclaration: return c.FunctionDeclaration( c.Value(self.__get_returns(), self.__name('')), self.__get_parameters() ) def __name(self, suffix: str) -> str: return self.name + suffix def __get_returns(self) -> str: match sel...
This code initializes an object to represent a function's structure by parsing its parameters, return types, and body from an AST node, creating structured data for analysis or documentation.
def __init__(self, source: ast.FunctionDef, name: str) -> None: self.name = name self.source = source self.declarator = self.__build_declarator() self.returns = c.Typedef(c.Value( name=self.__name("Returns"), typename=self.__get_returns() )) self...
def check_events(self): key_dict = { pygame.K_LEFT: self.bot.toggle_left, pygame.K_RIGHT: self.bot.toggle_right, pygame.K_UP: self.bot.toggle_up, pygame.K_DOWN: self.bot.toggle_down, pygame.K_F2: self.new_game, pygame.K_SPACE: self.tog...
The main task of the code is to run a continuous game loop that checks for events, renders the game window, and updates game elements like timers, coins, bonus coins, bots, and monsters when the game is active and not paused or over.
def main_loop(self): while True: self.check_events() self.draw_window() if not self.game_over and not self.game_paused: self.timer.add_counter() self.move_coin() self.move_bonus_coin() self.move_bot() ...
def get_tile(client: mqtt.Client, tile_name: str) -> Tile: """Returns the tile with the given name, or creates a new one if it doesn't exist.""" # Check if tile with name exists tile = get_existing_tile(tile_name) if tile != None: # Tile exists, return it return tile else: # Tile doesn't exist yet...
This function processes incoming MQTT messages by decoding the topic and payload, identifying if the message targets a project master command (e.g., RGB, effect) or a tile state update (e.g., online, system). It updates the relevant tile's state and broadcasts the change to connected WebSocket clients, ensuring real-ti...
def mqtt_on_message(client: mqtt.Client, userdata, msg: mqtt.MQTTMessage) -> None: """The callback for when a PUBLISH message is received from the server.""" #convert topic and payload to string topic = msg.topic payload = msg.payload.decode("utf-8") # Remove root topic from topic topic = topic.replace(ROO...
def objective_function(thickness,matrix_generalized): """ calculates objective function = -ln(likelihood function) """ indices = thickness_to_boundaries(thickness,matrix_generalized) #get indices of the layer boundaries in the matrix """ 2.2 eq. 2 & 1 Wang et al. (2013) """ P_eps_n = Eqs_Wa...
The code optimizes soil layer configurations using statistical models, minimizing an objective function for varying model classes (1 to N_max). It avoids zero probabilities, computes likelihoods, and applies prior distributions to determine the most probable model class. It enforces constraints to prevent consecutive l...
def calculator(matrix_generalized,params): """ main function solving for the different sections """ N_max = params["N max"] treshold = params["treshold model class"] std_Fr = params["std Fr"] #standard deviation of friction ratio std_Qt = params["...
def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) def load_and_cache_examples(args, file, tokenizer, mode): utils = MODEL_PROCESS[args.model_type] select_field,read_swag_examples,convert_examples_to_features = \ utils.select_field, utils.read_s...
The code trains a model using specified arguments, checking for existing output directories, setting up CUDA/GPU, loading a pre-trained model and tokenizer, preparing a training dataset, and executing the training process. It handles distributed training, device allocation, seed setting, and logs training parameters an...
def do_train(): args = train_args() if (os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite_output_dir): raise ValueError( "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(args.output_...
def ExtractData(filepath): # Ignore any broken lines in the file. fixedfilepath = Path(str(filepath) + '.fixed') with open(fixedfilepath, 'w') as fixedfile, open(filepath, 'r') as infile: for linenumber, line in enumerate(infile): try: t = float(line.split(',')[0]) x = float(line.split(',')[1]) fixe...
(TailFit performs exponential decay fitting on time-resolved data, optionally applying Weiner deconvolution for IRF correction. It selects optimal fitting regions around the peak, fits either single (ME) or double (BE) exponential models, evaluates goodness-of-fit, and returns best-fit parameters. The function generate...
def TailFit(filepath, biexp, autolife, passed_mu, passed_sigma, fit_type = 'NLL'): time_points, data_points = ExtractData(datafilepath) # if we know about the IRF do a Weiner deconvolution if passed_mu != 0. and passed_sigma != 0.: data_points = WeinerDeconvolution(time_points, data_points, pas...
def ExtractData(filepath): # Ignore any broken lines in the file. fixedfilepath = Path(str(filepath) + '.fixed') with open(fixedfilepath, 'w') as fixedfile, open(filepath, 'r') as infile: for linenumber, line in enumerate(infile): try: t = float(line.split(',')[0]) x = float(line.split(',')[1]) fixe...
The main task of the code is to perform a convolution fit on time-resolved data, either biexponential or monoexponential, based on input parameters. It extracts data, selects a fitting region, determines initial guesses, fits the data using specified models (BEC/MEC), evaluates fit quality, and generates visualizations...
def FastConvolutionFit(filepath, biexp, autolife, passed_mu, passed_sigma, fit_type = 'NLL'): time_points, data_points = ExtractData(datafilepath) plt.plot(time_points, data_points,'.') peak_index = np.argmax(data_points) peak_value = data_points[peak_index] IRF_centre_guess = time_points[peak_in...
def add_task(): task_name = input("Enter task name: ") description = input("Enter task description: ") due_date_str = input("Enter due date (YYYY-MM-DD): ") try: due_date = datetime.strptime(due_date_str, "%Y-%m-%d") except ValueError: print("Invalid date format. Please use YYYY-MM-...
The code defines a main function for a task management system, offering a menu-driven interface to add, view, mark tasks as completed, delete, sort by due date, show upcoming tasks, or exit. It continuously prompts the user for input and executes corresponding functions until the exit option is chosen.
def main(): print("Welcome to Task Manager!") while True: print("\n1. Add Task\n2. View Tasks\n3. Mark Task as Completed\n" "4. Delete Task\n5. Sort Tasks by Due Date\n6. Show Upcoming Tasks\n7. Exit") choice = input("Enter your choice: ") if choice == '1': add...
def wrong_guesses(s_word, guess_list): "wrong_guess: returns the number of wrong guesses" count = 0 for i in guess_list: if i not in s_word: count += 1 return count def guess_manager(guessed, guess_list): """guess_manager: prints string for failed input-condition and asks for new...
The code filters valid words from a file, selects a random secret word, and implements a Hangman game where the player guesses letters within 6 attempts. It checks guesses, masks correct letters, tracks wrong attempts, and declares a win/loss based on the player's success in uncovering the secret word.
def main(): with open("./test_data/words") as words: good_words = [] for i in words: i = i.strip() if len(i) <= 6: # No short words continue if not i.isalpha(): # No punctuation continue if i[0].isupper(): # No proper...
def fill_in_invoice_details(invoice_data): fields = invoice_data["fields"] invoice_number = get_field("Invoice no.", fields) invoice_date = get_field("Invoice Date", fields) invoice_total = get_field("Invoice Amount", fields) browser_lib.click_button("css:.btn-reset") browser_lib.input_text("id:...
The main task of the code is to process and submit multiple invoice files by extracting data using AWS Textract, filling in invoice details, uploading the files, agreeing to terms, and submitting each invoice through an automated workflow.
def submit_invoices(invoice_files): aws_lib = AWS(region="us-east-1", robocloud_vault_name="aws") aws_lib.init_textract_client(use_robocloud_vault=True) for invoice_file in invoice_files: invoice_data = extract.extract_invoice_data(aws_lib, invoice_file) fill_in_invoice_details(invoice_data)...
def open_integrated_invoicing_solution(url): browser_lib.open_chrome_browser("about:blank") override_user_agent("Chrome/92.0.4515.159") browser_lib.go_to(url) def download_invoices(url, target_file): HTTP().download(url, target_file, overwrite=True) def get_invoices_zip_url(): locator = "css:p.lead ...
The code automates accounts payable processing by opening an invoicing app, downloading invoice files, extracting and converting them to JPEG, submitting the invoices, and capturing results via screenshots.
def complete_accounts_payable_challenge(): open_integrated_invoicing_solution(INVOICING_WEB_APP_URL) download_invoices(get_invoices_zip_url(), INVOICES_ZIP_PATH) invoice_files = extract_invoice_files(INVOICES_ZIP_PATH, OUTPUT_DIR) invoice_files = convert.to_jpeg(invoice_files, OUTPUT_DIR) submit_inv...
def is_table_all_alphabetic(soup): table = soup.findAll('table') trs = table[0].findAll('tr') cell_count = 0 alphabetic_cells = 0 for tr in trs: tds = tr.findAll('td') for td in tds: cell_count += 1 numbers_count_in_cell = get_number_count(td.text) ...
This function calculates word counts from HTML content in a specified column. It parses the HTML, checks if a table is present and alphabetic, then combines word counts from the table (if applicable) and preprocessed data. If no alphabetic table exists, it returns only the preprocessed data's word count.
def get_word_count(row, training_column): soup = BeautifulSoup(row[training_column], features='lxml') table = soup.findAll('table') is_alphabetic_table = False if table: is_alphabetic_table = is_table_all_alphabetic(soup) return get_word_count_from_table(soup) + get_word_count_from_preproce...
def is_table_alphabetic_using_cell_rule(all_tables): CELL_RULE_PERCENTAGE = 0.4 word_count = 0 cou = 0 for i in all_tables: trs = i.findAll('tr') alphabetic_cells = 0 cou = cou + 1 cell_count = 0 for tr in trs: tds = tr.findAll('td') for ...
This function counts alphabetic words in HTML tables from a specified column using rule-based methods (WRDS, L&M_jar, Bodnaruk), combining results with preprocessed data word counts. It parses HTML, applies table/row rules for alphabetic content detection, and aggregates counts based on the specified method and numeric...
def get_word_count_using_rules(row, training_column, rule, number_percent_threshold): soup = BeautifulSoup(row[training_column], features='lxml') table = soup.findAll('table') word_count = 0 if table: if rule == 'WRDS': word_count = is_table_alphabetic_using_cell_rule(table) ...
def count_words(passage): return len(re.sub("[^\w]", " ", passage).split()) def count_sentences(passage): return len(re.split(r'[.!?]+', passage))-1 def count_syllables(passage): no_of_syllables = 0 word_list = re.sub("[^\w]", " ", passage).split() for word in word_list: no_of_syllables = ...
The function calculates the Flesch Reading Ease score, a readability metric estimating text complexity. It uses word count, sentence count, and syllable count from the input passage, applying the formula: 206.835 - 1.015*(words/sentences) - 84.6*(syllables/words). The result indicates ease of reading, with higher score...
def flesch_reading_ease(passage): no_of_words = count_words(passage) no_of_sentences = count_sentences(passage) no_of_syllables = count_syllables(passage) return 206.835-1.015*(no_of_words/no_of_sentences)-84.6*( no_of_syllables/no_of_words)
def count_words(passage): return len(re.sub("[^\w]", " ", passage).split()) def count_sentences(passage): return len(re.split(r'[.!?]+', passage))-1 def count_syllables(passage): no_of_syllables = 0 word_list = re.sub("[^\w]", " ", passage).split() for word in word_list: no_of_syllables = ...
The function calculates the Flesch-Kincaid grade level of a passage, estimating the U.S. school grade required to understand it. It uses word count, sentence count, and syllable count to apply the formula: 0.39*(words/sentences) + 11.8*(syllables/words) - 15.59.
def flesch_kincaid_grade_level(passage): no_of_words = count_words(passage) no_of_sentences = count_sentences(passage) no_of_syllables = count_syllables(passage) return 0.39*(no_of_words/no_of_sentences)+11.8*( no_of_syllables/no_of_words)-15.59
def backPropagationWeights(self, layer): for numbOfWeightsBlock, weightsBlock in enumerate(self.weights[layer]): for numbOfWeight, w in enumerate(weightsBlock): self.d_weights[layer][numbOfWeightsBlock][numbOfWeight] = 2*(self.d_neuronsLayers[layer+1][numbOfWeightsBlock])*self.deriva...
The main task of the code is to perform backpropagation in a neural network by iterating through layers in reverse order. For each layer, it updates weights, neurons, and biases using backward propagation calculations, then computes the error difference. This process adjusts model parameters to minimize prediction erro...
def backPropagation(self): for layer in range((len(self.neuronsLayers)-2),-1,-1): self.backPropagationWeights(layer) self.backPropagationNeurons(layer) self.backPropagationBias(layer) self.setDifference(layer)
def set_S_elements_work(self, dataList): assert len(dataList) == self.neuronsLayers[0].size, "NeuralNetwork.set_S_elements_work()\n Incorrect size of dataList" npDataList = np.array(dataList) self.neuronsLayers[0] = npDataList.copy() def fowardPropagation(self): for countOfLayer in rang...
The code processes input data by setting elements in a neural network structure, performs forward propagation to compute outputs, and returns the resulting answer.
def work(self, dataList): self.set_S_elements_work(dataList) self.fowardPropagation() return self.answer()
def set_S_elements_learning(self, dataList, numbOfGesture): assert len(dataList) == self.neuronsLayers[0].size, "NeuralNetwork.set_S_elements_learning()\n Incorrect size of dataList" assert (numbOfGesture >= 0 & numbOfGesture <= (self.neuronsLayers[len(self.neuronsLayers)-1]).size), "NeuralNetwork.set_S...
The main task of the code is to train a neural network model by processing input data (`dataList`) for a specified number of gestures (`numbOfGesture`). It initializes learning parameters, performs forward propagation to compute outputs, calculates errors at the final layer, prints the model's education level (likely a...
def learning(self, dataList, numbOfGesture): self.set_S_elements_learning(dataList, numbOfGesture) self.fowardPropagation() self.setDifferenceAtLastLayer() print("Level of education =", self.levelOfEducation()) self.backPropagation()
def buy(self, motivation): # if there is a merchant agent in this location if not self.model.grid.is_cell_empty(self.pos): # get the agent in this location agent = self.model.grid.get_cell_list_contents([self.pos])[0] # if the agent is a merchant if isinst...
The function processes unscheduled transactions by purchasing items when motivation scores exceed 20. With 10% probability, it selects a social network recipient, adjusts their weight, and, if a spending condition is met, initiates a 'Social' payment to them.
def unscheduled_txn(self): for motivation in self.motivation.motivation_list: if self.motivation.get_motivation(motivation) > 20: self.buy(motivation) if random.random() < 0.1: weight = self._social_network_weights recipient = random.c...
def move(self): if self._target_location is None: self.motivation.update_motivation('hunger', 1) else: self.move_to(self._target_location) self.motivation.update_motivation('hunger', 2) def pay_schedule_txn(self): # for all types of txn if the probability is ...
The code defines a `step` method that orchestrates three key actions: moving an entity, processing scheduled payments, and handling unscheduled transactions. Its main task is to sequentially execute these operations, likely simulating a process involving movement and financial transactions.
def step(self): self.move() self.pay_schedule_txn() self.unscheduled_txn()
def initialize_session_state(): st.session_state.setdefault('history', []) #for chat history st.session_state.setdefault('generated', ["Hello! I am here to provide answers to questions extracted from uploaded PDF files."]) #for ouput st.session_state.setdefault('past', ["Hello Buddy!"]) def create_conversa...
The main task of the code is to create a Streamlit-based chatbot that processes uploaded PDF documents by converting them into a FAISS vector store, integrates with a Mistral 7B LLM via llama.cpp, and provides conversational responses using a retrieval-augmented generation chain. The application includes UI customizati...
def main(): # Step 1: Initialize session state initialize_session_state() st.title("Chat Bot") image = Image.open('chatbot.jpg') st.image(image, width=150) hide_streamlit_style = """ <style> #MainMenu {visibility: hidden;} footer {visibility: hidde...
def get_wmt_enfr_train_set(directory): """Download the WMT en-fr training corpus to directory unless it's there.""" train_path = os.path.join(directory, "giga-fren.release2.fixed") if not (gfile.Exists(train_path +".fr") and gfile.Exists(train_path +".en")): corpus_file = maybe_download(directory, "training-g...
The function `prepare_wmt_data` retrieves WMT English-French datasets into a specified directory, generates vocabulary files for English and French based on given sizes, and tokenizes the data. It returns paths to tokenized training and development datasets for both languages, along with their corresponding vocabulary ...
def prepare_wmt_data(data_dir, en_vocabulary_size, fr_vocabulary_size, tokenizer=None): """Get WMT data into data_dir, create vocabularies and tokenize data. Args: data_dir: directory in which the data sets will be stored. en_vocabulary_size: size of the English vocabulary to create and use. fr_vocabul...
def handle_spk(data, k): # get k and T matrix from C API k_T_lst = sp.k_and_T_mat(data, k) k = k_T_lst[0] T_mat = k_T_lst[1] # use k-means++ algorithm to determine initial centroids centers, centers_inds = k_means_pp_alg(T_mat, k) # call C API to cluster the T matrix using k-means (with ini...
This function processes a given goal by performing specific matrix operations on input data. Depending on the goal value, it computes and prints weights, degree matrices, L-norm matrices, or Jacobi matrices. It handles SPK, WAM, DDG, LNORM, and JACOBI goals, converting 1D degree matrices to 2D format for printing and u...
def handle_goal(goal, data, k): if (goal == Goal.SPK.value): handle_spk(data, k) elif (goal == Goal.WAM.value): weights = sp.weights_mat(data) print_mat(weights) elif (goal == Goal.DDG.value): degree_1d = sp.degree_mat(data) # converting the 1d representation of ...
def read_args(argv): num_args = len(argv) myAssert(num_args == 4, invalid_input_msg) k = argv[1] myAssert(isInt(k), invalid_input_msg) k = int(k) myAssert(k >= 0, invalid_input_msg) goal = argv[2] myAssert(isLegalGoal(goal), invalid_input_msg) file_path = argv[3] return k, go...
The main task of the code is to validate command-line arguments, load CSV data into a list of lists, perform input checks (e.g., ensuring k is positive and valid for the specified goal), and delegate further processing to the `handle_goal` function based on the provided parameters.
def main(): # check validity of command line arguments k, goal, file_path = read_args(sys.argv) # read text to python's list of lists try: data = np.genfromtxt(file_path, delimiter=',').tolist() except OSError: myAssert(False, invalid_input_msg) # validate k if it is given (pos...
def pawnMovements(self, src): colorFactor = 1 coord = coordinates.Coordinates(-1, -1) possibleMoves = [] if (self.board.getPieceAt(src).pieceColor == "black"): colorFactor = -1 coord.assignValue(src.x - colorFactor, src.y) if (coord.isValid() and n...
This method retrieves all possible moves for the chess piece at the given source position, using type-specific movement logic (pawn, rook, knight, etc.), without considering check validity. It delegates to dedicated movement functions for each piece type and returns the generated moves as a list.
def getAllPossibleMoves(self, src): # all possible moves with that piece, but check is not considered allMovesWithCheck = [] if (self.board.getPieceAt(src).pieceType == "pawn"): allMovesWithCheck = self.pawnMovements(src) elif (self.board.getPieceAt(src).pieceType == "rook")...
def tweetfile2df(self): ''' USAGE: Creates a pandas dataframe of tweet data from a tweet data file ''' if self.df.empty: tweet_list = [] print('Adding Twitter data to dataframe...') with open(self.datafilepat...
The main task of the code is to convert a tweet dataframe into a GeoJSON file by encoding tweet events with spatial coordinates, user details, and metadata. It checks for required data columns, generates missing information if needed, structures each tweet as a GeoJSON Feature, and saves the resulting FeatureCollection...
def df2GeoJSON(self): ''' USAGE: Generates a GeoJSON encoding of tweet events from tweet dataframe, and saves the resulting dictionary to a JSON file. ''' if os.path.exists(self.tweetGeoJSONfile): print('No action. Tweet GeoJSON data already saved to...
def remove_vectors(json_fields, single=False): # Simple function to remove the vector from results in json file might be we remove that part from the json file if single: return json_fields.replace(":vector", "") for i in range(len(json_fields)): json_fields[i] = json_fie...
The main task of the code is to process a vector file by cleaning field names (removing ":vector" suffixes), converting it into a CSV format, pivoting the data structure, and consolidating output files. Key steps include parsing the input file, restructuring data with pivoting, and combining intermediate CSV chunks int...
def tidy_data(self, real_vector_path, json_fields, output_csv): # Simply remove the :vector part of vector names from both sets of vectors. found_vector = False for field in json_fields: if ":vector" in field: found_vector = True break if foun...
def reprintImgArr(): colSize = int(imgFrame.winfo_width()/(imageWidth+imageWidthPadding)) for i, label in enumerate(imgLabels): curRow = 0 if colSize==0 else i // colSize curCol = 0 if colSize==0 else i % colSize label.grid(row=curRow,column=curCol,padx=imageHeightPadding,pady=imageWi...
This code handles drag-and-drop functionality for image labels. When a Label is clicked, it records the click position, removes the label from the list, triggers a reprint of images, and binds motion/release events for dragging. The motion event tracks dragging, while release event restores the label at its new positio...
def on_click_img_arr(event): widget=event.widget if isinstance(widget,Label): start=(event.x,event.y) originIndex = imgLabels.index(widget) imgLabels.pop(imgLabels.index(widget)) reprintImgArr() widget.bind("<B1-Motion>",lambda event:drag_motion(event,widget,sta...
def _is_in_game(self) -> bool: try: result = pyautogui.locateOnScreen(self._get_filepath('wildcard_slot_empty'), region=(1335, 180, 185, 250), grayscale=True) if not result: raise pyautogui.ImageNotFoundException return True except pyautogui.ImageNotFo...
The code's main task is to continuously detect active games, solve them using a solver, execute solutions, and transition to the next game. It logs progress, checks game status, identifies the board, solves puzzles, executes moves, and handles new games or sleep states. The loop repeats indefinitely, ensuring games are...
def run(self): log.info("Start running...") while True: # Detects in game or not log.info("Detecting in game or not...") if self._is_in_game() and not self._is_win(): log.info("Found an active game.") gameboard = self._identify_board()...
def load_model_and_tokenizer(model_name): if CONDITIONAL_GEN: model, tokenizer = load_conditional_gen_model(model_name) elif OPENAI: model, tokenizer = load_openai_model(model_name) else: model, tokenizer = load_bert_like_model(model_name) return model, tokenizer def prep_infere...
The code runs gender pronoun prediction inference on multiple models using specified instructions and independent variables, processing input texts to generate and save results for female, male, and neutral pronouns into designated directories.
def run_inference( model_names, special_id, freeform_text, normalizing, results_dir=INFERENCE_FULL_PATH, model=None, tokenizer=None, ): for model_name in model_names: model_call_name = MODELS_PARAMS[model_name]["model_call_name"] is_instruction = MODELS_PARAMS[model_name]...
def _install_packages() -> None: """ Installs necessary packages. """ # package_install_command = ["poetry", "add"] # package_install_command.extend(_PACKAGES) dev_package_install_command = ["poetry", "add", "-D"] dev_package_install_command.extend(_DEV_PACKAGES) # _run(package_install_c...
The main task of the code is to install required packages, format the code using Black, and install dependencies via Poetry, ensuring the environment is set up and the code is standardized before execution.
def main(): _install_packages() _run_black() _run_poetry_install()
def get_lr(opt): for param_group in opt.param_groups: return param_group['lr'] def loss_epoch_rnn(model,loss_func,dataset_dl,sanity_check=False,opt=None,model_type=None): running_loss=0.0 running_metric=0.0 len_data = len(dataset_dl.dataset) for xb, yb in tqdm_notebook(dataset_dl): ...
The code trains and validates a machine learning model (supporting RNN, DG-CNN, and Meta types) over multiple epochs. It tracks training/validation loss and metrics, updates the model using the specified optimizer and learning rate scheduler, and saves the best model weights based on validation loss. The function retur...
def train_val(model, params): num_epochs=params["num_epochs"] loss_func=params["loss_func"] opt=params["optimizer"] train_dl=params["train_dl"] val_dl=params["val_dl"] sanity_check=params["sanity_check"] lr_scheduler=params["lr_scheduler"] path2weights=params["path2weights"] model_ty...
def extract_config(afile): try: module = dnlib.DotNet.ModuleDefMD.Load(afile) method = find_config_method(module) if not method: return "" config_list = [] last_string = "" for instr in method.Body.Instructions: if instr.OpCode == OpCodes.Ldstr: ...
The main task of the code is to scan a specified folder for files, extract configuration data from each file, filter those with at least 16 entries, convert them to strings, save them in "limerat_configs.txt", and display the extracted configurations with separators.
def main(folder): if folder.endswith('\\'): folder = folder[:-1] configs = [] for directory, subdirs, files in os.walk(folder): for pfile in files: print('checking', pfile) afile = os.path.join(directory, pfile) config_list = extract_config(afile) ...
def decode(config, item, defang=False): val = try_decode(config, item) if val != None: config[item] = val if defang: config[item] = defang_ip(val) def defang_ip(ip): if "," in ip: ips = ip.split(",") return ",".join([defang_ip(i)] for i in ips) else: ...
The function decodes and processes configuration values in a dictionary. It specifically handles the "PasteUrl" by retrieving its content from Pastebin, defanging IPs in both the URL and content, then applies decoding to other keys like Host, Port, KEY, etc., with varying defang parameters. The modified config is retur...
def decode_config_values(config): decode(config, "PasteUrl", defang=False) if "PasteUrl" in config: paste_content = defang_ip(retrieve_pastebin_text(config["PasteUrl"])) config["PasteUrl content"] = paste_content config["PasteUrl"] = defang_ip(config["PasteUrl"]) decode(config, "Host...
def get_resources(afile): resource_data = [] try: with open(afile, 'rb') as f: data = f.read() pe = pefile.PE(data=data) rt_string_idx = [ entry.id for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries ].index(pefil...
The code extracts configuration data and C2 IPs from a file by decrypting resources using candidate keys derived from SHA1 hashes. It verifies decrypted blobs via hash checks, selects the smallest blob as the config, decodes it, and appends extracted IPs. If no valid data is found, it returns an empty string.
def extract_config(afile): resources = get_resources(afile) decrypted_blobs = [] config_key_candidates = collect_config_keys(afile) for key_string in config_key_candidates: #print(key_string.decode('latin1')) if len(key_string) <= 1: continue m = hashlib.sha1() m.update(k...
def write(string): if not quiet and not print_only_c2s: print(string) def extract_config(afile): resources = get_resources(afile) decrypted_blobs = [] config_key_candidates = collect_config_keys(afile) for key_string in config_key_candidates: #print(key_string.decode('latin1')) if le...
The main task of the code is to process an input file by extracting its configuration data, generating a SHA-256 hash of the file, combining the hash and configuration into a string, optionally printing or saving this combined data, and returning the resulting string for further use.
def main_file(afile): write('checking ' + afile) config = extract_config(afile) config_str = sha256sum(afile) + "\n\n" + config + "\n\n" if not quiet: print("\n" + config) if write_c2s_to_file: write_config_to_file(config_str, c2_output_file) return config_str
def main_string_lookup(afile): decrypt_info = extract_decryption_data(afile) print() for table_num, info in enumerate(decrypt_info): write("===========Table " + str(table_num + 1) + " ===========\n") write("string key va: " + hex(info.key)) write("string table va: " + hex(info.data))...
The main task of the code is to extract C2 server information and decoded strings from QBot samples, supporting single file or directory input. It processes command-line arguments to control output format (C2-only, strings with offsets), quiet mode, and file storage. The code routes execution to `main_string_lookup`, `...
def main(): global print_only_c2s global quiet global write_c2s_to_file global c2_output_file parser = argparse.ArgumentParser(description='QBot config extractor and string decrypter') parser.add_argument('-f', '--file', help='path is a single qbot sample', action='store_true') parser.add_...
def _set_configuration_if_needed(): if not _is_configured(): ssh_key_path, ssh_key_name, do_token_path, user_username, user_default_pass = _ask_for_configuration() _create_configuration_file(ssh_key_path, ssh_key_name, do_token_path, user_username, user_default_pass) if not _has_droplet_invento...
The code defines a function `create` that sets up configuration, installs required dependencies, and creates a droplet (a virtual machine) using the provided specifications. It ensures prerequisites are met before provisioning the droplet.
def create(name, droplet_spec): _set_configuration_if_needed() _install_requirements_if_needed() _create_droplet(name, droplet_spec)
def findcalib(calib_file, parentdr): if calib_file == '': return None calib_path = os.path.join(parentdr, calib_file) if os.path.exists(calib_path): return calib_path else: return None def loadimages(filelist, parentdr): impaths = [] for name in filelist: name = o...
The main task of the code is to read and parse a scan configuration from a YAML file, validate its format, load associated data (calibration, images, metadata), and return an SData object. It handles version-specific logic, including loading annotations from a secondary YAML file if the version is ≥2.
def readscan(fpath): ## fpath is the scan dir if os.path.isdir(fpath): fpath = os.path.join(fpath, 'scan.yaml') ## fpath is the scan.yaml file if (not os.path.isfile(fpath)) or (not fpath.lower().endswith('.yaml')): print('not a valid yaml path') return None base_dir_pai...
def getData(): if not path.exists(local_store_file): save_object([]) with open(local_store_file, 'rb') as inp: data_list = pickle.load(inp) return data_list def get_all_address(): return [node.get_ip_addr() for node in getData()] def match_port(addr, port): for node in getData(): ...
The main task of the code is to validate if a given node's address and port exist in the existing address book. If the address exists, it checks port validity using `match_port` and returns the result. If invalid, it creates a new node, appends it to the node list, saves the updated list, and returns the new node. This...
def check_node_valid(address, port): node_list = getData() address_book = get_all_address() if address in address_book: result = match_port(address, port) if result: return result else: return None else: new_node = Node(address, port) node...
def get_all_filename(): return [file.getName() for file in getData()] def getData(): if not path.exists(local_store_file): save_object([]) with open(local_store_file, 'rb') as inp: data_list = pickle.load(inp) return data_list def saveData(data): save_object(data)
The main task of the code is to register new local files by checking if they exist in the existing filename space. If a file is not present, it creates a new `File` object, adds it to the data list, and returns the list of newly added files. The function ensures only non-duplicate files are registered and updates the s...
def register_local_file(file_list): added_file = [] filename_space = get_all_filename() data = getData() for file in file_list: if file not in filename_space: new_file = File(file) data.append(new_file) added_file.append(new_file) saveData(data) return...
def getData(): if not path.exists(local_store_file): save_object([]) with open(local_store_file, 'rb') as inp: data_list = pickle.load(inp) return data_list def remove_file_by_name(name): data = getData() for file in data: if file.getName() == name: data.remove(fi...
The code removes specified files from a dataset either by their object references (if type is "obj") or by their names (if type is "name"), then saves the updated dataset.
def remove_files(files, type): data = getData() if type == "obj": for file in files: data.remove(file) if type == "name": for file in files: remove_file_by_name(file) saveData(data)
def getData(): if not path.exists(local_store_file): save_object([]) with open(local_store_file, 'rb') as inp: data_list = pickle.load(inp) return data_list def check_node_valid(address, port): node_list = getData() address_book = get_all_address() if address in address_book: ...
The function registers a file chunk with a specific peer node. It validates the peer's address/port, locates the corresponding node in the data list, registers the chunk with the node, and updates the data. It returns the registration status or False if the peer is invalid.
def register_file_chunk(chunk_index, peer_addr, peer_port, filename, file_size): data_list = getData() check_node_valid(peer_addr, peer_port) index = -999 for i in range(len(data_list)): if data_list[i].get_ip_addr() == peer_addr and data_list[i].get_port() == peer_port: index =...
def check_node_valid(address, port): node_list = getData() address_book = get_all_address() if address in address_book: result = match_port(address, port) if result: return result else: return None else: new_node = Node(address, port) node...
This function handles client requests by processing incoming data based on a 'code' value. It registers files, retrieves file lists, locates files, registers chunks, and responds with status updates or errors. It validates nodes, sends structured responses, and manages connections for distributed file storage or sharin...
def threaded_client(connection, addr): address, port = addr print("incoming connection: ", address) # giving success response code connection.send(str.encode('200')) # recieving main content of data data = connection.recv(2048) data = json.loads(data.decode("utf-8")) if data['code'] == 1...
def Q_1(conn, execution_time): new_conn = load_database(conn) cursor = new_conn.cursor() #========================================================================== # Enter QUERY within the quotes: query = """ SELECT p.player_name, AVG(es.statsbomb_xg) AS avg_xg FROM playe...
The main task of the code is to execute a series of 10 predefined queries (Q_1 to Q_10) sequentially on a database connection, track their individual execution times in a list, and print each recorded time. The `execution_time` list is updated by each query function, which likely measures and stores the time taken for ...
def run_queries(conn): execution_time = [0,0,0,0,0,0,0,0,0,0] conn = Q_1(conn, execution_time) conn = Q_2(conn, execution_time) conn = Q_3(conn, execution_time) conn = Q_4(conn, execution_time) conn = Q_5(conn, execution_time) conn = Q_6(conn, execution_time) conn = Q_7(conn, execution...
def _check_path(self, path: str): """ Quick error handeling of the input parameter Parameters ---------- path : string path to Kilosort dataset Returns ------- Nothing if correct, but trows an error if the path is not a real path and ...
This code initializes an object to process data from a specified path. It validates the path, loads data, sets up signal and folder structures, adds plotting and sorting functionalities, and executes a custom script (`changeSet.py`) for data processing. The `save_data` flag controls data persistence during execution.
def __init__(self, path: str): # Error handeling # Store the path and other variables self.path = self._check_path(path) self._check_folder() # Load the data self._load_data() # The signal we'll use for analysis self.signal_path = self.params['dat_path...
def validate_header_size(data: bytes) -> bool: # per rfc1035 4.1.1, header will be 12 bytes return len(data) >= 12 def is_query(data: bytes): sbe_0_flags = 0x8000 # first bit is response field, sbe 0 for query sbe_0_flags |= 0x7800 # opcode_filter = 0x7800 , 0=std query sbe_0_flags |= 0x0200 # tr...
The main task of the code is to create a simple DNS server that listens on UDP port 53, processes incoming DNS queries, and responds with predefined IP addresses from a static dictionary. It binds to a specific IPv4 address, validates query packets, checks for 'A' record requests, and constructs DNS responses using raw...
def main(): # listen port and ipv4 # ipv4 = "" # socket.INADDR_ANY # 0.0.0.0 listen on all interfaces # env based config, windows is dev machine, anything else assume stage or prod (both linux systems) ipv4 = "" if sys.platform == 'win32' else "192.168.127.12" # listen on public addr port = 53 ...
def check_for_updates(stats: list) -> dict: cleaned_stats = clean_stats(stats) recent_flex = postgresStrategy.get_recent_flex_stats() recent_soloduo = postgresStrategy.get_recent_soloduo_stats() changed_soloduo, changed_flex = compare_changes(cleaned_stats, recent_flex, recent_soloduo) return {"fl...
The code updates summoner statistics by fetching data, checking for changes, inserting updates into a PostgreSQL database, generating announcements, and sending them via a Discord webhook with randomized embed colors if any updates exist.
def update(): load_dotenv() webhook_url = os.getenv("WEBHOOK_URL") summoners = postgresStrategy.get_summoners() stats = get_stats_for_all(summoners) updated_stats = check_for_updates(stats) insert_updated_stats_to_db(updated_stats) announcements = make_announcements(updated_stats) if l...
def create_new_summoner_entry(summoner) -> dict: return { "soloduo": create_new_cat_data(summoner["soloduo"]), "flex": create_new_cat_data(summoner["flex"]) } def check_if_updated(summoner: dict, summoner_data: dict, queue_type: str) -> (bool, str): new_rank = summoner[queue_type] old_ra...
The function updates summoner data by checking for new entries or changes in solo/duo and flex game modes, updating the JSON file with new data, and returning messages indicating additions or changes. It reads existing data, processes each summoner, creates new entries if needed, checks for updates, modifies the data s...
def update_stats(updated_summoners: list) -> list: try: summoner_data = json.loads(open("core/DataStoringStrategy/summoners_data.json", "r").read()) except: summoner_data = {} messages = [] for summoner in updated_summoners: name = summoner["name"] if name not in summo...
def backpropogate(self, node:MonteCarloTree): #print("BACKPROPOGATE") #print(node) #update UCB1 value too if node.parent_node is None: #print("reached root node") return if node.parent_node is not None: node.parent_node.ucb1_eval += node.ucb...
This code performs a recursive rollout in a Monte Carlo Tree Search (MCTS) to simulate game outcomes from a given node. It checks for terminal states, updates win counts and steps, and recursively expands unexpanded child nodes until a terminal state is reached, then backpropagates results.
def rollout(self, node: MonteCarloTree, steps=0): #print("ROLLOUT") #print(node) if node.board.is_win(self.color) > 0 or node.board.is_win(self.opponent[self.color]) > 0: #or steps > 1000: node.no_of_wins += int(node.board.is_win(self.color)) node.no_of_steps = steps ...
def expansion(self, node: MonteCarloTree): #print("EXPANSION") #print(node) if node.board.is_win(self.color) > 0 or node.board.is_win(self.opponent[self.color]) > 0: node.expanded = True return for move_set in node.move_list: for move in move_set: ...
The code performs a Monte Carlo Tree Search (MCTS) by expanding the given node, simulating outcomes through rollouts, updating node statistics with UCB1 evaluation, and selecting the best child node to determine the optimal move.
def monte_carlo_tree_search(self, node: MonteCarloTree): #print("MCTS SEARCH START") self.expansion(node) #print(node) for nd in node.child_nodes: #should be a while loop, and always start from the root self.rollout(nd) root_wins = node.no_of_wins self...
def get_transition(self, old_y, new_y): return self.transition(new_y, old_y) def get_emission(self, y, x): if not x in self.known_words: x = "#UNK#" return self.emission_v2(x,y) def set_policy(self, step, current_tag, word): best_value = -1 best_tag = None for...
The code implements the Viterbi algorithm to find the most probable sequence of hidden tags for a given word sequence. It calculates forward probabilities using transition and emission scores, tracks optimal tags in a policy dictionary, transitions to the STOP state, and backtracks to reconstruct the optimal tag sequen...
def viterbi(self, x_sequence): self.policy_dict = {} self.k = 1 # Moving forward recursively # init step 1 current_step = 1 self.policy_dict[current_step] = {} word = x_sequence[0] for tag in self.tags_list: if not word in self.known_words: ...
def get_transition(self, old_y, new_y): return self.transition(new_y, old_y) def get_emission(self, y, x): if not x in self.known_words: x = "#UNK#" return self.emission_v2(x,y) def insert_sort(self, array, value): if value[0] > array[0][0]: array[0] = value array.sor...
The code implements a modified Viterbi algorithm to find the top-k most probable tag sequences for a given word sequence. It processes each word step-by-step, maintaining k best paths with transition/emission probabilities. After forward processing, it backtracks from the end to reconstruct the top-k sequences, handlin...
def viterbi_kth(self, x_sequence, kth): self.policy_dict = {} self.k = 1 # Moving forward recursively # init step 1 current_step = 1 self.policy_dict[current_step] = {} word = x_sequence[0] for tag in self.tags_list: kth_ls = [(-1, None, None...
def add_to_maze(self, obj, **kwargs): self.cols[obj.x][obj.y] = obj def get_adjacent_coords(self, x, y, include_edges=False): all = [ [x-1, y], # left [x+1, y], # right [x, y-1], # top [x, y+1], # bottom ] if include_edges: ...
The code generates a maze using a randomized algorithm. It starts at a random cell, adds adjacent walls, and iteratively processes walls to carve passages by checking neighboring cells. It marks unvisited cells as walls, sets entrance/exit points on the maze edges, and identifies dead ends. The result is a maze with co...
def create_maze(self): # Randomize starting point and set it as a cell starting_height = random.randint(1, self.max_y - 1) starting_width = random.randint(1, self.max_x - 1) # Mark it as a cell and add surrounding walls to the list self.add_to_maze(Cell(starting_width, starting_...
def loggerConfig(level=0, log_file=None): lg.setLevel({1: 'ERROR', 2: 'WARNING', 3: 'INFO'}.get(level, 'DEBUG') if level else 'CRITICAL') try: fh = open(log_file, 'a') except: fh = sys.stderr ch = logging.StreamHandler(fh) formatter = logging.Formatter('%(asctime)s - %(filename)s:%(lineno)d - %(leve...
The main task of the code is to parse command-line arguments for a printing process, configure logging based on verbosity and log file settings, and execute a printing workflow by calling `start()`, `Dprint()`, and `finish()` functions. It handles port selection, G-code file input, and logging configuration to manage t...
def main(): global args parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', dest="port", default='/dev/ttyUSB0', help="Port. default - /dev/ttyUSB0") parser.add_argument('-f', '--file', dest="file", required=True, help="G-code file to print") parser.add_argument('-v', action='coun...
def read_pred(pred_file: str) -> Dict[str, List[str]]: """Read the prediction file. :param pred_file: The file path to a prediction file. """ with open(pred_file) as f: preds = json.load(f) return preds def read_gold(gold_file: str) -> Dict[str, Set[str]]: """Read the gold file. :p...
The function `multi_span_evaluate_from_file` evaluates the performance of a MultiSpan QA model by comparing predictions from `pred_file` against ground-truth answers in `gold_file`. It reads predicted and gold answers using helper functions, then computes evaluation metrics via `multi_span_evaluate`, returning the resu...
def multi_span_evaluate_from_file(pred_file: str, gold_file: str): """Evaluate the predictions of a MultiSpan QA model from a `pred_file` and a `gold_file` :param pred_file: The file name of the prediction file. :param gold_file: The file name of hte gold answers file. """ preds = read_pred(pred_fi...
def read_gold(gold_file: str) -> Dict[str, Set[str]]: """Read the gold file. :param gold_file: The file path to the file with the golden answers. """ with open(gold_file) as f: data = json.load(f)['data'] golds = {} for piece in data: golds[piece['id']] = set(map(lam...
The function determines the optimal probability threshold for maximizing F1 score by evaluating thresholds on sorted prediction probabilities from nbest_dev_file against gold standard labels in gold_dev_file. It starts with 0.5, iterates through descending probabilities, and updates the best threshold and corresponding...
def find_best_threshold(nbest_dev_file, gold_dev_file): golds = read_gold(gold_dev_file) nbest_preds = read_nbest_pred(nbest_dev_file) probs = list(map(lambda x: x[0]['probability'], nbest_preds.values())) sorted_probs = sorted(probs, reverse=True) # search probs in prob list and find the best thres...
def find_best_threshold(nbest_dev_file, gold_dev_file): golds = read_gold(gold_dev_file) nbest_preds = read_nbest_pred(nbest_dev_file) probs = list(map(lambda x: x[0]['probability'], nbest_preds.values())) sorted_probs = sorted(probs, reverse=True) # search probs in prob list and find the best thres...
This function evaluates the performance of nbest predictions against gold standard answers by determining the optimal threshold for selecting top predictions, then applying this threshold to filter predictions and assess their accuracy using multi-span evaluation metrics.
def eval_with_nbest_preds(nbest_file, gold_file): """ To use this part, check nbest output format of huggingface qa script """ best_threshold, _ = find_best_threshold(nbest_file, gold_file) nbest_preds = read_nbest_pred(nbest_file) golds = read_gold(gold_file) preds = apply_threshold_nbest(best_thre...
def checking_availability(model): """ This function will check, if GPTs models are available, there token limit, etc. """ models_available = [x["id"] for x in openai.Model.list()["data"]] if model not in models_available: cprint( f"Model {model} is not available.Try rerun...
The main task of the code is to execute a script, handle errors by using an AI model (e.g., GPT) to generate fixes, and apply those changes iteratively until the script runs successfully. It creates a backup of the original script, checks model availability, and either reverts changes or applies AI-suggested modificati...
def main(script_name, *script_args, revert=False, model=default_gpt_model, confirm=True): """ main function for running """ if revert: backup_file = script_name + ".bak" if os.path.exists(backup_file): shutil.copy(backup_file, script_name) print(f"Reverted change...
def get_args(): if len(sys.argv) != 6: print('usage: {} file x y year-from dir-out'.format(sys.argv[0])) sys.exit(1) (file_name_in, latitude, longitude, year_from, out_dir) = sys.argv[1:] pixel = latitude_longitude_to_pixel(float(latitude), float(longitude)) file_name_out = '{}/...
The main task of the code is to process input data, organize it by date (month and day), and write it into a CSV file with a header. It reads data from an input file, iterates through months and days, formats each date, and writes corresponding data rows to the output CSV file.
def main(): (file_name_in, file_name_out, pixel, out_dir, year_from) = get_args() data = get_data(file_name_in, year_from) with open(file_name_out, 'w') as csvfile: csvfile.write('{}\n'.format(','.join(header(year_from)))) row = 0 for month, name in MONTH.items(): for d...
def plot_figure_1_panels(): """ Plot panels used in Figure 1. """ ### # Top - Overview of the WGS method. ### reads_per_sample = 16e6 ff = 0.2 genome_size = 3e9 bin_size = 50e3 depth_per_bin = reads_per_sample / (genome_size / bin_size) chroms = range(1, 23) + ["X", "Y"...
The main task of the code is to generate individual panels for figures 1 through 4 in a manuscript by sequentially calling dedicated plotting functions for each figure. The `main()` function orchestrates this process, ensuring each figure's panels are rendered as specified.
def main(): """ Plot the individual panels of each of the figures in the main manuscript. """ plot_figure_1_panels() plot_figure_2_panels() plot_figure_3_panels() plot_figure_4_panels()
def fit_beta_to_mu_sd(mu, sd): """ Return the alpha and beta parameters that produce a beta distribution with specified mean and stdev. Args: mu (float): Mean value of the distribution sd (float): Standard deviation of the distribution Returns: alpha,beta Note: ...
The code simulates SNP read data by generating maternal, paternal, and fetal haplotypes under specified chromosomal states (H), then sampling allele counts using beta-binomial and negative-binomial distributions. It returns a DataFrame with maternal genotypes, A-allele counts, total counts, and population allele freque...
def simulate_snp_sample(ff, H, num_snps, mean_counts, bbdisp, nbdisp): """ Generate maternal, paternal, and fetal haplotypes for a chromosome, then sample reads according to these genotypes and the specified fetal fraction. Args: ff (float): Fetal fraction H (tuple): Fetal chromsosomal ...
def read_pcg_df(infile): """ Read in table corresponding to p(gf|gm,gp,H), or the probability of the fetal genotype, gf, given the maternal and paternal genotypes (gm, gp) and the chromosomal copy number hypothesis, H, and return as a dict. The table was obtained from: Rabinowitz M, Gemelos G,...
The function calculates the log-odds ratio (LOR) for a disomic fetus using SNP simulation data, fetal fraction, and beta-binomial dispersion parameters. It iterates through SNPs, evaluates chromosomal hypotheses (e.g., disomy vs. trisomy), integrates over fetal and paternal genotypes, and computes likelihoods using pre...
def calculate_snp_method_lor(df, ff, bbdisp): """ Given a dataframe containing the output of the SNP method simulation, the fetal fraction, and the beta-binomial dispersion parameter, calculate the log-odds ratio of a disomic fetus: LOR = log( L(Hd) / (1-L(Hd)) ) Method obtained from: Rab...
def parse_args(): class CustomFormatter(argparse.RawDescriptionHelpFormatter): pass epilog = """\ Possible ploidy states are: d, disomy m1, maternal meiosis I trisomy m2, maternal meiosis II trisomy p1, paternal meiosis I trisomy p2, paternal meiosis II trisomy If the beta-binomial dispersion parame...
The main task of the code is to perform permutation-based statistical analysis on simulated SNP data by generating synthetic datasets with specified parameters, calculating log odds ratios (LOR) for each permutation, and saving the results to a CSV file. It validates input parameters, handles reproducibility via random...
def main(): args = parse_args() #If --reproducible/-e option is set, seed the random number generator in #order to reproduce the same output for the same parameter set. if args.reproducible: seed = get_snp_seed(args) np.random.seed(seed) if args.bbdisp != "binomial": asser...
def map_compound_field(self, compound_template_field: dict): """ Maps compound field where only a single nested object is expected. A compound field that is not a multiple will have a single dictionary as the value. For every nested field we find the first value in the metadata using th...
This method maps source metadata to compound fields by selecting between three strategies: mapping entire objects for single compounds, creating indexed lists for multiple compounds, or extracting first items from lists for non-multiple compounds. It uses different helper functions based on whether the field is multipl...
def map_compound(self, field: dict): """ This method handles the different ways of mapping to a compound. There are currently three different ways of mapping to a compound. The complex way is to map an entire object in the source metadata to a compound in its entirety. map_object_onto_c...
def newDataInput(self, date=None): if data == None: print("Please enter the date you would like to record.") date = self.getDate() exists, day = verifyDate(date) if exists: # NOTE need to add some time checking to ensure entries are duped print("Th...
The code defines a user interface for a Habit Tracker application, presenting a loop with options to input new data into an XML file, view a histogram of current data, or exit. It handles user choices by calling corresponding methods: `newDataInput()` for data entry, `getXMLdata()` and `printData()` for visualization, ...
def interface(self): while(True): print("Habit Tracker v0.1\n") option = input("1: Input new data to XML.\n2: View current histogram\n3: Exit\nEnter one of the options above: ") if option == "1": self.newDataInput() elif option == "2": ...
def calc_scale(): #print(_bounds) _height = SCREENSIZE[1]-(2*PADDING[0]) _width = SCREENSIZE[0]-(2*PADDING[1]) max_x = abs(_bounds[0]) + abs(_bounds[1]) max_y = abs(_bounds[2]) + abs(_bounds[3]) global x_scale x_scale= _width / max_x global y_scale y_scale= _height / max_y ...
The code initializes a Pygame visualization environment to display a grid with obstacles and pathfinding elements. It reads environmental data, sets up nodes, draws a line between them, and continuously updates the screen with a grid. The loop handles events, clears the display, and renders the grid, while commented-ou...
def main(): solution.read_env_file(filename,_obstacles,_bounds) calc_scale() #print("this is yscale ",y_scale) #print(-1*y_scale) #print(_obstacles[0].__str__()) global n1 n1 = solution.Node(5,9,"01") global n2 n2 = solution.Node(0,0,"origi") draw_line(n1,n2) pygame.init() ...
def current_time(self): return datetime.now().strftime("%H:%M:%S") def handle_message(self, sender, recipient, message): if recipient.lower() == 'broadcast': self.broadcast(message, owner=sender) elif recipient.lower() == 'multicast': self.multicast(message, owner=sender)...
This code manages a new client connection by receiving the client's name, storing it, and handling subsequent messages. It processes private messages (starting with '@'), forwards files (starting with 'file:'), and broadcasts regular messages. The loop continues until no data is received, at which point the client is d...
def new_client(self, connection): try: client_name = connection.recv(1024).decode('utf-8') self.user[connection] = client_name self.users_last_message[connection] = False print(f'{self.current_time()} {client_name} bergabung!') while True: ...
def str2list(line: str) -> list: ret = [[0 for _ in range(9)] for _ in range(9)] for x in range(9): for y in range(9): idx = x * 9 + y digit = int(line[idx]) ret[x][y] = digit return ret def run_solver(bo: list) -> list: # import pdb # pdb.set_trace() ...
The code processes a range of Sudoku puzzles from a CSV file (indices L to R), solves each using a solver function, and saves the quizzes and their solutions to an output CSV. It counts puzzles with multiple solutions. The function returns the count of such puzzles.
def main(sudoku_file: str, output_file: str, L: int, R: int): _multi_quiz_cnt = 0 sudoku_df = pd.read_csv(sudoku_file) output_df = pd.DataFrame(columns=['quizzes', 'solutions']) for _index in tqdm(sudoku_df.index): if not (L <= _index <= R): # L and R is closed interval c...
def is_empty(table, board, i, j): index = table.table_number if (i >= 2) and (j >= 2) and (i + table.length + 1 < len(board)) and (j + table.width + 1 < len(board[0])): if ((board[i - 2, j - 2] == 0 or board[i - 2, j - 2] == index) and (board[i + table.length + 1][j - 2] == 0 or board[i ...
The function `fix` optimizes a table's position on a board by evaluating possible moves (up, right, down, left) to empty spaces. It calculates the minimal distance from other tables for each direction, selects the move that increases this distance, updates the table's position, and recursively repeats the process to en...
def fix(table, board, i, j, tables_list): next_coor = (-1, -1) min_dis = table.min_distance # check if we can move the table one step in some direction empties_squares = [is_empty(table, board, i - 1, j), is_empty(table, board, i, j + 1), is_empty(table, board, i + 1, j), ...
def find_potential_spots(table, board): possible_spots = [] # for every empty spot on the board, we check if by placing there the top left corner of --> # --> the curr table and then checks if we can also place all other corner for i in range(len(board)): for j in range(len(board[0])): ...
The function `add_tables` aims to place tables on a board in positions that minimize the distance between them while avoiding collisions. It iterates through each table, identifies valid spots, selects the optimal position using a heuristic, and checks for collisions. If no valid spots exist or a better solution is fou...
def add_tables(board, best_distance, tables, try_num): min_distance = np.inf for i in range(len(tables)): # find all possible points in the board for placing next table possible_spots = find_potential_spots(tables[i], board) # in case there are no spots to put the next table or the cu...
def create_init_board(initial_matrix, tables): restaurant_length = 0 restaurant_width = 0 # finding the dimensions of the restaurant for i in range(10): for j in range(10): # light indicate a 1X1m spot in the user's restaurant ( a square he marked as chosen) if initial_...
The code implements an algorithm to optimally arrange tables within a restaurant layout matrix, minimizing spatial conflicts or distances between tables. It initializes a board, iteratively places tables, evaluates distances, and refines placements to achieve the best configuration. If successful, it updates table posi...
def tables_arrangement_algorithm(tables_list, restaurant_matrix): init_board = create_init_board(restaurant_matrix, tables_list) # initialize board best_board = init_board.copy() global_min_distance: int = -1 # represent the minimal distance between some tables on the board for i in range(decide_num_...
def define_var_constraints(self, entities): """ Define variable constraints, i.e., state the indices of reoccurring entities in a walk. Parameters: entities (list): entities in the temporal walk Returns: var_constraints (list): list of indices for reoccurring en...
The main task of the code is to generate a rule dictionary from a cyclic temporal random walk. It extracts the head relation, processes reversed body relations using inverse IDs, defines variable constraints from reversed entities, and calculates confidence metrics. The rule is stored if unique, ensuring no duplicates.
def create_rule(self, walk): """ Create a rule given a cyclic temporal random walk. The rule contains information about head relation, body relations, variable constraints, confidence, rule support, and body support. A rule is a dictionary with the content {"head_rel": in...
def sym_exec_ins(params, block, instr, func_call, current_func_name): global MSIZE global visited_pcs global solver global vertices global edges global blocks global g_src_map global g_slot_map global calls_affect_state global instructions stack = params.stack mem = para...
This function performs symbolic execution on a basic block of code, handling different control flow types (terminal, unconditional, conditional jumps). It tracks visited edges, checks for loop/gas limits, executes instructions, and recursively explores paths using a solver to manage constraints. For conditional branche...
def sym_exec_block(params, block, pre_block, depth, func_call, current_func_name): global solver global visited_edges global money_flow_all_paths global path_conditions global global_problematic_pcs global all_gs global results global g_src_map visited = params.visited stack = p...
def get_init_global_state(path_conditions_and_vars): global_state = {"balance": {}, "pc": 0} init_is = ( init_ia ) = ( deposited_value ) = ( sender_address ) = ( receiver_address ) = ( gas_price ) = ( origin ) = ( currentCoinbase ...
The function performs symbolic execution starting from the beginning of a program. It initializes path conditions, global state, and analysis parameters, then triggers symbolic execution on a block of code using `sym_exec_block`, likely for path analysis or vulnerability detection, with a fallback handling mechanism.
def full_sym_exec(): # executing, starting from beginning path_conditions_and_vars = {"path_condition": []} global_state = get_init_global_state(path_conditions_and_vars) analysis = init_analysis() params = Parameter( path_conditions_and_vars=path_conditions_and_vars, global_state=gl...
def _get_compiled_contracts(self): if not self.compiled_contracts: if self.input_type == InputHelper.SOLIDITY: self.compiled_contracts = self._compile_solidity() return self.compiled_contracts def _prepare_disasm_files_for_analysis(self, contracts): for contract, byt...
The function retrieves contract analysis inputs for NFTGuard by collecting source maps, disassembly files, and metadata. It filters contracts based on targetContracts (if provided) and returns structured data for each contract, including source code, slot maps, and disassembly paths, enabling analysis of Solidity contr...
def get_inputs(self, targetContracts=None): """ Retrieves the inputs required for NFTGuard analysis. Args: targetContracts (list): List of target contract names to analyze. If None, all contracts will be analyzed. Returns: list: List of dictionaries containing t...
def change_format(): """Change format for tokenization and buildng CFG""" with open(g_disasm_file) as disasm_file: file_contents = disasm_file.readlines() i = 0 firstLine = file_contents[0].strip("\n") for line in file_contents: line = line.replace(":", "") ...
The main task of the code is to build a control flow graph (CFG) from a disassembled file by tokenizing input, identifying vertices, constructing basic blocks and static edges, then performing symbolic execution for analysis. It processes disassembly data, constructs program structure, and executes symbolic analysis to...
def build_cfg_and_analyze(): """Build cfg and perform symbolic execution""" change_format() logging.info("Building CFG...") with open(g_disasm_file, "r") as disasm_file: disasm_file.readline() # Remove first line tokens = tokenize.generate_tokens(disasm_file.readline) # tokenization ...
def initGlobalVars(): # Initialize global variables global g_src_map global solver # Z3 solver solver = Solver() solver.set("timeout", global_params.TIMEOUT) global MSIZE MSIZE = False global revertible_overflow_pcs revertible_overflow_pcs = set() global g_disasm_file ...
The main task of the code is to execute symbolic analysis via `build_cfg_and_analyze()` within a timeout constraint. If the operation completes normally, it logs success; if it times out, it sets a global timeout flag and invokes a user-provided timeout callback. The function handles both successful execution and timeo...
def run_build_cfg_and_analyze(timeout_cb=do_nothing): initGlobalVars() global g_timeout try: with Timeout(sec=global_params.GLOBAL_TIMEOUT): build_cfg_and_analyze() log.debug("Done Symbolic execution") except TimeoutError: g_timeout = True timeout_cb()
def train_epoch(self, train_loader): self.train() train_loss = 0.0 for batch_idx, sample in enumerate(train_loader): x = sample['volume'] x = x.to(self.device) covariates = sample['covariates'] covariates = covariates.to(self.device) id...
The code defines a training loop that iterates over epochs, trains the model on a shuffled training dataset, records training loss, logs metrics using TensorBoard, tests the model on a test set at specified intervals, saves model checkpoints periodically, and closes the logging writer. It handles data loading, loss tra...
def train_loop(self, loaders, epochs=100, test_freq=2, save_freq=10, save_dir = ''): print("="*40) print("Training: epochs", self.epoch, "to", self.epoch+epochs-1) print("Training set:", len(loaders['Shuffled_train'].dataset)) print("Test set:", len(loaders['test'].dataset)) prin...
def get_exposure_metadata(observatory: str, mjd: int, **kwargs): """ Return a generator of metadata for all exposures taken from a given observatory on a given MJD. """ paths = glob(f"{SAS_BASE_DIR}/sdsswork/data/apogee/{observatory}/{mjd}/a?R-*.apz") yield from starmap(_get_meta, get_unique_ex...
This function retrieves exposure metadata and fiber mapping data for a specified observatory and Modified Julian Date (MJD). It returns a tuple containing sorted exposure records, sequence indices for objects/arclamps, and fiber maps (if requested) by querying database tables and cross-matching configurations. The outp...
def get_almanac_data(observatory: str, mjd: int, fibers=False, xmatch=True, profile="operations", **kwargs): """ Return a generator of metadata for all exposures taken from a given observatory on a given MJD. """ exposures = get_exposure_metadata(observatory, mjd, **kwargs) exposures =...
def clearscreen(): print("\033[H\033[J") def star(message): return cprint(figlet_format(message, font='starwars'), 'blue', attrs=['bold','blink']) def get_input(db): commands = [{"Key": " S ", "Action": "Show CSV List"}, {"Key": " L ", "Action": "Load/View List"}, ...
This code provides a command-line interface (CLI) for managing medical data stored in CSV files. It allows users to list, load, view, update, create, duplicate, and delete CSV files, with error handling for missing files. The interface maintains a current database state and displays alerts for actions like loading, upd...
def main(): clearscreen() star("MedTrac") db = None mainloop = True while mainloop: action = get_input(db) if action == "S": clearscreen() allfiles = os.listdir(".") csv_files = list(filter(lambda f: f.endswith(".csv"), allfiles)) pr...
def draw_data_with_two_classes(m): no_two_classes_exists = True while no_two_classes_exists: X, y = get_data(m) if np.unique(y).size == 2: no_two_classes_exists = False return X, y def create_svm(X, y): clf = SVC(C=SVM_C, kernel='linear') clf.fit(X, y) return clf def...
The code evaluates and compares the performance of SVM and Perceptron classifiers by varying training data size. It runs multiple trials, computes average accuracies across sample sizes, and plots accuracy trends for both models against training data size.
def q5(): svm_results = np.zeros((NUMBER_OF_TRYS, len(SAMPLE_SIZES))) perceptron_results = np.zeros((NUMBER_OF_TRYS, len(SAMPLE_SIZES))) for i in range(NUMBER_OF_TRYS): m_number = 0 for m in SAMPLE_SIZES: X_train, y_train = draw_data_with_two_classes(m) X_test, y_...
def SetlenBrea(self): length = simpledialog.askstring(title="Dimensions Length", prompt="Number of LED's length wise") breadth = simpledialog.askstring(title="Dimensions Breadth", prompt="Number of LED's width wise") return int(length), int(breadth) def SelectCom(self): COM = simpledialo...
The code initializes a class to handle serial communication for a device with specific dimensions, setting up serial parameters, selecting a COM port, and launching a main window. It prepares hardware interaction by configuring length, breadth, and command structures, likely for a GUI-based system controlling or monito...
def __init__(self): self.SP = SerialProcessor() self.SendCommandStr = "" self.Serial = SerialProcessor() Length, Breadth = self.SetlenBrea() self.COMPort = self.SelectCom() self.l = Length self.b = Breadth self.MainWindow()
def check_solvability(state): inversion = 0 for i in range(len(state)): for j in range(i + 1, len(state)): if (state[i] > state[j]) and state[i] != 0 and state[j] != 0: inversion += 1 return inversion % 2 == 0 def bfs(problem): frontier = deque([Node(problem.initial)...
The code solves an 8-puzzle problem using specified algorithms (BFS, IDS, or A* with heuristics). It reads input from a file, checks puzzle solvability, executes the chosen search algorithm, and outputs solution details (path, time, nodes generated) or error messages. It supports custom output formats and handles inval...
def main(): #Check users inputs if len(sys.argv) < 3: print("Please enter 2 arugments in the form <filepath> <algorithm>.") print("Algorithm options are BFS, IDS, h1, h2, or h3.") return file_path = sys.argv[1] algo = sys.argv[2].lower() #Secret input for Part 3 print_fo...
def initialize_game(game, state, eval_func, preset=None): #Black's first move move = ((game.h // 2) + 1, (game.v // 2) + 1) print("Alpha-Beta's move:", move) state = game.result(state, move) game.display(state) print() #White's first move move = human_player(game, state, preset) sta...
The main task of the code is to run a Gomoku game where the user chooses between a preset move sequence or manual input. It alternates between an AI (alpha-beta pruning) and a human player, tracks game duration, and displays the winner or tie. The code initializes the game, handles turns, and evaluates outcomes using a...
def main(): if input("Are you using the preset (Yes or No)? ").lower() == "yes": use_preset = True else: use_preset = False eval_func = int(input("Which evaluation function do you want to use (1 or 2)? ")) #Initialize the game start_time = time.time() state = Gomoku().initial ...
def login_with_passwd(self, hostname, user, passwd): ip = self.get_ip_by_hostname(hostname) return self.__login(ip, user, passwd) def get_ip_by_hostname(self, hostname): return self.host_ip_dict[hostname] def __login(self,ip, user, passwd): print("logging into " + ip) if ip in self.ip_tn_dict.keys(...
This function logs in to a host using default credentials, but if the hostname is 'T', it uses test credentials. It retrieves the IP address for the hostname and calls the private __login method with the obtained IP and credentials.
def login_no_passwd(self, hostname): if hostname == 'T': return self.login_with_passwd(hostname, self.test_user, self.test_passwd) ip = self.get_ip_by_hostname(hostname) user = self.user passwd = self.passwd return self.__login(ip, user, passwd)
def login_with_passwd(self, hostname, user, passwd): ip = self.get_ip_by_hostname(hostname) return self.__login(ip, user, passwd) def get_tn(self,ip): return self.ip_tn_dict[ip] def logout(self,ip): tn = self.get_tn(ip) tn.close() return tn.read_all().decode('ascii')
This code tests a login process to a remote system using provided credentials, establishes a connection, and interacts with a shell session. It continuously accepts user commands, sends them to the remote terminal, and prints responses until the 'exit' command is issued, at which point it logs out and terminates the se...
def test(self): msg = self.login_with_passwd('T',self.test_user,self.test_passwd) print(msg) tn = self.get_tn(self.T) print(tn.read_until(b'#',1).decode('ascii'),end=' ') while True: cmd = input() + '\n' tn.write(cmd.encode('utf-8')) print(tn.read_until(b'hadoop@Slave2:~$',1...
def config_R(self): commands = [] with open('./scripts/R.txt') as f: commands = f.readlines() commands = [i.split('\n')[0] for i in commands] return self.run_cmds('R', commands) def config_S1(self): commands = [] with open('./scripts/S1.txt') as f: commands = f.readlines() c...
The code defines a method `config` that selects and returns a specific configuration function based on the provided `hostname` parameter. If the hostname matches 'R', 'S1', 'S2', 'S3', or 'T', it calls the corresponding private method (e.g., `config_R()`). Otherwise, it returns an error message and the value -1 for inv...
def config(self, hostname): if hostname == 'R': return self.config_R() elif hostname == 'S1': return self.config_S1() elif hostname == 'S2': return self.config_S2() elif hostname == 'S3': return self.config_S3() elif hostname == 'T': return self.config_T() else: ...
def get_data_from_s3(bucket_name, file_name): """get all data from bucketS3 to json type Args: bucket_name (string): name of the bucket file_name (string): name of the file Returns: json: rawl table s3 """ s3 = boto3.resource('s3') content_object = s3.Object(bucket_name...
The code performs an ETL process: extracts data from S3 (deals, links, reviews) using a date-stamped filename, transforms the data into structured DataFrames, retrieves AWS Secrets Manager credentials, and loads the transformed data into DynamoDB. The task automates data pipeline operations for Steam-related datasets, ...
def main(): now = datetime.now() current_day_str = f"{now.day}_{now.month}_{now.year}.json" input_deal = "deal/deal" + current_day_str input_link = "link/link" + current_day_str input_reviews = "reviews/reviews" + current_day_str bucket_name = "steametl" links = get_data_from_s3(bucket_name...
def cal_one_alpha(self, trans_data): row_n, col_n = len(trans_data[0]), len(trans_data[1]) state_n = len(self.mec_state) # add initial state first alpha = np.zeros([state_n+1, self.state_d_max+1, self.state_d_max+1, row_n+1, col_n+1]) alpha[0,0,0,0,0] = 1 for i in range(r...
The function `cal_one_lik` computes the observation likelihood (`temp_obs_lik`) for a given transition data (`trans_data`). It first calculates temporary parameters `temp_alpha` and `temp_beta` using `cal_one_alpha` and `cal_one_beta`, respectively. These values are then passed to `cal_one_nu` to derive the observation...
def cal_one_lik(self, trans_data): temp_alpha = self.cal_one_alpha(trans_data) temp_beta = self.cal_one_beta(trans_data) _, temp_obs_lik = self.cal_one_nu(temp_alpha, temp_beta) return temp_obs_lik
def cal_one_alpha(self, trans_data): row_n, col_n = len(trans_data[0]), len(trans_data[1]) state_n = len(self.mec_state) # add initial state first alpha = np.zeros([state_n+1, self.state_d_max+1, self.state_d_max+1, row_n+1, col_n+1]) alpha[0,0,0,0,0] = 1 for i in range(r...
This function computes the parameters 'one_nu', 'one_xi', and optionally 'obs_lik' for a given transition data in a Hidden Markov Model (HMM). It calculates intermediate values 'one_alpha' and 'one_beta' using forward-backward algorithms, then derives 'one_nu' and 'one_xi' from these. The function returns these values,...
def cal_one_nu_xi(self, trans_data, cal_obs_lik = True): one_alpha = self.cal_one_alpha(trans_data) one_beta = self.cal_one_beta(trans_data) one_nu, obs_lik = self.cal_one_nu(one_alpha, one_beta) one_xi = self.cal_one_xi(trans_data,one_alpha, one_beta, obs_lik) if cal_obs_lik: ...