dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def generate_flat_author_list(self, author_list: list) -> list: """ Input: Matrix of authors first name and last name Output: Flat list of authors full name """ if not author_list: return [] author_flat_list = [] for author in author_list: ...
This code processes a JSON file line-by-line, extracting paper metadata, authors, and categories. It inserts authors and categories into a database using helper methods, then inserts the paper data with its associated entities. If the 'full' option is set, it uses a specific filename. The task involves parsing JSON lin...
def handle(self, *args, **options): try: if options["full"]: self.filename = "arxiv-metadata.json" with open(self.filename, "r") as file: for line in file: data = json.loads(line) """ the m2m ent...
def __setHostNameIP(self, ): hostname, IPAddr = getOwnHostIP() self.hostNameLbl.setText(hostname) self.IPLbl.setText(IPAddr) def __configureTables(self, ): # Setting table widths topTW = self.TopTW.horizontalHeader() topTW.setSectionResizeMode(0, QtWidgets.QHeaderView.Re...
This code initializes a GUI application by setting up the user interface, configuring tables, establishing host/IP details, navigating to the home page, connecting signal-slot interactions, enabling system monitoring, and configuring network analyzer components for data processing and analysis.
def __init__(self, parent=None): super().__init__(parent) self.setupUi(self) # Set hostName and IP self.__setHostNameIP() # Configure Tables self.__configureTables() # Set current widget self.__openHomePage() # Connecting signal slots s...
def fetch_latest_admission_notice(): url = "https://daffodilvarsity.edu.bd/admission" return scrape_admission_notice(url) def fetch_varsity_ranking(): url = "https://daffodilvarsity.edu.bd/rankings" return varsity_ranking(url) def predict_class(sentence, model): p = bow(sentence, words, show_details...
The code processes user input to determine if it relates to admission notices or university rankings. If so, it fetches and returns the latest information. Otherwise, it uses a model to predict intent, returns a response if confident, or directs users to a Google Form if uncertain.
def chatbot_response(user_input, intents): # user_input = correct_spelling(user_input) admission_keywords = ["admission notice", "upcoming admission", "next admission", "next semester"] ranking_keywords = ["diu ranking", "varsity ranking", "daffodil ranking", "rank"] if any(keyword in user_input.lower(...
def getEmptyValuesCoords(map): coords = [] for row_index, row in enumerate(map): for index, value in enumerate(row): if value == blank_character: coords.append([row_index, index]) return coords def getValues(empty_value_coords, map_inpt): def getCrossValues(coor...
The main task of the code is to recursively solve a map (likely a puzzle like Sudoku) by identifying empty cells, determining possible values for them, and iteratively updating the map until all cells are filled. It generates visual outputs and prints progress at each step, returning the solved map, its vector represen...
def walk(map): empty_values_coords = getEmptyValuesCoords(map) all_crossValues = getValues(empty_values_coords, map) if '.' in my_flatten(map): make_image(map) print(map, prettyPrintVector(map), "\n") return walk(step(all_crossValues, map)) ...
def get_name(outline_elem): return outline_elem.get("text") def parse_sections(section_elems: list[ET.Element]) -> list[Section]: sections = [] for section_elem in section_elems: name = get_name(section_elem) tasks = parse_tasks(get_children(section_elem)) sections.append(Section(nam...
This function parses an XML file at the given path, detects its encoding, extracts the 'outline' element from the XML structure, retrieves the project name and sections from the outline, and returns a Project object containing these parsed details.
def parse(path: str) -> Project: # Mindomo exports xml declaration with wrong encoding encoding = detect_encoding(path) parser = ET.XMLParser(encoding=encoding) tree = ET.parse(path, parser) project_elem = tree.getroot().find("body/outline") name = get_name(project_elem) sections = parse_s...
def remove_hits(otu): filteredOtu = [] for line in otu: if filter_check(args.filterHitsParam, line[-1]): filteredOtu.append(line) return filteredOtu def check_best_hit(otu): if float(otu[0][4]) >= float(args.topid) and float(otu[0][5]) >= float(args.topcoverage): ...
This function determines the taxonomy of an OTU (Operational Taxonomic Unit) by filtering hits if specified, then writing the result to an output file. It uses either the best hit or Lowest Common Ancestor (LCA) method based on parameters, defaulting to "no identification" if no valid hits are found. The output include...
def determine_taxonomy(otu): if args.filterHitsParam.strip(): otu_filtered = remove_hits(otu) with open(args.output, "a") as output: if otu_filtered: if args.tophit == "yes": bestHit = check_best_hit(otu_filtered) if bestHit: pass ...
def write_header(): """ Write a header line to the output file """ with open(args.output, "a") as output: output.write("#Query\t#lca rank\t#lca taxon\t#kingdom\t#phylum\t#class\t#order\t#family\t#genus\t#species\t#method\n") def linecount(): i = 0 with open(args.input, "r") as f: ...
The code processes BLAST output by grouping hits per OTU (Operational Taxonomic Unit), then determines the Lowest Common Ancestor (LCA) taxonomy for each OTU using the `determine_taxonomy` method. It reads input lines, collects OTU-related hits, and resets tracking variables after processing each OTU to prepare for the...
def lca(): """ This method loops trough the BLAST output and all the hits per otu will be the input for the get_lca method. Every hit is stored in the otuLines variable. """ write_header() lastLineCount = linecount() with open(args.input, "r") as input: otuList = [] otuLines ...
def _check_data(self,x,y): if x.shape[0] != y.shape[0]: raise ValueError('shape of x and y do not match') def err_insample(self): if self.__x.size == 0 or self.__y.size == 0: raise RuntimeError('in-sample data not found') return self.err(self.__x,self.__y) def err(self,x...
This function trains a linear model using the pseudo-inverse (normal equation) method with optional regularization (alpha). It computes weights and bias by solving the regularized normal equation, stores them, and evaluates in-sample error. If validation data is provided, it also reports validation error.
def train_by_pseudo_inverse(self,x, y, alpha=0,validate_data=None): self._check_data(x,y) self.__x=x self.__y=y num_data = x.shape[0] dim_wt = x.shape[1] argu_X = np.hstack((np.ones(num_data).reshape(num_data,1),x)) A_plus = np.dot(np.linalg.inv(np.dot(argu_X....
def _check_data(self,x,y): if x.shape[0] != y.shape[0]: raise ValueError('shape of x and y do not match') def _gd_update(self,x, y ,wt,b,rate,alpha): num_data = x.shape[0] # y_pred y_pred = np.sum(wt * x,axis=1) + b # y_pred - y y_diff = y_pred - y #...
This function trains a linear model using gradient descent to minimize prediction error. It initializes weights/bias, processes data in batches, updates parameters iteratively via _gd_update, and optionally validates performance each epoch. Regularization (alpha) and learning rate (rate) control optimization.
def train_by_gradient_descent(self,x, y, init_wt=np.array([]),init_b=0, rate=0.01, alpha=0,epoch=1000,batch=None, validate_data = None): self._check_data(x,y) if init_wt.size == 0: init_wt = np.zeros(x.shape[1]) self.__x = x self.__y = y ...
def get_versions(file_name, number_of_versions=20): from s3_client import S3_CLIENT bucket = ENV['S3_BUCKET_NAME'] logger.info( f"Retrieving available versions for {file_name} from {bucket}") try: response = S3_CLIENT.list_object_versions( Bucket=bucket, Prefix=...
The main task of the code is to handle backup/restore operations, including logging configuration, S3 file download, data extraction, and conditional restoration of MySQL, MongoDB, and Caddy services based on input parameters. It processes date-based file naming, version listing, and selective exclusion of components v...
def main(exclude, date, version, download, list_versions): loglevel = logging.INFO try: loglevel = getattr(logging, ENV['LOG_LEVEL'].upper()) except KeyError: pass handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(levelname)s %(message)s') ha...
def mysqldump(): user = ENV['MYSQL_ROOT_USERNAME'] password = ENV['MYSQL_ROOT_PASSWORD'] host = ENV['MYSQL_HOST'] port = ENV['MYSQL_PORT'] single_transaction = bool(strtobool(ENV['MYSQL_SINGLE_TRANSACTION'])) outfile = MYSQL_DUMPFILE mysql_databases = ENV.get('MYSQL_DATABASES') if mysql...
The main task of the code is to configure logging, back up specified services (MySQL, MongoDB, Caddy) if not excluded, archive the backups, and optionally upload them to S3. It initializes logging, checks exclusion parameters, executes service-specific dump functions, collects file paths, archives them, and triggers an...
def main(exclude, upload): loglevel = logging.INFO try: loglevel = getattr(logging, ENV['LOG_LEVEL'].upper()) except KeyError: pass handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(levelname)s %(message)s') handler.setFormatter(formatter) ...
def calc_avg_efficiency(chp=None, demand=None, load_following_type=None, ab=None): """ Docstring updated 9/24/2022 Calculates the average CHP electrical and thermal efficiencies using part-load efficiency data. Used in calc_annual_fuel_use_and_costs function Parameters --------- ab: A...
The function calculates annual fuel use (in BTU) and costs (in USD) for a CHP system, considering electrical/thermal load following scenarios. It uses average efficiency, electricity generation data, and net metering status to compute fuel consumption and multiplies by fuel prices to determine costs, returning both met...
def calc_annual_fuel_use_and_costs(chp=None, demand=None, load_following_type=None, ab=None): """ Docstring updated 9/24/2022 Uses average electrical efficiency and average CHP electricity generation to calculate annual fuel use and annual fuel costs. Used in the command_line.py module Parame...
def process_output(self, output, data): if output is not None: self.publish(output,config.PUBLISH_QUEUE_NAME, config.PUBLISH_ROUTE_KEY, config.PUBLISH_QUEUE_EXCHANGE_NAME, config.PUBLISH_QUEUE_EXCHANGE_TYPE) else: error = "transcript was not generated" config.lo...
The main task of the code is to process input data by invoking a service layer method (`DemoService.doSomething()`), convert the result to JSON if non-empty, and pass it to `process_output`. On exceptions, it logs errors, processes error data, and publishes it to an error queue using specified parameters like queue nam...
def process_data(self, data): # only change this method to call the service layer try: output = DemoService.doSomething() if output != "": output = json.dumps(data) else: output = None self.process_output(output, data) ...
def gis_module_to_buildmodel(river_data): optimize_network = river_data["optimize_network"] return { "losses_in_kw": optimize_network["losses_cost_kw"]["losses_in_kw"], "cost_in_kw": optimize_network["losses_cost_kw"]["cost_in_kw"], } def cf_module_to_buildmodel(river_data): river_conver...
The function `mapping_teo` integrates input data, updates it with user inputs, and generates three modules (`platform`, `gis-module`, `cf-module`) using the combined data. It returns these modules in a structured dictionary, enabling downstream processing or modeling tasks.
def mapping_teo(optimize_network_data, convert_sinks_data, convert_sources_data,user_inputs): river_data = { "optimize_network": optimize_network_data, "convert_sink": convert_sinks_data, "convert_source": convert_sources_data} river_data.update(user_inputs) _gis_module_to_buildmo...
def connectToWiFi(): wifi.radio.enabled = False wifi.radio.enabled = True wifi.radio.hostname="TARDIS" wifi.radio.connect(secrets["wifi_ssid"], secrets["wifi_pw"]) def initMqtt(): global mqtt_client broker = ipaddress.IPv4Address(secrets["mqtt_broker_hostname"]) while wifi.radio.ping(b...
The main task of the code is to initialize a system by connecting to WiFi, setting up MQTT communication, preloading an MP3 file into memory to optimize runtime resource usage, and then entering a main loop for continuous operation. The global MP3Decoder is initialized once here to minimize memory overhead during execu...
def main(): global decoder connectToWiFi() initMqtt() decoder = MP3Decoder(open("/sounds/startup.mp3", "rb")) #Opening a MP3Decoder takes up a lot of memory, so we do it here to save the precious KBs during runtime loop()
def operations(self): if self.message.startswith("ENTITIES:"): doc = self.doc_nlp(self.message.replace("ENTITIES:", '')) self.response = [(ent.text, ent.label_) for ent in doc.ents] elif self.message.startswith("POS:"): doc = self.doc_nlp(self.message.replace("POS:",...
This code generates a response based on user input. It checks for a "bye" command to terminate the conversation, otherwise processes the message using bot logic, evaluates emotion, and logs the interaction. If no response is generated, it defaults to a pre-set bot response.
def generate_response(self, text, username): self.message = text self.username = username if "bye" in self.message.lower(): self.response = "Bye" self.emotion = 'None' else: self.operations() self.prompt_for_relation() ...
def store_log(message, response): with open(cwd+"/user/bot/log_ML.txt", "a") as log: log.write(f"User:\t{message}\n") log.write(f"Bot:\t{response}\n") def predict_class(sentence): bow = bag_of_words(sentence) res = model.predict(np.array([bow]))[0] ERROR_THRESHOLD = 0.25 results = [[...
This code processes user messages by performing Named Entity Recognition (NER) or Part-of-Speech (POS) tagging when prefixed with "ENTITIES:" or "POS:", respectively. For other inputs, it predicts intent using a model, retrieves a response from predefined intents, and logs interactions. The function dynamically handles...
def response(message): if message.startswith("ENTITIES:"): doc = doc_nlp(message[9:]) res = f"Here is a list of entities with NER {[(ent.text, spacy.explain(ent.label_)) for ent in doc.ents]}" store_log(message, res) return res if message.startswith("POS:"): doc...
def sendMsg(self, connection, func=None, useData=False, start=None, *args, final=None, hardData=None, returnData=False): ''' The sendMsg function is used to send any number of messages to the client, receiving a response after each message, and then using that response to get data from the database. ...
The main task of the code is to handle client connections for a flag submission server. It authenticates users by receiving their username and password, verifies credentials via `checkUser`, retrieves the user from the database, processes user input, and closes the connection after handling. It includes error handling ...
def handleConnection(self, conn): userContinue = 'True' try: _ = conn.recv(1024).decode()[:-1] # Receives Nothing so that data can be sent to the client claimed, _ = self.sendMsg(conn, self.checkUser, False, 'Welcome to the flag submission server.\nEnter your username and passwor...
def _img_stem(img: Path) -> str: return img.name.removesuffix(".gz").removesuffix(".nii") def _predict_fsl_anat_output(out: Path, basename: str) -> Path: return (out / basename).with_suffix(".anat").absolute() def _precrop(anatdir: Path): """ im=failing outputname=out i90=$( fslstats $im -P 90 )...
This function processes a brain MRI image using FSL's fsl_anat tool to generate anatomical segmentation. It copies the input image to a temporary directory, applies optional preprocessing flags (precrop/strongbias), runs the FSL command, verifies outputs, and copies results to the specified output path, avoiding redund...
def _fslanat( image: Path, out: Path, precrop: bool = False, # noqa: FBT002, FBT001 strongbias: bool = False, # noqa: FBT002, FBT001 ): basename = _img_stem(image) anat = _predict_fsl_anat_output(out, basename) # if the output already exists, we don't want this to run again. # fsl_ana...
def gensym(x): global gensym_num gensym_num = gensym_num + 1 return f'{x}_{gensym_num}' def si_stmt(e: cfun.Stmt) -> List[x86.Instr]: if isinstance(e, cfun.Collect): return [x86.Movq(x86.Reg('r15'), x86.Reg('rdi')), x86.Movq(x86.Int(e.amount), x86.Reg('rsi')), ...
The code translates control flow constructs in a high-level function (e.g., returns, conditionals, jumps, tail calls) into x86 assembly instructions. It handles return statements by storing values in registers and jumping to conclusions, processes sequential execution, implements conditional branches with comparisons, ...
def si_tail(def_name: str, e: cfun.Tail) -> List[x86.Instr]: if isinstance(e, cfun.Return): new_var = gensym('retvar') instrs = si_stmt(cfun.Assign(new_var, e.exp, False)) return instrs + \ [x86.Movq(mk_var(new_var, False), x86.Reg('rax')), ...
def policy_evaluation(self, beta): delta = 1 theta = 1e-5 while delta > theta: delta = 0 for s in range(self.mdp.N_s): belief = np.zeros(self.mdp.N_s) belief[s] = 1 for t in range(self.t_max): # Update th...
The code performs policy iteration for a reinforcement learning agent, alternating between policy evaluation and improvement until convergence or 100 iterations. It uses discount factor 'beta' to compute rewards/costs, prints performance metrics, and tracks the value function's mean. The main task is optimizing the pol...
def run(self, beta): policy_stable = False max_iter = 100 i = 0 while not policy_stable: self.policy_evaluation(beta) policy_stable = self.policy_improvement(beta) print('Reward and cost: ', self.eval_perf(100)) print(np.mean(self.V[:,0,0])...
def watch_power_on(self): if self.pi_driver.is_powered_on() == False: # double check if rig is powered off time.sleep(1) if self.pi_driver.is_powered_on() == False: err_msg = "RIG {rig_name} is powered off. Power on...".format(rig_name=self.rig_conf['name']) ...
The main task of the code is to periodically execute health checks for a system's components (power, Claymore, and pool worker). If any check fails, it increments failure counters, logs the error, and triggers a reboot if the failure threshold is reached. Successful checks reset the failure counter.
def execute_periodic_task(self): try: self.watch_power_on() self.watch_claymore() self.watch_pool_worker() except Exception as e: self.fails_after_reboot += 1 self.fails_after_last_success += 1 logging.exception( "RI...
def heatmap_panel( title: str, metric: str, description=None, label_selectors: list[str] = [], yaxis=yaxis(UNITS.NO_FORMAT), tooltip=Tooltip(shared=True, valueType="individual"), color=heatmap_color(), decimals=1, data_source=DATASOURCE, ) -> Panel: assert metric.endswith( ...
This function generates two visualization panels: a heatmap and a histogram/graph with quantile data. It takes parameters like titles, descriptions, metric names, and label selectors to create panels for monitoring metrics, with options to hide specific data types (count/avg) in the graph. The heatmap uses a bucketed m...
def heatmap_panel_graph_panel_histogram_quantile_pairs( heatmap_title: str, heatmap_description: str, graph_title: str, graph_description: str, yaxis_format: str, metric: str, label_selectors=[], graph_by_labels=[], graph_hides: list[str] = ["count"], ) -> list[Panel]: hide_count...
def is_jemalloc_enabled(features): return not features or "jemalloc" in features def pr(s): if sys.stdout.isatty(): sys.stdout.write("\x1b[2K\r" + s) sys.stdout.flush() else: print(s.strip()) def check_jemalloc(executable): p = os.popen("readelf -s " + executable) found = set...
The code checks if jemalloc is enabled, then processes input JSON lines to validate binaries against jemalloc and OpenSSL requirements, skipping whitelisted executables. It measures and reports execution time.
def check_tests(features): if not is_jemalloc_enabled(features): print("jemalloc not enabled, skip check!") return else: print("Checking bins for jemalloc") start = time.time() for line in sys.stdin.readlines(): if not line.startswith('{'): continue d...
def ensure_link(args, require_static, libs): p = os.popen("uname") if "Linux" not in p.readline(): return for bin in args: p = os.popen("ldd " + bin) requires = set(l.split()[0] for l in p.readlines()) for lib in libs: if any(lib in r for r in requires): ...
The code checks if specified features (jemalloc, SSE4.2, OpenSSL linking) are enabled in a release build and verifies their presence in binaries. It ensures static linking of SYS_LIB, identifies enabled features, and validates each binary against these features. If features are disabled, it skips checks. For enabled fe...
def check_release(enabled_features, args): # Ensure statically link SYS_LIB. ensure_link(args, True, SYS_LIB) checked_features = [] if is_jemalloc_enabled(enabled_features): checked_features.append("jemalloc") if is_sse_enabled(enabled_features): checked_features.append("SSE4.2") ...
def is_bot_left_corner(floor_coords, all_floor_coords): """ Determine if a tuple representing (x,y) coordinates of a floor cell is a bottom left corner in the Warehouse. For example: # \n #X \n ###\n @param floor_coords: A tuple representing (x,y) coordinates of a ...
The function `is_corner` checks if a given floor cell's coordinates (`floor_coords`) represent a corner in a warehouse. It evaluates whether the cell is a bottom-left, bottom-right, top-right, top-left, or "caved" corner by calling respective helper functions. The result is `True` if any of these conditions are met, in...
def is_corner(floor_coords, all_floor_coords): """ Determine if a tuple representing (x,y) coordinates of a floor cell is a corner in the Warehouse. @param floor_coords: A tuple representing (x,y) coordinates of a floor cell in the Warehouse @param all_floor_coords: A list of (x, y...
def get_floor_cells(floor): """ Returns the set of (x, y) tuples which contains pairs of coordinates of all internal floor cells to a warehouse using a modified version of Graph BFS @param floor: A Floor object (inherits search.Problem), representing the subject to this search problem. @re...
The function identifies taboo cells in a warehouse by applying two rules: (1) corner cells that are not targets are taboo, and (2) cells between two aligned corners along a wall are taboo if none are targets or blocked by walls. It returns a set of (x, y) coordinates representing all such taboo cells.
def taboo_cells_coords(warehouse): """ Returns the set of (x, y) tuples which contains pairs of coordinates of all taboo cells in the Warehouse object specified. Use only the following rules to determine the taboo cells; Rule 1: if a cell is a corner and not a target, then it is a taboo cell. ...
def get_floor_cells(floor): """ Returns the set of (x, y) tuples which contains pairs of coordinates of all internal floor cells to a warehouse using a modified version of Graph BFS @param floor: A Floor object (inherits search.Problem), representing the subject to this search problem. @re...
The code identifies "taboo cells" in a warehouse—cells where pushing a box would make the puzzle unsolvable. It applies two rules: (1) corners not marked as targets are taboo, and (2) cells between aligned corners along walls are taboo if none are targets. The function ignores boxes, workers, and targets, marking walls...
def taboo_cells(warehouse): """ Identify the taboo cells of a warehouse. A "taboo cell" is by definition a cell inside a warehouse such that whenever a box get pushed on such a cell then the puzzle becomes unsolvable. Cells outside the warehouse are not taboo. It is a fail to tag an outside cel...
def generic_grad(f, gf, lsearch, x0, eps): xk = x0 xk_1 = xk - lsearch(f, xk, gf(xk)) * gf(xk) fs, gs, ts = [f(xk)], [np.linalg.norm(gf(xk))], [time.time()] while np.abs(f(xk) - f(xk_1)) > eps: xk = xk_1 xk_1 = xk - lsearch(f, xk, gf(xk)) * gf(xk) fs.append(f(xk)) gs.appe...
The code compares the convergence of different gradient descent methods (constant step, exact quadratic, and backtracking) on a specific optimization problem. It calculates the objective function values and gradient norms over iterations, plotting them on log scales to analyze performance. The matrix A defines the prob...
def q1(): A = np.array([[100, 2, 3, 4, 5], [6, 100, 8, 9, 10], [11, 12, 100, 14, 15], [16, 17, 18, 100, 20], [21, 22, 23, 24, 100]]) s = 1 / (2 * np.max(np.linalg.eigvals(np.dot(A.T, A)))) x0 = np.array([1, 1, 1, 1, 1]) eps = 1 / np...
def generic_grad(f, gf, lsearch, x0, eps): xk = x0 xk_1 = xk - lsearch(f, xk, gf(xk)) * gf(xk) fs, gs, ts = [f(xk)], [np.linalg.norm(gf(xk))], [time.time()] while np.abs(f(xk) - f(xk_1)) > eps: xk = xk_1 xk_1 = xk - lsearch(f, xk, gf(xk)) * gf(xk) fs.append(f(xk)) gs.appe...
The code compares gradient descent results with and without noise by plotting their convergence rates on a log-log scale. It computes gradients using `generic_grad` (noise-free) and `generic_grad_noise` (with Gaussian noise, parameters `mu`, `sigma`), then visualizes the iterates' progress. The function returns the opt...
def ex3(mu, sigma, x0, epsilon): x0 = np.array(x0) res = generic_grad(f_q3, df_q3, const_step(1 / 10), x0, epsilon) res_noise = generic_grad_noise(f_q3, df_q3, const_step(1 / 10), x0, epsilon, mu, sigma) plt.loglog(np.arange(len(res[1])), res[1], label="res") plt.loglog(np.arange(len(res_noise[1]))...
def q3_a(): plt.figure(figsize=(10, 10)).suptitle('generic_grad', fontsize=16) ax = plt.subplot(3, 2, 1) plt.imshow(original_x.reshape(dimen, dimen), cmap='gray') ax.set_title(f'Original image') ax = plt.subplot(3, 2, 2) plt.imshow(b.reshape(dimen, dimen), cmap='gray') ax.set_title(f'Origi...
The main task of the code is to execute four functions—q3_a(), q3_b(), q3_d_1(), and q3_d_2()—sequentially within the main() function. This suggests the code is structured to address multiple subtasks or components of a larger problem, likely related to data processing, analysis, or problem-solving steps, as indicated ...
def main(): q3_a() q3_b() q3_d_1() q3_d_2()
def ex1(A, x): if not is_valid_input(A=A, x=x): return n = A.shape[0] X = np.array([x, ] * n).T i = np.arange(1, n + 1) B = np.add(A, np.multiply(X, i)).T np.fill_diagonal(B, 0) return B def ex2(A, B, n, b): if not is_valid_input(A=A, B=B, x=b): return """ Create P ""...
The code executes three tasks: (1) Calls `ex1` with matrix `A` and vector `x` to compute a result, (2) Constructs matrices `A_2`, `B_2` and vector `b_2`, then calls `ex2` with them, and (3) Passes matrix `X` to `ex5` to process and print outputs. Each function likely performs specific matrix operations or solves system...
def main(): A = np.array([[1, -2, 3, 7], [4, 5, 6, 7], [-7, 8, 9, 7], [10, -11, 12, 7]]) x = np.array([17, 6, -3, 0]) print('EX1: ') print(ex1(A, x)) n_2, m_2 = 4, 3 A_2 = np.arange(1, m_2 * 3 + 1).reshape(3, 3) B_2 = A_2 + (np.ones(m_2 * 3, dtype=int) * 2).reshape(3, 3) b_2 = np.arange...
def q1(): A = np.array([[100, 2, 3, 4, 5], [6, 100, 8, 9, 10], [11, 12, 100, 14, 15], [16, 17, 18, 100, 20], [21, 22, 23, 24, 100]]) s = 1 / (2 * np.max(np.linalg.eigvals(np.dot(A.T, A)))) x0 = np.array([1, 1, 1, 1, 1]) eps = 1 / np...
The main task of the code is to execute three functions—q1(), q2(), and q3()—in sequence within the main() function. This structure organizes the program's workflow, ensuring each function is called and executed one after the other. The purpose of main() is to orchestrate these operations, likely performing a series of...
def main(): q1() q2() q3()
def wait(): time.sleep(3) def check_box(): try: time.sleep(3) driver.find_element('xpath', '/html/body/ui-view/app-root/div[3]/landlord-dashboard/div/div/div/div[2]/ui-view-ng-upgrade/ui-view/app/div/ng-component/div/file-manager-list/panel/panel-body/file-manager-tab...
The code automates downloading data from a webpage by interacting with Chrome's user profile. It waits for elements, selects checkboxes, navigates menus, triggers the download button, pauses for completion, and handles pagination across multiple pages.
def download(): # use when chrome user profile is available wait() check_box() action_menu() download_button() long_wait() pagination(page_no)
def is_game_over(self): return self.is_player_in_checkmate(self.player_color_turn, self.board) def is_player_in_check(self, player_color: str, board: Board): opponent_color = self.get_opponent_color(player_color) player_turn_king = self.piece_king_white if player_color == Colors.WHITE else self....
This function manages the game loop by repeatedly checking if the game is over, displaying the current board state, informing the player of their turn and check status, executing their move, and switching turns until the game concludes.
def game_turns_loop(self): while(not self.is_game_over()): self.user_input.say_drawn_board(self.board) if self.is_player_in_check(player_color=self.player_color_turn, board=self.board): self.user_input.say_player_is_in_check(player_color=self.player_color_turn) ...
def generate_default_board(self) -> Board: board = Board() board_num_lines = len(board.squares) self.piece_king_white = King(color=Colors.WHITE) self.piece_king_black = King(color=Colors.BLACK) board.set_squares( pieces_and_positions=[ [Tower(color=Col...
The code executes a game loop by initializing a board, setting the first player's turn, and repeatedly processing game actions until a winner is determined. It then announces the winner's color, asks the user if they want to play again, and recursively restarts the game if confirmed.
def execute(self): self.board = self.generate_default_board() self.set_players_turn(Colors.WHITE) self.game_turns_loop() self.user_input.say_color_wins(winner_color=self.get_opponent_color(self.player_color_turn)) if self.user_input.ask_for_play_again(): return self.e...
def roll_dice(self): return (random.randint(1,6), random.randint(1,6)) def game_over(self): for p in self.players: if len(self.off_board[p]) == 15 and self.pieces_left[p] == 0: return True def find_moves(self, roll, player): moves = [] # Probably can get rid o...
The code simulates a backgammon game by rolling dice to determine the first player, alternating turns, selecting optimal moves, tracking game states, and returning the winner and collected states once the game ends.
def play(self): # print("White player rolled {}, Black player rolled {}".format(p1Roll[0] + p1Roll[1], p2Roll[0] + p2Roll[1])) p1Roll = (0,0) p2Roll = (0,0) while sum(p1Roll) == sum(p2Roll): p1Roll = self.roll_dice() p2Roll = self.roll_dice() if ...
def get_stats(x, y, nrmse = False): if type(x) == xr.DataArray: x = x.values.ravel() if type(y) == xr.DataArray: y = y.values.ravel() if type(x) == list: x = np.array(x) if type(y) == list: y = np.array(y) idx = (~np.isnan(x)) & (~np.isnan(y)) x, y = x[idx], y[idx] if len(x) < 4 or len(y) < ...
The code generates random datasets under different conditions, optimizes parameters (A, B, C) to model snow depth, calculates statistical metrics (R, RMSE, Fisher-Z), and saves results in CSV files. It processes input data, iterates through scenarios, and compares optimized vs. random model outputs for validation.
def make_random_results(out_dir, A, B, C, fp): print(fp) stem = fp.stem # ds, stem = ds_pair full_ds = xr.open_dataset(fp) full_ds = full_ds.load() # full_ds.where(full_ds['lidar-sd'] > 2) site_name = stem.replace('_', ' ').replace('Frasier', 'Fraser').split('-')[0] im_date = pd.to_date...
def findNearPipes(coordinate): i, j = coordinate possible = [(i-1, j), (i+1, j), (i, j+1), (i, j-1)] finals = [] for possible_pipe in possible: if traverse(coordinate, possible_pipe) != None: finals.append(possible_pipe) return finals def getStartSide(start, pipe): if start[1] < pipe[1]: # right return "...
The main task of the code is to traverse a grid of pipes starting from a given position, identify valid paths by checking neighboring cells, handle special cases like the 'S' character (which requires side-based translation), and return the list of edges (coordinates) along the path. It modifies the grid in-place when ...
def getEdges(start): global lines possible_paths = findNearPipes(start) # list of (i,j) print("start: ", start) print('*******************') for pipe in possible_paths: print('pipe', pipe) # get start side start_side = getStartSide(start, pipe) # try this pipe # print("trying pipe: ", pipe) prev = st...
def findStart(): for i, line in enumerate(lines): for j, char in enumerate(line): if char == "S": return (i,j) def findNearPipes(coordinate): i, j = coordinate possible = [(i-1, j), (i+1, j), (i, j+1), (i, j-1)] finals = [] for possible_pipe in possible: if traverse(coordinate, possible_pipe) != None: ...
The code finds the shortest path in a grid of pipes starting from a determined point, exploring possible directions. It traverses the grid, counting steps until reaching 'S', and returns the ceiling of half the step count, likely accounting for bidirectional movement.
def run(): start = findStart() # (i, j) possible_paths = findNearPipes(start) # list of (i,j) print("start: ", start) print('*******************') # print(possible_paths) for pipe in possible_paths: print('pipe', pipe) # try this pipe # print("trying pipe: ", pipe) prev = start cur = pipe count = 1 ...
def findStart(): for i, line in enumerate(lines): for j, char in enumerate(line): if char == "S": return (i,j) def getEdges(start): global lines possible_paths = findNearPipes(start) # list of (i,j) print("start: ", start) print('*******************') for pipe in possible_paths: print('pipe', pipe) ...
The code's main task is to count the number of enclosed regions in a grid. It starts by locating an initial position, retrieves adjacent edges, and iteratively explores neighboring cells to identify enclosed areas. The `exploreNeigbors` function likely marks these regions, and the final count is returned as the length ...
def run(): start = findStart() # (i, j) edges = getEdges(start) print(lines) # now loop back over edges and explore inside = [] for coordinate in edges: # explore the 4 neighbors exploreNeigbors(coordinate, edges, inside) return len(inside)
def stack(): print("==============") if len(opstack) < 1: print("The opstack is empty.") else: for op in list(reversed(opstack)): if isArray(op): print(op[1]) else: print(op) print("==============") if len(dictstack) == 0: ...
This function interprets PostScript tokens in a given scope (static/dynamic), processing operands, operators, and functions. It pushes names/variables to the operand stack, executes operators via a dictionary, handles function calls by pushing a new dictionary context, and interprets nested code arrays recursively. Deb...
def interpretSPS(tokenL,scope): for c in tokenL: #debug if isDebug: print("---------------------") #debug print("=> {}".format(c)) stack() print("---------------------") #debug #/debug if type(c) is str: if('/' == c[0]): #c ...
def opPop(): # opPop should return the popped value. # The pop() function should call opPop to pop the top value from the opstack, but it will ignore the popped value. if len(opstack) != 0: op = opstack.pop() while str == type(op): if '/' is not op[0]: if("static"...
The function `psFor` implements a loop operation similar to PostScript's `for` command. It pops four operands from the opstack: a code block, final value, increment, and initial value. It verifies these operands are valid (numbers for init, incr, final; a list for code). If the increment is non-negative, it iterates fr...
def psFor(): if len(opstack) < 4: raise Exception("Error: Cannot perform `for` operation. Insufficient operands on the opstack: Expected 3, but found {}.".format(len(opstack))) code = opPop() final = opPop() incr = opPop() init = opPop() if not isNumber(init): raise Exception("Er...
def clearBoth(): opstack[:] = [] dictstack[:] = [] def initBuiltInOps(): dictPush({},0) operators['add'] = add operators['sub'] = sub operators['mul'] = mul operators['eq'] = eq operators['lt'] = lt operators['gt'] = gt operators['length'] = length operators['get'] = get ...
The code defines an interpreter function that processes a string `s` within a specified `scope`. It initializes the environment, tokenizes and parses the input, then executes the parsed tokens using `interpretSPS`, leveraging built-in operations and scope context for evaluation.
def interpreter(s, scope): global scopetype scopetype = scope clearBoth() initBuiltInOps() tokenL = parse(tokenize(s)) interpretSPS(tokenL,scope)
def compute_conceptors(self) -> None: """ Computes conceptors for all given signals using formula XX ... :return: None. """ if self.W is None: self.load_patterns() for r in self.create_r_i(): scaled_id = (self.alpha**-2)*np.identity(self.n) ...
The main task of the code is to regenerate a specific signal (given by its index) using a neural network with a conceptor. It initializes the network state, iterates through the signal's values, runs the network with the conceptor for each step, and accumulates the output. Finally, it returns the regenerated signal as ...
def reg_sig_with_conc(self, idx: int): """ Runs the network with a conceptor and loaded matrix for the duration of the signal. Tries to regenerate the original signal whose index was given. :param idx: The index of the signal that should be regenerated. :return: Array with the r...
def regenerate_signals(self): """ Regenerates all signals using W_out and recorded state matricies. :return: List containing all signals to the original signal. """ if self.state_response is None: self.save_state_response() # To save the signals reg_...
The code visualizes and compares conceptor-based signal processing results, including regenerated signals, singular values, neuron responses, and function approximations. It plots outputs against original signals, evaluates NRMSE, and contrasts conceptor-loaded/unloaded models, singular value energy, and tanh function ...
def vis_conceptor(self): res_2 = self.regenerate_signals() rs = self.create_r_i() # Conceptors output vs original signal ax = plt.subplot(2, 2, 1) pacing = self.L space = self.space y1 = res_2[1] y2 = self.sig[1] y3 = self.reg_sig_with_conc(1) ...
def spawn_food(self): self.all_food = [FoodToken(self.get_random_coord(), e, self) for e in self.current_epoch.energy_list] def make_agents(self, pop=None): if pop is not None: if isinstance(pop, str): pop = pickle.load(open(pop, 'rb')) self.global_id = pop[0].mod...
This code initializes a simulation environment for evolving agents using NEAT (NeuroEvolution of Augmented Topologies). It sets up parameters like population size, data collection, environment dimensions, and directories for saving models. It loads or generates agent populations, configures neural network settings, spa...
def __init__( self, initial_population=100, epochs=None, size=None, name_run='sim', pop=None, # either a path or an array of pop server_model=None, reset_on_extinction=False, collect_data=False, **kw...
def get_grads(im): """ return the x and y gradients. """ [H, W] = im.shape dx, dy = np.zeros((H, W), 'float32'), np.zeros((H, W), 'float32') j, k = np.atleast_2d(np.arange(0, H - 1)).T, np.arange(0, W - 1) dx[j, k] = im[j, k + 1] - im[j, k] dy[j, k] = im[j + 1, k] - im[j, k] return d...
The function combines two images using Poisson blending, merging gradients from the top image with the background image based on the specified mode ('max', 'src', or 'blend'). It scales gradients, mixes them to preserve edges, solves the Poisson equation for each color channel, and returns the blended result. Recursive...
def blit_images(im_top, im_back, scale_grad=1.0, mode='max'): """ combine images using poission editing. IM_TOP and IM_BACK should be of the same size. """ assert np.all(im_top.shape == im_back.shape) im_top = im_top.copy().astype('float32') im_back = im_back.copy().astype('float32') im...
def init_infinite_impossible_box(): # These boxes are impossible, because the mins are larger than the maxs. my_box = {'xmin': float("inf"), 'xmax': float("-inf"), 'ymin': float("inf"), 'ymax': float("-inf"), 'region_size' : 0, 'valid': False} return( my_box ) def backward_optimization( model, layer_name, f...
The function performs backward optimization for each feature in a specified neural network layer to determine the Effective Receptive Field (ERF). It computes optimal inputs that maximize feature activation, tracks spatial boundaries of ERF via bounding boxes, and generates visualizations of optimized inputs. The ERF b...
def calc_and_plot_backward_optimization_results_one_layer( model, i_layer, ny, nx, nchans, n_iterations, grad_step_size, save_every_n_th_figure_in_history, i_loss_function, CLIP_OPTIMAL_INPUT, zmin, zmax, my_lambda, start_image_neutral_value, start_image_noise_level, start_image_REMOVE_NEGATIVE_VALUES, buffer_in_pixels...
def find_minimal_bounding_box_in_multi_channel_image ( this_MC_image ): n_chans = this_MC_image.shape[-1] # last dimension is # of channels # Initialize box to keep track of overall min and max coordinates my_box = init_infinite_impossible_box() for i_chan in range( n_chans ): this_i...
This function visualizes the optimization history of a backward optimization process by generating a multi-channel image grid showing iterative changes in input data. It identifies the region of interest (ERF) where the final result differs from the initial input, adds a buffer around this area, and plots each optimiza...
def plot_backward_optimization_history( BO_start_input, BO_final_result, BO_result_history, BO_index_history, ny, nx, nchans, i_layer, i_feature, buffer_in_pixels, my_plot_filename ): # Plot preparation: find relevant area in input image - this is an estimate of ERF. ## Find min/max x-/y-coordinate for which o...
def get_goals_list(s: UserStatus, *args): """ Get a list of available goals Usage: /goals [all] [any] [todo] [active] [done] [low] [normal] [high] [critical] * If a category/board is selected, only it's goals are displayed, else all available. * Status selection: 'any' for all statuses (todo and active by default) ...
The function selects a user-specified goal, validates its existence, retrieves its details, and returns formatted info including title, description, due date, status, priority, and board role. If no goal is selected, it lists available goals. It also handles category selection if unspecified, updating the board and cat...
def select_goal(s: UserStatus, goal): """ Select a goal and/or get selected goal info Usage: /goal [num] """ if goal: if goal not in s.present_goals: return 'Goal number unknown, please use an existing one\\.\n' + get_goals_list(s) s.goal = get_goal_details(s, s.present_goals[go...
def show_board(self): print("-" * 13) print("| " + self.cells[0].value + " | " + self.cells[1].value + " | " + self.cells[2].value + " |") print("-" * 13) print("| " + self.cells[3].value + " | " + self.cells[4].value + " | " + self...
The main task of the code is to launch a game by prompting the user to select a mode (player vs computer, player vs player, or computer vs computer), display the game board, and direct execution to the corresponding game mode method based on the input.
def start_game(self): print('Please, choose a game mod: \n' 'Enter 1 if you want to play against computer;\n' 'Enter 2 if you want to play against another player.\n' 'Enter any other symbols if you want ' 'to watch a game computer against computer;\n') ...
def extract_stream_image(self, pdf_object, obj_num): """ extract image from pdf object :param pdf_object: the pdf object containing the image :param obj_num: the number of the object with image in it :return: """ self.save_image_in_temp_pdf(pdf_object) try...
The main task of the code is to analyze PDF objects to identify and extract content from image streams and FlateDecoded objects, then save the processed document. It parses PDF content, checks for image and compressed data streams, extracts relevant data using specific handlers, and writes the output if file separation...
def extract_content(self): """ Loop through pdf objects to find objects with interesting content :return: """ pdf_objects = pdf_parsers.parse_to_objects(self.file_content) for obj_num in pdf_objects: obj = pdf_objects[obj_num] if (re.search(rb"/Sub...
def load_metadata_from_safetensors(model: str) -> dict: if not model.endswith(".safetensors"): return {} with safetensors.safe_open(model, framework="pt") as f: metadata = f.metadata() return metadata if metadata else {} def build_metadata(state_dict: Optional[dict], **kwargs) -> dict: m...
The code initializes and processes metadata for a machine learning model by loading a checkpoint, merging provided metadata arguments into existing metadata, optionally calculating a hash, and saving the updated model with metadata. It handles timestamp settings, metadata construction, hash generation, and model output...
def initialize_and_process_metadata(args): print("Initializing metadata builder...") if args.timestamp is None: args.timestamp = time.time() print(f"Loading checkpoint from: {args.ckpt}...") state_dict = load_file(args.ckpt) print("Checkpoint loaded successfully.") existing_metadata =...
def _entropy(self, ids): if len(ids) <= 0: return 0 freq = list(itemgetter(*ids)(self.target)) freq = pd.Series(freq) freq = freq.value_counts() return entropy(freq) def _isSameClass(self,node): ids=node.ids if(len(ids)==0): return False ...
This code trains a decision tree classifier by recursively splitting nodes based on entropy and depth constraints. It initializes a root node, processes nodes in a queue, and splits them into children if they meet criteria (depth < max_depth or entropy > min_gain). Nodes are labeled as leaves if they can't be split fur...
def fit(self): self.Ntrain = self.data.count()[0] # 14 ids = range(self.Ntrain) # range(0 14) (0 <1000) self.root = TreeNode(ids=ids, entropy=self._entropy( ids), depth=0,arrAttr=self.arrAttr) # entropy=0.9402859586706311 queue = [self.root] # len=1 [1,2,3,46,"str",Tree] ...
def extract_basic_res_line(self, line): if self.base_res_line == None and "micros/op" in line and "ops/sec" in line: self.base_res_line = line def extract_delay_percentiles_line(self, line): if self.delay_percentiles_line == None and line.startswith("Percentiles: P50"): self.dela...
The code parses each line to extract basic response data and delay percentiles, storing results in instance variables. If a 'res' object is provided, it aggregates extracted data into 'res' using put_all_res() for both basic results and percentiles.
def parse_all(self, res=None): self.base_res_line = None self.delay_percentiles_line = None for line in self.lines: self.extract_basic_res_line(line) self.extract_delay_percentiles_line(line) if res != None: res.put_all_res(self.get_basic_res()) ...
def fillseq(self): return self.run_db_bench(benchmarks="fillseq", use_existing_db=False) def readseq(self): return self.run_db_bench(benchmarks="readseq") def overwrite(self): return self.run_db_bench(benchmarks="overwrite") def readrandom(self): return self.run_db_bench(benchmarks="read...
The `benchmark_all` method executes a series of benchmark tests to evaluate performance metrics of a storage system or database. It sequentially performs fill, read, overwrite, random read, and concurrent read/write operations to assess sequential and random access efficiency, data modification speed, and concurrency h...
def benchmark_all(self): self.fillseq() self.readseq() self.overwrite() self.readrandom() self.readwhilewriting()
def intersect(s1, s2): s1 = set(s1.split()) s2 = set(split for sent in s2 for split in sent.split()) return len(s1 & s2) > 0 def levenshtein_check(keyword, k_list, threshold=1): """ Checks a keyword against a list of keywords, returning true if the keyword is at a Levenshtein distance of less o...
The function `true_positive_check` determines if a keyword is a true positive by verifying its presence in reference labels and absence in predicted keywords, using a specified matching method (`strict`, `intersect`, `levenshtein`, or `spacy`). It ensures the keyword is relevant (present in labels) and not a repetition...
def true_positive_check(keyword, labels, predictions, match_type): """ This function handles the main check for whether a found keyphrase is a true positive, by checking whether (1) it is relevant, and (2) it is not a repetition. :param keyword: The keyword that is being evaluated. :param labels: Th...
def scan_face(self, index): print("Scanning face", index) if self.flipper.position > 35: self.push_flipper_away() i = 1 self.put_color_sensor_edge() if index == 1: self.calibrate_rgb() self.wait_rotate() self.rotate.stop(bra...
This code scans all six faces of a Rubik's Cube by systematically rotating and flipping the cube, captures color data, saves it as JSON, and uses it to compute solving steps via a resolver function.
def scan(self): self.scan_face(1) self.flip() self.scan_face(2) self.flip() self.scan_face(3) self.rotate_cube(-1, 1) self.flip() self.scan_face(4) self.rotate_cube(1, 1) self.flip() self.scan_face(5) self.flip() ...
def calibrate_rgb(self): self.put_color_sensor_edge(8) self.white = self.rgb.read_rgb(calibrate=True) print("White: ", self.white) def push_flipper_away(self): self.flipper.start_move(direction=-1, speed=30) sleep(1) self.flipper.stop(brake=True) self.flipper.pos...
The code scans a cube face by rotating it, capturing RGB color data at specific positions (0 to 8) using a color sensor. It calibrates, moves the sensor to middle/corners/edges, reads colors during rotation, stores results in a dictionary, and validates completion. If fewer than 9 positions are scanned, it raises an er...
def scan_face(self, index): if index == 1: self.calibrate_rgb() print("Scanning face", index) if self.flipper.position > 35: self.push_flipper_away() self.put_color_sensor_middle() self.colors[str(self.scan_order[self.k]) ] = self.rg...
def scan_face(self, index): if index == 1: self.calibrate_rgb() print("Scanning face", index) if self.flipper.position > 35: self.push_flipper_away() self.put_color_sensor_middle() self.colors[str(self.scan_order[self.k]) ] = self.rg...
The main task of the code is to scan all six faces of a Rubik's Cube by systematically rotating and flipping the cube, capture its color configuration, save the data in a JSON file, and return a resolved cube string representing the scanned state.
def scan(self): self.scan_face(1) self.flip() self.scan_face(2) self.flip() self.scan_face(3) self.rotate_cube(-1, 1) self.flip() self.scan_face(4) self.rotate_cube(1, 1) self.flip() self.scan_face(5) self.flip() ...
def general_attack_on_reward(self, M_0, pi_t, epsilon, p): n_states, n_action, R_T, P = reward_attack_general(M_0, pi_t, epsilon, p) return (n_states, n_action, R_T, P), True def non_target_attack_on_reward(self, M_0, pi_t, epsilon, p): n_states, n_action, R_T, P = reward_attack_nontargetonly(M_...
This function determines the type of attack strategy based on `self.teacher_type` and applies the corresponding method to modify the initial matrix `M_0`. It returns the altered matrix after processing through either reward-based or dynamics-based attacks, which may be targeted or non-targeted, using parameters like ep...
def get_target_M(self, M_0): if self.teacher_type == "general_attack_on_reward": return self.general_attack_on_reward( M_0, self.target_pi, self.epsilon, self.p) elif self.teacher_type == "non_target_attack_on_reward": return self.non_target_attack_on_reward(M_0, self.target_pi,...
def init_layers(self, input_size, output_size): hidden_layers = [] for i in range(self.hidden_count): if i == 0: layer = Layer(self.hidden_size, input_size) else: layer = Layer(self.hidden_size, self.hidden_size) hidden_layers.append(la...
The code trains a neural network model using batch gradient descent over specified epochs. It initializes layers, performs forward/backward propagation, updates parameters, and evaluates training/validation accuracy/loss per epoch. Results are stored in lists and returned for monitoring performance.
def fit( self, epochs, batch_size, train_data, train_labels, valid_data, valid_labels ): """A method to train the model. Args: epochs (int): number of epochs. batch_size (int): size of the batch. train_data (np.array): training data. train_lab...
def generate_fine_stains_texture(self, oxsize, oysize): """Generate a fine stains similar texture using combination of normal distribution noise and FFT. :param oxsize: The width of the output texture image. :type oxsize: int :param oysize: The height of the output texture image. ...
The main task of the code is to generate a severe stains texture by combining fine and rough stains textures. It merges the two textures, removes high-frequency components, normalizes the result, applies a median blur for smoothing, and resizes the output to the specified dimensions, producing a final uint8 image suita...
def generate_severe_stains_texture(self, oxsize, oysize): """Generate severe stains texture using combination of fine and rough stains texture. :param oxsize: The width of the output texture image. :type oxsize: int :param oysize: The height of the output texture image. :type oy...
def get_customize_path() -> Tuple[Path, bool]: """ When using venv, site.ENABLE_USER_SITE is False. When using virtual environments, the effort is to isolate the activities within one virtual environment per Python system from other virtual environments. Were the user site enabled within a virtual e...
The main task of the code is to inject and verify the SysPathSleuth into Python's sitecustomize module to wrap sys.path, ensuring proper path management. It handles reinstalling, patching, and validating the customization, raising errors if sys.path isn't correctly wrapped by SysPathSleuth.
def inject_sleuth(syspath_sleuth_path: Optional[Path] = None): customize_path, is_user_path = get_customize_path() if customize_path and customize_path.exists(): name, _ = get_name_and_relative_path(customize_path, syspath_sleuth_path) sleuth_logger.warning( "Reinstalling %s in %s ...
def getAllSuits(self): for card in self.handOfThree: self.sortedSuits.append(card.suit) #Not needed for logic, just sorting suit to be self.sortedSuits.sort() def getAllValues(self): for card in self.handOfThree: ...
The code initializes a three-card poker hand evaluator. It converts input card strings into Card objects, extracts and sorts suits/values, and determines the hand type (e.g., straight, flush). It prepares attributes for scoring and comparison, setting up the foundation for evaluating hand strength and determining winne...
def __init__(self, lsThreeCards): #['2c', 'As', '4d'] self.handOfThree = [] self.sortedSuits = [] self.sortedValues = [] self.handType = "" self.kicker = 0 self.handScore = 0 for item in lsThreeCards: self.handOfThree.append(Card(item)) ...
def isStraightFlush(self): if self.isStraight() and self.isFlush(): print(f'isStraightFlush: True') return True else: return False def isThreeOfKind(self): # 3 same Rank # 4c 4h 4d # currRank = self.handOfThree[0]['rank'] # for card in...
This code determines the type of a poker hand by checking conditions in descending order of priority, returning the corresponding hand name (e.g., 'StraightFlush', 'ThreeOfKind') or an error message if no valid type is found.
def findHandType(self): if self.isStraightFlush(): #500 return 'StraightFlush' elif self.isThreeOfKind(): #400 return 'ThreeOfKind' elif self.isStraight(): #300 return 'Straight' elif self.isFlush(): #200 return 'Flush' elif self.i...
def isStraightFlush(self): if self.isStraight() and self.isFlush(): print(f'isStraightFlush: True') return True else: return False def isThreeOfKind(self): # 3 same Rank # 4c 4h 4d # currRank = self.handOfThree[0]['rank'] # for card in...
The main task of the code is to calculate a composite score for a poker hand by evaluating its type (e.g., straight flush, three of a kind) and adding sorted card values as modifiers. It assigns base scores based on hand rankings, then incorporates the highest three card values (scaled by 10000, 100, and 1) to create a...
def getScore(self): if self.isStraightFlush(): #500 self.handScore = 5000000 print(f'StraightFlush',self.handScore) elif self.isThreeOfKind(): #400 self.handScore = 4000000 print(f'ThreeOfKind',self.handScore) elif self.isStraight(): #300 ...
def getAllSuits(self): for card in self.handOfThree: #[cardObj1, cardObj2, cardObj3] self.sortedSuits.append(card.suit) #['c','s','d'] self.sortedSuits.sort() #Not needed for logic, sorting suit for my own testing convenience print(" "*20) ...
This code initializes a three-card poker hand by converting input card strings into objects, extracting and sorting their suits and values, and preparing to evaluate the hand's type (e.g., straight, flush) and score. It sets up attributes for further analysis of the hand's strength and classification.
def __init__(self, lsThreeCards): #['2c', 'As', '4d'] self.handOfThree = [] self.sortedSuits = [] self.sortedValues = [] self.handType = "" self.kicker = 0 self.handScore = 0 for item in lsThreeCards: self.handOfThree.append(Card(item)) ...
def get_all_input_to_train(content_path, style_path='emotions\color.jpg'): content_layer = [('block5_conv4',1)] STYLE_LAYERS = [ ('block1_conv1', 0.2), ('block2_conv1', 0.2), ('block3_conv1', 0.2), ('block4_conv1', 0.2), ('block5_conv1', 0.2) ] vgg = initializ...
The main task of the code is to perform a single training step in neural style transfer by optimizing a generated image to balance content and style. It calculates gradients of the total cost (combining content and style losses) using TensorFlow's GradientTape, applies Adam optimizer updates, clips pixel values, and re...
def train_step(generated_image, alpha = 10, beta = 40): optimizer = tf.keras.optimizers.Adam(learning_rate = 0.01) nst_img_path = Image.objects.get() content_layer, STYLE_LAYERS, a_C, a_S, vgg_model_outputs = get_all_input_to_train(content_path=nst_img_path.photo) with tf.GradientTape() as tape: ...
def random_generated_image(nst_img_path): content_image, _ = get_image(nst_img_path, 'emotions\color.jpg', img_size = 400) generated_img = tf.Variable(tf.image.convert_image_dtype(content_image, tf.float32)) noise = tf.random.uniform(tf.shape(generated_img), -0.25, 0.25) generated_img = tf.add(generated...
This code performs neural style transfer on an input image, generating stylized versions over multiple epochs. It saves intermediate results, deletes old records, and returns the latest generated image alongside the original for display in a web template.
def neural_style_transfer_call(request): tf.config.run_functions_eagerly(True) nst_img_path = Image.objects.get() generated = random_generated_image(nst_img_path.photo) generated_image = tf.Variable(generated) epochs = 6 to_delete = NSTImage.objects.all() to_delete.delete() for i in ra...
def union(uft, rank, x, y): x = root(uft, x) y = root(uft, y) if x == y: return if rank[x] >= rank[y]: uft[y] = x if rank[x] == rank[y]: rank[x] += 1 else: uft[x] = y def same(uft, x, y): return root(uft, x) == root(uft, y) def root(uft, x): if uf...
The code processes social network relationships using Union-Find (Disjoint Set Union) to group friends. It calculates, for each user, the number of non-friend and non-blocked users in their connected component. Key steps: (1) Group friends via union operations, (2) Track friend counts during unions, (3) Block users in ...
def answer(): n, m, k = map(int, input().split()) friend = defaultdict(int) block = defaultdict(int) group = defaultdict(set) uft = [i for i in range(n+1)] rank = [0] * (n+1) for i in range(m): a, b = map(int, input().split()) union(uft, rank, a, b) friend[a] += 1 ...
def find_distance_between_x_and_y(package_x, package_y): """ input: [Package object] - package_x, [Package object] - package_y finds the distance, in miles, between x and y output: [float] - miles """ u_address = find_u_address(package_x.get_f_...
The function determines if a new package can be added to a truck's route without violating deadlines. It removes existing packages from the truck's stack (up to 16 times) to accommodate the new package, ensuring delivery times stay within limits. If feasible, it adds the package, handles collisions, and reroutes using ...
def check_truck_for_package_replacement(truck, truck_departure_time, time_from_hub, deadline, package_to_be_added): """ input: [Truck object] - truck to check [int] - truck departure time; minutes from 00:00 hours [int] - time to deliver from hub; minutes ...
def find_distance_between_x_and_y(package_x, package_y): """ input: [Package object] - package_x, [Package object] - package_y finds the distance, in miles, between x and y output: [float] - miles """ u_address = find_u_address(package_x.get_f_...
The function ensures timely delivery of packages with deadlines by adjusting truck schedules and replacing packages on trucks if necessary. It checks for packages still at the hub after truck departures, calculates delivery times, and uses replacement logic to meet deadlines, prioritizing adjustments to truck2's depart...
def ensure_timely_delivery(list_of_truck_tuples): """ input: [list[(Truck object, int)]] - list of tuples (Truck, time_returning_to_hub) ensures that IF there are packages with deadlines still at the hub after the trucks leave, that they will be delivered on time when the trucks return ...
def find_nearest_neighbor_path(package, truck, current_time): """ input: [Package object] - starting package to find the nearest neighbor of [Truck object] - truck packages are being routed on [int] - current time; minutes from 00:00 hours Recursive function...
The function routes packages for prepared trucks using the nearest neighbor algorithm, starting from the hub. It orders trucks by earliest departure time, ensures timely delivery, calculates return times to the hub, and updates truck mileage. The output is a list of tuples containing each truck and its return time to t...
def route_daily_packages_wrapper(prepared_trucks): """ input: [list[Truck object]] - list of prepared trucks takes empty prepared trucks and efficently routes packages via find_nearest_neighbor_path(); starting at the hub ensures_timely_delivery given the routed package roster from fin...
def __set_up_logging(self) -> None: log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), Constants.LOG_FOLDER_NAME) if not os.path.exists(log_dir): os.makedirs(log_dir) log_file = os.path.join(log_dir, Constants.LOG_FILE_NAME) logging.basicConfig( fo...
The main task of the code is to initialize a program by setting up logging, initializing a contents location variable, logging a start message, printing a welcome message, and executing the main program logic via the `__run()` method.
def __init__(self) -> None: self.__set_up_logging() self.contents_location = "" logging.info("Starting program") self.__print_welcome_message() self.__run()
def clear(): # Cross-platform clear screen os.system('cls' if os.name == 'nt' else 'clear') def print_header(): """Function that prints the logo and header.""" print(blackjack_logo) print(" Welcome to Blackjack! ".center(200, '-')) print() def start_round( round_count, player_bank ): """ Functi...
The main task of the code is to initialize and reset the Blackjack game, displaying previous round statistics (bank balance and rounds played) while allowing the player to restart the game or exit. It resets the player's bank to 1000, tracks changes from the previous round, and uses user input to control game continuat...
def start_game(): """Function to start the game. Restarts everything. Bank value is reset.""" restart_game = False while restart_game == False: clear() print_header() random = input("Press Enter to Start".center(200," ")) # Reset the round counter and the player's...
def gradient_descent(self, epoch, gamma=0.001, batch_size=1): """ General gradient descent algorithm :param gamma: learning rate :param epochs: number of epochs :param batch_size: number of samples in each batch (default to 1 - Stochastic Gradient Descen...
The code trains a Multi-Layer Perceptron (MLP) using gradient descent, optimizing weights to minimize a specified loss function. It supports batch processing, validation split, and learning rate adjustment. Key steps include data splitting, handling activation function warnings, and tracking training/validation accurac...
def fit(self, X, y, BATCH_SIZE=1, EPOCHS=300, val_split=0.3, l=0.1, print_res = True): """ Training of the MLP (fitting the weights with gradient descent) :param X: training data matrix(n_samples,n_features) :param y: training labels :param loss: loss function to use for training...
def K_fold_separation(X, y, K=10): """ K fold separation of training set :param X: Training set :param y: Label vector :param K: Number of folds acquired from the K fold separation :return: Train_sets, Train_y 3D arrays Test_sets, Test_y 2D arrays The 1st dim correspond...
The function performs K-fold cross-validation by splitting data into K folds, training a model on each training set, predicting on the corresponding test set, and calculating accuracy. It returns the average accuracy across all folds along with its standard deviation, while also recording training times for each fold.
def Kfold_simulation(self, X, y, Kfold=10, BATCH_SIZE=32, EPOCHS=300, l=0.1, print_res = False): """ Simulate the K fold cross validation on the data. At each step (0 to K-1), accuracy on current test set is displayed. :param X: Train set / feature array (2D) :param y: Label vect...
def entropy_of(df, attr_dict, attr_name, is_cont=False, cont_val=0): """ Entropy of a given attribute :param df: :param attr_dict: :param attr_name: :param is_cont: :param cont_val: :return: """ sum = 0 if is_cont: p = prob_cont(df, attr_name, cont_val, 0) if ...
The code selects the optimal attribute for splitting in a decision tree based on specified criteria (Information Gain, Gain Ratio, or Gini Impurity). It evaluates each attribute's type (binary, nominal, continuous), computes relevance scores using the chosen criterion, and identifies the best attribute (or split point ...
def choose_attribute(df, attr_dict, criteria): dict = {} if criteria == Criteria.IG or criteria == Criteria.GR: entropy_class = entropy_of(df, attr_dict, CLASS_NAME) for attr_name in attr_dict: type = attr_type(attr_dict, attr_name) if type == AttrType.BIN or type == AttrType.NOM:...
def rating_cal(activity, static_rating, dynamic_rating): new_rating = interest_eval(activity['type'], activity['description']) if activity['type'] == 'score': static_rating[activity['movie_id']] = new_rating else: if activity['movie_id'] not in dynamic_rating.keys(): dynamic_rating[activity['mov...
This code handles POST requests to process user interactions (view, score, hover) on anime/movies, updates ratings, generates recommendations, and renders an HTML template with results, warnings, and historical rating data.
def index(): try: if request.method =='POST': id = request.form.get("id") if int(id) not in id_list: assert() action = request.form.get("action") description = request.form.get("description") if action not in ['view', 'score', 'hover']: ...
def globalization(): """ variables order is important while loading """ global po , file_name , Reports_directory ,\ Pre_Flop1_Deside , Flop1_Deside , Turn1_Deside , River1_Deside ,\ Round_Pre_Flop , Round_Flop , Round_Turn , Round_River ,\ Card_1th , Card_2th , Card_3th , Card_4th , Card_5th , My_1...
The function `Me_pocket_full_house_Ranking` evaluates a player's "full house" hand against the community cards (based on poker stages: Flop, Turn, River) to determine its ranking (1st, 2nd, 3rd). It processes the card list, identifies the highest-ranking hand (pair, two pairs, three of a kind), and compares key card va...
def Me_pocket_full_house_Ranking( List = None ) : """ Ranks: 1,2,3 Table_1_pair: 1 ([2,5,5,7,9] 7,7). 2 ([2,5,5,7,9] 2,2). Table_2_pair: 1 ([2,2,5,5,7] 7,7). 2 ([2,2,5,7,7] 5,5). 3 ([2,5,5,7,7] 2,2). Table_3_of_kinds: 3 ([5,5,5,7,8] 7,7). """ global Flop1_Deside , Turn1_Deside , River1_De...
def globalization(): """ variables order is important while loading """ global po , file_name , Reports_directory ,\ Pre_Flop1_Deside , Flop1_Deside , Turn1_Deside , River1_Deside ,\ Round_Pre_Flop , Round_Flop , Round_Turn , Round_River ,\ Card_1th , Card_2th , Card_3th , Card_4th , Card_5th , My_1...
The function evaluates a poker hand's ranking for three-of-a-kind (3K) and higher combinations. It determines the hand strength by checking if the player's pocket pair plus community cards form 3K or 4-of-a-kind (4K). If 4K is detected, it returns rank 6. Otherwise, it sorts the cards and calculates matches with the pl...
def Me_pocket_3_of_kinds_Ranking( List = None ) : """ Ranks: 1,2,3,4,5,6 6: if Table_4_of_kinds : ([4,4,4,4,10],10,10) """ global Flop1_Deside , Turn1_Deside , River1_Deside ,\ Card_1th , Card_2th , Card_3th , Card_4th , Card_5th , My_1th_Card , My_2th_Card globalization() if List =...
def display_board(board): for row in range(ROW): for col in range(COL): print(board[row, col], end = ' ') #to seperate the rows print("\n") #just to seperate gameboards after moves are played print("--------------------------") def input_number (x, y, z): while Tr...
The code provides a menu for a Pentago game, allowing users to choose between PvP or Computer mode. It handles game setup, player input validation, move application, and checks for victory or draw. In PvP mode, two players take turns; in Computer mode, the player faces an AI opponent with difficulty levels. The game co...
def menu(): global game_board print("Welcome to Pentago!") while True: #prompt for whether player wants to go against another player or computer choice = (input("PvP or Computer: ")).upper() if choice == "PVP": print("Player 1 will go first") ...
def to_stderr(msg): print(msg, file=sys.stderr) def get_updates_list(updates_db, catalog_db, resource_mgr_db, logos_dir): updates_rows = logosmgr.get_updates_list(updates_db) updates_info = [] for row in updates_rows: resource_id = row[0] url = row[4] size_int = row[5] re...
The code's main task is to locate the Logos installation directory, retrieve user-specific databases, identify available updates, and apply resource updates based on user input. It validates the input directory, locates Logos.exe, extracts the user ID, fetches catalog and update databases, generates an update list, set...
def main(): start_dir = Path(sys.argv[1]) if not start_dir.is_dir(): to_stderr(f'Error: Not a valid folder: {start_dir}') exit(1) # Find Logos.exe first to find install dir "Logos". logos_exe = utils.get_logos_exe(start_dir) if logos_exe is None: to_stderr(f"Error: Logos.exe ...
def bubble_sort(bars, canvas): start = timeit.default_timer() for i in range(len(bars)): for j in range(len(bars)): if j <= i: continue if bars[j][0] < bars[i][0]: swap(bars, i, j, canvas, start) def heap_sort(arr, canvas): start = timeit.defau...
The function `sort_by_time` initiates a visual sorting process by clearing the canvas, initializing graphical bars, and executing the selected sorting algorithm (bubble, heap, or quick sort) based on the global `algo` variable. It measures the sorting duration using `timeit` and re-enables the sort button after complet...
def sort_by_time(): global photo,canvas canvas.delete("all") bars = graphics.init_graphics(height, width, arr, canvas) start = timeit.default_timer() if algo == ALGO_OPTIONS[0]: bubble_sort(bars, canvas) elif algo == ALGO_OPTIONS[1]: heap_sort(bars...
def _conflicting(calItem1, calItem2): begin1 = calItem1.begin_datetime begin2 = calItem2.begin_datetime if begin2 < begin1 < calItem2.end_datetime: if _related_by_user(calItem1, calItem2): return True elif begin1 < begin2 < calItem1.end_datetime: if _related_by_user(calItem1,...
This function schedules an item by checking for conflicts with existing scheduled items, resolving conflicts by removing less important items, and attempting to reschedule removed items. It returns overall success status and a list of items that failed rescheduling.
def _add_event_to_schedule(item_to_schedule, scheduled, tick, allowed_time): global print_level item_to_schedule_obj = item_to_schedule[0] print_level += 1 indent = " " * print_level logger = logging.getLogger("mylogger") to_remove = [] removed_items = [] for item in scheduled: ...
def _get_all_related_scheduling_info(user): logger = logging.getLogger("mylogger") all_events = set(CalAppModels.Event.objects.filter(owner=user, parent__isnull=False, exception=False)) all_tasks = set(CalAppModels.Task.objects.filter(owner=user, parent__isnull=False, exception=False)) all_event_shares ...
The code schedules user tasks and events by resolving conflicts, checking time constraints, and managing a queue within a 15-minute window. It processes unscheduled items, attempts to add them to the schedule, logs progress, and updates user scheduling records. If conflicts arise or time expires, it adjusts priorities ...
def _schedule_user_slow(user): global _user_queue slow_allowed_time = 900 logger = logging.getLogger("mylogger") tick = time.time() right_now = make_aware(datetime.datetime.now()) all_events, all_tasks, all_related_users = _get_all_related_scheduling_info(user) cal_item_stats = sorted(_get_...
def _get_all_related_scheduling_info(user): logger = logging.getLogger("mylogger") all_events = set(CalAppModels.Event.objects.filter(owner=user, parent__isnull=False, exception=False)) all_tasks = set(CalAppModels.Task.objects.filter(owner=user, parent__isnull=False, exception=False)) all_event_shares ...
The function schedules user events/tasks by acquiring locks to prevent conflicts, processes related users' scheduling info, resolves conflicts, and attempts to schedule items within a time limit. It logs progress, adjusts for conflicts by unscheduling items, and updates user schedule records while managing lock states ...
def _schedule_user_quick_2(user): global print_level fast_allowed_time = 30 logger = logging.getLogger("mylogger") tick = time.time() right_now = make_aware(datetime.datetime.now()) all_events, all_tasks, all_related_users = _get_all_related_scheduling_info(user) DBScheduleLock.lock.acquire...
def _unshare_all_between_contacts(user1, user2): # Unshare tasks shared between them try: tasksOwnedBy1 = CalAppModels.Task.objects.filter(owner=user1) tasksToUnshare = CalAppModels.User_Task.objects.filter(user=user2).filter(task__in=tasksOwnedBy1) tasksToUnshare.delete() except: ...
The main task of the code is to delete a contact relationship between the authenticated user and another user. It checks authentication, retrieves the target user and contact record, deletes the contact, unshares related data, and updates the contact list. If any step fails (e.g., invalid user or contact), it returns a...
def DeleteContact(request): if request.user.is_authenticated: try: otherUser = CalAppModels.User.objects.get(pk=request.POST["pk"]) except ObjectDoesNotExist: return bad_request(request, "Failed") try: contactObj = CalAppModels.Contact.objects.filter(user1...
def getGoalDistace(self): goal_distance = math.hypot(self.goal_position.position.x - self.position.x, self.goal_position.position.y - self.position.y) self.end_goal_wrt_robot_odom = [self.goal_position.position.x,self.goal_position.position.y] self.past_distance = goal_distance return g...
The function generates local waypoints for navigation by analyzing a costmap and the robot's position. It calculates paths using a modified pathfinding algorithm (MCP), converts grid coordinates to real-world positions relative to the robot's odometry, and returns a list of waypoints in the robot's coordinate frame. Th...
def get_local_waypoints(self,costmap,end_goal_wrt_robot_odom,end_goal_wrt_robot_init): waypoint_as_goal_threshold = 10.1 scaling_factor = 0.5 current_distance = self.getGoalDistace() data_odom = rospy.wait_for_message(self.odom_topic_name, Odometry, timeout=5) self.getOdometry(...
def arr_normalize(self,x): xmax, xmin = x.max(), x.min() x = (x - xmin)/(xmax - xmin) # arr = arr - arr.mean(axis=0) # arr = arr / np.abs(arr).max(axis=0) return x def threshold_up(self,map,threshold_val,assign_val): threshold_idx = np.where(map >= threshold_val) ...
The code plans waypoints by combining an attention mask (derived from cbam_out) with an elevation map to create a costmap. It normalizes, thresholds, and adjusts the costmap, using it to generate local waypoints toward a goal. If attention is disabled, it directly uses the elevation map for waypoint planning.
def waypoint_planner(self,cbam_out, elevation_map,without_attention): # print(np.shape(cbam_out)) # np.save("elevation_map2.npy",elevation_map) cbam_out_sum = cbam_out.squeeze(0)[0] # # plt.subplot(1,6,1) cbam_norm = np.array(self.arr_normalize(cbam_out.squeeze(0)[0])) # ...
def get_valid_locations(board): valid_locations = [] for col in range(COLUMN_COUNT): if is_valid_location(board, col): valid_locations.append(col) return valid_locations def is_terminal_node(board): return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_...
This code implements the Minimax algorithm with alpha-beta pruning for a Connect Four-like game. It evaluates board states recursively to determine the optimal move for the AI player (maximizing player) or the opponent (minimizing player). The function considers terminal game states, depth limits, and uses either rando...
def minimax(board, depth, alpha, beta, maximizingPlayer, RNG_mode): global pc valid_locations = get_valid_locations(board) is_terminal = is_terminal_node(board) if depth == 0 or is_terminal: if is_terminal: if winning_move(board, AI_PIECE): return (None, 100000000000...
def h_1(xs: np.ndarray, ys: np.ndarray): # gradient descent theta = np.array([3.0]) theta, history = train(theta, xs, ys) history_cost = np.array(list(map(lambda x: cost(x, xs, ys), history))) # brute force interval = np.arange(0.0, 3.0, 3.0/1000.0) cost_values = np.array(list(map(lambda x:...
The main task of the code is to load data from "data_ex7.mat" using scipy.io.loadmat, extract variables "x" and "y", and sequentially pass them to three functions h_1, h_2, and h_3 for processing or analysis.
def main(): mat = scipy.io.loadmat("data_ex7.mat") xs = mat["x"] ys = mat["y"] h_1(xs, ys) h_2(xs, ys) h_3(xs, ys)
def isprimitive(exp): """Determines if syntax of "exp" matches a Logo primitive value.""" if ( type(exp).__name__ == "list" or exp.isdigit() or exp.lower() == "true" or exp.lower() == "false" ): return True return False def isvariable(exp): """Determines if sy...
This function evaluates expressions by handling primitives, variables, quoted expressions, and procedure definitions. It processes expressions using the environment, updates the 'evals' list for argument passing, and applies procedures with type checks. It manages state by adding procedures to the environment and retur...
def exp_eval(exp): nonlocal evals # gives write access to evals inside this scope if isprimitive(exp): return exp elif isvariable(exp): _, v = env.get_var(exp[1:]) return v elif isquoted(exp): return eval_quoted(exp) elif isdefini...
def _get_permutation_during_learning_and_after_learning(self, iterations): # norm = torch.linalg.norm( # self._get_permutation_during_inference(self.permutation_weights) - self.permutation_weights, dim=(1, 2) # ) # print(self._get_permutation_during_inference(self.permutation_weights...
This code computes permutation weights and entropy regularization during training/inference. It updates iteration counts, generates permutation weights based on training mode, calculates entropy regularization if training, and tiles weights if needed. Returns permutation weights and scaled regularization term for loss ...
def forward(self, inputs): training = self.training self.iterations = self.iterations.to(inputs.device) if training: increment = torch.ones_like(self.iterations) else: increment = torch.zeros_like(self.iterations) self.iterations += increment if ...
def print_info(self, epoch): """ prints and logs current learning rates as well as the epoch. :param epoch: the current epoch. """ if not self.state['quiet']: s = 'learning rates ' + (', '.join(map(str, self._lrs()))) print(s) self.logger.info...
The code trains a machine learning model for a specified number of epochs, logging training and validation metrics, printing progress with an ETA, and saving model snapshots each epoch. It also generates a loss plot visualizing total loss, autoencoder loss, and classifier loss over training. The function handles except...
def train(self, num_epochs, start_epoch=0): """ starts the training, logs loss and metrics in logging file and prints progress in the console, including an ETA. Also stores snapshots of current model each epoch. :param num_epochs: number of epochs to train :param sta...
def print_info(self, epoch): """ prints and logs current learning rates as well as the epoch. :param epoch: the current epoch. """ if not self.state['quiet']: s = 'learning rates ' + (', '.join(map(str, self._lrs()))) print(s) self.logger.info...
The code trains a model for a specified number of epochs, logging training and validation metrics, printing progress with an ETA, and saving model snapshots each epoch. It also generates plots of loss and accuracy metrics over time, storing them in a designated directory.
def train(self, num_epochs, start_epoch=0): """ starts the training, logs loss and metrics in logging file and prints progress in the console, including an ETA. Also stores snapshots of current model each epoch. """ try: rem = ETATimer(num_epochs - start_epoch) ...
def getusrf(usr): """ Get usrfile """ sipusr = uff.vsiper(usr) if len(usr) < 4 or not sipusr: return 4, "Error: (uf) Invalid userid." usrfile = os.path.join(cons('usrsdir'), sipusr) return 0, usrfile def valpwd(pwd, npwd=''): """ Validate pwd & npwd """ if npwd and (len(npwd) < 8 or ...
The main task of the code is to verify a user's credentials by checking if the provided username exists, validating the password format, and confirming the password matches a stored hash in the user's file. It returns success or specific error codes based on validation steps, including checking the existence of the use...
def verusr(usr, pwd): """ Verify usr & pwd """ # Verify usrid rc, usrfile = getusrf(usr) if rc: return rc, usrfile if not os.path.isfile(usrfile): return 8, "Error: (vu) Userid does not exist." # Validate pwd rc, msg = valpwd(pwd) if rc: return rc, msg with op...
def getusrf(usr): """ Get usrfile """ sipusr = uff.vsiper(usr) if len(usr) < 4 or not sipusr: return 4, "Error: (uf) Invalid userid." usrfile = os.path.join(cons('usrsdir'), sipusr) return 0, usrfile def valpwd(pwd, npwd=''): """ Validate pwd & npwd """ if npwd and (len(npwd) < 8 or ...
The function adds a new user by validating the username length, checking for existing user files, ensuring password consistency and strength, hashing the password, validating user details, writing formatted data to a file, verifying the user, and optionally removing the file if the 'rmv' flag is True. It returns succes...
def addusr(usr, pwd, pwc, nam, adr='', phn='', eml='', rmv=False): """ Add new user """ if len(usr) < 4: return 8, "Error: (au) Invalid userid." rc, usrfile = getusrf(usr) if rc: return rc, usrfile if os.path.isfile(usrfile): return 8, "Error: (au) Userid already exists." ...