dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def cateringOptions(con): previewDay = con.recv(255) print(previewDay) Day = (previewDay.decode()).capitalize() with open(f'{Day}.txt') as preview: menuExtracted = preview.read() menuEncoded = menuExtracted.encode() con.sendall(menuEncoded) print("Menu has been successful...
This function handles client-server interaction by receiving menu choices, sending the menu file if option 1 is selected, or delegating to admin functions (login, add, remove) or file logging based on other choices. It maintains a loop until a valid choice is processed, ensuring appropriate responses are sent over the ...
def menuPrep(con): print("connected") while True: buf = con.recv(255) choice = buf.decode() if choice == '1': with open(f'{dateToday}.txt') as file: menuExtracted = file.read() menuEncoded = menuExtracted.encode() con.sendall(me...
def check(menuEncoded): global secret_phrase privkey_bytes = open('Serverprivatekey.der' , 'rb').read() if len(privkey_bytes) == 0: return key_generator(secret_phrase,menuEncoded) else: return key_importer(secret_phrase,menuEncoded) def cateringOptions(con): previewDay = con.recv(255...
The code handles server-side menu operations by receiving client choices, generating a digital signature for the menu using RSA, and sending the signed menu list. It also delegates to sub-functions for catering options, admin login, and file logging based on client input.
def menuPrep(con): print("connected") while True: buf = con.recv(255) choice = buf.decode() if choice == '1': with open(f'{dateToday}.txt') as file: menuExtracted = file.read() signature = check((menuExtracted).encode()) #Input RSA signing code...
def get_cell_by_id(self, id_): parent = self for i in range(len(id_)): if not parent.children: if i < len(id_) - 1: logging.warning('get_cell_by_id reached end of ' 'fragmentation but `id_` is not over') ...
This function maps points from a component graph's nodes to a target coordinate system using x_mapping and y_mapping, checks if the mapped points lie within a specified area, and connects nodes in the component graph to corresponding cells in the target system, provided the cells are not discarded.
def fill_symbolic_image(self, component_graph, x_mapping, y_mapping): for node in component_graph.nodes: zoomable_area = self.get_cell_by_id(node) cell_points = [] zoomable_area.get_active_area_points(100, cell_points, []) for point in cell_points: ...
def validateIfMrpCanBeCreated(self, project_task): if not project_task.date_deadline: self.show_error_message("You need to set the Project Task Deadline before creating Manufactoring Order!") return False return True def create_product(self, name, warehouse): product_to_b...
The main task of the code is to create an MRP (Manufacturing Resource Planning) production record for a project task based on a sales line, generating associated stock moves and picking, and linking the MRP to the task. It checks validity, creates a product and BOM, sets up customer delivery logistics, confirms stock m...
def action_create_mrp_production(self): self.ensure_one() action = {} for project_task in self: if self.validateIfMrpCanBeCreated(project_task): if project_task.sale_line_id and not project_task.mrp_production_id: company = self.env['res.company']....
def conv_bn(self, x, filter, kernel = 3, strides = (1, 1), padding = 'same'): x = Conv2D(filter, kernel, strides = strides, padding = padding)(x) x = BatchNormalization()(x) x = Activation('relu')(x) return x def encoder(self, x, filter): en_conv1 = self.conv_bn(x, filter, 3, st...
The code defines a neural network model with an encoder-decoder architecture. It starts with convolutional layers and max-pooling, followed by four encoder blocks. The decoder reconstructs features using skip connections from the encoder, then applies convolutional layers and a softmax activation for classification. Th...
def base(self, shape): input = Input(shape = shape) x = self.conv_bn(input, 64, 7, (2, 2), padding = 'same') x = MaxPooling2D((3, 3), strides=(2, 2), padding = 'same')(x) for i in range(4): self.encoder_block.append(self.encoder(x, self.encoder_filter[i])) x = se...
def collision(self, particles): """Sees if a collision occured and return between which objects the collision occurs""" collision_list = [] for n in particles: distance = vector_math.magnitude(vector_math.subtract(n.get_position(), self.get_position())) radius_sum = n.rad...
The code updates particle velocities by checking for collisions. If collisions occur, it processes them; otherwise, it calculates new velocity using acceleration, previous velocity, and time step, then updates the velocity attribute.
def set_velocity(self, particles): """Sets velocity using acceleration, previous velocity, and time_step""" collision_list = self.collision(particles) if(collision_list): self.perform_collision(collision_list, particles) else: velocity = self.get_velocity() ...
def _getSetting(helper, setting): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_getSetting Invoked") myDefaults = { 'max_log_batch': 60000, 'user_limit': 200, 'group_limit': 200, 'app_limit': 500,...
The main task of the code is to collect users from an Okta API by querying users updated between a checkpoint start date and the current time, updating the checkpoint with the latest user update timestamp, and returning the retrieved users list. It uses filtering parameters, handles date ranges, and stores the last upd...
def _collectUsers(helper): #Distinct entry point for user collection opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" global_account = helper.get_arg('global_account') cp_prefix = global_account['name'] resource = "/users" method = "Get" opt_limit...
def _getSetting(helper, setting): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_getSetting Invoked") myDefaults = { 'max_log_batch': 60000, 'user_limit': 200, 'group_limit': 200, 'app_limit': 500,...
The function retrieves Okta group users via API, processes them based on configuration settings, and either writes user data to Splunk or returns user IDs. It logs metrics, respects pagination limits, and conditionally formats output depending on 'write_groupUser' and 'group_limit' settings.
def _collectGroupUsers(helper, ew, gid): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_collectGroupUsers has been invoked: " + gid ) resource = "/groups/" + gid + "/skinny_users" method = "Get" write_groupUser = bool(_ge...
def _getSetting(helper, setting): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_getSetting Invoked") myDefaults = { 'max_log_batch': 60000, 'user_limit': 200, 'group_limit': 200, 'app_limit': 500,...
The function retrieves Okta app users for a given app ID (aid), processes their data based on configuration settings (write_appUser, app_limit), and returns either detailed user records or just user IDs. If configured, it logs results and writes them to Splunk.
def _collectAppUsers(helper, ew, aid): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_collectAppUsers has been invoked: " + aid ) resource = "/apps/" + aid + "/skinny_users" method = "Get" write_appUser = bool(_getSetting...
def _getSetting(helper, setting): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_getSetting Invoked") myDefaults = { 'max_log_batch': 60000, 'user_limit': 200, 'group_limit': 200, 'app_limit': 500,...
The main task of the code is to collect and enrich Okta group data by filtering groups updated or modified after specified timestamps, retrieving their members and assigned apps, and updating checkpoints for future syncs. It uses API calls with dynamic filters, processes results to track the most recent updates, and st...
def _collectGroups(helper, ew): #Distinct entry point for group collection opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" global_account = helper.get_arg('global_account') cp_prefix = global_account['name'] resource = "/groups" method = "Get" ...
def _getSetting(helper, setting): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_getSetting Invoked") myDefaults = { 'max_log_batch': 60000, 'user_limit': 200, 'group_limit': 200, 'app_limit': 500,...
The main task of the code is to retrieve active Okta applications, collect their assigned users and groups, and return them. It fetches apps via an API call with filtering, then enriches each app object with user and group data from helper functions before returning the enhanced list.
def _collectApps(helper, ew): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_collectApps has been invoked") resource = "/apps" method = "Get" opt_limit = int(_getSetting(helper,'app_limit')) params = {'limit': op...
def _getSetting(helper, setting): opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "_getSetting Invoked") myDefaults = { 'max_log_batch': 60000, 'user_limit': 200, 'group_limit': 200, 'app_limit': 500,...
The code collects and sends specific Okta data types (logs, users, groups, apps) to Splunk based on the `metric` parameter. It enforces rate limits, validates input ranges, and skips collection if constraints are violated. For "zset", it resets checkpoints. Data is fetched via helper methods, logged, and written to Spl...
def collect_events(helper, ew): """ Do this thing """ opt_metric = helper.get_arg('metric') log_metric = "metric=" + opt_metric + " | message=" helper.log_debug(log_metric + "Fetching Metric") global_account = helper.get_arg('global_account') cp_prefix = global_account['name'] loglevel =...
def is_face(card): return 1 <= card <= 4 def value(card): """ Precondition: not is_face(card) """ return card >> 1 def is_movable_number(pile, d): """ Preconditions: - len(pile) >= d - not is_face(pile[-d]) """ for i in range(1, d): lo = pile[-i] hi = pile[-i-...
The function checks if a pile is valid by ensuring it's non-empty, the first card is not a face card, the first card has a value of 10, and the pile meets a movable number condition based on its length.
def is_good_pile(pile): if not pile: return False elif is_face(pile[0]): return False else: return value(pile[0]) == 10 and is_movable_number(pile, len(pile))
def is_face(card): return 1 <= card <= 4 def is_valid_face(pile, d): """ Preconditions: - len(pile) >= d - is_face(pile[-d]) """ # All cards in pile must match top for i in range(1, d): if pile[-i] != pile[-d]: return False return True def is_movable_number(pile, ...
This function checks if a given pile meets specific validity conditions based on its length and the type of its first element. It returns True if the pile is either a valid face pile (when its length equals MAX_FACE_PILE and the first element is a face) or a valid number pile (when its length equals MAX_NUMBER_PILE and...
def is_solved_pile(pile): if not pile: return True if len(pile) == MAX_FACE_PILE and is_face(pile[0]): return is_valid_face(pile, MAX_FACE_PILE) if len(pile) == MAX_NUMBER_PILE and not is_face(pile[0]): return is_movable_number(pile, MAX_NUMBER_PILE) return False
def is_good_pile(pile): if not pile: return False elif is_face(pile[0]): return False else: return value(pile[0]) == 10 and is_movable_number(pile, len(pile)) def is_face(card): return 1 <= card <= 4 def is_movable_face(pile, d): """ Preconditions: - len(pile) >= d ...
The main task of the code is to determine whether transferring `d` cards from the source pile (`src`) to the destination pile (`dst`) is valid. It checks if the source and destination are different, verifies the source pile's state, ensures sufficient cards exist, validates face/number card rules for movability, and co...
def can_transfer(self, src, dst, d): if src == dst: return False if is_good_pile(self.piles[src]): return False if len(self.piles[src]) < d: return False if len(self.piles[src]) > d: pile = self.piles[src] if is_face(pile[-d-1])...
def is_good_pile(pile): if not pile: return False elif is_face(pile[0]): return False else: return value(pile[0]) == 10 and is_movable_number(pile, len(pile)) def is_face(card): return 1 <= card <= 4 def is_movable_face(pile, d): """ Preconditions: - len(pile) >= d ...
This function determines if a card from a specified pile can be freed by checking conditions related to the pile's state, including the presence of a free cell, pile validity, and movement rules for face cards and numbers. It returns True if the top card is eligible for removal based on these constraints.
def can_free(self, src): if self.free_cell is not None: return False pile = self.piles[src] if not pile: return False if is_good_pile(self.piles[src]): return False if len(pile) > 1: if is_face(pile[-2]) and is_movable_face(pile, 2)...
def is_solved(self): if self.free_cell is not None: return False for pile in self.piles: if not is_solved_pile(pile): return False return True def can_unfree(self, dst): if self.free_cell is None: return False pile = self.piles[...
This code solves a puzzle using backtracking by recursively exploring possible moves, tracking visited states to avoid cycles, and attempting to unfreeze, transfer, or free elements in shuffled orders to find a solution path.
def solve(self, seen, moves): if self.is_solved(): return True if len(seen) > 10**4: raise GaveUp key = str(self) if key in seen: return False seen.add(key) srcs = list(range(NUM_PILES)) dsts = list(range(NUM_PILES)) ...
def header(root,text,gridx = 0,gridy = 0,font_size = 52,pady = (0,50),padx = 20): text = ct.CTkLabel(root,text = text,font = ("",font_size)) text.grid(row = gridx,column = gridy,padx = padx,pady = pady) return text def button(root,gridx,gridy,text,font_size = 16,width = 200,height = 50,padx = 20,pady = 10,c...
The code initializes a GUI interface for managing courses, featuring input fields for course names and IDs, buttons to add/delete courses, a scrollable frame to display courses, and confirmation/cancel options. It binds keyboard events for input navigation, uses dictionaries to track changes, and disables the delete bu...
def __init__(self, master, manger, *args, **kwargs): super().__init__(master, manger, *args, **kwargs) self.header = header(self,"Edit courses",pady=20) self.header.configure(font=("",25)) self.header.grid(row=0,column=0,sticky = "new") self.cont = ct.C...
def is_binary(binary): for bit in binary: if not bit in ['0', '1']: return False return True def addition(a, b): result = bin(int(a, 2) + int(b, 2))[2:] adjust_count = len(seperate(result)) - len(seperate(a)) adjust_string = ' ' * adjust_count if adjust_count > 0 else '' #...
The main task of the code is to perform arithmetic operations (addition, subtraction, multiplication, division) on two user-input binary numbers. It validates the inputs as binary strings, handles basic error checking, and delegates the computation to corresponding functions based on user-selected operations.
def main(): top_binary = input('Top Binary: ') if not is_binary(top_binary): print('\nPlease only put binary!') exit(1) bottom_binary = input('Bottom Binary: ') if not is_binary(bottom_binary): print('\nPlease only put binary!') exit(1) operation = input('...
def prettify(number): return int(number) if float(number).is_integer() else number def calculate_mean(values, show_solution=False): sum_ = 0 for value in values: if show_solution: print('{} + {} = {}'.format(sum_, value, sum_ + value)) sum_ += value if show_solution: ...
The main task of the code is to collect user-input numerical values, compute statistical measures (mean, median, mode, range, variance, standard deviation), and display formatted results. It prompts users to enter numbers, calculates each statistic step-by-step, and presents the outcomes with solutions and prettified n...
def main(): values = [] print('\nType "go" to calculate.') while True: print('\nValues: ' + ', '.join(map(lambda x: str(prettify(x)), values))) value_input = input('Value: ') if value_input.lower() != 'go': try: values.append(float(value_input)) ...
def getVocabToken(self, embeddingInstance, sentenceList): vocabArray = [] for sentence in sentenceList: sentence = embeddingInstance.removeStopWords(embeddingInstance, sentence) #print(sentence) vocabArray.extend(re.split('\s+', sentence)) return(voca...
The code processes sentiment-related vocabulary tokens by filtering duplicates, generating confusion matrices, and writing results to a file for word cloud visualization. It iterates thrice, prompting user input to select sentiment categories, extracts associated tokens, compares them against decoy sets, removes stop w...
def screenTokensForLLR(self): embeddingInstance = EmbeddingRepresentation.EmbeddingRepresentation embeddingInstance.__init__(embeddingInstance) embeddingInstance.readMultiClassLabel(embeddingInstance) self.multiCLassLabelInput = embeddingInstance.multiCLassLabelInput limitSize = ...
def openConfigurationFile(self,jsonVariable): path = os.path.dirname(sys.argv[0]) tokenMatcher = re.search(".*TwitterPregnancyIdentification_1.0\/", path) if tokenMatcher: configFile = tokenMatcher.group(0) configFile="".join([configFile,"config.json"]) ...
The main task of the code is to load training data by reading a configuration file, process the data to determine the maximum sentence size, and generate tweet vector embeddings for subsequent tasks. It initializes necessary resources for text processing and model training.
def loadResource(self): trainDataPath = self.openConfigurationFile(self,"trainDataPath") self.readResourceData(self,trainDataPath) print("max sentence size>>",self.tweetSize) self.findTweetVectorEmbeddings(self) return()
def _command_calibrate(self): pose = self.calibration_pose + np.random.uniform(-self.diff, +self.diff, (len(self.joint_names))) self._move_to_joint_goal(self.manipulator_group, pose) def _command_save(self): tstamped_m_ee = self.tf_buffer.lookup_transform( self.robot_effector_frame, ...
This code processes events in a loop, executing corresponding commands (e.g., calibrate, save, home) based on the value of 'self.event', then resets the event and waits for the next cycle. It runs continuously until ROS shutdown, handling robot control tasks through predefined functions.
def command(self): while not rospy.is_shutdown(): if self.event is not None: if self.event == "calibrate": self._command_calibrate() elif self.event == "save": self._command_save() elif self.event == "calculate":...
def start_gui(self, sleepTime: int = 60): log.warning("GUI version is only experimental!") import tkinter as tk window = tk.Tk() window.title("Falconry monitor") frm_counter = tk.Frame() def quick_label(name: str, x: int, y: int = 0): lbl = tk.Label(master=...
The main task of the code is to safely initiate a manager process with optional GUI support, handling interruptions and errors. It starts either a GUI or non-GUI mode based on the 'gui' parameter, uses a sleep interval for job checks, logs errors on KeyboardInterrupt or exceptions, saves data, prints failed jobs, and e...
def start_safe(self, sleepTime: int = 60, gui: bool = False): try: if gui: self.start_gui(sleepTime) else: self.start(sleepTime) # argument is interval between checking of the jobs except KeyboardInterrupt: log.error("Manager interrupt...
def make_output_fn(symb, year, target_dir): return os.path.join(target_dir,year+'_'+symb+'.csv') def construct_prediction(target_fn,model,time_step=70): data = pd.read_csv(target_fn,delim_whitespace=True) data, scaler, data_dt, price_col = prep_data(data) dataX, dataY = make_input_data(data, time_step) trainX, tes...
The function `predict_sell_time` predicts the optimal sell time for a given stock using a machine learning model. It constructs a prediction dataset, identifies the best stopping point based on a threshold, and converts this index to a calendar date. The output is the predicted date to sell the stock, derived from hist...
def predict_sell_time(write_dir,year,stock,model,valid_days,ts=70,stop=.2): #target_fn = os.path.join(write_dir,stock + '.csv') target_fn = make_output_fn(stock,year,write_dir) predict_vals = construct_prediction(target_fn,model,time_step=ts) best_ind = opt_stopping(predict_vals,stopping=stop) return convert_ind_t...
def get_valid_days(month_dir): #print(month_dir) for (root, dirnames, filenames) in os.walk(month_dir): #print(root) #print(dirnames) #print(filenames) return dirnames def predict_sell_time(write_dir,year,stock,model,valid_days,ts=70,stop=.2): #target_fn = os.path.join(write_dir,stock + '.csv') target_fn = ...
The function generates a list of formatted sell transactions for each stock in the provided dictionary. It predicts potential sell times using a model, validates these against actual transaction data, and formats the results into structured entries. The output is a list of transactions with details like date, time, sto...
def make_sell_transaction_list(stock_dict,year,month_dir,write_dir,model,ts=70,stop=.2): valid_days = get_valid_days(month_dir) sell_list = len(stock_dict.keys()) * [None] for i,stock in enumerate(stock_dict.keys()): bday,btime = predict_sell_time(write_dir,year,stock,model,valid_days,ts,stop) actual_time = most...
def get_stock_dict_from_fundamental(fund_fp,cash=1e5,portfolio_size=50): df = load_fundamental_data(fund_fp,portfolio_size) df = add_on_stock_cap(df,portfolio_size, cash) # convert dataframe to dict: keys are symbols and values are daily vol stock_dict = df.set_index('company_name').T.to_dict('list') return stock_...
The code generates a transaction list (buy/sell) using a machine learning model to optimize stock portfolio decisions. It processes fundamental data, converts streaming files to CSV, creates buy/sell transactions, and exports results to a text file. Key parameters include portfolio size, cash allocation, and stop-loss ...
def main(): # optional parameters: portfolio size (50), allocated cash (90k), stopping percent (20%) ym1, ym2, fund_fp, write_dir, out_fn = sys.argv[1:] #pd.options.mode.chained_assignment = None #tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) year,m1 = ym1.split('/') _ ,m2 = ym2.split('/')...
def initial_population(pop_size, city_list): #pop_size is a sample population should be less than len(city_list)! population = [] for i in range(0, pop_size): population.append(create_route(city_list)) return population def rank_routes(population): #determination of fitness function fitness_resu...
This code implements a genetic algorithm to optimize a route by evolving a population over multiple generations. It initializes a population, iteratively generates new generations using elitism and mutation, and returns the best route found. The algorithm aims to minimize travel distance, with initial and final distanc...
def ga(population, pop_size, elite_size, mutation_rate, generations): pop = initial_population(pop_size, population) print("Initial distance: " + str(1 / rank_routes(pop)[0][1])) for i in range(0, generations): pop = next_generation(pop, elite_size, mutation_rate) print("Final distance: " + st...
def initial_population(pop_size, city_list): #pop_size is a sample population should be less than len(city_list)! population = [] for i in range(0, pop_size): population.append(create_route(city_list)) return population def rank_routes(population): #determination of fitness function fitness_resu...
This code implements a genetic algorithm to optimize a route (likely TSP) over multiple generations. It initializes a population, iteratively evolves it using selection, elitism, and mutation, tracks the best solution's distance, and visualizes progress and the final optimized path.
def gaPlot(population, pop_size, elite_size, mutation_rate, generations): pop = initial_population(pop_size, population) progress = [] progress.append(1 / rank_routes(pop)[0][1]) print("Initial distance: " + str(1 / rank_routes(pop)[0][1])) for i in range(0, generations): pop = next_generat...
def exit_on_error(err): print("ERROR!",err) print(USAGE) sys.exit(2) def get_db_info(dbname, dbpath): res_name = None res_path = None res_pid = None cmd = "ps aux | grep [m]server5 " if dbpath: cmd = cmd + "| grep \"" + dbpath + "\"" dbname = os.path.basename(dbpath) ...
The code parses command-line arguments to configure database monitoring parameters, validates input consistency, checks for required tools like 'mclient', sets up logging directories, and initiates monitoring with specified database and logging configurations.
def main(argv): logbase = "" dbname = None dbpath = None dbpid = None # TODO: maybe a better way to parse the commandline options, e.g. to have # option help messages and the option parser in one place try: opts, args = getopt.getopt(argv, "", [ "help", "dbc...
def initiate(key): clear_lfsr() key_str = '' for i in key: key_str += bin(i)[2:].zfill(8) for bit in key_str[:LFSR1_SIZE]: LFSR1.append(int(bit)) for bit in key_str[LFSR1_SIZE:LFSR1_SIZE+LFSR2_SIZE]: LFSR2.append(int(bit)) for bit in key_str[LFSR1_SIZE+LFSR2_SIZE:]: ...
The code performs iterative cryptographic operations by generating random bytes, comparing them to a hash-derived target value (cp), and reinitializing a state with new random bytes if a match is found. It runs this process for a specified number of iterations (iter), using a password and initial seed (cs) to influence...
def start(password,cs,iter): initiate(seed(password,cs,iter)) cp = list(hashlib.sha1(cs.encode()).digest())[:len(cs)] count = 0 temp = [nextByte() for i in range(len(cs))] for i in range(iter): count = 0 new_seed = [] while(1): count += 1 if cp == temp...
def tdf_file_signature_check(filepath): with open(filepath, "rb") as file: if file.read(4) != b'TDF$': raise ValueError('wrong file type (TDF$ header not found)') version = file.read(4) data = file.read() m = hashlib.md5() m.update(data[:-16]) data_size = len(data) ...
The main task of the code is to decrypt a key data file by parsing its structured binary content, deriving a base key from a salt and passcode, and decrypting a local key block. It validates the file signature, extracts metadata (header, version, salt, etc.), generates a base key using the salt and passcode, decrypts t...
def decrypt_key_datas(path, passcode): try: tdf_file_signature_check(path) except ValueError as e: exit(f"Cannot read key_datas file: {e}") with open(path, 'rb') as key_datas_file: key_datas = key_datas_file.read() print("\n##### key_datas parse #####") cur = 0x00 head...
def display_board(): print(board[0]+ "|" + board[1] + "|" + board[2]) print(board[3]+ "|" + board[4] + "|" + board[5]) print(board[6]+ "|" + board[7] + "|" + board[8]) def handle_turn(player): #print whos turn it is print(player + "'s turn.") position = input("Choose a position from 1-9: ") va...
The code defines a function to play a game, displaying the initial board, handling player turns, checking for game-ending conditions, and flipping players. It loops until the game ends, then declares the winner or a tie based on the outcome.
def play_game(): #display starting board display_board() #create loop while the game is still running while game_still_going: #handle a single turn of an arbitrary number handle_turn(current_player) # Check if game is over check_if_game_over() # Flip to other pl...
def _handle_invlid_types( source_paths: Set[Path], target_paths: Set[Path], quiet: bool ) -> Tuple[Set[Path], Set[Path]]: """Checks if the paths are valid (i.e. if they are files or directories) and asks the user if he wants to continue if there are invalid paths. Invalid paths are deleted from the targ...
The function `sync_folders` synchronizes two directories by making the target folder identical to the source. It identifies discrepancies (missing, extra, or differing files/folders), logs planned actions (delete, create, copy), and executes them in parallel using threads. Files in the source are copied to the target, ...
def sync_folders( source_folder: Path, target_folder: Path, n_threads: int = 100, operations_per_thread: int = 10, shallow_comparison: bool = True, max_logged_paths: int = -1, quiet: bool = False, ): """Syncs two folders. This means the target folder will be made identical to the source ...
def leave_date_taken(sd,ed): sdate = split_input_date(sd) start_dt = date(sdate[2], sdate[1], sdate[0]) edate = split_input_date(ed) end_dt = date(edate[2], edate[1], edate[0]) list_of_leave = [] for dt in daterange(start_dt, end_dt): list_of_leave.append(dt.strftime("%d-%m-%Y")) ret...
This function processes a leave application by checking for overlaps with peak periods, other members' leaves, holidays, and weekends. It calculates the valid leave balance, updates the leave records, saves data to a JSON file, and adjusts the employee's balance if the application is valid.
def apply_leave(start_date,end_date,userdata): emp_id = userdata.emp_id la = len(leaves)-1 newid = int(leaves[la].leave_id)+1 listleave = leave_date_taken(start_date,end_date) pperiod = compare_list_date(listleave,peak_periods) #check peak period if pperiod > 0: print("Cannot tak...
def check_keydown_event(ai_settings,aliens,bullets,event,screen,ship,stats): if event.key == pygame.K_q: if stats.game_score > stats.high_score: with open('Game_Record.json','w') as f_obj: json.dump(stats.game_score,f_obj) sys.exit() elif event.key == pygame.K_RIGHT: ship.move_right = True elif even...
The function `check_events` processes user inputs and triggers game actions. It handles quitting the game, keyboard presses/releases for ship movement, and mouse clicks on the play button. Events are delegated to helper functions like `check_keydown_event`, `check_keyup_event`, and `mouse_play_event` to manage game mec...
def check_events(ai_settings,aliens,bullets,play_button,screen,ship,stats): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_event(ai_settings,aliens,bullets,event,screen,ship,stats) elif event.type == pygame.KEYUP: check_ke...
def _generative_step(self, batch): kwargs = { 'inputs': batch["source_ids"], 'attention_mask': batch["source_mask"], 'use_cache': True, 'decoder_attention_mask': batch['target_mask'], 'max_length': self.hparams.max_output_length, 'num_b...
This code evaluates a model's performance on a validation set by comparing generated predictions against ground truth answers. It calculates exact match (EM) and F1 scores for each example, aggregates metrics across the batch, and logs average EM/F1 scores. It also detects discrepancies where EM=1 but F1≠1, and optiona...
def validation_step(self, batch, batch_idx): total_cnt = len(batch['source_ids']) em_correct_num = 0 f1_total = 0 preds = self._generative_step(batch) texts = self.ids_to_clean_text(batch["source_ids"], skip_special_tokens=True) for i in range(total_cnt): pred...
def Fint(y): return np.log(1.+y)-y/(1.+y) def rho_c_z(z): return rho_c*( Omega_m*(1.+z)**3. + Omega_l ) def Deltac(z): d = Omz(z) -1. return 18.*np.pi**2. + 82.*d - 39.*d**2.
The code computes the central gas density in a cosmological context, integrating a function involving exponential terms and cosmological parameters (e.g., Omega_b, Omega_m, rho_c_z, Deltac) to derive the gas density profile, scaled by factors of y³ and the integral result.
def rho_gas_central(z,y): A = 2.*y/Fint(y) lntvec = np.linspace(np.log(1.e-10),np.log(y)) integral = integrate.simps((1.+np.exp(lntvec))**(A/np.exp(lntvec))*np.exp(lntvec)**3.,lntvec) return (Omega_b/Omega_m)*rho_c_z(z)*Deltac(z)/3.*y**3.*np.exp(A)/integral
def rho_c_z(z): return rho_c*( Omega_m*(1.+z)**3. + Omega_l ) def Deltac(z): d = Omz(z) -1. return 18.*np.pi**2. + 82.*d - 39.*d**2. def Fint(y): return np.log(1.+y)-y/(1.+y) def Rvir(M,z): return 0.784*(M/1.e8)**(1./3.)*(Omega_m/Omz(z)*Deltac(z)/(18.*np.pi**2.))**(-1./3.)*((1.+z)/10.)**(-1.)
This function calculates the dark matter density profile using the Navarro-Frenk-White (NFW) model. It computes the density at radius `r` for a halo of mass `M` at redshift `z`, incorporating cosmological parameters via `rho_c_z` and `Deltac`, and normalizing with `Rvir` and the integral `Fint`. The result is the densi...
def rho_nfw(M,z,y,r): rho_0 = rho_c_z(z)*Deltac(z)/3.*y**3./Fint(y) x = y*r/Rvir(M,z) return rho_0/x/(1.+x)**2.
def Rvir(M,z): return 0.784*(M/1.e8)**(1./3.)*(Omega_m/Omz(z)*Deltac(z)/(18.*np.pi**2.))**(-1./3.)*((1.+z)/10.)**(-1.) def Vcirc(M,z): return 23.4*(M/1.e8)**(1./3.)*(Omega_m/Omz(z)*Deltac(z)/(18.*np.pi**2.))**(1./6.)*((1.+z)/10.)**(1./2) def Fint(y): return np.log(1.+y)-y/(1.+y)
The function `Vesc2` calculates the squared escape velocity using parameters `M` (mass), `z` (redshift), `y`, and `r` (radius). It computes `x` as the ratio of `r` to the virial radius `Rvir`, then combines the circular velocity squared `Vcirc²` with integral terms `Fint` and algebraic factors involving `y*x` to derive...
def Vesc2(M,z,y,r): x = r/Rvir(M,z) return 2.*Vcirc(M,z)**2.*( Fint(y*x) + y*x/(1.+y*x) )/(x*Fint(y))
def Vcirc(M,z): return 23.4*(M/1.e8)**(1./3.)*(Omega_m/Omz(z)*Deltac(z)/(18.*np.pi**2.))**(1./6.)*((1.+z)/10.)**(1./2) def Fint(y): return np.log(1.+y)-y/(1.+y) def rho_gas_central(z,y): A = 2.*y/Fint(y) lntvec = np.linspace(np.log(1.e-10),np.log(y)) integral = integrate.simps((1.+np.exp(lntvec))**(...
The function calculates the gas density at radius r in a galactic halo by adjusting the central gas density ($\rho_{\text{gas\_central}}$) with an exponential factor. This factor depends on the escape velocity ($V_{\text{esc}}$), virial temperature ($T_{\text{vir}}$), and thermal energy, accounting for how gas density ...
def rho_gas(M,z,y,r): Vesc2_0 = 2.*Vcirc(M,z)**2.*y/Fint(y) return rho_gas_central(z,y)*np.exp(-mu*m_p*(Vesc2_0-Vesc2(M,z,y,r))*1.e10/(2.*Tvir(M,z)*kelvintoerg))
def Rvir(M,z): return 0.784*(M/1.e8)**(1./3.)*(Omega_m/Omz(z)*Deltac(z)/(18.*np.pi**2.))**(-1./3.)*((1.+z)/10.)**(-1.) def Tvir(M,z): return 1.98e4*(mu/0.6)*(M/1.e8)**(2./3.)*(Omega_m*Deltac(z)/(Omz(z)*18.*np.pi**2.))**(1./3.)*((1.+z)/10.) def rho_gas(M,z,y,r): Vesc2_0 = 2.*Vcirc(M,z)**2.*y/Fint(y) retu...
The code computes the optical depth for 21 cm line emission in a dark matter halo, integrating over the radial distribution of neutral hydrogen gas. It calculates physical quantities like temperature, density, and Doppler broadening, then numerically integrates the product of these factors with a geometric factor. The ...
def OptDepth21(M,z,y,al): prefactor = 3.*hplanck*c**3.*A10/(32.*np.pi*nu21**2.) # cm^3*erg/s RRmax = np.sqrt(1.-(al/Rvir(M,z))**2.) # Maximum radius to integrate if RRmax==0.: # avoid division by 0 return 0. logRR = np.linspace(np.log(1.e-3),np.log(RRmax)) RR = np.exp(logRR) r...
def print_ext(self, *args): if self.silent == False: print_ext(*args) def create_test_train(self, test_split=0.2): indC = range(0,2100) classnum = range(1,22) classNum = np.tile(classnum,[100,1]) classNum = np.transpose(classNum,(1,0)) classNum...
The main task of the code is to run cross-validation experiments on a neural network. It constructs the network, splits data into train/test sets, evaluates performance using F-score with a given beta, logs metrics (timestamp, execution time, accuracy) into a file, and returns the accuracy. Key steps include network cr...
def run_experiments(self, beta=1.0, test_split=0.2, threshold=0.5): self.net_constructor.create_network(self.net_desc, []) #calling th function in run_graph file to create network desc = self.net_desc.get_description() self.print_ext('Running CV for:', desc) start_time = time.time() ...
def initializeData(dataset,orginialDatasetPath,dataFolderPath = '/content/drive/My Drive/Proposal work/MLeaks/data/'): if(dataset == 'CIFAR10'): print("Loading data") dataX, dataY, _, _ = readCIFAR10() print("Preprocessing data") cluster = 10520 dataPath = dataFolderPath+dataset+'/Preprocessed' toTrainData...
This function generates attack data by either training or loading target and shadow models, preprocessing data, clipping top features, and returning processed datasets for adversarial attacks.
def generateAttackData(dataset, classifierType, dataFolderPath ,pathToLoadData ,num_epoch ,preprocessData ,trainTargetModel ,trainShadowModel,topX=3 ): attackerModelDataPath = dataFolderPath+dataset+'/attackerModelData' if(preprocessData): initializeData(dataset, pathToLoadData, dataFolderPath) if(trainTargetMod...
def clean_up(): import os import shutil shutil.rmtree(CONFIG['audio_dir'], ignore_errors=True) shutil.rmtree(CONFIG['video_dir'], ignore_errors=True) shutil.rmtree(CONFIG['image_dir'], ignore_errors=True) if os.path.exists(CONFIG['output_file']): os.remove(CONFIG['output_file']) pass...
This function converts a PowerPoint (.pptx) file into a video file. It performs cleanup, creates necessary directories, and executes the conversion process using the `make_all` function, saving the output to the specified file path.
def pptx_to_video(pptx_file, output_file): clean_up() create_dir() make_all(pptx_file, output_file)
def receive_welcome(self, username: str): # Expect: WELCOME;$username logging.debug("Computer sagt ja.") def receive_new_season(self, season: str): # Expect: NEW SEASON;$season self.send_join(season) def receive_new_game(self, opponent: str): # Expect: NEW GAME;$opponent ...
This code listens for UDP messages, parses incoming data by splitting it into parts, and triggers specific handler methods based on the message type (e.g., WELCOME, NEW SEASON). It processes commands by decoding relevant parameters and passing them to designated functions like receive_welcome or receive_new_game, enabl...
def udp_listen(self): while True: data, addr = self._socket.recvfrom(1024) # buffer size is 1024 bytes logging.debug(f"received message: {data}") message = data.split(b";") if message[0] == b"WELCOME": self.receive_welcome(username=message[1].dec...
def setUpWindow(self): self.screen.title(self.title) self.screen.geometry("1350x750+0+0") self.screen.configure(background="Light Yellow") def CreateLayout(self): self.Tops = Frame(self.screen, bg="Light yellow", pady=2, width=1350, height=100, relief=SUNKEN) self.Tops.grid(row=0...
The code initializes a test environment by setting up a window, creating a layout, configuring a game board, and establishing options, likely preparing a GUI-based application or game for testing or operation.
def setUp(self): self.setUpWindow() self.CreateLayout() self.CreateBoard() self.CreateOptions()
def getConcept(formalcontextName,dictionnaire): expression = '(\d+) \[.*\{Concept\_'+formalcontextName+'\_(\d+).*' for line in content: res = re.search(expression,line) if res: conceptId = res.group(1) conceptName = 'Concept_'+formalcontextName+'_'+res.group(2) lst=line.split('|') lstExtension...
The main task of the code is to extract rules from a formal context of stations by analyzing concept relationships. It processes concepts, their attributes, and hierarchical links (successors/predecessors) to generate rules between introducer concepts and their successors. These rules are written to an output file, cap...
def extractRules(content,formalContextStationsName): getConcept(formalContextStationsName,dictConceptStations) getSuccessorsPredecessors(dictConceptStations) getIntroductorsConcept(dictConceptStations) getIdSourceIdTarget(dictConceptStations) print("introductor concepts stations number : "+str(len(introductorsCon...
def lg(self, text): global logFile # print(logFile) startLogs = 1 if startLogs == 1: log(text, logFile) def dlg(self, text): global detailedLogs global logFile startLogs = 1 # print(str(detailedLogs)) if str(detailedLogs) == "1" and sta...
The code processes a file by removing comments, validating its structure (e.g., checking for "CREATE FUNCTION/PROCEDURE" syntax), and identifying functions/procedures to extract details. It uses global flags to track context (e.g., inside a function/procedure) and validates file format. If invalid, it marks the file as...
def processFile(self, fullFileName): global multiLineComment global insideFunction global targetNameNext global parameterNameNext global parameterTypeNext global parameterDirectionNext global returnTypeNext global functionDeclareNext global functio...
def listFiles(self): # global fileOrDir # global outFileLoc global outFile outFile = CommonParams.outFileLoc + "\\SqlTool_Output.csv" out_initialize(outFile) dirname = self.gui.getDir() fileNamePath = self.gui.get_filename() showFullPath = self.gui.showFul...
The function `workerThread1` processes GUI commands by executing corresponding methods. It retrieves a command from the GUI, locks the screen, and triggers actions like listing files, executing Oracle commands, deploying UI files, or processing tasks based on the received command.
def workerThread1(self): command = self.gui.getCommand() print(command) self.gui.lockScreen = 1 if command == "LIST_FILES": self.listFiles() elif command == "EXEC_ORACLE": self.execInOracle() elif command == "DEPLOY_UI_FILES": self.depl...
def _get_flat_user_data_from_json( d: dict, ref_list: list, invited_by: Optional[ReferalUserModel] = None ) -> Tuple[int, int]: # No safety checks for format validness, for now ref_id = d["id"] user_info = [ref_id, invited_by] ref_list.append(user_info) direct_desc = len(d["refs"]) total_de...
This code imports user data from a JSON file, processes it to create/update referral user records in a database, calculates referral bonuses for existing users, and validates the operation. It uses bulk operations for efficiency, extracts nested data, and applies bonus logic based on user relationships.
def add_users_from_json(path_to_json: Union[str, Path]): with open(path_to_json, "r") as fp: data = load(fp) print("Fetching users") user_data = [] _get_flat_user_data_from_json( d=data, ref_list=user_data, ) print("Creating users") create_user_data = (ReferalUserMo...
def parse_config(): """ Helper function to parse config """ parser = argparse.ArgumentParser() parser.add_argument( "-opt", type=str, required=True, help="Path to option YAML file." ) args = parser.parse_args() opt = parse(args.opt) device = select_de...
The main task of the code is to evaluate a trained LLIE model on a test dataset by computing image quality metrics (PSNR, SSIM, MAE, LPIPS) between low-light and normal-light image pairs. It loads pre-trained generator/refiner models, processes test images, runs inference, and outputs average metric values to assess mo...
def main(): """ main function for LLIE training """ opt = parse_config() init_log(opt) logger = logging.getLogger(__name__) with torch.no_grad(): # get models generator, refiner = get_model(opt["model"], device=opt["device"]) # opts if opt["train"]["optim"][...
def _find_prev_models(self): for trial, model_file in all_prev_models(self.saved_model_regex): if trial not in self.prev_models: self.prev_trials.append(trial) self.prev_models[trial] = model_file def learn( self, total_timesteps: int, callback...
The main task of the code is to perform multiple training trials using a reinforcement learning algorithm (e.g., PPO), where each trial runs for a specified number of timesteps. It saves intermediate models after each trial, tracks the time taken per trial, and stores the saved model paths for later retrieval. The func...
def learn_trials( self, n_trial: int, n_timestep_per_trial: int, callback: MaybeCallback = None, log_interval: int = 1, tb_log_name: str = "PPO", reset_num_timesteps: bool = True, progress_bar: bool = False, exclude: Optional[Iterable[str]] = None,...
def search(file, account): end = findEnd(file) shift = file.readline() file.readline() while file.tell() < end: line = file.readline() temp = line.split()[0] temp = decrypt(temp, shift) if temp == account: return line return "0" def update_account(account)...
The main task of the code is to add a new account to a file, ensuring it doesn't already exist. It encrypts the username and password using a given shift value, writes them to "DO-NOT-DELETE.txt", and handles duplicate accounts by allowing the user to either add a different account or update the existing one.
def addaccount(shift): account = input("Account Name: ").strip() found = "" with open("DO-NOT-DELETE.txt", "r+") as data: # check to see if account already exists found = search(data, account) if found == "0": data.write(account + " ") userInput = input("Usern...
def socket_init(self): self.send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.recv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(self): if not self.quiet: print("Connecting...") while True: try: self.send_socket.conn...
This code initializes a client socket connection to a server, setting up send and receive ports. It stores the client's socket information, connects to the server, and sends initialization commands to establish communication channels. The 'quiet' parameter may suppress output.
def __init__(self, host, port, quiet=False): self.host = host self.port = port self.quiet = quiet self.socket_init() self.connect() sockname = self.send_socket.getsockname() self.client_str = f'{sockname[0]}:{sockname[1]}' self.recv_port = self.recv_socket...
def get_user(self, addr): user_id = self.user_table[addr] if user_id: return User.objects(pk=user_id).first() else: return None def send_msg_to_room(self, user, msg): for other in user.location.users: if other == user: continue addr = self....
This function handles client disconnection by removing related entries from socket, user, and receive tables. It closes the client socket, notifies the room of a user's departure, updates the game world, and recursively processes any linked addresses in the receive table to ensure complete cleanup of disconnected clien...
def drop_client(self, addr): if addr in self.sock_table: client = self.sock_table[addr] del self.sock_table[addr] del self.sock_table[client] client.close() # print("Connection closed with", addr) if addr in self.user_table: user =...
def bind(self): try: self.master_socket.bind(('', self.port)) except OSError: print("Port is already in use!") quit() address = self.master_socket.getsockname() self.host, self.port = address print(f"Bound to {self.host}:{self.port}") def send...
The code sets up a server for a distributed dungeon game, initializing the game world, managing client connections, processing requests, and maintaining room states. It listens for clients, sends welcome messages, handles login/new-user commands, and manages user interactions. The server gracefully handles disconnectio...
def run(self): if 'dungeon' not in self.db.list_database_names(): print('Loading default world') world.load_rooms() # makes sure rooms are empty on startup for room in Room.objects(): room.users = [] room.save() self.bind() self.m...
def one_hot(y): array = np.zeros((N_CLASSES, 1)) if 0 <= y < 10: array[y] = 1 return array def _forward_propagation(self, x): # we only want a single x because we're going to be doing stochastic gradient descent, so we'll be propagating training examples one-by-one self.activations[0] = x for i in range(1, s...
This code trains a neural network using mini-batch gradient descent with L2 regularization. It splits training data into training/validation sets, performs forward/backward propagation, updates weights/biases, and evaluates accuracy on validation and test sets after each epoch.
def fit(self, training_images, training_labels, test_images, test_labels): X = np.split(training_images, training_images.shape[0]) y = np.split(training_labels, training_labels.shape[0]) data = list(zip(X, y)) training_data = data[:-500] validation_data = data[-500:] for epoch in range(self.epochs): r...
def ProposalFunction(u,sigma_theta,sigma_dm): x = np.random.normal(0.0, sigma_theta) + u[0] y = np.random.normal(0.0, sigma_dm) + u[1] return np.array([x,y]) def nll(theta,dm, sim = sim, data = data): ''' Calculates the Negative log Likehood for a set of input parameters u = [theta, dm**2], sim ...
This code performs simulated annealing optimization over a series of decreasing temperatures (3.0 to 0.25), running 50,000 iterations per temperature. It uses a proposal function to generate candidate states, evaluates their negative log-likelihood (nll), and applies temperature-dependent acceptance criteria. The chain...
def runchain(nll,theta0, dm0, sim, data): T = 3 temps = np.arange(T,0,-0.25) iterations = 50000 values = [theta0,dm0] listofvalues = [] for T in temps: zeros = np.zeros((iterations+1,2)) zeros[0,:] = values print('Currently runnin on temp =', T) fo...
def ProposalFunction3(u,sigma_theta,sigma_dm, sigma_a): x = np.random.normal(0.0, sigma_theta) + u[0] y = np.random.normal(0.0, sigma_dm) + u[1] z = np.random.normal(0.0, sigma_a) + u[2] return np.array([x,y,z]) def nll3(theta, dm, a, sim = sim, data = data): ''' Calculates the Negative log Like...
The code performs a simulated annealing algorithm with multiple temperature steps to optimize parameters (theta, dm, a) by minimizing the negative log-likelihood (nll). It runs 50,000 iterations per temperature, proposing new states via a proposal function, calculating energy differences, and accepting/rejecting update...
def runchain3(nll,theta0, dm0, a0, sim, data): T = 3 temps = np.arange(T, 0.0, -0.25) #this should not be 0 iterations = int(50000) #iterations per temperature values = [theta0, dm0, a0] listofvalues = [] for T in temps: zeros = np.zeros((iterations+1,len(values))) ...
def minimize_theta3(theta, dm, a0, sim, data, extra = 0, parabminimiserthreshold = 1e-7): ''' these are here to find the index of the lowest value to be used as a guess ''' thetas = np.linspace(0, 2*np.pi/4, 1000) dms = np.array([dm] * len(thetas)) a = np.array([a0] * len(thetas)) nllt...
The function performs iterative parameter optimization by alternating minimization of theta, dm, and a in either clockwise or anticlockwise order, depending on the 'first' flag. It adjusts parameters using external minimization functions until changes fall below a threshold or after 50 iterations, returning the optimiz...
def univariate3(theta, dm, a, sim, data, first = 0, threshold = 1e-4): count = 0 #clockwise theta -> dm -> a minimisation if first == 0: u0 = [theta,dm,a] u1 = minimize_theta3(*u0,sim,data) while abs(u0[0] - u1[0]) > threshold or abs(u0[1] - u1[1]) > threshold or abs(...
def augment(dataDir, center, left, right, steeringAngle, rangeX=100, rangeY=10): image, steeringAngle = chooseImage(dataDir, center, left, right, steeringAngle) image, steeringAngle = randomFlip(image, steeringAngle) image, steeringAngle = randomTranslate(image, steeringAngle, rangeX, rangeY) image = ra...
This function generates batches of images and corresponding steering angles for training or validation. It randomly shuffles image paths, applies data augmentation (if training) to center/left/right camera images, preprocesses them, and yields batches of size 'batchSize' containing (images, steering_angles) arrays for ...
def batchGenerator(dataDir, imagePaths, steeringAngles, batchSize, isTraining): images = np.empty([batchSize, imageHeight, imageWidth, imageChannels]) steers = np.empty(batchSize) while True: i = 0 for index in np.random.permutation(imagePaths.shape[0]): center, left, right = ima...
def augment(dataDir, center, left, right, steeringAngle, rangeX=100, rangeY=10): image, steeringAngle = chooseImage(dataDir, center, left, right, steeringAngle) image, steeringAngle = randomFlip(image, steeringAngle) image, steeringAngle = randomTranslate(image, steeringAngle, rangeX, rangeY) image = ra...
The code generates batches of images and corresponding steering angles for training a neural network. It shuffles image paths, applies random data augmentation during training, preprocesses images, and yields batches of size `batchSize` containing images and their associated steering angles.
def batchGenerator(dataDir, imagePaths, steeringAngles, batchSize, isTraining): images = np.empty([batchSize, imageHeight, imageWidth, imageChannels]) steers = np.empty(batchSize) while True: i = 0 for index in np.random.permutation(imagePaths.shape[0]): center, left, right = ima...
def loadData(dataDir,testSize): dataDf = pd.read_csv(os.path.join(os.getcwd(), dataDir, 'driving_log.csv'), names=['center', 'left', 'right', 'steering', 'throttle', 'reverse', 'speed']) X = dataDf[['center', 'left', 'right']].values y = dataDf['steering'].values XTrain, XValid, yTrain, yValid = train_t...
The main task of the code is to train a machine learning model using varying learning rates. It iterates through a predefined list of learning rates, loads data from 'dataDir', splits it into training/test sets, builds a model with specified parameters (epochs, batch size, etc.), and trains the model. Parameters like t...
def main(): # Define parameters dataDir = 'data' testSize = 0.2 nbEpoch = 10 samplesPerEpoch = 10000 batchSize = 32 saveBestOnly = True learningRate = [1.0e-1,1.0e-2,1.0e-3,1.0e-4] for lr in range(len(learningRate)): lr=learningRate[lr] # Print para...
def loadData(dataDir,testSize): dataDf = pd.read_csv(os.path.join(os.getcwd(), dataDir, 'driving_log.csv'), names=['center', 'left', 'right', 'steering', 'throttle', 'reverse', 'speed']) X = dataDf[['center', 'left', 'right']].values y = dataDf['steering'].values XTrain, XValid, yTrain, yValid = train_t...
The main task of the code is to train a machine learning model with varying learning rates. It initializes hyperparameters, iterates through a list of learning rates, prints configuration details, loads data, constructs a model, and trains it using specified settings. The loop allows evaluating model performance across...
def main(): # Define parameters dataDir = 'data' testSize = 0.2 keepProb = 1 nbEpoch = 10 samplesPerEpoch = 10000 batchSize = 32 saveBestOnly = True learningRate = [1.0e-1,1.0e-2,1.0e-3,1.0e-4] for lr in range(len(learningRate)): lr=learningRate[lr] ...
def _copy_paths(self, paths, source, destination, output_path, final_path=None): """Copy all the paths from source to destination""" for path in paths: source_path = os.path.join(source, path) if final_path: if os.path.isfile(source_path): des...
The main task of the code is to copy or link static files from the theme to the output directory. It checks each static file's update status: if updated, it copies/links it; if not, it logs that the file is already up to date. The function ensures theme assets are properly synchronized with the output path, maintaining...
def generate_output(self, writer): self._copy_paths( self.settings["THEME_STATIC_PATHS"], self.theme, self.settings["THEME_STATIC_DIR"], self.output_path, os.curdir, ) for sc in self.context["staticfiles"]: if self._file_upd...
def _sopen(filepath): """I/O context manager Parameters ---------- filepath Path to the file. Returns ------- Context manager for file handle. """ kwargs = {} if filepath.suffix == ".gz": kwargs["mode"] = "rt" fopen = gzip.open ...
This function parses a GSE SOFT file by reading its structured data, extracting metadata for SERIES, SAMPLE, PLATFORM, and DATABASE entries, and constructing a GSE object containing parsed GSMs and metadata. It processes grouped file sections, identifies entry types, and organizes data into a GSE instance with associat...
def parse_GSE(filepath: Union[Path, str]): """\ Parse GSE SOFT file. Parameters ---------- filepath Path to GSE SOFT file. Returns ------- :obj:`GSE`: A GSE object. """ gsms = {} metadata = {} gse_name = None platform_metadata = {} database_met...
def consume_cpu_time(delay): initial_time = time.process_time() while (time.process_time() - initial_time) < delay: pass def filter_classes(dept=None, num=None, area=None, title=None): """ Inputs: -d dept show only those classes whose department contains dept -n num show only those ...
This function processes client queries by filtering classes based on parameters or retrieving details, introduces a delay, and sends results back via socket. It handles exceptions, closes the socket, and logs actions.
def handle_client(sock, delay): """ input: client-socket, busy-wait delay output: prints-logs """ print('Forked child process') try: # Read query from client in_flo = sock.makefile(mode="rb", encoding="utf-8") query = pickle.load(in_flo) in_flo.flush(...
def unset_loopdev(self): self.exec_cmd(' '.join(["sudo", "losetup", "-d", Runner.LOOPDEV]), self.dev_null) def umount(self, where): while True: time.sleep(1) p = self.exec_cmd("sudo umount " + where, self.dev_null) if p.returncode != 0: ...
This function initializes a memory-based disk by unmounting existing paths, creating a tmpfs mount, generating a large disk image, and associating it with a loop device. It returns success status and the loop device path, adding a cleanup hook if successful.
def init_mem_disk(self): self.unset_loopdev() self.umount(self.tmp_path) self.unset_loopdev() self.exec_cmd("mkdir -p " + self.tmp_path, self.dev_null) if not self.mount_tmpfs("mem", "tmpfs", self.tmp_path): return False self.exec_cmd("dd if=/dev/zero of=" ...
def game(): gridsize = Label(master, text="Height: ", width=15, font=large_font) #"Questions" gridsize.grid(row=0) gridsize = Label(master, text="Length: ", width=15, font=large_font) gridsize.grid(row=2) gridsize = Label(master, text="Bomb Rate: ", width=15, font=large_font) gridsize.grid(row=4...
The main task of the code is to generate a Minesweeper game board with user-specified rows, columns, and bomb density. It validates input parameters, destroys existing UI elements, creates a grid of interactive buttons (safe or bomb), initializes game state tracking, and adds UI controls for restarting or quitting the ...
def game_board(): global col_total global row_total global bomb_rate try: col_total = (col_tot.get()) row_total = (row_tot.get()) bomb_rate = (bomb.get()) except: game() return for widget in master.winfo_children(): widget.destroy() if row_tota...
def game(string): gridsize = Label(master, text="Height:", font=small_font) #"Questions" gridsize.grid(row=5, sticky=W+E) gridsize = Label(master, text="Width:", font=small_font, justify='center') gridsize.grid(row=7, sticky=W+E) gridsize = Label(master, text="Bomb percentage:", font=small_font) ...
The main task of the code is to generate a Minesweeper game board with dynamically sized grids based on user inputs for rows, columns, and bomb density. It creates interactive buttons representing safe cells and bombs, binds click events for gameplay mechanics (flagging and revealing cells), and initializes UI elements...
def game_board(): for child in master.winfo_children(): child.destroy() global col_total global row_total global bomb_rate try: col_total = (col_tot.get()) row_total = (row_tot.get()) bomb_rate = (bomb.get()) except: game('Start Game') return ...
def handle_event(self): """ Handles all pygame events. """ for event in pygame.event.get(): # Exit the program if event.type == pygame.QUIT: self.__run = False # Mouse held down to select obstacle Nodes if pygame.mouse.get_pressed()[0]: ...
The main task of the code is to execute a Pygame application's main loop, initializing the library, handling user events, updating game state, and rendering graphics repeatedly until the program exits. The loop runs with a delay to control frame rate, processes input via `handle_event()`, updates game logic via `update...
def main(self): """ Executes main program loop. """ pygame.init() self.__run = True while self.__run: pygame.time.delay(self.__pause_time) self.handle_event() self.draw() self.update() pygame.quit()
def make_training(dataset_without_noise, activation_fun_names_layer_1, no_neurons_in_layer_1, activation_fun_names_layer_2, no_neurons_in_layer_2, val_loss, no_epochs_from_val_loss): if no_neurons_in_layer_2 == 0: no_of_layers = 1 else: no_of_layers = 2 f...
The code systematically evaluates various neural network configurations by iterating over different activation functions and neuron counts for single-layer and two-layer networks. It trains models on the provided dataset, collects validation loss and epochs, computes statistical metrics (average loss, standard deviatio...
def make_model(dataset_without_noise): # activation_fun_names_1 = ["sigmoid", "tanh", "elu", "swish"] activation_fun_names_1 = ["sigmoid", "tanh", "elu", "swish"] no_neurons_in_layer_1 = list(chain( range(3, 10, 1), range(10, 30, 2), range(30, 80, 5), range(80, 180, 10), ...
def _new_round(self): '''Starts a new round (new piece)''' # Generate new bag with the pieces if len(self.bag) == 0: self.bag = list(range(len(Tetris.TETROMINOS))) random.shuffle(self.bag) self.current_piece = self.next_piece self.next_piece = sel...
The `reset` method initializes a Tetris game by clearing the board, resetting the score, shuffling the piece bag, and preparing the next piece. It returns the current game state as a NumPy array, formatted based on the specified mode: raw board, glimpsed state, or derived features (4/12 features). This ensures a fresh ...
def reset(self): '''Resets the game, returning the current state''' self.board = [[0] * Tetris.BOARD_WIDTH for _ in range(Tetris.BOARD_HEIGHT)] self.game_over = False self.bag = list(range(len(Tetris.TETROMINOS))) random.shuffle(self.bag) self.next_piece = self.bag.pop() ...
def _check_collision(self, piece, pos): '''Check if there is a collision between the current piece and the board''' for x, y in piece: x += pos[0] y += pos[1] if x < 0 or x >= Tetris.BOARD_WIDTH or y < 0 or y >= Tetris.BOARD_HEIGHT ...
The code processes a Tetris move by adjusting the piece's position and rotation based on its type, simulates dropping the piece until collision, updates the board, clears completed lines, calculates a reward based on lines cleared, and returns the game state, reward, and game-over status according to the specified mode...
def play(self, move, render=False, render_delay=None): '''Makes a play given a position and a rotation, returning the reward and if the game is over''' action = Tetris.action_map[move] x = action[0] rotation =action[1] if self.current_piece == 0: if ...
def get_edge_weights(apple_locations): edge_weight = {} for i in range(len(apple_locations)): for j in range(i+1,len(apple_locations)): edge_weight[i,j] = math.sqrt((apple_locations[j][0]-apple_locations[i][0])**2 + (apple_locations[j][1]-apple_locations[i][1])**2 + (apple_locations[j][2]-ap...
The code implements Kruskal's algorithm to compute the minimum spanning tree (MST) connecting all apple locations and a starting point. It calculates edge weights between nodes, sorts edges by weight, and uses Union-Find to avoid cycles. The MST is built incrementally, ensuring the starting node is included once. After...
def Kruskals(apple_locations, starting_location): # tracemalloc.start() forest = [] traversed = [] all_nodes = apple_locations all_nodes.append(starting_location) starting_location_index = len(all_nodes) - 1 edge_weight = get_edge_weights(all_nodes) sorted_edges = sort_edge_weights(edge_...
def load_files(data_dir='data'): """ Loads the speech command data directory and returns the files and the labels :param data_dir: path to directory containing audio files :return: filenames, commands """ commands = np.array(tf.io.gfile.listdir(str(data_dir))) not_needed = ['README.md', 'sp...
The function `collect_data` loads and prepares training, validation, and test datasets from specified directories. It splits data into batches, applies caching and prefetching for efficiency, and returns TensorFlow datasets along with command labels for model training and evaluation.
def collect_data(batch_size, data_dir): """ Takes batch size and data directory as input and returns train_ds, test_ds and val_Ds :param batch_size: batch size of train set and val set :param data_dir: :return: train_ds, test_ds, val_ds, commands """ filenames, commands = load_files() tr...
def magicFrame(content): """ make a frame containing magic(an unknown command) this function creates a frame to do some device magic and these frames are used in the preamble and finalizer commands. """ command = bytes([0x84]) msg = command + content return format_frame(msg) def eprint(*a...
The function `magicwrite` performs a timed sequence of three specific data transmissions over a serial interface: first sending a "magic" frame with predefined data, then a write command containing an address and message, followed by a second magic frame. It enforces 70ms delays between transmissions to avoid device ha...
def magicwrite(sio, addr, msg, verbosity=0): """ Perform a magic write This function mimics a particular packet pattern seen in the preamble and finalizer where a write command is surrounded by two magic frames. Timing of these packets is special and sending these too close together causes a hang. ...
def knockFrame(): """ make a frame containing a knock command this function creates a frame that I assume wakes up the device for further commands. """ command = bytes([0x04]) content = bytes([0x03, 0x00, 0x00, 0x00, 0x01]) msg = command + content return format_frame(msg) def eprint(*...
This function sends a predefined "knock" sequence over a serial interface, waits for a specific response (sequence 1 with content 0x80), and retries up to 25 times if unsuccessful. It returns a boolean indicating whether the knock was successfully acknowledged.
def knock(sio, verbosity=0, retries=25): """ Replays the initial knock sequence This sequence and timing is from the CPS software capture. """ knock_worked = False while not knock_worked and retries > 0: sio.write(knockFrame()) if verbosity: eprint(">" + knockFrame().hex()) ...
def knock(sio, verbosity=0, retries=25): """ Replays the initial knock sequence This sequence and timing is from the CPS software capture. """ knock_worked = False while not knock_worked and retries > 0: sio.write(knockFrame()) if verbosity: eprint(">" + knockFrame().hex()) ...
The code initializes hardware by sending predefined serial commands to configure a device. It first checks communication success, then sends 25 magic commands. It fetches a memory address, writes specific byte sequences to control hardware behavior (e.g., blinking LEDs, populating headers), and clears destination areas...
def preamble(sio, verbosity=0 ): """ Replay the preamble """ knock_worked = knock(sio, verbosity) if not knock_worked: eprint("Serial communication failed") return # Begin the preamble for x in range(0, 25): content = bytes([0x03, 0x00, 0x00, 0x00, 0x80]) magicc...
def fetchWord(sio, addr, verbosity=0): pointer = readmem(sio, addr, verbosity) return int.from_bytes(pointer, 'little') def readmem(sio, addr, verbosity=0, retries=25): """ Perform a simple read This is a simple memory reading routine. A read frame is sent and the received frame is decoded and mat...
This function reads a specified memory range from a device, outputting data in 4-byte chunks to stdout. It periodically sends a predefined "magic" command to maintain communication, ensuring the connection remains active by checking elapsed time since the last command.
def readMemRange(sio, begin, end, verbosity=0 ): """ Read a memory range """ # Make a note of the last time we sent a magic command last_magic_write = time.time() magicaddr = fetchWord(sio, 0x81c00270, verbosity) addr = begin while addr < end: data = readmem(sio, addr, verbosity) ...
def draw(self, screen: "curses._CursesWindow") -> None: """draw the curses ui on the screen, handle scroll if needed""" screen.clear() x, y = 1, 1 # start point max_y, max_x = screen.getmaxyx() max_rows = max_y - y # the max rows we can draw lines, current_line = self...
This function handles a curses-based interactive loop for selecting items from a list. It processes keyboard inputs to navigate (up/down), mark selections (in multiselect mode), and return chosen items when Enter is pressed, adhering to minimum selection constraints.
def run_loop( self, screen: "curses._CursesWindow" ) -> Union[List[PICK_RETURN_T], PICK_RETURN_T]: while True: self.draw(screen) c = screen.getch() if c in KEYS_UP: self.move_up() elif c in KEYS_DOWN: self.move_down() ...
def parse_good_player(player_id: str) -> None: player_tournaments = getj(f"{player_id}:results") def data_to_start_time(data): return datetime.strptime(data["info"]["start_time"], "%Y-%m-%dT%H:%M:%S") for tournament_id, tournament_data in sorted( player_tournaments.items(), key=lambda x: d...
The main task of the code is to parse player data from URLs, map player IDs to names, extract relevant information (wins, losses, head-to-head stats, tournament details), and write this data into sheets. It also tracks and records the total parsing time.
def main(): start = time.time() for player_name, player_url in get_player_tags_urls_list(): logger.debug("parsing, player_name=" + player_name) player_id = url_to_id(player_url) ID_TO_NAME[player_id] = player_name parse_good_player(player_id) logger.info("got player " + p...
def Inventory(self): """ Verify all entries, find extra entries, and build up workqueues """ # initialize all states for struct in self.config.getchildren(): for entry in struct.getchildren(): self.states[entry] = False ...
The main task of the code is to execute a workflow that manages inventory operations, installation, decision-making, and cleanup. It sequentially calls methods like Inventory, InstallImportant, Decide, Install, Remove, and ReInventory if modified, while recording timestamps at each stage and updating display states fro...
def Execute(self): """Run all methods.""" self.Inventory() self.times['inventory'] = time.time() self.CondDisplayState('initial') self.InstallImportant() self.Decide() self.Install() self.times['install'] = time.time() self.Remove() self.ti...
def rotate_routine(self, goal: PoseStamped): rospy.logdebug('Rotate routine begin') while not rospy.is_shutdown(): try: transform: tf2_ros.TransformStamped = self.tfBuffer.lookup_transform('base_link', 'map', rospy.Time()) break except Exception as...
The main task of the code is to navigate a robot to a specified goal by rotating to its entrance pose, adjusting the yaw goal tolerance, publishing the entrance pose as a movement goal, waiting for navigation completion, and publishing a navigation status message. It updates ROS parameters, sends goals via MoveBase, an...
def entrance_routine(self, goal: str): self.rotate_routine(self.goals[goal].entrance_pose) self.message_pub.publish(String(data='Navigating to ' + goal)) self.update_move_base('yaw_goal_tolerance', 0.05) self.move_base_goal_pub.publish(self.goals[goal].entrance_pose) rospy.slee...
def rotate_routine(self, goal: PoseStamped): rospy.logdebug('Rotate routine begin') while not rospy.is_shutdown(): try: transform: tf2_ros.TransformStamped = self.tfBuffer.lookup_transform('base_link', 'map', rospy.Time()) break except Exception as...
The function navigates a robot to a specified door's entrance, checks if the door is open using a service request, and proceeds through it if open. If the door is closed, it logs the status and halts. It adjusts navigation parameters, publishes status messages, and uses move_base goals to control movement, ensuring pre...
def inside_routine(self, goal: str): door: Door = self.goals[goal] self.rotate_routine(door.inside_pose) self.message_pub.publish(String(data='Navigating to ' + goal.replace('Inside', 'Entrance') + ' and then through the door if open')) self.update_move_base('yaw_goal_tolerance', 0.05)...
def rotate_routine(self, goal: PoseStamped): rospy.logdebug('Rotate routine begin') while not rospy.is_shutdown(): try: transform: tf2_ros.TransformStamped = self.tfBuffer.lookup_transform('base_link', 'map', rospy.Time()) break except Exception as...
The function navigates a robot to a specified waypoint by rotating towards it, publishing navigation status, adjusting movement parameters, sending the goal pose, and waiting for completion. It retrieves the goal's pose, updates tolerance settings, and triggers motion via MoveBase, ensuring proper alignment and task ex...
def waypoint_routine(self, goal: str): waypoint = self.goals[goal] self.rotate_routine(waypoint.poseStamped) self.message_pub.publish(String(data='Navigating to ' + goal)) self.update_move_base('yaw_goal_tolerance', 6.28) self.move_base_goal_pub.publish(waypoint.poseStamped) ...
def entrance_routine(self, goal: str): self.rotate_routine(self.goals[goal].entrance_pose) self.message_pub.publish(String(data='Navigating to ' + goal)) self.update_move_base('yaw_goal_tolerance', 0.05) self.move_base_goal_pub.publish(self.goals[goal].entrance_pose) rospy.slee...
The function processes a waypoint request by checking if the goal exists, then selects and executes the appropriate navigation routine (entrance, inside, or general waypoint) based on the goal's name, returning a WaypointResponse after handling valid or invalid inputs.
def navigate_to_waypoint(self, msg: WaypointRequest): if msg.data is None or msg.data == '': return WaypointResponse() goal = msg.data if goal not in self.goals.keys(): rospy.logdebug('Goal unknown') return WaypointResponse() if 'Entrance' in goal: ...
def _check_keydown_events(self, event): """Respond to keypresses""" if event.key == pygame.K_UP: self.ship.moving_up = True elif event.key == pygame.K_DOWN: self.ship.moving_down = True elif event.key == pygame.K_q: sys.exit() elif event.key ==...
The main task of the code is to handle user input events in a Pygame application. It checks for window close requests, keyboard key presses/releases, and mouse button clicks. For each event, it triggers corresponding methods: exiting the game on quit, processing key actions, and detecting mouse clicks on the play butto...
def _check_events(self): """Respond to keypresses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) ...
def _check_fleet_edges(self): """Respond appropriately if any chopsticks have reached an edge""" for chopstick in self.chopsticks.sprites(): if chopstick.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """Respond to ship being ...
This method updates the positions of all chopsticks in the fleet by checking fleet edges, updating their movement, detecting collisions between chopsticks and the player's ship, triggering a ship-hit response if collided, and verifying chopstick positions against screen boundaries.
def _update_chopsticks(self): """Update positions of all chopsticks in fleet""" self._check_fleet_edges() self.chopsticks.update() if pygame.sprite.spritecollideany(self.ship, self.chopsticks): self._ship_hit() self._check_chopsticks_side()
def _check_events(self): """Respond to keypresses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) ...
The main task of the code is to start and manage the game's main loop, handling events, updating game elements (ship, bullets, chopsticks) when active, saving the ultimate high score, and maintaining a 60 FPS frame rate through continuous screen updates and clock ticking.
def run_game(self): """Start main loop for game""" while True: self._check_events() if self.game_active: self.ship.update() self._update_bullets() self._update_chopsticks() self.sb.save_ultimate_high_score() ...
def get_column_db(): conn = sqlite3.connect("project_database.db") cursor = conn.cursor() cursor.execute("SELECT name FROM ingredients") rows = cursor.fetchall() first_column = [row[0] for row in rows] cursor.close() conn.close() return first_column def isfloat(value): try: f...
The main task of the code is to create a recipe management system that allows users to view ingredient lists (with or without nutritional data), input recipe details (name, ingredients with quantities, and description), validate user inputs, and generate a JSON output and PDF of the recipe. It uses conditional logic, t...
def main(): #Display Table while True: try: inp = input("Make your recipe here!, to view the ingredients alone, please click 'v' and enter, to view the ingredients with there \ nutrious value plesae click 'x' and enter, otherwise, press ENTER: ") if inp =...
def find_best_split(self, df: pd.DataFrame, target: str): if len(df) <= 2: self.print( 'Impossible to find split, len(df) <= 2\n------------------------------\n') return None if len(set(df[target])) == 1: self.print( 'Impossible to find...
The code fits a decision tree model by first one-hot encoding categorical features, then constructing the tree structure through recursive splitting based on the best features and thresholds, up to a specified maximum depth.
def fit_legacy(self, df: pd.DataFrame, target: str): if self.cat_features is not None: self.encoder = MyOneHotEncoder() enc_cat_features = pd.DataFrame(self.encoder.fit_transform( X=df[self.cat_features]), index=df.index) df = df.join(enc_cat_features) ...
def rand_choice_dep(preset_data, prev=None): if prev is None: return rand_choice(preset_data) elif prev is not None and prev == preset_data: return gen_wallet_address() return preset_data def get_timestamp(): return int(round(time.time() * 1000)) def gen_balance(): return round(rando...
The code generates a response object simulating a transaction history entry by randomly selecting a sender and recipient address from the provided list, adding a timestamp, and assigning a random balance amount.
def gen_history_response_object(address): address_from = rand_choice_dep(address) return { "address_from": address_from, "address_to": rand_choice_dep(address, address_from), "timestamp": get_timestamp(), "amount": gen_balance() }
def feature_transform(self, X): """ Appends a vector of ones for the bias term. Inputs: - X: A numpy array of shape (N, D) consisting of N samples each of dimension D. Returns: - X_transformed: A numpy array of shape (N, D + 1) """ #########...
The code trains a linear regression model using stochastic gradient descent (SGD) on training data, with optional validation. It initializes weights, iteratively samples minibatches, computes loss/grads, updates parameters via SGD, applies learning rate decay, and logs loss and RMSE metrics for training/validation. The...
def train(self, X, y, X_val=None, y_val=None,learning_rate=1e-3, learning_rate_decay=0.95, num_iters=1000, batch_size=200, verbose=False): """ Train Linear Regression using stochastic gradient descent. Inputs: - X: A numpy array of shape (N, D) containing training data; ther...
def poly_feature_transform(self, X, poly_order=1): """ Transforms the input data to match the specified polynomial order. Inputs: - X: A numpy array of shape (N, D) consisting of N samples each of dimension D. - poly_order: Determines the order of the polynomial of ...
The code trains a polynomial linear regression model using stochastic gradient descent (SGD), applying polynomial feature transformation to input data. It initializes weights, iteratively updates them using gradients from mini-batches, and tracks the loss history over iterations. Regularization is applied via a lambda ...
def train(self, X, y, poly_order=1, learning_rate=0.2, lambda_reg=0, num_iters=100, std_dev=1e-2, batch_size=20, verbose=False): """ Train Linear Regression using stochastic gradient descent. Inputs: - X: A numpy array of shape (N, D) containing training data; there are N ...
def omega0(b, t): result = mp.power(mp.power(b, 3) - b + 1, -t) - mp.power(b, -3 * t) assert result >= 0 return result def omega1(b, t): result = mp.power(mp.power(b, 2) - b + 1, -t) - mp.power(b, -2 * t) - omega0(b, t) assert result >= 0 return result def omega2(b, t): result = ( mp...
The function computes a mathematical expression involving gamma functions, logarithms, and omega terms to determine a value based on required_bits, parameters b, and t, returning a float result.
def mvp_fgra_func(required_bits, b, t): sum = ( mp.power(omega0(b, t), 2) / omega0(b, 2 * t) + mp.power(omega1(b, t), 2) / omega1(b, 2 * t) + mp.power(omega2(b, t), 2) / omega2(b, 2 * t) + mp.power(omega3(b, t), 2) / omega3(b, 2 * t) ) return float( required_bits ...
def omega0(b, t): result = mp.power(mp.power(b, 3) - b + 1, -t) - mp.power(b, -3 * t) assert result >= 0 return result def omega1(b, t): result = mp.power(mp.power(b, 2) - b + 1, -t) - mp.power(b, -2 * t) - omega0(b, t) assert result >= 0 return result def omega2(b, t): result = ( mp...
The function `calculate_contribution_coefficients_fgra` computes contribution coefficients using mathematical operations involving the `omega0` to `omega3` functions. It converts input parameters `b` and `t` to high-precision numbers, calculates a sum of squared ratios of these functions, constructs a numpy array of th...
def calculate_contribution_coefficients_fgra(r): assert r.d == 2 b = mp.mpmathify(r.b) t = mp.mpmathify(r.t) sum = ( mp.power(omega0(b, t), 2) / omega0(b, 2 * t) + mp.power(omega1(b, t), 2) / omega1(b, 2 * t) + mp.power(omega2(b, t), 2) / omega2(b, 2 * t) + mp.power(omeg...
def plot_relative_error(ax, relative_error_function, title): bases = numpy.linspace(1.2, 5, 100) ax.set_title(title) ax.set_yscale("log", base=10) ax.set_ylim([1e-8, 1e-1]) ax.set_xlim([1, 5]) ax.set_yticks([1e-8, 1e-6, 1e-4, 1e-2]) ax.set_xlabel(r"$\symBase$") ax.plot( bases...
The main task of the code is to generate and save a comparison chart of maximum relative approximation errors for Fisher information and Shannon entropy. It creates a 1x2 subplot figure, plots error metrics for both concepts, adjusts layout parameters, and exports the visualization as a high-resolution PDF file.
def print_relative_error_charts(): fig, ax = plt.subplots(1, 2, sharex=True, sharey=True) fig.set_size_inches(5, 2) plot_relative_error( ax[0], lambda b, d: calculate_fisher_information_max_relative_error(d=d, b=b), "Fisher information", ) plot_relative_error( ax[1],...
def get_arguments(self): parser = argparse.ArgumentParser() parser.add_argument( "--prompt", type=str, nargs="?", default="a painting of a virus monster playing guitar", help="the prompt to render", ) parser.add_argument( ...
The main task of the code is to edit an image using a pre-trained latent diffusion model (txt2img-large) by loading a configuration, initializing the model on GPU/CPU, processing input images/masks, and generating edited images via DDIM sampling. It handles mask inversion, directory creation, and visualization saving f...
def edit_image(self): self.opt = self.get_arguments() config = OmegaConf.load("configs/latent-diffusion/txt2img-1p4B-eval.yaml") self.device = ( torch.device(f"cuda:{self.opt.gpu_id}") if torch.cuda.is_available() else torch.device("cpu") ) se...