dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def setup(): pointer = turtle.Turtle() screen = turtle.getscreen() screen.setup(WIDTH, HEIGHT, 0, 0) screen.setworldcoordinates(0, 0, WIDTH, HEIGHT) pointer.hideturtle() screen.delay(delay=0) return pointer def drawXAxis(pointer, xo, yo, ratio): xmin = 0 xmax = 0 # Defining and ...
The main task of the code is to create a graphical interface for plotting mathematical expressions on a coordinate system. It allows users to input an origin, pixel ratio, and arithmetic expressions, which are then drawn with distinct colors. The program first sets up axes, captures coordinate ranges, and iteratively p...
def main(): #Setup window pointer = setup() #Get input from user xo, yo = eval(input("Enter pixel coordinates of origin: ")) ratio = int(input("Enter ratio of pixels per step: ")) #Set color and draw axes (store discovered visible xmin/xmax to use in drawing expressions) pointer.color(AXIS...
def matrixWidth(piece): return len(piece[0]) def rotatePiece(piece): width = matrixWidth(piece) height = matrixHeight(piece) newPiece = [[0 for j in range(height)] for i in range(width)] for j in range(width): for i in range(height): newPiece[j][height-i-1] = piece[i][j] r...
This code implements a Tetris-like game loop, handling user input for piece movement/rotation, collision detection, piece placement, line clearing, and game over conditions. It uses a timer to control falling speed, updates the game state, and redraws the board continuously.
def gameLoop(): global fallingPiece, currentPace, oldRow, points, level clockcount = 0 refreshInterval = 10 fallingCol = fallingRow = 0 currentPace //= level while True: # Event Capture event, values = window.read(timeout=refreshInterval) if event == sg.WIN_C...
def initGame(): seed(datetime.now()) def initBoard(): global board board = [[0 for j in range(BOARD_WIDTH)] for i in range(BOARD_HEIGHT)] def drawWindow(): global window, canvas canvasWidth = BOARD_WIDTH*(TILE_SIZE+TILE_MARGIN*2) canvasHeight = BOARD_HEIGHT*(TILE_SIZE+TILE_MARGIN*2) layou...
The main task of the code is to initialize a game by setting up its components (initGame(), initBoard()), rendering the game window (drawWindow()), and starting the game loop (gameLoop()) to handle ongoing game operations, such as updates, rendering, and user interactions, thereby launching and managing the game's exec...
def main(): initGame() initBoard() drawWindow() gameLoop()
def calculate_dir_counts_for_levels(subject, train_test): if train_test=='train': calculate_train_counts_for_levels(subject) else: calculate_test_counts_for_levels(subject) def determine_candidates_based_on_difficulty(subject, max_level_of_difficulty, train_test='train'): candidates = [] ...
The code selects a random subset of problems from a specified subject, limited by a maximum difficulty level, for either training or testing. It first calculates difficulty level counts, identifies eligible candidates, then randomly selects the required number of problems from them.
def select_examples(subject, max_level_of_difficulty, n_problems_to_select, train_test): calculate_dir_counts_for_levels(subject, train_test) candidates = determine_candidates_based_on_difficulty(subject, max_level_of_difficulty, train_test=train_test) select_randomly_among_candidates(candidates, n_problems...
def make_reproducible(SEED=64357): np.random.seed(SEED) def prepare_final_directory(): print('Final directory is being prepared.') if not os.path.isdir('./selectedProblems'): os.mkdir('./selectedProblems') if not os.path.isdir('./selectedProblems/train'): os.mkdir('./selectedProblems/tra...
The main task of the code is to prepare a reproducible algebra problem dataset by selecting 1000 training and 100 test examples with difficulty ≤4, checking for duplicates, and organizing output in a designated directory structure.
def main(): make_reproducible() prepare_final_directory() select_examples(subject='algebra', max_level_of_difficulty=4, n_problems_to_select=1000, train_test='train') select_examples(subject='algebra', max_level_of_difficulty=4, n_problems_to_select=100, train_test='test') check_for_duplicates()
def implicit_perfect_matches(self): for man in self.probability_grid.columns: if len(self.probability_grid[self.probability_grid[man]==100])>0: woman = self.probability_grid[self.probability_grid[man]==100].index.values[0] perf_match = (woman,man) if p...
This function simulates a day's process in a matching algorithm by updating perfect matches and results matrices, selecting the best truth booth couple, adding them to the truth booth, and updating the solution space. It then repeats updates, performs a random night guess, simulates the night's events, and updates the ...
def random_day_n(self): self.implicit_perfect_matches() self.update_results_matrices() woman_min, man_min = self.get_best_truth_booth_couple() self.add_truth_booth(woman_min, man_min) self.get_solution_space(suppress_print=True) self.implicit_perfect_matches() ...
def preprocessing(image): hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) lower_white = np.array([180, 180, 210]) upper_white = np.array([255, 255, 255]) mask = cv2.inRange(image, lower_white, upper_white) image = cv2.bitwise_and(image, image, mask=mask) image[np.where((image == [0, 0, 0]).all(axis...
The code crops an image based on a predefined 'preset' value, extracting specific regions and applying corresponding preprocessing functions. Each preset defines unique coordinates for cropping, followed by specialized processing (e.g., general, phone, cutscene, message handling). The main task is to select and process...
def crop(image): match preset: case 1: crop_sub = image[765:1000, 450:1480] preprocessing(crop_sub) case 2: crop_phone = image[100:260, 500:1500] crop_sub = image[765:1000, 450:1480] preprocessing_phone(crop_sub, crop_phone) case 3:...
def moveForward(): getData() motorUpdates() sendMotorCommands() global lines_hit if (lines_hit>=2): lines_hit = 0 global state state = 2 print("turning right") turnRight() def moveForward2(): getData() motorUpdates() sendMotorCommands() if (lin...
The main task of the code is to run an infinite loop that continuously monitors and prints motor states, system state, and sensor data, then executes predefined movement commands (moveForward, moveForward2, stopState) based on the global 'state' variable. The loop acts as a control system for a robotic or motorized dev...
def main(): while(True): global state print(str(leftMotor), str(rightMotor)) print(state) print(lines_hit) #print(incomingData) if (state == 1): moveForward() elif (state == 2): moveForward2() elif (state == 3): stop...
def update(tick): global play, newKeyboard, rectsToFill, playerSprite, screenshotPressedLastFrame [playerSprite.remove(sprite) for sprite in playerSprite if sprite not in sprites] rectsToFill = [] fullboard = pygame.key.get_pressed() newKeyboard = copy.deepcopy(blankKeyboard) for event in p...
This code initializes a game sprite with customizable image, position, scale, and animations. It loads/scales images, sets animations, applies extra arguments (like controls/triggers), positions the sprite, and integrates it into the game's sprite list. It also updates global state variables for level editing and trigg...
def __init__( self,image,pos=[0,0],assetPath="assets/",scale=4, extraImages="default",extraArgs={}, animations=None,weight=0 ): global levelEdit, triggers, playerSprite self.aliveFrames = 0 self.extraArgs = vars.defaultExtraArgs.copy() # Default Args self....
def reset_level(): global staticSurface, levelData, prevGridPos, previousMouse, levelName, bg, spriteTypes, hudSurface, fonts, size with open(f"levels/{levelName}.json","r") as f: levelData = json.load(f) if levelEdit: levelEdit.levelData = levelData size = levelData['level']['size']....
The code initializes and runs a game level using a timer, handles pausing, level changes, and main menu navigation. It manages game states, updates the loop, processes events, resets the level when needed, and displays the game. The function checks for level name validity, updates the pause menu title, and returns to t...
def start(): global clock,frameN,goMainMenu,levelName,levelChange,timer if not levelName: return timer = Timer(levelName) frameN = 0 reset_level() reset() goMainMenu = False levelChange = False while 1: if pauseMenu.is_enabled(): if pauseMenu.get_widgets()...
def encryptPassword(self, login, passwd): ''' Encrypt credentials using the google publickey, with the RSA algorithm ''' # structure of the binary key: # # *-------------------------------------------------------* # | modulus_length | modulus | exponent_l...
The code's main task is to authenticate a user to a Google Account. It supports two scenarios: first-time login using email/password to obtain tokens, or subsequent logins using existing gsfId and authSubToken. If anonymous is True, it fetches tokens via a dispenser. It handles encryption, token retrieval, device confi...
def login( self, email=None, password=None, gsfId=None, authSubToken=None, anonymous=False, tokenDispenser=URL_DISPENSER, check=True, ): ''' Login to your Google Account. For first time login you should provide: * em...
def details(self, packageName): ''' Get app details from a package name. packageName is the app unique ID (usually starting with 'com.'). ''' path = URL_DETAILS + '?doc={}'.format(requests.utils.quote(packageName)) data = self.executeRequestApi2(path) return util...
The main task of the code is to download an already purchased Android app (APK) and its optional expansion files using a download token. It constructs a request with parameters like package name, version code, and offer type, fetches the download URL, authenticates via cookies, and retrieves the APK file. If expansion ...
def delivery(self, packageName, versionCode=None, offerType=1, downloadToken=None, expansion_files=False): ''' Download an already purchased app. Args: packageName (str): app unique ID (usually starting with 'com.') versionCode (int): version to download offe...
def details(self, packageName): ''' Get app details from a package name. packageName is the app unique ID (usually starting with 'com.'). ''' path = URL_DETAILS + '?doc={}'.format(requests.utils.quote(packageName)) data = self.executeRequestApi2(path) return util...
The function downloads an app's APK file from Google Play, requiring authentication and handling purchase tokens for free apps. It retrieves the latest version if unspecified, sends a purchase request, extracts a delivery token from the response, then calls the delivery method to obtain the APK and optional expansion f...
def download(self, packageName, versionCode=None, offerType=1, expansion_files=False): ''' Download an app and return its raw data (APK file). Free apps need to be 'purchased' first, in order to retrieve the download cookie. If you want to download an already purchased app, use *delivery...
def load_grid_from_file(file_path): with open(file_path, 'r') as file: lines = file.readlines() grid = [[int(cell) for cell in line.strip().split(',')] for line in lines] # Update starting_spot and ending_spot based on the loaded grid for row in range(len(grid)): for col...
The main task of the code is to run an interactive A* pathfinding visualization for a specific maze, allowing user input via key events. The code includes commented-out sections for comparing different A* variants (e.g., Low/High G, Forward/Backward, Adaptive A*) across 50 mazes, but these comparisons are disabled by d...
def main(maze_num): pygame.init() script_dir = os.path.dirname(os.path.abspath(__file__)) #############################PART 2: COMPARISION TEST BETWEEN REPEATED FORWARD A (LOW G) AND REPEATED FORWARD A (HIGH G)############################# ''' #UNCOMMENT THIS SNIPPET OF CODE TO RUN THE ASSOCI...
def generateTimestamp(): # Generate a random row-key-format timestamp within time range. return datetime.fromtimestamp( randint(*TIME_RANGE)).strftime('%Y%m%d%H%M%S') def generateSuffix(): # Generate a random suffix within suffix range. return randint(*SUFFIX_RANGE) def generateLocations(maxLocs...
The main task of the code is to generate test data for a BigTable by iterating through a range of vendors, creating randomized row keys with timestamps and suffixes, generating location data, and calling a backend server to populate these rows. This simulates populating a database with sample data for testing purposes.
def main(): # Clear old test data. # postURL('/test/clear') # Generate packages for each vendor within vendor range. for vendor in range(*VENDOR_RANGE): # For each vendor, generate up to n rows. for i in range(randrange(10)): # Create row key and generate locations. ...
def logg(line, error=False): global logfile, num_errors if not logfile: logfile = open(LOG_FILENAME, 'w') print(line) logfile.write(line + '\n') if error: num_errors += 1 def get_report_found(): found = [] for wadname in REPORT_WADS: if get_wad_filename(wadname): ...
The main task of the code is to process WAD files by extracting their contents, organizing them into a structured directory, and compressing them into a pk3 file. It checks for dependencies, cleans up previous runs, logs progress, and handles user confirmation before generating the final compressed file with details on...
def main(): start_time = time.time() version = open(VERSION_FILENAME).readlines()[0].strip() title_line = 'WadSmoosh v%s' % version logg(title_line + '\n' + '-' * len(title_line)) found = get_report_found() input_func = raw_input if sys.version_info.major < 3 else input # bail if no wads in ...
def parse_xml(xml): data = parse_xml_cached(xml) # clone object since st.cache does not like it when cached returned objects are mutated later data = pickle.loads(pickle.dumps(data)) return data def create_match_hash(data): return hashlib.sha256(pd.util.hash_pandas_object(data[["profileid", "mmr"]]...
The code processes XML match files from a backup directory by parsing, deduplicating, validating (if enabled), adding metadata like match numbers and timestamps, and consolidating the data into a structured DataFrame, which is then saved as a Parquet file for efficient storage and analysis.
def main(check_sanity=True): matches = pd.DataFrame() files = sorted([filepath for filepath in glob(os.path.join(BACKUP_DIR, "*.xml"))]) match_history = set() for i, path in enumerate(files): yield (i/len(files), path) with open(path, "r", errors="ignore", encoding="utf-8") as infile: ...
def move_monsters(monsters, player_x, player_y, maze, visibility): ''' Move all monsters in the player's visible range. Monsters move toward the player if they are in the visible range, otherwise they remain in their current positions. Dead monsters stay in their positions. Args: monsters (...
This function processes post-movement game logic by updating scores, monster positions, visibility arrays, and collision checks. It toggles blink states for monsters/crystals, handles player movement effects (step sound, score deduction), and resets loop counters. Collision checks for monsters, crystals, and exits are ...
def post_movement_processing(): ''' Process events and calculations after player's movement. Adjusts game states like loop counter, monster and crystal blink states, score, and monster positions. Updates visibility arrays and handles various collisions (monsters, crystals, exit). Plays step sound w...
def check_winner(): for row in range(3): if buttons[row][0]['text'] == buttons[row][1]['text'] == buttons[row][2]['text'] != " ": return True for column in range(3): if buttons[0][column]['text'] == buttons[1][column]['text'] == buttons[2][column]['text'] != " ": return...
This function handles a player's move in a Tic Tac Toe game by placing an 'X' on the clicked button, checking for a win or tie, then invoking the computer's move. It updates the game status label, ensures valid moves, and alternates turns until the game concludes with a win or tie.
def next_turn(row, column): global player label.config(text="Tic Tac Toe") if not check_winner() and empty_spaces(): if buttons[row][column]['text'] == ' ': buttons[row][column]['text'] = 'X' if check_winner(): label.config(text=('X'+" wins")) elif...
def randomAddress(self): #0 - 7 addressValue = pf.randomNumber(80) # Discrete Uniform Distribution with mod return addressValue % 8 def randomValue(self): #0 - 65535 value = int(random.uniform(0, 65535)) return hex(value)[2::].zfill(4) def MOESI(self, instruction, memAddress, value): listCachesWithAddress = s...
This function generates a random CPU instruction (WRITE, READ, or CALC) using a discrete uniform distribution. It creates a formatted instruction string with random memory addresses and values, invokes the MOESI protocol method for memory operations, and updates the CPU block's instruction queue with the generated comm...
def randomInstruction(self): # CALC - READ - WRITE instructionString = "" instructionType = pf.randomNumber(100) # Discrete Uniform Distribution if(instructionType < 33): # WRITE memAddress = self.randomAddress() hexValue = self.randomValue() instructionString = "WRITE " + (bin(memAddress)[2::]).zfill...
def fw_add_rule_menu(): colour_print("#00FF00", "\t[1]Add Port") colour_print("#00FF00", "\t[2]Add services") colour_print("#00FF00", "\t[3]Add sources") colour_print("#00FF00", "\t[4]Back to Main menu") def fw_add_port(): port = Prompt.ask("Enter port number") proto = Prompt.ask("Enter protocol...
This function provides a menu-driven interface to add firewall rules. It repeatedly displays options for adding ports, services, sources, or exiting. Based on user input, it calls respective functions to handle each rule type. The loop breaks when the user selects option 4, ensuring valid input handling and error messa...
def fw_add_rule(): while True: fw_add_rule_menu() ch = Prompt.ask("Enter your option", choices=["1", "2", "3","4"]) if ch == "1": fw_add_port() elif ch == "2": fw_add_services() elif ch == "3": fw_add_sources() elif ch == "4": ...
def fw_delete_rule_menu(): colour_print("#00FF00", "\t[1]Delete Port") colour_print("#00FF00", "\t[2]Delete services") colour_print("#00FF00", "\t[3]Delete sources") colour_print("#00FF00", "\t[4]Back to Main menu") def fw_delete_port(): port = Prompt.ask("Enter port number") proto = Prompt.ask(...
The code provides a menu-driven interface for deleting firewall rules. It repeatedly displays options to delete port rules, service rules, source rules, or exit. User input directs function calls to handle specific deletions. Invalid inputs trigger error messages, ensuring users retry valid choices.
def fw_delete_rule(): while True: fw_delete_rule_menu() ch = Prompt.ask("Enter your option", choices=["1", "2", "3","4"]) if ch == "1": fw_delete_port() elif ch == "2": fw_delete_services() elif ch == "3": fw_delete_sources() elif c...
def create_transcript_feature(): class_dict = read_class() bed_dict = read_bed() correct_isoforms = pull_isoforms_to_analyze() ensembl_dict = read_ensembl_gtf_transcripts() source = sys.argv[1] transcript_feature_dict = {} for isoform in correct_isoforms: single_isoform_class = class...
This code aggregates genomic features (transcripts, exons, codons, UTRs, CDS) by calling multiple creation functions, then writes each feature's data into a tab-separated file. It appends all entries from seven feature types to the specified output file, joining list elements with tabs and adding newlines. The main tas...
def write(): transcript_features = create_transcript_feature() exon_features = create_exon_feature() start_codon_features = create_start_codon_feature() stop_codon_features = create_stop_codon_feature() five_prime_utr_features = create_five_prime_UTR_feature() three_prime_utr_features = create_t...
def get_file_size(filename): return os.stat(filename)[6] def btprint(text): print(text) if radio is not None and radio.connected: uart_server.write((text+'\n').encode()) def save(self, byte_list=None): if byte_list is None: try: with open(self.filename,'wb') as f...
This method loads a bloom filter file into memory by verifying its size matches the expected length, then reading and writing data in 256-byte chunks. If loading fails, it catches exceptions, logs an error, and creates a new bloom file.
def load_at_startup(self): # try to load the data try: size0 = get_file_size(self.filename) assert size0 == len(self.bits), 'bad file size = {}'.format(size0) with open(self.filename,'rb') as f: rsize = 256 pos = 0 while...
def draw_backdrop(self): with open('images/backdrop2.tsu', 'rb') as f: num_bytes = (self.width >> 3) * self.height f.readinto(self.framebuf[0], num_bytes) f.readinto(self.framebuf[1], num_bytes) def draw_big_number(self, val, do_clear=False): self.displayed_unique_con...
This function renders UI elements by drawing a backdrop, history bar (if enabled), a large number displaying total unique items, and dials. It updates the display window, clears dirty rectangles, and finalizes the frame with a display update, then logs "draw done" to confirm completion.
def draw_everything(self, cc): # draw stuff here self.draw_backdrop() if cc.history_bar: cc.history_bar.draw(self) num_unique = cc.get_total_unique() self.draw_big_number(num_unique, do_clear=False) self.draw_dials(cc, force=True) self.dirty_rects = []...
def check_low_battery_warning(self, cc): low_batt = self.display.check_low_battery_warning() if low_batt: btprint('LOW BATTERY WARNING:') if self.displaying_low_batt_warning != low_batt: self.displaying_low_batt_warning = low_batt message = 'LOW BATTERY' if lo...
This function updates the display by checking battery status (if not on a feather device), redrawing dials, and adjusting visual elements based on changes in the number of unique contacts. It triggers full redraws when contact counts decrease or updates large numeric displays when counts increase, ensuring the interfac...
def periodic_update(self, cc, buttons): if not is_feather: self.check_low_battery_warning(cc) self.draw_dials(cc, force=False) num_unique = cc.get_total_unique() if num_unique != self.displayed_unique_contacts: if num_unique < self.displayed_unique_contacts: ...
def unpack(buffer, format, position): # DEBUG # print('from', position, # 'to', position + struct.calcsize(format), # 'size', struct.calcsize(format), # 'of ', format, # 'raw bytes ', buffer[position:position + struct.calcsize(format)].hex(), # 'values ', struct...
This function parses session data from a buffer by reading metadata and data for each channel, updating the data structure and returning the new buffer position along with the parsed session data.
def read_data(buffer, position): # NB of channels data_data = OSCARSessionData() position, (mcsize,) = unpack(buffer, 'h', position) data_data.mcsize = mcsize for c in range(mcsize): position, channel_data = read_channel_metadata(buffer, position) data_data.channels.append(channel_da...
def clone(): # Checking the directory already exists before cloning # Update this with by checking the last commit from the github - thereby it is dynamically updatable if path.isdir("pulse"): pass else: try: git.Git("data").clone("https://github.com/PhonePe/pulse") e...
The main task of the code is to clone a GitHub repository, create a MySQL schema, read files from the repository, and extract data from those files. The function automates the process of data extraction from GitHub into a structured MySQL database.
def execute_github_data_extraction(): clone() create_mysqlschema() filepaths = read_dir() extract_data(filepaths) return 1
def plot_data(type, year, quarter): df = data_extraction(type) # Data Preprocessing df['state'] = df['state'].str.title() df['state'] = df['state'].replace('Andaman & Nicobar Islands', 'Andaman & Nicobar',regex=True) df['state'] = df['state'].replace('Dadra & Nagar Haveli & Daman & Diu', 'Dadra and ...
The main task of the code is to create an interactive data visualization dashboard for PhonePe Pulse data, allowing users to explore transaction and user metrics at country or state levels. It provides options to select data classification (Transactions/User), year, and quarter, and displays choropleth maps, bar charts...
def front_end(): #st.divider() #topcol1, topcol2, topcol3, tempcol = st.columns([1,1,1,1], gap="large") st.sidebar.subheader("PhonePe Pulse Data Visualization", divider="rainbow") data=st.sidebar.radio(label="Select the Classification:", options=["***Country***", "***State***"], horizontal=True) ...
def get_square_position(self, pixel): ''' Method -- get_square_position converts a pixel to a row/col location Parameters: self -- the current Game object pixel -- the x or y coordinate of where the user clicked Returns: ...
This method handles user clicks to track and validate moves in a board game. It checks if clicks are within bounds, identifies the clicked piece, validates the first click, tracks moves, updates possible moves, executes valid moves, checks for additional captures, changes players, and checks game status.
def click_handler(self, x, y): ''' Method -- click_handler Determines how to handle a user click, tracking the first and second click to form a complete move Parameters: self -- the current Game object x -- X coordinate of the click. Automatically ...
def get_ai_move(self): ''' Method -- get_ai_move gets a move for the AI to do, helper function for ai_turn Parameters: self -- the current Game object Returns: a move object ''' # if move in capture list, pick ra...
The main task of the code is to execute the AI's turn by randomly selecting and performing a move for the red team. It checks for additional capture moves, displays possible jumps if available, and schedules the AI's next turn if captures remain. If no further captures exist, it switches to the next player and checks t...
def ai_turn(self): ''' Method -- ai_turn randomly selects a move for red team and carries it out Parameters: self -- the current Game object ''' chosen_move = self.get_ai_move() # make move with randomly chosen move self.mak...
def read_data(self, brain_number, slice_number): """ Reads data from table with respect to the 'view' """ #lock = threading.Lock() #with lock: slice_ = self.data_storage[brain_number].transpose(self.view_axes)[slice_number] label_ = self.t...
This function loads and preprocesses medical imaging data by reading brain slices, normalizing modalities, applying random transformations, concatenating data with labels, splitting into features and labels, converting labels to categorical format, and returning batches as numpy arrays for training or evaluation.
def data_load_and_preprocess(self, idx): """ Generates data containing batch_size samples """ slice_batch = [] label_batch = [] # Generate data for i in idx: brain_number = i[0] slice_number = i[1] slice_, label_ = se...
def get_inputs(args: argparse.Namespace, tiled=False) -> Tuple[samba.SambaTensor]: # If tiling is enabled, we trace the graph with the tile size, and pass the original size through tiling metadata if tiled: assert args.in_height % args.num_row_tiles == 0, "Input image is not evenly divisible by row tile...
The code defines a `main` function that processes command-line arguments to control a UNet model's workflow. It sets a random seed, parses arguments, initializes the model, and configures an optimizer. Depending on the command (`compile`, `test`, `measure-performance`, `run`), it performs tasks like model compilation, ...
def main(argv: List[str]): # Set random seed for reproducibility. sn_utils.set_seed(256) # Get common args and any user added args. args = parse_app_args(argv=argv, common_parser_fn=add_args) # Dummy inputs required for tracing. inputs = get_inputs(args) print(f'Inputs: {[d.shape for d in ...
def find_tfls(self, curr_image, points, colors): img = self.add_border(curr_image) img = np.array(img, dtype='uint8') tfls = [] tfl_colors = [] cropped = [] for p in points: x = p[1]+41 y = p[0]+41 a = img[x - 40:x + 41, y - 40:y + 41] ...
This code processes an image to detect and track traffic lights (TFLs), computes their positions and colors, tracks changes over time using previous frames and ego-motion data, and visualizes TFLs along with their spatial relationships across consecutive frames.
def manage(self, curr_image, ego_motion): img1 = np.array(curr_image, dtype='uint8') points, colors = find_tfl_lights(img1) tfls, tfl_colors = self.find_tfls(curr_image, points, colors) self.all_tfls.append(tfls) if len(self.all_tfls) > 1: prev_container, curr_contai...
def getArgs(): parser = argparse.ArgumentParser( prog="Port Sniper", description="A simple and efficient TCP port-scanner" ) parser.add_argument('-s', '--scan', type=str, help="specify a scan type, default is SYN scan", choices=["syn", "connect"], default="syn", ...
The main task of the code is to execute a network scan based on user-specified arguments. It retrieves command-line arguments, displays them, and initiates either a SYN scan or a connect scan depending on the 'scan' parameter value. The function acts as a control flow for selecting and executing different scanning meth...
def main(): args = getArgs() Display(args) if args.scan == "syn": synScan(args) elif args.scan == "connect": connectScan(args)
def add_newstudents_from_list(ccde, df): slist = get_class_list(ccde) r = df.shape[0] students = [a for a in df['ID'].values] newstu = [s for s in slist if s not in students] df.drop([r - 1], axis=0, inplace=True) for idn in newstu: df = df.append({'ID': str(idn)}, ignore_index=True) ...
The main task of the code is to update an attendance CSV file for a specified course by adding new students, calculating totals, sorting data, and saving changes, while also updating a database. It returns a success/failure status based on whether the file existed and was processed.
def update_list(course): atfl = os.path.join(BASE, 'AttendanceData', course + '_attendance.csv') if os.path.exists(atfl) and os.path.isfile(atfl): df = pd.read_csv(atfl) df = add_newstudents_from_list(course, df) calc_total(df) sort_df(df) df.to_csv(atfl, index=False) ...
def helper_init(): sl = os.path.join(BASE, 'StudentList') ad = os.path.join(BASE, 'AttendanceData') if not os.path.isdir(sl): logger(f'{msgtags[1]}making student list dir...') os.makedirs(sl) logger(f'{msgtags[0]}done') if not os.path.isdir(ad): logger(f'{msgtags[1]}makin...
The main task of the code is to handle tutor course submission by validating input credentials (ID, PIN, course code), verifying tutor-course associations, and initiating RFID/face detection processes if validation succeeds. It checks for tutor existence, course availability, PIN match, and substitution status, then la...
def submit(): helper_init() idn = ID.get() pn = pin.get() sub = checkvar.get() ccde = course_field.get().upper() proceed = validate(idn, pn, ccde) if proceed: try: course = myh.Course.objects(code__iexact=ccde).get() except mg.DoesNotExist: logger(f"{m...
def getLines(cn="cpu"): if cn is None: return else: if cn == "cpu": col = 1 elif cn == "mem": col = 2 else: col = 1 command = f"ps -eo pcpu,pmem,comm | tail +2 | sort -hrk {col}" result = subprocess.run(command, shell=True, stdo...
The code's main task is to process and sort data based on user input. It retrieves lines using a choice, converts them into a dictionary, sorts the entries, and prints the result. The steps involve fetching data, structuring it, ordering it, and displaying the output according to the selected criteria.
def main(): choice = CHOICE lines = getLines(choice) processDict = getProcesses(lines) processList = getSortedList(processDict, choice) printOut(processList)
def starting_round(self, roller, roller_function=GameLogic.roll_dice): """ | This Function Will Be Called In Each New Roll, A Tuple With Random Numbers Between 1 And 6 Will Be Passed To | This Function,The Tuple Length Depending On The Remaining Dices | :param roller: | :return: ...
The main task of the code is to run a game loop that initializes the game, processes user input to start or quit, manages rounds using a dice-rolling function, tracks scores, and terminates when the player presses 'q' or rounds reach 21, displaying the final earned points.
def play(self, roller=GameLogic.roll_dice): """ This Function Is the Starting Point Of The Game, And It Will Keep The Game Running Until The Player Press q And Terminate The Game :param roller: :return: No output """ print("Welcome to Ten Thousand") print...
def _get_view_mapping(self, data, viewname, schema): """Get the view mapping for viewname.""" # Get the view mapping, if any # defaults have already been applied try: view = data['__view__'][viewname] except KeyError: view = {} # Fill in any mis...
The function `_get_view_dict` constructs a dictionary of default values from provided data, using a specified view and schema. It recursively processes defaults, maps values via `_get_view_mapping`, and populates the result by fetching defaulted values, ignoring missing keys. The output is a dictionary of resolved defa...
def _get_view_dict(self, data, viewname, schema): # Do we have any defaults? defaults = data['defaults'] #print("*** START ***") #print("_get_view_dict data %s defaults %s" % (data, defaults)) #print("Get default view dict") if defaults: data_defaults = se...
def method(self, method, params, **kwargs): result = {} recv = True if 'recv' in kwargs: recv = kwargs['recv'] try: # if self.debug: # print("Method: " + method) # print("Params: " + json.dumps(params, indent=4)) requ...
The main task of the code is to update network configuration and interface settings via API calls, commit changes, disconnect, reconnect to a WebSocket using the interface's IP address, re-authenticate with provided credentials, and perform a check-in on the interface.
def set_network(self, networks, username, password): response = self.method("network.configuration.update", [ networks['config']]) response = self.method("interface.update", [ networks['interface_id'], networks['interface']]) response...
def reset(self) -> None: self.scratchpad = '' self.curr_step = 1 def is_truncated(self) -> bool: return self.env.is_truncated() or (len(self.enc.encode(self._build_agent_prompt())) > 3896) def is_terminated(self) -> bool: return self.env.is_terminated() def step(self) -> None: # ...
The code's main task is to run an environment loop, resetting the environment and internal state if specified. It repeatedly calls `self.step()` until the episode terminates or gets truncated, managing the simulation's lifecycle by checking termination conditions after each step.
def run(self, reset = True) -> None: if reset: self.env.reset() self.reset() while not (self.is_truncated() or self.is_terminated()): self.step()
def health_bar(self, x, y): if self.health > 60: col = GREEN elif self.health > 30: col = YELLOW else: col = RED width = 100 h = 5 health_bar = HealthBar(x - 60 - GL.offset.x, y - 80 - GL.offset.y, width, h, 100, col) health_bar...
This code updates a game entity's state by rendering a health bar, managing movement, decrementing a footsteps cooldown, checking if the entity is alive, detecting player proximity to trigger collision checks, hunting behavior, or roaming. If not alive, it triggers a death animation and sound. The entity's movement sta...
def update(self): self.health_bar(self.position[0], self.position[1]) self.isMoving() if self.footsteps_cooldown > 0: self.footsteps_cooldown -= 1 if self.alive: self.check_alive() if self.get_vector_distance(pygame.math.Vector2(player.base_player_rect...
def getBackgroundColors(url, top=3, renderColor = True): backgroundColors = [] cssPagesSample = getStylePages(url) cssPages = list(cssPagesSample) #print(cssPages) for cssPage in cssPages: if cssPage[0:4]=='http': styleSample = cssPage else: styl...
The main task of the code is to process a CSV file containing website data, extract specific information (categories, colors, fonts, and text) from each website's URL, and save the results as a structured CSV file. It iterates over a subset of rows, scrapes data using helper functions, and outputs a new CSV with collec...
def main(inputs, start, end, output_name): df = pd.read_csv(inputs) Table = [] Row = [] for row in df.values[int(start):int(end)]: if row[0] % 100 == 0: print(row[0], str(row[1])) Row.append(row[1]) Row.append(row[2]) try: # Get colors ...
def transform_streams_for_comparison(outputs): """Makes failure output for streams better by having key be the stream name""" new_outputs = [] for output in outputs: if (output.output_type == 'stream'): # Transform output new_outputs.append({ 'output_type': 's...
The main task of the code is to compare outputs from test and reference data by flattening and sanitizing keys, checking for missing/unexpected keys, and verifying value equality. It handles 'data' fields specially, skips specified keys, and logs mismatches in a traceback, returning False on discrepancies and True if a...
def compare_outputs(self, test, ref, skip_compare=None): # Use stored skips unless passed a specific value skip_compare = skip_compare or self.parent.skip_compare test = transform_streams_for_comparison(test) ref = transform_streams_for_comparison(ref) # Color codes to use for ...
def raise_cell_error(self, message, *args, **kwargs): raise NbCellError(self.cell_num, message, self.cell.source, *args, **kwargs) def coalesce_streams(outputs): """ Merge all stream outputs with shared names into single streams to ensure deterministic outputs. Parameters ---------- out...
The `runtest` function executes individual Jupyter notebook cells in a single kernel, verifying they run without errors and produce output matching the notebook's stored outputs. It handles timeouts by interrupting the kernel, captures execution outputs (e.g., text, errors, results), and compares them against expected ...
def runtest(self): """ Run test is called by pytest for each of these nodes that are collected i.e. a notebook cell. Runs all the cell tests in one kernel without restarting. It is very common for ipython notebooks to run through assuming a single kernel. The cells are ...
def nodeReaderPM(self,jsonData): # if (True): try: # print(jsonData) self.dataInPM = jsonData self.ctNowPM = datetime.strptime(self.dataInPM['dateTime'],'%Y-%m-%d %H:%M:%S.%f') # print(self.ctNowPM) if (self.ctNowPM>self.lastPMDat...
The code updates sensor data by routing the sensorDictionary to specific processing methods (nodeReaderPM, nodeReaderClimate, nodeReaderGPS) based on the provided sensorID, which matches predefined sensor identifiers (self.pmSensor, self.climateSensor, self.gpsSensor).
def update(self,sensorID,sensorDictionary): if sensorID == self.pmSensor: self.nodeReaderPM(sensorDictionary) if sensorID == self.climateSensor: self.nodeReaderClimate(sensorDictionary) if sensorID == self.gpsSensor: self.nodeReaderGPS(sensor...
def getNum(self, col, row): return self.grid[row][col] def getPossibilities(self, col, row): sqrPoss = theSet - set(self.getSqr(col,row)[0]) rowPoss = theSet - set(self.getRow(row))#[0]) colPoss = theSet - set(self.getCol(col))#[0]) poss_vals = list(sqrPoss.intersection(rowPoss)....
This function determines if a Sudoku cell at (col, row) can be uniquely filled by checking if its possible values are restricted to one number through row, column, and 3x3 square constraints. If so, it sets the value and returns True; otherwise, returns False.
def findMulti(self, col, row): if self.getNum(col, row) == 0: tilePossSet = set(self.getPossibilities(col, row)) rowPoss = self.findRow(col, row) colPoss = self.findCol(col, row) sqrCoords = self.getSqr(col, row)[1] sqrCoords.remove((col, row)) ...
def create_quad_by_predicate(uri, resource, result): # create quads by predicate, and do a label lookup for each thing on hand quads_by_predicate = {} for subject_uri, predicate_uri, object_uri, graph in result.quads(): object = None is_subject = True if subject_uri == uri: ...
This code handles HTTP GET requests by performing content negotiation based on the Accept header, querying a SPARQL endpoint for structured data, and returning either a redirect to data/page views or rendering an HTML page with queried data, using JSON-LD/Turtle serialization formats depending on client preferences and...
def get(request, URI): resource = Resource(request, URI) accept = request.META.get("HTTP_ACCEPT").lower() serialization = "html" # Not a real content negotiation, simply the first match # in our dictionary is used. for mime in mime2serialisation: if mime in accept: serializa...
def _get_params(self) -> dict[str, str] | None: file_info = self._get_file_info() try: width = int(file_info["width"]) rate = int(file_info["bit_rate"]) except KeyError: raise Exception("Unable to determine file info") # TODO: Better exception rate_m...
This code transcodes video files using FFmpeg, handling parameters, file renaming, and error recovery. It checks if transcoding is needed, constructs FFmpeg commands, executes the process, manages success/failure states, deletes partial outputs, and retries without subtitles if specified. Logs runtime and operations fo...
def transcode(self, drop_subs: bool = False) -> bool: # TODO: timeout? could do on subprocess.run start = time.time() params = self._get_params() if params is None: self._log("No Transcode Required") return False if drop_subs: params.pop("c:s...
def compute_landmarks(img, path): hog_face_detector = dlib.get_frontal_face_detector() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces1 = hog_face_detector(gray) p = "Phase1/shape_predictor_68_face_landmarks.dat" predictor = dlib.shape_predictor(p) lpoints = [] for face in faces1: ...
The main task of the code is to perform a two-face blending on an image using Thin Plate Spline (TPS) transformations. It computes facial landmarks, generates convex hulls, creates masks, applies TPS blending to transfer features between two face regions, and combines the results. The function returns the blended image...
def TPS_twoface(img, path): source = copy.deepcopy(img) dest = copy.deepcopy(img) lpoints = compute_landmarks(source, path) lpoints1 = lpoints[:68] lpoints2 = lpoints[68:] if len(lpoints2) < 5: return source,False points1 = np.array(lpoints1, np.int32) points2 = np.array(lpoints2...
def compute_landmarks(img, path): hog_face_detector = dlib.get_frontal_face_detector() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces1 = hog_face_detector(gray) p = "Phase1/shape_predictor_68_face_landmarks.dat" predictor = dlib.shape_predictor(p) lpoints = [] for face in faces1: ...
This function performs face blending between two images using TPS (Thin Plate Spline) transformation. It detects facial landmarks, computes convex hulls, creates a mask for the destination face, applies TPS warping, and blends the source image with the transformed mask. The result is a merged image with the face from t...
def TPS_face(img1, img2, path): source = copy.deepcopy(img1) dest = copy.deepcopy(img2) lpoints1 = compute_landmarks(source, path) lpoints2 = compute_landmarks(dest, path) if len(lpoints1) < 5 or len(lpoints1) < 5: return source, False points1 = np.array(lpoints1, np.int32) points...
def detect_face(img1, img2, path, flag): source = copy.deepcopy(img1) dest = copy.deepcopy(img2) lpoints1 = compute_landmarks(source, path) lpoints2 = compute_landmarks(dest, path) if flag == 1: lpoints1 = lpoints1[:68] lpoints2 = lpoints2[68:] if len(lp...
The code processes a video file to perform face swapping using either Triangulation (tri) or Thin Plate Spline (tps) methods. It reads input video frames, resizes them if necessary, applies face swapping with a reference image, and saves the processed video. The method choice determines the transformation technique, wh...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--InputFilePath', default='my_test_imgs/', help='Folder in which the input files are located') parser.add_argument('--InputFileName', default='Test1.mp4', help='Name of the input file') parser.add_argument('--RefFileName', default='None...
def set_seed(seed): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) def load_data(seq_type): seqs = list(set(pd.read_csv(rf'datasets\{seq_type}.csv')['Sequence'].tolist())) if seq_type == 'nonAVPs': set_seed(42) seqs.sort() indexes = random.sample(range(len(seqs)), 154...
The code's main task is to generate augmented sequences from original data by applying a combination of augmentation techniques controlled by parameter 'p', then deduplicate the results using a set, and return the unique augmented sequences. It ensures reproducibility by setting a random seed and processes data based o...
def load(p, seq_type): set_seed(42) original_seqs = load_data(seq_type) augmented_seqs = augmentation_combination(original_seqs, p, seq_type) augmented_seqs = list(set(augmented_seqs)) return augmented_seqs
def Ybar(self, n): return sum(self.y)/n def a(self,n): return self.Cov(n) / self.Var(n) def tbar(self, n): return sum(self.t)/n
The function calculates and returns the difference between the result of method Ybar(n) and the product of methods a(n) and tbar(n), likely representing a mathematical or statistical computation involving these components.
def b(self, n): return self.Ybar(n) - (self.a(n) * self.tbar(n))
def CoefS_MMC(self,n): final = [] res , _ = self.MMC(n) for i in range(0,int(len(self.y)/4)): temp = [] for j in range(i,len(self.y),4): temp.append(self.y[j] - res[j]) final.append(sum(temp)/len(temp)) return final def a(self,n): ...
The code computes predicted values by combining coefficients from `CoefS_MMC(4)` with linear transformations of time points in `t1 = [17,18,19,20]`. It calculates `T` using `a = self.a(16)` and `b = self.b(16)` as `T[i] = a*i + b`, then constructs `prev` by adding corresponding elements from `T` and `S`. The function r...
def Prevision(self): S = self.CoefS_MMC(4) t1 = [17,18,19,20] T = [] prev = [] a = self.a(16) b = self.b(16) for i in t1: T.append(a * i + b) for i in range(4): prev.append(T[i] + S[i]) return t1,prev,T
def Trend(self, n): T = [] a = self.a(n) b = self.b(n) for i in range(n): T.append( a * self.t[i] + b ) return T def MMC(self,n): temp = [] res = 0 if n%2!=0: k = int((n-1)/2) for t in range(k,len(self.y)-k): ...
The main task of the code is to plot an additive chronological series, visualizing original sales data, predicted values, trend lines, and MMC components. It generates a graph with multiple overlays: original data (blue), predictions (brown), predicted trend (orange), baseline trend (red), and MMC (green), enabling com...
def PlostSerie(self,n): pt.title("Additive Chronological Series") pt.xlabel("Temp in Trimister") pt.ylabel("Sales") X = self.t Y = self.y t = self.Trend(n) mmc , _ = self.MMC(4) mmc[:] = [x if x != 0 else nan for x in mmc] t2,previs,T = self.Previs...
def container_state(self): """Get container state""" client = self.get_client() try: info = client.inspect_container(self.container_id) return info.get('State', {}) except DockerAPIError: return None def get_client(self): """Create Docker clien...
This code manages a Docker container context for a build environment. It checks for and removes stale containers, creates necessary directories, and initializes a new container. If a running container exists, it raises an error. It handles Docker API errors and ensures proper setup for the build process.
def __enter__(self): """Start of environment context""" log.info('Creating container') try: # Test for existing container. We remove any stale containers that # are no longer running here if there is a collision. If the # container is still running, this would...
def add_ball(self): """Create a Ball and store a reference in self.Paddle as well.""" if self.ball is not None: self.ball.delete() paddle_coords = self.paddle.get_position() # set the ball on top of player's paddle at start x = (paddle_coords[0] + paddle_coords[2]) * ...
(The code initializes a game by adding a ball, updating the lives display, rendering a start instruction message, and binding the spacebar key to trigger the start_game() method, ensuring the event is only bound once to prevent repeated triggers.)
def setup_game(self): """Do all the necessary things to start the game.""" self.add_ball() self.update_lives_text() self.text = self.draw_text(300, 200, "Press Spacebar to start") # Bind only here otherwise would call start_game() each time pressed self.canvas.bind('<spac...
def reset_keys_mouse_state(self): self.ctrl_down = False self.shift_down = False def get_events(self): 'Handles user interactivity e.g. keyboard and mouse input' for event in pygame.event.get(): # App handles below if event.type == pygame.QUIT: sel...
The main task of the code is to reset input states, process events, and update graphics. It first resets keyboard and mouse states, retrieves input events, processes them, and then updates the graphical interface to reflect changes, ensuring smooth interaction and rendering in applications like games or GUI systems.
def update(self): self.reset_keys_mouse_state() self.get_events() self.process_events() self.update_gfx()
def init_population(n: int) -> np.array: """ initialize n candidates """ pop = rand(n,2) return pop def iterate(pop_x: list[float],pop_y: list[float]) -> list[list[float]]: """ perform mutation, crossover, and selection on a population. input: pop_x, pop_y returns [pop_x, po...
This code performs iterative optimization using a population-based approach, visualizing each generation's state by plotting population points, their mean, and the global minima. It checks for convergence using a tolerance threshold, saves intermediate plots as PNGs, and compiles them into a GIF to demonstrate the opti...
def main(pop_size: int, x_min: float, x_max: float, y_min: float, y_max: float, tol: float, iters: int) -> None: #grab population of points and plot pop = init_population(pop_size) pop_x = pop[:,0] pop_y = pop[:,1] #scale to range of plot pop_x = [x_diff * i + x_min for i in pop_x] pop_y = [...
def get_game(lobby) -> quantum_game.Game: return get_games().get(lobby) def update_lobby(lobby): game = get_game(lobby) emit("update_lobby", {'turn': game.turns}, to=lobby) def get_choices(lobby, user): choices = request_choices(lobby, user.id) print(choices) emit("get_choices", choices)
The main task of the code is to handle a user joining a game lobby by adding them to the game, updating the lobby state, and preparing the game for play. It checks if the game exists, adds the current player, broadcasts player updates, and initiates game logic (remote run or choice retrieval) based on the game's state ...
def join(data): username: quantum_game.Player = current_user lobby = data['lobby'] game = get_game(lobby) if not game: return redirect('/create_game') game.add_player(current_user) print(f"{username}, {lobby} - Joined") join_room(lobby) emit("players", game.get_players_list(), to=lobby) ...
def set_up_target_db(name='sentinel'): global mbTiles global work_dir mbTiles = None # attach to the correct output database dbname = f'satellite_z{args.zoom}-z{args.topzoom - 1}_2020.mbtiles' if not os.path.isdir(work_dir): #os.mkdir('./work') work_dir = '/tmp' dbpath = '%s/%s'%(work_...
The code's main task is to download satellite tiles from a WMTS source across specified zoom levels, track download statistics (time, duplicates, total tiles), and log results. It initializes the WMTS connection, sets up a target database (if not 'avni'), iterates through zoom levels, downloads tiles for given coordina...
def do_downloads(): # Open a WMTS source global src # the opened url for satellite images global start, bound_string global total_tiles try: src = WMTS(url) except: print('failed to open source') sys.exit(1) # the following sets up a copy of the real sat dbase -- # Commenting ...
def parse_args(): parser = argparse.ArgumentParser(description="Download WMTS tiles arount a point.") parser.add_argument('-z',"--zoom", help="zoom level minimum", type=int,default=10) parser.add_argument("-m", "--mbtiles", help="mbtiles filename.") parser.add_argument("-v", "--verify", help="verify mbt...
The main task of the code is to process command-line arguments, initialize map tile sources (MBTiles or WMTS), calculate tile coordinates based on geographic parameters, and execute actions like summarizing, verifying, or downloading map tiles. It sets defaults for input parameters, handles file operations, and uses a ...
def main(): global args global mbTiles global url global bounds global xytools xytools = Tools() args = parse_args() # Default to standard source if not os.path.isdir('./work'): os.mkdir('./work') if not args.mbtiles: args.mbtiles = sat_dir +'/' + sat_mbtile_fname print('mbt...
def update_bgr(self, input_bgr_img): self.__bgr = input_bgr_img # update initial bgr array to be used when filtering the image to retrieve channel self.update_channel() def update_min(self, pos): if(pos < self.__bounds[1]): # this will ensure that the trackbar does not move if the min position i...
This code initializes a class for image channel processing using OpenCV, creating trackbars to adjust channel bounds (min/max) for real-time filtering. It sets up two trackbars per channel in a specified window, linking them to update image thresholds. The constructor handles image data storage, trackbar callbacks, and...
def __init__(self, bgr_img, window_name, limits=[0, 255], bounds=[0, 255], create_trackbar=True): ''' Common constructor for all image channel derived classes. This class is based on OpenCV....
def refresh_btn_clicked(self): print('refreshing..') self.refresh_ui_data() def searchAuthor_btn_clicked(self): authorName=self.ui.searchField.text() authorName=authorName.lstrip().rstrip() if authorName=='': self.refresh_ui_data() else: ...
The code initializes a Qt user interface for a main window application. It sets up the main window, configures a table widget's column widths, connects button clicks to specific functions (refresh, search by author/title, sell), and links cell clicks to a handler. The purpose is to create an interactive GUI for managin...
def init_ui(self): self.app = QtWidgets.QApplication([]) self.MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.MainWindow.setWindowTitle(self._title) self.ui.booksTable.setColumnWidth(0,300) self.ui.booksTable.se...
def addSection(self,section): self._sections.append(section) def init_ui(self): self.app = QtWidgets.QApplication([]) self.MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.MainWindow.setWindowTitle(self._title) s...
The code initializes a library by loading book data from a JSON file, organizing books into sections, and setting up the UI. It processes each book entry, creates Section objects if needed, and populates data structures like _sections and _sections_dict. The constructor also initializes UI components and refreshes the ...
def __init__(self,title): """library constructor @title is title of the library builds required data and structures in single loop iteration from source json file and sets required initial instance members beside UI initialization""" self._title=title self._sections=[] ...
def get_valid_datetime_str(): doctor_double_booked, patient_double_booked = is_double_booked() if not (doctor_double_booked or patient_double_booked): c_date = get_selected_datetime_str() return c_date else: return None def get_valid_patient(): selected_patient_index = patient_li...
The main task of the code is to collect validated consultation data (date, patient, doctor, reason, fee) using helper functions, compile them into a structured dictionary, and return it for further processing or storage.
def get_consultation_info(): c_date = get_valid_datetime_str() c_patient = get_valid_patient() c_doctor = get_valid_doctor() c_reason = get_valid_reason() c_fee = get_valid_fee() cons_info = { 'c_date': c_date, 'c_patient': c_patient, 'c_doctor': c_doctor, 'c_...
def run_yc(yc_options): result = {"changed": False} yc_cmd = f"yc --no-user-output --format yaml {yc_options}" yc_result = subprocess.run(yc_cmd, stdout=PIPE, stderr=PIPE, shell=True) if yc_result.returncode > 0: module.fail_json( msg=f"Error running yc: {to_native(yc_result.stderr)...
This code is an Ansible module for managing Yandex Cloud instances. It checks if an instance with the specified name exists and meets configuration requirements (cores, memory, disk). If not, it deletes the existing instance and creates a new one with the provided parameters. It returns details like instance name, reso...
def run_module(): module_args = dict( name=dict(type='str', required=True), cores=dict(type='int', required=False, default=DEFAULT_CORES), memory_g=dict(type='int', required=False, default=DEFAULT_MEMORY_G), disk_g=dict(type='int', required=False, default=DEFAULT_DISK_G), ima...
def handle_read_only(self): if config.HANDLED_READ_ONLY: return # check that Display Message when Modifying Read-Only Parts is not set # (Customer Defaults > Assemblies > Miscellaneous > Display Message when Modifying Read-Only Parts) read_only_warn_mod = self.session.Optio...
The main task of the code is to process a CAD part by checking if it is read-only, handling read-only status if necessary, orienting the part to a top view, and exporting it as a DXF file for further use or sharing.
def process_part(self, filename): if self.work_part.IsReadOnly: self.logger.warning("!!! Part is Read Only !!!") if self.handle_read_only(): return self.orient_top_view() self.export_dxf()
def add_tag_usage_count(df, key): res = df cols = result_columns() for c in cols: res = res.withColumn(c+'_count', F.count(c).over(Window.partitionBy(key, c))) return res def add_tag_rank(df, key): res = df for c in result_columns(): res = res.withColumn(c+"_rank", F.row_number()...
This function merges contact and interest data by user IDs, calculates tag usage counts and ranks, then aggregates top tags per user. It renames columns, joins datasets, processes tags, groups results, and returns structured user-interest mappings with ranked tags.
def get_contact_interests(contacts, interests): return contacts\ .withColumnRenamed("user_id", "u")\ .join(interests, F.col("contact_id") == F.col("user_id"))\ .transform(lambda df: add_tag_usage_count(df, "u"))\ .transform(lambda df: add_tag_rank(df, "u"))\ .groupBy("u")\ .agg(*[top_direct_...
def input_event_paths(base_path, date, depth): dt = datetime.datetime.strptime(date, '%Y-%m-%d') return [f"{base_path}/date={(dt-datetime.timedelta(days=x)).strftime('%Y-%m-%d')}" for x in range(int(depth))] def get_contacts(direct_messages): return direct_messages\ .select(F.col("event.message_from").a...
The main task of the code is to process social media data using Apache Spark, analyzing user interactions (messages, subscriptions) to generate user interests. It reads input data, filters events, extracts contacts and subscription-based interests, combines them, and writes the results as Parquet files to an output pat...
def main(): date = sys.argv[1] days_count = sys.argv[2] events_base_path = sys.argv[3] interests_base_path = sys.argv[4] verified_tags_path = sys.argv[5] output_base_path = sys.argv[6] conf = SparkConf().setAppName(f"ConnectionInterestsJob-{date}-d{days_count}") sc = SparkContext(conf=...
def evaluate( self, eval_dataset: Optional[Dataset] = None, prediction_loss_only: Optional[bool] = None, ) -> Dict[str, float]: """ Run evaluation and return metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent...
This function evaluates a model, logs metrics, and saves checkpoints. It initializes evaluation headers, tracks metrics like accuracy/loss, appends results to history, and stores model/optimizer/scheduler states in output directories. The code handles distributed training by verifying model references, ensures checkpoi...
def evaluate_and_save_model(self, model, optimizer, scheduler): metrics = self.evaluate() # In all cases (even distributed/parallel), self.model is always a reference # to the model we want to save. if hasattr(model, "module"): assert model.module is self.model else: ...
def _add_arg_to_parser( prefix: str, arg_type: weave.types.Type, parser: argparse.ArgumentParser ): if isinstance(arg_type, weave.types.Boolean): parser.add_argument(f"--{prefix}", action="store_true", default=False) elif isinstance(arg_type, weave.types.Int): parser.add_argument(f"--{prefix...
This function parses command-line arguments into a Weave object instance and publishes it. It converts arguments to a typed dictionary, resolves URIs to objects, creates the Weave object, and publishes it with a default name derived from the class. The TODO indicates a need for better control over W&B Artifact naming a...
def weave_object_main(weave_obj_class): weave_type = typing.cast(weave.types.ObjectType, weave_obj_class.WeaveType()) equiv_typed_dict = weave.types.TypedDict(weave_type.attr_types()) parser = argparse.ArgumentParser( usage=f"Publishes a {weave_obj_class.__name__} Weave Object" ) _add_arg_t...
def _add_arg_to_parser( prefix: str, arg_type: weave.types.Type, parser: argparse.ArgumentParser ): if isinstance(arg_type, weave.types.Boolean): parser.add_argument(f"--{prefix}", action="store_true", default=False) elif isinstance(arg_type, weave.types.Int): parser.add_argument(f"--{prefix...
This function executes a Weave operation by parsing input arguments, configuring WandB (if enabled), running the operation, and logging results. It converts input types to configuration values, handles artifact publishing, initializes WandB tracking, and updates run summaries with operation outputs, bridging Weave and ...
def weave_op_main(weave_op: op_def.OpDef): input_type = weave_op.input_type if not isinstance(input_type, op_args.OpNamedArgs): raise NotImplementedError( "Only weave_op.input_type.named_args is supported for now" ) weave_input_type = input_type.weave_type() parser = argparse...
def checkwin(board): for r in range(Rows): for c in range(Cols - 3): if board[r][c] == 0 and board[r][c + 1] == 0 and board[r][c + 2] == 0 and board[r][c + 3] == 0: return 0 if board[r][c] == 1 and board[r][c + 1] == 1 and board[r][c + 2] == 1 and board[r][c + 3] == 1...
The code implements a Monte Carlo Tree Search (MCTS) algorithm to select the optimal child node from a given parent node. It performs iterative expansion, simulation, and backpropagation to evaluate potential moves, prioritizing nodes with higher visit counts or scores. The function returns the child node with the high...
def mcts_n(parent_node, n): initial_node = copy.deepcopy(parent_node) while n > 0 and checkwin(parent_node.state) == 2 and not checkdraw(parent_node.state): if parent_node.Poss_Child and random.uniform(0, 1) >= 0: parent_node = expansion(parent_node) result = simulation(parent_no...
def checkwin(board): for r in range(Rows): for c in range(Cols - 3): if board[r][c] == 0 and board[r][c + 1] == 0 and board[r][c + 2] == 0 and board[r][c + 3] == 0: return 0 if board[r][c] == 1 and board[r][c + 1] == 1 and board[r][c + 2] == 1 and board[r][c + 3] == 1...
This function performs Monte Carlo Tree Search (MCTS) to select the optimal child node from a given parent node. It iterates `n` times, expanding and simulating game states, updating node statistics, and selecting the child with the highest score or visit count. If a winning move exists, it returns that immediately. Ot...
def mcts_n(parent_node, n): initial_node = copy.deepcopy(parent_node) while n > 0 and checkwin(parent_node.state) == 2 and not checkdraw(parent_node.state): if parent_node.Poss_Child and random.uniform(0, 1) >= 0: parent_node = expansion(parent_node) result = simulation(parent_no...
def checkwin(board): for r in range(Rows): for c in range(Cols - 3): if board[r][c] == 0 and board[r][c + 1] == 0 and board[r][c + 2] == 0 and board[r][c + 3] == 0: return 0 if board[r][c] == 1 and board[r][c + 1] == 1 and board[r][c + 2] == 1 and board[r][c + 3] == 1...
The main task of the code is to simulate multiple games (10 games) between two Monte Carlo Tree Search (MCTS) players with different exploration parameters (2000 and 6). It tracks the number of wins for each player, draws, and measures the total execution time. The code alternates turns, uses MCTS to select moves, and ...
def MCTS_vs_MCTS(): turn = 0 count = 0 draw = 0 winner2 = 0 num_games = 10 in_time = time.time() for _ in range(num_games): print(_) board = Board.create_board() current_node = TreeNode(board, None, 0, 0) current_state = current_node.state lastmove = 0...
def checkwin(board): for r in range(Rows): for c in range(Cols - 3): if board[r][c] == 0 and board[r][c + 1] == 0 and board[r][c + 2] == 0 and board[r][c + 3] == 0: return 0 if board[r][c] == 1 and board[r][c + 1] == 1 and board[r][c + 2] == 1 and board[r][c + 3] == 1...
The code implements a Connect 4 game loop where a human player competes against an AI using Monte Carlo Tree Search (MCTS). The AI uses a preloaded Q-table and performs 200 simulations per move. The game alternates turns, updating the board state and rendering graphics via Pygame. Human moves are captured via mouse inp...
def game_driver(screen, SQAIZE, width, RADIUS): turn = 0 count = 0 draw = 0 winner2 = 0 num_games = 1 in_time = time.time() qtable = pickle.load(gzip.open("C:\\Users\\agraw\\PycharmProjects\\AI-Assignment2\\20180827_final_5.dat.gz", "rb")) board = Board.create_board() current_node = ...
def checkwin(board): for r in range(Rows): for c in range(Cols - 3): if board[r][c] == 0 and board[r][c + 1] == 0 and board[r][c + 2] == 0 and board[r][c + 3] == 0: return 0 if board[r][c] == 1 and board[r][c + 1] == 1 and board[r][c + 2] == 1 and board[r][c + 3] == 1...
The code simulates a series of games between two AI players using Monte Carlo Tree Search (MCTS). Player 1 uses MCTS with 200 iterations, while Player 2 uses MCTS with 6 iterations. It tracks wins, draws, and time taken over a fixed number of games (1), comparing the performance of the two MCTS configurations in a turn...
def parta(node): initial_node = copy.deepcopy(node) turn = 0 count = 0 draw = 0 winner2 = 0 num_games = 1 in_time = time.time() for _ in range(num_games): print(_) current_node = initial_node current_state = current_node.state lastmove = 0 while ch...
def mcts_n(parent_node, n): initial_node = copy.deepcopy(parent_node) while n > 0 and checkwin(parent_node.state) == 2 and not checkdraw(parent_node.state): if parent_node.Poss_Child and random.uniform(0, 1) >= 0: parent_node = expansion(parent_node) result = simulation(parent_no...
This code trains a Q-learning agent using Monte Carlo Tree Search (MCTS) in a board game. It loads a Q-table, runs 10,000 episodes, alternates between MCTS and Q-learning moves, tracks wins/draws, updates the Q-table with rewards, and visualizes cumulative rewards. The agent improves its strategy by combining explorati...
def trainer(): qtable = pickle.load(gzip.open("qplay.dat.gz", "rb")) qtable = {} initial_time = time.time() n = 10000 draw = 0 qlearn = 0 mcts = 0 start_time = time.time() print("Start") reward_episode = [0] * n i = 0 while n > 0: print(n) # print("_______...
def create_board(n = Rows, m = Cols): Rows = n Cols = m board = [] board_row = [] for r in range(Rows): board_row.append(2) for c in range(Cols): board.append(copy.deepcopy(board_row)) return board def parta(node): initial_node = copy.deepcopy(node) turn = 0 count...
The code's main task is to execute a game simulation with two AI strategies: MCTS_40 vs MCTS_200 or MC_n vs Q-Learning. It initializes game parameters, creates a board, and prompts user input to select the mode. Depending on the choice, it runs either the parta function for MCTS-based competition or q_play for Q-Learni...
def main(): turn = 0 count = 0 draw = 0 winner2 = 0 num_games = 100 in_time = time.time() board = create_board() current_node = TreeNode(board, None, 0, 0) current_state = current_node.state lastmove = 0 print("Enter game mode as given below: ") print("1) MCTS_40 vs MCTS_...
def initial_settings(self): directory = os.path.dirname(os.path.realpath(__file__)) try: os.makedirs(os.path.join(directory, "Modified")) os.makedirs(os.path.join(directory, "Raw")) print("Initialization for first excution") print("Editor Initiali...
The code initializes an image processing setup by creating directories, selecting an image file, and preparing it for modification. It sets up user, raw, and output directories, lists available images, lets the user choose one, opens the selected image, and initializes a command handler for further processing. The main...
def __init__(self) -> None: self.User_directory = self.initial_settings() self.Raw_directory = os.path.join(self.initial_settings(),"Raw") self.Output_directory = os.path.join(self.User_directory, "Modified") self.Image_Name = self.ListDirectory(self.Raw_directory) self...
def compute_results(SNR_sigma, wordRandom, noiseRandom, sample_num, batch_size, sampling_type, N_proto, M_proto, z_value, train_on_zero_word, input_llr, input_codeword, training_iter_end, sess, net_dict, etha_value, decoding_type, punct_start, punct_end,q_bit): Results = np.zeros((4, SNR_sigma.size), dtype=np....
The function `print_result` computes and prints performance metrics (BER, FER, loss) from given inputs using `compute_results`, updates optimization values if in training mode, and saves results to files. It differentiates between validation and test phases based on `test_flag`, prints relevant metrics, and returns opt...
def print_result(input_llr, input_codeword, curr_epoch, opt_value, Perf_filename, out_filename, sharing, sampling_type, decoding_type, punct_start, punct_end, training_iter_start, training_iter_end, sample_num, batch_size, SNR_sigma, wordRandom, noiseRandom, z_value, q_bit, N_proto, M_proto, train_on_zero_word, etha_c...
def _load_working_table(self): table = p.loadURDF('../data/table/table.urdf', self.table_pos, self.table_orientation) p.resetBasePositionAndOrientation(table,self.table_pos, self.table_orientation) return table def reset_model(self,): ''' to be replaced in all child classes ...
This code resets a simulation environment by initializing the physics engine, loading a robot and environment objects, configuring joint positions, and setting up initial conditions for a new episode. It disables rendering during setup, loads the Sawyer robot, resets its joints, sets specific angles, records initial po...
def reset(self): # if (p.connect(p.SHARED_MEMORY) < 0 and not p.isConnected()): p.connect(p.GUI) p.loadURDF("plane.urdf",[0,0,-.85]) self.table_id = self._load_working_table() p.configureDebugVisualizer(p.COV_ENABLE_RENDERING,0) self.body_id = p.loadURDF("sawyer_...
def is_flaged(self): return self.type == self.FLAG def remove_flag(self): self.type = self.old_type self.set_icon(remove = True) def set_icon(self, remove = False): if remove : icon_path = '' else: icon_path = self.getFilePath(self.ICONS_DIR, self.get_icon...
The `reveal` method handles revealing a Minesweeper cell. If the cell is a zero (no adjacent mines), it recursively reveals adjacent cells. Otherwise, it displays the cell's state, removes flags if present, triggers mine explosion if it's a mine, and disables the cell after processing.
def reveal(self): if self.type == self.CELL_0 : grid_btns = MineSweeperUI.get_grid_buttons() row_size = len(grid_btns[0]) column_size = len(grid_btns) row_min = max(min(self.row - 1 , row_size), 0) row_max = max(min(self.row + 1 , row_size), 0) ...
def is_flaged(self): return self.type == self.FLAG def add_flag(self): self.type = self.FLAG self.set_icon() def remove_flag(self): self.type = self.old_type self.set_icon(remove = True) def is_revealed(self): return self._revealed def reveal(self): if self.type =...
This code handles mouse click events on a cell. Right-click toggles a flag (adding/removing it) and emits a signal, while left-click reveals the cell if unflagged and unrevealed.
def mousePressEvent(self, event): super(Cell, self).mousePressEvent(event) if event.button() == QtCore.Qt.RightButton: if not self.is_flaged(): self.add_flag() self.flaged.emit(True) else: self.remove_flag() self.fla...
def create_actions(self): self.easy_action = QtWidgets.QAction('Easy', self) self.medium_action = QtWidgets.QAction('Medium', self) self.hard_action = QtWidgets.QAction('Hard', self) self.custom_action = QtWidgets.QAction('Customize...', self) def create_widgets(self): self.menu...
The code initializes a Minesweeper UI by setting the window title, creating actions, widgets, layouts, starting a new game with 'easy' difficulty, and establishing signal-slot connections for interactivity.
def __init__(self, parent = None): super(MineSweeperUI, self).__init__(parent) self.setWindowTitle(self.WINDOW_TITLE) self.create_actions() self.create_widgets() self.create_layouts() self.new_game('easy') self.create_connections()
def prioritize(thisId,avail,atoms,adjlist,atmMap): # first screen by connectivity rank = [len(adjlist[i]) for i in avail] pval = [atoms[atmMap[i]].pval for i in avail] maxC = max(rank) # if there are equal connectivity proceed to priority numbers if (rank.count(maxC) > 1 ): rank = [pi if ri == maxC else...
This code performs iterative molecular graph contraction by grouping atoms based on mass, charge, and priority, using page rank algorithms to prioritize nodes. It contracts low-priority atoms into heavier groups, updates group properties, and records the reduction history. The process repeats until no further coarsenin...
def reduction_mapping(files,options,moli,atoms,adjlist,atmMap): history = [] curr = {} queue= [] # Set up initial list and mark atoms to be reduced files['summary'].write("Initial Number of atoms: {}\n".format(len(moli))) print("# Beginning reduction mapping of molecule with {} atoms...".format(len(moli)))...
def print_status(status): print("\n********************************************************") print("# {}...".format(status)) print("********************************************************") return def assign_values(atoms,mapFile,key): if mapFile is not None: print(mapFile) if mapFile != "pdb...
The code processes molecular structure files to generate coarse-grained (CG) models by assigning atomic attributes, mapping molecules, and writing CG coordinates. It screens PDB files, assigns mass/polarization charges, processes bonds, and reduces molecules into CG sites. Types are assigned hierarchically across histo...
def CGmapping(files,options): #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # SCREEN FILES AND GENERATE MAPS #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ print_status("Screening PDB file and assigning attributes") atoms = pdb.process_atoms(files['pdb']) assign_values(atoms,files['mmap'],'mass') ...
def create_parser(): parser = argparse.ArgumentParser(description='Generates a graph-based coarse-grained (GBCG) particle mapping based on a specified degree of connectivity, i.e., the spectral grouping scheme.\ Details of the formalism can be found in the publication: Michael A. Webb, Jean-Yves Delan...
The main task of the code is to parse command-line arguments, prepare input parameters, execute a mapping process via `CGmapping`, measure its execution time, and return a success status. It initializes a timer, runs the mapping operation, calculates elapsed time, and prints the result before returning `True`.
def main(argv): # PARSE ARGUMENTS parser = create_parser() args = parser.parse_args() (files,options) = convert_args(args) # BEGIN MAPPING t0 = time.time() CGmapping(files,options) print("# The elapsed time is {} seconds".format(time.time()-t0)) return True
def dataPartition(data, attribute): """ Partitioning the data according to an attribute :param data: dataset that contains data objects, is a tuple: (obj_1, ..., obj_n) :param attribute: an attribute :return: a dictionary attributeValue_subset, as form as {attributeValue_1: subset_1,... } """ ...
The function selects the attribute from the given list that provides the highest information gain for splitting the dataset, using a loop to compare gains from each attribute and updating the result accordingly.
def selectAttribute(data, attributeList): """ :param data: :param attributeList: :return: the attribute that denotes the split criterion """ attributeValue_subset = dataPartition(data, attributeList[0]) dataSize = len(data) maxGain = info(data) - infoForAttribute(dataSize, attributeVa...
def is_valid_move(board, row, col): return 0 <= row < len(board) and 0 <= col < len(board[0]) def is_valid_solution(board): # Check if the board satisfies the revealed cells' constraints for row in range(len(board)): for col in range(len(board[0])): cell = board[row][col] if ...
This function performs backtracking to solve a board configuration by recursively attempting to place mines ('M') or empty cells (' '), checking validity at each step. It explores possible placements, backtracking when invalid, and returns True if a valid solution is found, resetting the board state accordingly.
def backtrack(row, col): if not is_valid_move(board, row, col): return False if board[row][col] != 'X': return backtrack(row, col + 1) if col < len(board[0]) - 1 else backtrack(row + 1, 0) # Try placing a mine and check if it leads to a valid solution board[row][...
def nlstSafe(self, directory): """ creates a directory tree for all directories and file in directory. Note that this replaces the nlst() command in the ftplib, because this was not able to parse square brackets, and the ftp server could not handle escaped strings, for whatever r...
The code recursively clones a remote FTP directory by iterating through its items, checking if each is a directory (recursively processing subdirectories) or a file. If a file matches a specified pattern, it downloads the file to the local system, respecting the overwrite flag. The function handles directory traversal ...
def cloneRemoteDir(self, name, overwrite, guess_by_extension, pattern): """replicates a directory on an ftp server recursively""" for item in self.nlstSafe(name): if self.isFtpDir(item, guess_by_extension): self.cloneRemoteDir(item, overwrite, guess_by_extension, pattern) ...
def setup(self): # initialize window pg.display.set_caption(TITLE) self.clock = pg.time.Clock() def events(self): # Game loop game_over = False while not game_over: self.clock.tick(FPS) # events for event in pg.event.get(): ...
The code defines a `run` method that sequentially executes three key steps: initializing setup, processing events, and terminating the application. Its main task is to orchestrate the application lifecycle by first preparing resources (`setup`), handling event-driven operations (`events`), and finally cleaning up or ex...
def run(self): self.setup() self.events() self.quit()
def factor_Sketch(X,ks, law="g"): factors =[] Omegas =[] for i,n in enumerate(X.shape): #gives the count and the values n_array = list(X.shape) del n_array[i] omega = TRP(n_array,ks[i], law) #then the dimension would be (I_(-n), ks[i]) V = tl.unfold(X,i) @ omega #tl.unfold.s...
The code performs a Tucker decomposition of the input tensor X, generating orthogonal factors and a core tensor. It approximates X by reconstructing it from the decomposed components, returning both the reconstructed tensor X_hat and the core tensor. The process involves sketching factors, orthogonalizing them, and adj...
def One_Pass(X,ks,s, law="g"): Qs = [] factors, Omegas = factor_Sketch(X, ks) core,Phis= core_Sketch(X,s) for factor in factors: Q = ortho(factor) Qs.append(Q) for mode in range(len(factors)): core = tl.tenalg.mode_dot(core, np.linalg.pinv(Phis[mode].T@Qs[mode]), mode) X_...
def make_wheel(self, v0, first=False): v0 = float(v0) self.v = v0 # for returing hsv value img = np.zeros((self.dim, self.dim, 3)) for i in range(img.shape[0]): for j in range(img.shape[1]): v = v0 # v in hsv s = np.sqrt((i-self.c)**...
This code initializes an interactive GUI application with an HSV color wheel visualization and draggable data points. It sets up a Tkinter window with a matplotlib figure, creates a canvas for the HSV image, places draggable tokens around the canvas, and includes controls for adjusting HSV values and toggling groups. T...
def __init__(self, fig, line): # organize windows mngr = plt.get_current_fig_manager() mngr.window.setGeometry(0,0,750,500) root = tk.Tk() root.title('hsvplot') root.geometry('250x300+825+0') self.fig= fig self.line = line self.update = update ...
def get_bert_m(model = "finetuned_sent_embeddings", PATH = "finetuned_sent_embeddings_ngram1_no_phrasing_stf-False_mdf-0.4_hashtags"): '''Load bert model and labels from corresponding topic model. Return dataframe with text and label columns. Parameters ---------- model : str ...
The main task of the code is to compare pairs of models (BERT, LDA, BTM) based on command-line arguments, compute their agreement using specific functions, and output the average agreement. It checks valid model combinations, loads corresponding labeled data, and executes comparison logic for each valid pair, printing ...
def main(): '''Check that correct sys.argvs are given and then compare models.''' models = sys.argv[1:3] cols = ['text', 'label'] if set(['bert', 'lda']) == set(models): print('Comparing bert and lda.') bert_ft = get_bert_m() lda_df = pd.read_csv("data/lda_labels.csv", useco...
def test(self, pic, trained_model): encoded_img = {} encoded_img[pic] = self.encode(self, images_path+pic) img = encoded_img[pic].reshape((1,2048)) greedy_search_caption = "Greedy Search: " + self.greedySearch(self, img, trained_model) print(greedy_search_caption) beam_se...
The code generates image captions using a neural network. It loads a pre-trained model or trains a new one if none exists, processes image descriptions, builds vocabulary mappings, and uses GloVe embeddings. The function prepares training data, constructs a model combining image features and LSTM, trains it, and evalua...
def generateCaption(self, pic = '2398605966_1d0c9e6a20.jpg'): try: trained_model = load_model(model_path+"trained_model") #Reading Vocab size vocab = [] with open(param_path+'vocab_size.csv', newline='') as f: ...
def bootstrapped_feature_select_best_hyperparameter(self, X_train, y_train, X_val, y_val, bootstrap_replicates: Union[int, None], soft_J_percentage: float = None): if self.bootstrapped_reg_dict is Non...
This function evaluates a model's performance using bootstrap replicates and soft J percentage. It selects optimal hyperparameters, computes test set MSE, retrieves J values, calculates portfolio returns, and assesses daily tracking error against index returns. Results include J size, MSE, tracking error, and J values ...
def _run_once(self, X_train, y_train, X_val, y_val, X_test, y_test, bootstrap_replicates: Union[int, None], soft_J_percentage: float = None): self.bootstrapped_feature_select_best_hyperparameter(X_train, y_train, X_val, y_val, bootst...