dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def train_val_split(file_name_list): ham_fname_list = [file_name for file_name in file_name_list if 'ham' in file_name] spam_fname_list = [file_name for file_name in file_name_list if 'spam' in file_name] ham_train_set, ham_val_set = train_test_split(ham_fname_list, train_size=0.7) # For ham spam_trai...
The function determines the optimal regularization constant for a logistic regression model by training and evaluating it on validation data for each constant in the provided list. It processes text files from the given path, splits them into training and validation sets, iterates through regularization parameters, tra...
def learn_reg_const(train_file_path, reg_const_list=(0.1, 0.5, 1, 5, 10, 50, 100), num_iterations=45, *, model='bow'): # text_file_path = r'C:\Users\kxg220013\Documents\Machine Learning\Naive-Bayes-Classifier\data\train' file_list = [os.path.join(train_file_path, file_name) for file_name in os.listdir(train_fil...
def get_json(name, coerce=identity): try: return coerce(request.json[name]) except (ValueError, KeyError): return err('invalid-json', f"`{name}` is a required parameter") def _req(*args, **kwargs): try: return requests.request(*args, **kwargs) except (ConnectionError, ReadTimeout...
The function `link_preview` generates a preview for a given URL. It checks if the URL points to an image by examining the `Content-Type` header. If true, it returns a dictionary with the image URL and empty title/description. Otherwise, it delegates to `_get_link_preview` to fetch metadata, defaulting to an empty dicti...
def link_preview(): url = get_json('url') res = _req('head', url) if (res.headers.get('Content-Type', '') if res else '').startswith('image/'): return {'title': "", 'description': "", 'image': url, 'url': url} return _get_link_preview(url) or {}
def pdf_download_request(self, pdf_file,server): cookies = { '_ga': 'GA1.1.1647596621.1700544196', '__gads': 'ID=daf152396cd20381:T=1700544196:RT=1700560948:S=ALNI_MZCABeP7GFKQJTIAs4A_eho8mYUfQ', '__gpi': 'UID=00000c9043d849cf:T=1700544196:RT=1700560948:S=ALNI_MbjfdEA0odiKpW...
The main task of the code is to download content from a PDF file using random servers, save it as a text file in a specified folder, and retry up to three times if the download fails. It returns the file path on success or None if all retries fail.
def create_text_file(self, pdf_file, count, new_text_folder): retry = 0 file_path = f"{new_text_folder}/textfile{count}.txt" content = self.pdf_download_request(pdf_file, self.get_random_servers()) if content: with open(file_path, 'wb') as file: file.write(con...
def pre_addition(sn1, sn2): if sn1: return '[' + sn1 + ',' + sn2 + ']' return sn2 def find_explosion(expression, config): if config['verboseFindExplosion']: print('Finding pair:') start_position = 0 while (True): finding = find_pair(expression, start_position) if find...
The main task of the code is to perform a custom addition operation on two numbers (sn1 and sn2), applying explosion and splitting rules iteratively until the expression is fully reduced. It uses configuration flags to control verbose output of intermediate steps, including the initial expression, explosion/splitting p...
def addition(sn1, sn2, config): expression = pre_addition(sn1, sn2) if config['verboseAddition']: print('\nAdd:') print('\t' + expression) splitted = True while (splitted): exploded = True while (exploded): expression, exploded = find_explosion(expression, co...
def locations2lines(locations): lines = ['#############','#...........#','###.#.#.#.###',' #.#.#.#.# ',' #.#.#.#.# ',' #.#.#.#.# ',' ######### '] for amphipod_type in locations.keys(): for room, position in locations[amphipod_type]: lines = change_lines(lines, room, position, amphipo...
The function generates all possible moves for amphipods in a grid-based puzzle, recursively exploring paths to reach target rooms while avoiding obstructions. It checks each amphipod's position, identifies valid destinations based on current occupancy, and recursively processes each move to update the state, aiming to ...
def locations2moves(locations_history, ocupation, level): if level > 66: #print(locations) #print(ocupation) exit(1) return locations = dict(locations_history[0]) for amphipod_type in locations.keys(): for specimen, (room, position) in enumerate(locations[amphipod_typ...
def printMatrix(_matrix): for row in _matrix: print(' ' + ' '.join([ '+' if i == 1 else ' ' if i == 0 else i for i in row ])) def insertStartEnd(): maze = copy.deepcopy(MAZE) maze[START[0]][START[1]] = 'S' maze[END[0]][END[1]] = 'E' return maze def mainLoop(): prev_pos = [] current_pos = ...
The main task of the code is to execute the `main()` function, which prints empty lines, displays a matrix generated by `insertStartEnd()` using `printMatrix()`, and then initiates the core processing loop via `mainLoop()`. This sequence initializes the program's state, visualizes structured data, and transitions to th...
def main(): print(''), printMatrix(insertStartEnd()) print(''), mainLoop()
def _reconstruct_params(params: jnp.ndarray, n: int, f: int, m: int) -> Params: """Rearrange parameters into original shape from flat (real) vector. Returns: a 5-tuple of initial parameters: weights: The weights of the discrete measure (m,); real pos_spectrum: initial log values of pos spectrum...
The code periodically saves model parameters and metrics during iterations. It checks if the current iteration count is a multiple of a specified frequency, reconstructs parameters, computes action and boundedness values, logs them, appends to results, and writes checkpoints. The task involves iterative tracking, loggi...
def callback(self, xk): if self.n_iter % checkpoint_freq == 0: cur_params = _reconstruct_params(xk, n, f, m) cur_act = action(cur_params) cur_bnd = boundedness(cur_params) logging.info(f"{self.n_iter}: action: {cur_act:.5f} " f"bound.: {cur_bnd:.5f}") ...
def resetTimer(self, client): if client.timer is not None: client.timer.cancel() client.timer = threading.Timer(1.5 * client.keepAlive, client.toDec) client.timer.start() def printLog(self, log): self.logs.insert(0, log) self.logBox.delete(1, 'end') self.logBo...
This code handles MQTT protocol packets from clients, processing CONNECT, SUBSCRIBE, PUBLISH, and other packet types. It manages session states, subscription topics, message routing, QoS handling, and acknowledgments. It logs client activity, updates topic subscriptions, forwards retained messages, and sends appropriat...
def handleClient(self, data, client, packet_type, flags): if client.connected: self.resetTimer(client) self.printLog(f'{client.id if client.id is not None else client.addr} a trimis {packet_type}') if packet_type == 'CONNECT': # timer pentru primirea pachetului connect in...
def build_protocol_message(sock, command, msg): full_msg = command + '~' + msg print(full_msg) send_one_message(sock, full_msg) def parse_message_protocol(msg): code = msg[:4] msg = msg[5:] text = msg.split('~') print(text) if code == "SGIN": return "The user is in the system" ...
The main task of the code is to implement a login system that sends a username and password over a socket using a custom protocol. It constructs a message, transmits it, receives a response, and checks if the user exists in the system. If successful, it proceeds to the application system.
def login_system(sock, username, password): msg = username + '~' + password build_protocol_message(sock, 'ISSG', msg) d = recv_one_message(sock) res = parse_message_protocol(d) if res == "The user is in the system": app_system(sock)
def end_turn(self): # End turn and draw up to four cards. Also handles the draw two logic if self.has_moved == True: self.info_gui.turn_num += 1 if self.info_gui.num_cards < 4: # If less than four cards, draw up to four. Reset selections. self.card_gui.draw_up_to_four() ...
The code manages game graphics, user interactions, and logic for a tile-based game. It draws the background, grid, GUI elements, and hints; handles button clicks for actions like ending turns or toggling hints; manages fullscreen transitions; processes card and tile selections; and executes movement/flip actions based ...
def game_logic(self): # Handles most of the game graphics and logic self.s.blit(self.bg, [0,0]) # Draw the background self.grid.draw_tiles() # Draw the tilegrid self.info_gui.draw(self.point_sum) # Draw the info gui at the top of the screen self.card_gui.draw(self.grid.gridstate, self...
def log(msg): with open('garage.log', 'at') as file: t = nowstring() + msg print(t, file=file) print(t) def trigger_garage_button(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) pin = 22 GPIO.setup(pin, GPIO.OUT) log('GPIO ON') GPIO.output(pin, True) sleep(1) ...
This code handles a web request for a garage system. It processes POST requests by validating a nonce, triggering a garage action if valid, and sending a Discord notification. For GET requests, it calculates distance, determines garage status, generates a new nonce, and renders a template with dynamic data like distanc...
def garage(): ipstring = request.remote_addr if request.method == 'POST': log('POST ' + ipstring) req_nonce = request.form.get('nonce') if app.nonce == req_nonce: app.nonce = None trigger_garage_button() discordmsg.send_message('Garage button pressed b...
def MostrarTablero(): print("\n") print(" " + Tablero[0] + " | " + Tablero [1] + " | " + Tablero[2] +" 1|2|3") print("------------" + " -----") print(" " + Tablero[3] + " | " + Tablero [4] + " | " + Tablero[5] +" 4|5|6") pr...
The code defines a function "Jugar()" to manage a two-player game loop. It initializes the board, alternates turns between players (X and O), checks for a win or draw after each move, and switches players until the game ends. Upon termination, it announces the winner or declares a draw. The core tasks include handling ...
def Jugar(): # reiniciar el tablero MostrarTablero() # bucle principal, el bucle cerrara cuando haya ganador o tablas while el_juego_funciona: #Jugada de cada jugador Jugada(Jugador_del_Turno) # comprobamos victoria y empate Comprobar_fin_juego() # cambiamos de X a O y viceversa Cam...
def hashtag_counts(self): '''returns a collections.Counter object for a dict of # counts''' cnt = Counter() for twt in self.tweets(): tags = self.get_twt_hashtags(twt) cnt.update({tag:1 for tag in tags}) return cnt def tweets(self): ''' an iterator...
The code calculates the polarity of specific hashtags (marker_hts) by comparing their frequency in tweets containing them against the most common hashtags. It returns the calculated polarity scores and a list of top hashtags.
def hashtag_polarity(self, top=200, marker_hts=['wuhanvirus', 'fakenews', 'maga']): """Returns the polarities of the top hashtags""" ht_cnt = self.hashtag_counts() baseline = [(ht,cnt/len(self)) for ht,cnt in ht_cnt.most_common(top)] base_hts = [ht for ht,_ in baseline] marker_se...
def calculateNormals(vertices, faceIndices): verticesTotal = vertices.shape[1] normalVectors = numpy.zeros([3, verticesTotal]) #a zero initialized array for the normal vectors of each vertex vertexTrianglesCount = numpy.zeros([verticesTotal]) #a zero initialized array for the number of triangles each vert...
The function renders a 3D object into a 2D image using specified lighting and shading models. It calculates vertex normals, projects vertices onto a camera view, rasterizes them into pixels, sorts triangles by depth, and applies Gouraud or Phong shading to each triangle. The final image is normalized and returned with ...
def renderObject(shader, focalLength, eyeVector, lookatVector, upVector, backgroundColor, imageHeight, imageWidth, ccdHeight, ccdWidth, vertices, verticesColors, faceIndices, ka, kd, ks, n, lightPositions, lightIntensities, environmentalIntensity): verticesNormalVectors = calculateNormals(vertices, faceIndices) #g...
def LoadParameters(filename): parameters = numpy.load(filename, allow_pickle=True) # loads file's parameters. parameters = numpy.ndarray.tolist(parameters) # convert numpy array to list. return [parameters["verts3d"], parameters["vcolors"], parameters["faces"], parameters["c_org"], parameters["c_lookat"], ...
The code renders a 3D object using Gouraud shading, applies affine transformations (translation and rotation) to its vertices, and saves four rendered images showing the object's appearance before and after each transformation. It loads parameters, renders the initial model, applies translations, rotations, and re-rend...
def demoRun(): [verts3d, vcolors, faces, c_org, c_lookat, c_up, t_1, t_2, u, phi] = LoadParameters("hw2.npy") # load parameters. f = 3.6 squarecamerawh = 0.08 I = render_object(verts3d, faces, vcolors, 512, 512, squarecamerawh, squarecamerawh, f, c_org, c_lookat, c_up) RGB2BGR(I) npyGouraudImag...
def TriangleEdges(triangleVertices): # return the triangle edges as pairs of vertices, (edge = [vertex1, vertex2]). verticesTotal = 3 triangleEdges = [] for startVertexIdx in range(3): for endVertexIdx in range(startVertexIdx + 1, 3): triangleEdges.append([triangleVertices[startVertexIdx...
This function fills a triangle in an image with color using either flat or Gouraud shading. It calculates triangle edges, determines scan lines, and iterates through each pixel within the triangle's bounds. For each scan line, it identifies active edge points, applies color based on the shading type (flat/Gouraud), and...
def shade_triangle(image, triangleVertices, triangleVerticesColor, shade_t): # color filling the triangle. verticesTotal = 3 height = len(image) width = len(image[0]) triangleEdges = TriangleEdges(triangleVertices) # finds triangle edges. triangleMinYCoord = TriangleMinYCoord(triangleVertices) # fi...
def EdgeMinYCoord(edge): # return edges's minimum y coordinate. edgeMinYCoord = min(edge[0][1], edge[1][1]) return edgeMinYCoord def EdgeMaxYCoord(edge): # return edges's maximum y coordinate. edgeMaxYCoord = max(edge[0][1], edge[1][1]) return edgeMaxYCoord def EndPointsColorAndNormalVectors(edge, trian...
This function implements Gouraud shading by interpolating colors along triangle edges based on y-coordinates, then across scan lines using x-coordinates. It calculates pixel color at (xCoordIdx, yCoordIdx) by interpolating vertex colors and normal vectors, applying Phong reflection model with given lighting parameters ...
def PhongColoring(xCoordIdx, yCoordIdx, activePointsAndCorrespondingEdges, triangleVertices, triangleVerticesColor, image, eyeVector, ka, kd, ks, n, lightPositions, lightIntensities, environmentalIntensity, bcoords, triangleNormalVectors): # implements gouraus coloring algorithm. firstActiveEdgeAndNormalVector = a...
def TriangleEdges(triangleVertices, triangleNormalVectors): # return the triangle edges as pairs of vertices, (edge = [vertex1, vertex2]) and corresponding edges. verticesTotal = 3 triangleEdgesAndCorrespondingNormalVectors = [] for startVertexIdx in range(verticesTotal): for endVertexIdx in range(s...
This function shades a triangle in an image using Phong reflection model by iterating through scan lines, calculating pixel colors based on light positions, intensities, material properties (ka, kd, ks), and normals. It initializes active edges, updates them per scan line, and applies shading for each pixel within the ...
def shade_triangle_phoneHW3(image, triangleVertices, triangleVerticesColor, triangleNormalVectors, eyeVector, ka, kd, ks, n, lightPositions, lightIntensities, environmentalIntensity, bcoords): # color filling the triangle. triangleEdgesAndNormalVectors = TriangleEdges(triangleVertices, triangleNormalVectors) # find...
def LoadParameters(filename): parameters = numpy.load(filename, allow_pickle=True) # loads file's parameters. parameters = numpy.ndarray.tolist(parameters) # convert numpy array to list. # separate and return the parameters. return [numpy.ndarray.tolist(parameters["verts2d"]), numpy.ndarray.tolist(para...
The main task of the code is to load 3D model parameters, render both flat and Gouraud-shaded images, convert them to BGR format for OpenCV compatibility, concatenate the images horizontally, and display the combined result. This demonstrates a comparison between two shading techniques applied to a 3D model.
def RunDemo(): [verts2d, vcolors, faces, depth] = LoadParameters("hw1.npy") # load parameters. flatImage = render(verts2d, faces, vcolors, depth, "flat") # render flat image. RGB2BGR(flatImage) npyFlatImage = numpy.array(flatImage) # convert image (list of lists) to a numpy array. gouraudImage = r...
def random_number(): rand64 = uuid.uuid4().int & (1 << 64) - 1 return rand64 def preprocess(lines,questions_as_words,questions_as_words_64): # questions start on line 2 for i in lines[1:]: if len(i.split('\t')) == 2: (qid_0, question) = i.split('\t') # express words in question as a set, to remove duplica...
The code processes a TSV file containing questions, using a hashing algorithm to identify similar questions. It initializes hash tables, preprocesses question data into dictionaries, builds hash structures, and computes similarities. The output writes pairs of question IDs and their similar counterparts into a new TSV ...
def main(): f = open('./question_150k.tsv', encoding='utf8') output = open('./question_sim_150.tsv', "w") #header for tsv file output.write("qid" + '\t' + "similar-qids\n") #make ditionary of random values for the 14*6 hash functions used in this algorithm for i in range(B): for j in range(R): RANDOM_NUM_...
def logIt_thread(self, log_path=None, debug=False, msg=''): self.logit_thread = Thread(target=self.logIt, args=(log_path, debug, msg), name="Log Thread") self.logit_thread.start() return def task_to_kill(self, ip): self.logIt_thread(self.log_path, msg=f'Running self.task_to_kill()...') ...
The main task of the code is to prompt the user to confirm whether to kill a task or pass it, handle input validation, execute task termination or send a 'pass' command to a remote IP, and manage exceptions like connection errors or invalid inputs, logging each step for transparency.
def kill_tasks(self, ip): self.logIt_thread(self.log_path, msg=f'Running self.kill_tasks()...') while True: try: self.logIt_thread(self.log_path, msg=f'Waiting for user confirmation...') choose_task = input(f"[?]Kill a task [Y/n]? ") except ValueE...
def coerceData(self, exog: np.ndarray, endog: np.ndarray, categorical: tuple, col_names: tuple) -> Tuple[np.ndarray, np.ndarray]: """ Coerce data to default datatype :param exog: :param endog: :param categorical: :param col_names: :return: ...
This function fits a Tobit regression model using maximum likelihood via Newton-Raphson iterations. It processes exogenous/endogenous data, adds a constant if specified, handles categorical variables, initializes parameters, and iterates until convergence (based on residual threshold or max iterations). Returns a Regre...
def fit(self, exog: np.ndarray, endog: np.ndarray, include_constant: bool = True, categorical: tuple = (), col_names: tuple = ()) -> RegressionResult: """ Fir the Tobit regression model to the data :param exog: array of exogeneous variables :param endog: array of output varia...
def select_annotations(self): images=[] with open(self.input, newline='') as f: reader = csv.reader(f) for r in reader: images.append(r[0]) print("list---------------------", images) #self.outputfile = 'images_similarity.csv' with open(sel...
This code computes pairwise similarity between ultrasound images using annotated findings, disorders, and technical elements. It calculates similarity scores for each image pair, aggregates them with weighted averages, and writes results to a CSV file, including similarity metrics and timestamps.
def similarity_images(self): self.select_annotations() self.computeSimilarityAllAnnotations() previous = [] counter1 = 0 today = date.today() d = str(today) with open(self.output+'/similarity_images_' + self.measure + '_' + d + '.csv', 'w', new...
def lca(self, c1, c2): l = None if nx.lowest_common_ancestor is not None: l = nx.lowest_common_ancestor(self._taxonomy, c1, c2) return l def shortest_path_length(self, node1, node2): length = 0 if nx.has_path(self._taxonomy, node1, node2): length = (nx.sho...
This function calculates the similarity between two nodes (c1, c2) in a tree structure. It returns 1 if nodes are identical, 0 if they share no common ancestor, or a normalized score based on the average distance from their lowest common ancestor (LCA) to each node, adjusted by the LCA's information content (IC). The r...
def sim_suog(self, c1, c2): if c1 == c2: sim = 1 else: if self.lca(c1, c2) is None: sim = 0 else: dist1 = self.shortest_path_length(self.lca(c1, c2), c1) dist2 = self.shortest_path_length(self.lca(c1, c2), c2) ...
def shortest_path_length(self, node1, node2): length = 0 if nx.has_path(self._taxonomy, node1, node2): length = (nx.shortest_path_length(self._taxonomy, node1, node2)) return length def lca(self, c1, c2): l = None if nx.lowest_common_ancestor is not None: ...
This function calculates the similarity between two nodes (c1 and c2) in a tree structure using their Lowest Common Ancestor (LCA). It computes the average distance from each node to the LCA, combines this with the information content (IC) of the LCA, and applies a formula to derive a similarity score between 0 and 1. ...
def sim_suog_t(self, c1, c2): if c1 == c2: sim = 1 else: dist1 = self.shortest_path_length(self.lca(c1, c2), c1) dist2 = self.shortest_path_length(self.lca(c1, c2), c2) dist = (dist1+dist2)/2 ic = self.IC(self.lca(c1, c2)) sim = np...
def getTargetInfo(sequenceFrameLines, backComp=False): """ Returns the number of targets and a list of their corresponding labels as tuple. This function searches for target labels given that 'RESULTS' fields can sometime contain 'empty' lines. Therefore, a static line index can yield undesired '' labe...
The code normalizes scores in the 'RESULTS' section of 'sequenceGroupedLines' using min-max normalization across all frames. It then recalculates trajectory-level scores by accumulating normalized transaction-level scores, maintaining a sliding window of track frames. Best scores and labels are updated for each target,...
def addNormalizedScoreResults(sequenceGroupedLines): """ Adds a 'NORMALIZED' section to 'sequenceGroupedLines' to contain normalized scores from the 'RESULTS' section. Scores are normalized across all 'frameLines' of the whole 'RESULTS' for transaction-level using MIN-MAX rule, then trajectory-level sco...
def display_books(): print(r''' ░█████╗░██╗░░░░░██╗░░░░░  ██████╗░░█████╗░░█████╗░██╗░░██╗░██████╗ ██╔══██╗██║░░░░░██║░░░░░  ██╔══██╗██╔══██╗██╔══██╗██║░██╔╝██╔════╝ ███████║██║░░░░░██║░░░░░  ██████╦╝██║░░██║██║░░██║█████═╝░╚█████╗░ ██╔══██║██║░░░░░██║░░░░░  ██╔══██╗██║░░██║██║░░██║██╔═██╗░░╚═══██╗ ██║░░██║███████╗...
The main task of the code is to search for books by ISBN, author, or title, display their details (including author, title, publisher, genre, etc.), and return to the main menu after user confirmation. It uses ASCII art for visual appeal and formats the output to show retrieved book information.
def search_books(): """ Prompts user to input ISBN, name of author and/or title. Displays header for the function. """ print( r""" ░██████╗███████╗░█████╗░██████╗░░█████╗░██╗░░██╗  ██████╗░░█████╗░░█████╗░██╗░░██╗ ██╔════╝██╔════╝██╔══██╗██╔══██╗██╔══██╗██║░░██║  ██╔══██╗██╔══██╗██╔══██╗██║...
def clear(): os.system("cls" if os.name == "nt" else "clear") def display_books(): print(r''' ░█████╗░██╗░░░░░██╗░░░░░  ██████╗░░█████╗░░█████╗░██╗░░██╗░██████╗ ██╔══██╗██║░░░░░██║░░░░░  ██╔══██╗██╔══██╗██╔══██╗██║░██╔╝██╔════╝ ███████║██║░░░░░██║░░░░░  ██████╦╝██║░░██║██║░░██║█████═╝░╚█████╗░ ██╔══██║██║░░░░░█...
The main task of the code is to provide a user interface for adding new books to a collection. It displays existing books, prompts for new book details, confirms the input, adds the book if validated, and allows users to add another book or return to the main menu. Error handling ensures robustness, and the interface e...
def add_book_interface(): clear() print( r""" ██████╗░░█████╗░░█████╗░██╗░░██╗  ░█████╗░██████╗░██████╗░██╗████████╗██╗░█████╗░███╗░░██╗ ██╔══██╗██╔══██╗██╔══██╗██║░██╔╝  ██╔══██╗██╔══██╗██╔══██╗██║╚══██╔══╝██║██╔══██╗████╗░██║ ██████╦╝██║░░██║██║░░██║█████═╝░  ███████║██║░░██║██║░░██║██║░░░██║░░░██║██║...
def clear(): os.system("cls" if os.name == "nt" else "clear") def display_books(): print(r''' ░█████╗░██╗░░░░░██╗░░░░░  ██████╗░░█████╗░░█████╗░██╗░░██╗░██████╗ ██╔══██╗██║░░░░░██║░░░░░  ██╔══██╗██╔══██╗██╔══██╗██║░██╔╝██╔════╝ ███████║██║░░░░░██║░░░░░  ██████╦╝██║░░██║██║░░██║█████═╝░╚█████╗░ ██╔══██║██║░░░░░█...
The main task of the code is to allow users to update specific details of a book in a database. It displays all books, lets users search by ISBN, author, or title, validates input for new details (e.g., ISBN length, date formats), checks for duplicates, and confirms updates before applying changes. The function ensures...
def update_book_interface(): """ Calls the clear function to clear the screen for better visiblity. Displays header for the function. (Book Update) """ clear() print( r""" ██████╗░░█████╗░░█████╗░██╗░░██╗  ██╗░░░██╗██████╗░██████╗░░█████╗░████████╗███████╗ ██╔══██╗██╔══██╗██╔══██╗██║░██...
def clear(): os.system("cls" if os.name == "nt" else "clear") def display_books(): print(r''' ░█████╗░██╗░░░░░██╗░░░░░  ██████╗░░█████╗░░█████╗░██╗░░██╗░██████╗ ██╔══██╗██║░░░░░██║░░░░░  ██╔══██╗██╔══██╗██╔══██╗██║░██╔╝██╔════╝ ███████║██║░░░░░██║░░░░░  ██████╦╝██║░░██║██║░░██║█████═╝░╚█████╗░ ██╔══██║██║░░░░░█...
This function provides a user interface to delete a book from a library system. It displays all books, prompts the user to input an ISBN, confirms the deletion of the selected book, and executes the deletion if confirmed. It includes error handling for invalid inputs and allows users to cancel the operation or return t...
def delete_book_interface(): clear() print(r''' ██████╗░███████╗██╗░░░░░███████╗████████╗███████╗  ██████╗░░█████╗░░█████╗░██╗░░██╗ ██╔══██╗██╔════╝██║░░░░░██╔════╝╚══██╔══╝██╔════╝  ██╔══██╗██╔══██╗██╔══██╗██║░██╔╝ ██║░░██║█████╗░░██║░░░░░█████╗░░░░░██║░░░█████╗░░  ██████╦╝██║░░██║██║░░██║█████═╝░ ...
def sort_book_superlist(category, order): """ Gets superlist of books in sublist form. """ book_superlist = turn_books_into_sublists() """ Sorts the superlist of books according to 'category' which determines which detail to sort by (using index of detail in book sublist), and order, which ...
The function `sort_books()` repeatedly prompts the user to sort books by category (e.g., ISBN, author, title) and order (ascending/descending). It validates inputs for integer values and valid options (1–7 for categories, 1–2 for order). If invalid, it displays errors. Valid inputs trigger sorting via `sort_book_superl...
def sort_books(): """ Loop to repeatedly ask user if they want to sort the display of books. If 'n' or 'N' is entered, breaks the loop. If anything else is entered, continues on with sorting options. """ while input("------------------------------------------------------------------------------...
def generate_points(npoints, radius): points = [Point() for _ in range(npoints)] # note: this is not a uniform 2-d distribution for p in points: r = random() * radius ang = random() * 2 * pi p.x = r * cos(ang) p.y = r * sin(ang) return points def lloyd(points, nclusters...
The code's main task is to generate 30,000 3D points, cluster them into 7 groups using Lloyd's algorithm (a k-means variant), and visualize the resulting clusters in an EPS image file, showcasing the spatial distribution of data points and their assigned cluster centers.
def main(): npoints = 30000 k = 7 # # clusters points = generate_points(npoints, 10) cluster_centers = lloyd(points, k) print_eps(points, cluster_centers)
def build_graph(self, g, root, x): p = [0] * len(g) G = nx.Graph() lt = {} def dfs(u, d): nonlocal x nonlocal G G.add_node(u); if g[u][0] >= 0: G.add_edge(u, g[u][0]) dfs(g[u][0], d - 1) p[u] = x lt[u] = [x, d, 0] x += 1 if g[u][1] >= 0: ...
This code constructs two graph structures (likely binary trees) from string patterns "LRLR" and "LRLLR", adds them to the scene, labels them as "Zig-zag" and "Zig-zig", then applies splay operations to demonstrate tree rotations or transformations, visualizing structural changes in each graph with specific parameters.
def construct(self): G, g, _, _ = self.build_graph(self.from_str("LRLR"), 0, -5) G1, g1, _, _ = self.build_graph(self.from_str("LRLLR"), 0, 1) self.add(G) self.add(G1) self.play(Write(Text('Zig-zag').next_to(G, UP)), Write(Text('Zig-zig').next_to(G1, UP))) self.splay(G, g, 4, -5) self.splay(...
def initialize_class_expression_learning_problem(self, pos: Set[OWLNamedIndividual], neg: Set[OWLNamedIndividual]): """ Determine the learning problem and initialize the search. 1) Convert the string representation of an individuals into the owlready2 representation. 2) Sampl...
This code learns an OWL Class Expression that distinguishes positive and negative examples by iteratively refining candidate concepts, validating inputs, sampling negatives when needed, and terminating based on runtime or concept limits. It uses heuristic search with quality evaluation and Q-value prediction to find a ...
def fit(self, pos: Set[OWLNamedIndividual], neg: Set[OWLNamedIndividual], max_runtime=None): """ Find an OWL Class Expression h s.t. \\forall e in E^+ K \\model h(e) \\forall e in E^- K \\not\\model h(e) """ assert isinstance(pos, set) and isinstance(neg, set) try...
def assign_embeddings(self, rl_state: RL_State) -> None: """ Assign embeddings to an rl state. An rl state is represented with vector representation of all individuals belonging to a respective OWLClassExpression """ assert isinstance(rl_state, RL_State) # (1) Detect mod...
The code implements an exploration-exploitation tradeoff mechanism to select the next state. With probability epsilon, it randomly explores next_states; otherwise, it exploits by choosing the optimal next state via the exploitation method. It then updates embeddings and evaluates the next state's quality before returni...
def exploration_exploitation_tradeoff(self, current_state: AbstractNode, next_states: List[AbstractNode]) -> AbstractNode: """ Exploration vs Exploitation tradeoff at finding next state. (1) Exploration (2) Exploitation """ if np....
def init_training(self, pos_uri: Set[OWLNamedIndividual], neg_uri: Set[OWLNamedIndividual]) -> None: """ Initialize training. @return: """ """ (1) Generate a Learning Problem """ self._learning_problem = PosNegLPStandard(pos=pos_uri, neg=neg_uri).encode_kb(self.kb) ...
The main task of the code is to implement a reinforcement learning (RL) training loop for an ontology reasoning system. It initializes the RL environment with given positive/negative examples, optionally learns from a provided goal path, and runs multiple episodes where it generates state transitions, collects rewards,...
def rl_learning_loop(self, pos_uri: Set[OWLNamedIndividual], neg_uri: Set[OWLNamedIndividual], goal_path: List[RL_State] = None) -> List[float]: """ Standard RL training loop 1. Initialize RL environment for training 2. Learn from an illustration if possible ...
def retrieve_concept_chain(rl_state: RL_State) -> List[RL_State]: hierarchy = deque() if rl_state.parent_node: hierarchy.appendleft(rl_state.parent_node) while hierarchy[-1].parent_node is not None: hierarchy.append(hierarchy[-1].parent_node) hierarchy...
The `train` method trains a reinforcement learning (RL) agent on learning problems using a dataset of target concepts and example sets. It iterates over the dataset `relearn_ratio` times, processing each problem by generating a goal path, executing RL learning loops to accumulate rewards, and logging progress. It track...
def train(self, dataset: Iterable[Tuple[str, Set, Set]], relearn_ratio: int = 2): """ Train RL agent on learning problems with relearn_ratio. @param dataset: An iterable containing training data. Each item corresponds to a tuple of string representation of target concept, a set of positi...
def get_combined_result(path): """ path: String of parent path Return combined DF(all_model worked, ISO_SW_support, Local support) """ # Path and files for worked list # path is # 'C:/Users/tskdkim/Current_Job/ANAB/ANAB_Capability/Meta_data/worked_list' # save_path = # 'C:/Users/tsk...
The main task of the code is to initialize an object that processes data from a given parent path. It combines data from multiple sources into a unified DataFrame (`self.df`), initializes lists for model and volume distributions (`pl_models_list`, `pl_vol_list`), and prepares these distributions using `set_pl_model_dis...
def __init__(self, parent_path): """ parent_path: String, path name of parent's path """ # Combined DF of model's worked, ISO_SW_Support,and Local Capability self.parent_path = parent_path self.df = get_combined_result(parent_path) self.pl_models_list = None ...
def _set_game_variables(self) -> None: """ assigns default values for the game :return: None """ self.game.set_current_word(tk.StringVar()) self.game.set_discovered_str(tk.StringVar()) self.game.set_timer(tk.StringVar()) self.game.set_score(tk.IntVar()) de...
The code initializes a BoggleUserInterface, setting up a Tkinter GUI window, linking it to a BoggleGame instance, loading assets, creating main menu and rules screens, and configuring window properties like title, size, and visibility for a Boggle game application.
def __init__(self, game: BoggleGame) -> None: """ initializes a BoggleUserInterface instance :param game: a BoggleGame instance to manage all dynamic variables and make calculations :return: None """ # Initilization root = tk.Tk() root.attributes('-alpha',...
def play_song(name: str) -> None: """ plays a song via pygames mixer :param name: path to the song file :return: None """ mixer.music.load(name) mixer.music.set_volume(consts.MUSIC_VOLUME) mixer.music.play() def _set_game_variables(self) -> None: """ assigns default value...
This method initializes and displays the game interface by playing the theme song, restarting the game, setting variables, starting a countdown, creating the game screen, configuring layout weights for the display frame, and showing the game frame to the user.
def _show_game_frame(self) -> None: """ brings the game frame to the front, shows it to the user and plays the game theme song :return: None """ play_song('assets/game-theme.mp3') self.game.restart() self._set_game_variables() self.game.start_timer() ...
def _show_game_frame_and_destroy(self, root: tk.Tk) -> None: """ shows game frame and destroys root """ self._show_game_frame() root.destroy() def _show_main_menu_frame_and_destroy(self, root: tk.Tk) -> None: """ shows game frame and destroys root """ ...
This function displays an end-of-game popup showing the player's score, offering options to restart the game or return to the main menu. It stops the game timer, creates a Tkinter window with score label, "Play again?" prompt, and Yes/No buttons. Each button triggers respective actions: "Yes" restarts the game, "No" re...
def show_end_message(self) -> None: """ shows the ending message pop up for the game :return: None """ self.game.stop_timer() root = tk.Tk() root.title("End") frame = tk.Frame(root, width=300, height = 250) l1 = tk.Label(frame, font=(consts.MAIN_FO...
def doGrow(self, player, action): coord = self.getCoordByIndex(action.targetId) cell = board.map.get(coord) targetTree = trees.get(cell.getIndex()) if not targetTree: raise Exception('tree not found') if targetTree.owner != player: raise Exception('not owner of tree') ...
The code processes player actions by executing grow, seed, or complete actions, skips waiting players, checks for seed conflicts, plants seeds, removes dying trees, updates nutrients, and transitions to a sun move frame if all players are waiting.
def performActionUpdate(self): for p in self.gameManager.players: if p.waiting: continue if p.action.isGrow(): self.doGrow(p, action) elif p.action.isSeed(): self.doSeed(p, action) elif p.action.isComplete(): self.doComplete(p, a...
def obtener_socket(self): """ Metodo para obtener el socket definido """ return self.mi_socket def obtener_direccion(self): """ Metodo para obtener la direccion del cliente que se va a conectar con el servidor. """ return self.direccion_cliente def...
The main task of the code is to establish a client connection to a server by initializing a socket connection, handling incoming messages, and managing outgoing message transmission, ensuring bidirectional communication between the client and server.
def ejecutar_cliente(self): """ Metodo que se encarga de conectar al cliente con el servidor """ self.obtener_socket().connect(self.obtener_direccion()) self.manejar_mensajes() self.enviar_mensajes()
def _create_cells(self): self._cells = [] for i in range(0, self._num_cols): col = [] for j in range(0, self._num_rows): x1 = self._x + i * self._cell_size y1 = self._y + j * self._cell_size x2 = x1 + self._cell_size ...
This code initializes a maze structure with specified dimensions and cell size. It creates a grid of cells, sets entrance/exit points, generates maze paths using a recursive backtracking algorithm (with optional random seed), and resets cell visitation status for future traversal.
def __init__( self, x, y, num_rows, num_cols, cell_size, win=None, seed=None, ): self._cells = None self._x = x self._y = y self._num_rows = num_rows self._num_cols = num_cols ...
def handle_height_width(image: NDArray, out_height: int, out_width: int, forward_implementation: bool): """ Changes height and width of image, according to input parameters """ greyscale_image = utils.to_grayscale(image) in_height, in_width = greyscale_image.shape horizontal_seams = None ver...
The main task of the code is to resize an input image to specified dimensions using either a forward or basic implementation. It returns a dictionary containing the resized image and visualizations of vertical/horizontal seams, where seams are highlighted in red (vertical) or black (horizontal) for analysis. The functi...
def resize(image: NDArray, out_height: int, out_width: int, forward_implementation: bool) -> Dict[str, NDArray]: """ :param image: ِnp.array which represents an image. :param out_height: the resized image height :param out_width: the resized image width :param forward_implementation: a boolean flag...
def VerifyToken(): currentEpochTime = int(round(time.time() * 1000)) remainingMilliseconds = _tokenExpiry - currentEpochTime remainingMilliseconds = 1 # token no longer valid, refresh if (remainingMilliseconds < 5000): # give it 5 seconds to react GetToken(); def UploadText(text): parameters = {'input': [text],...
The main task of the code is to translate input text using a service. It verifies a token, uploads the text, retrieves a request ID, waits for translation completion, and returns the translated result.
def TranslateText(text): VerifyToken(); res = UploadText(text); requestId = LanguageWeaverUtil.GetNamedNode(res, 'requestId') translationRes = WaitForTranslation(requestId) return LanguageWeaverUtil.GetNamedNode(translationRes, 'translation')[0]
def VerifyToken(): currentEpochTime = int(round(time.time() * 1000)) remainingMilliseconds = _tokenExpiry - currentEpochTime remainingMilliseconds = 1 # token no longer valid, refresh if (remainingMilliseconds < 5000): # give it 5 seconds to react GetToken(); def UploadFile(path): # requests will generate a ...
This function translates a file by uploading it to a service, waiting for the translation to complete, and then saving the result to a specified output path. It verifies a token for authentication, uploads the input file, retrieves a request ID, waits for translation completion, and writes the translated content to the...
def TranslateFile(inpath, outpath): VerifyToken(); res = UploadFile(inpath) requestId = LanguageWeaverUtil.GetNamedNode(res, 'requestId') translationRes = WaitForTranslation(requestId) f = open(outpath, "wb") try: bytes = f.write(translationRes) finally: f.close()
def checkGameEnd(self): if (2048 in self.board): # Win self.gameEndFrame("Win") self.timerPaused() return True elif self.movePossible(): # Lose self.gameEndFrame("Lose") self.timerPaused() return True else: retur...
This method handles keyboard inputs to control a game. It processes AI gameplay using expectimax or MCTS algorithms, executes single AI moves, pauses the game, or triggers user-controlled moves. Depending on the key pressed, it updates the game board, adds new blocks, updates scores, and refreshes the GUI until the gam...
def keyPress(self, event): validGame = True key = repr(event.char) # gets char value of input if key == AIPLAY and not self.isPaused: #AI Play Game validMove = True while not self.checkGameEnd(): # loops until game ended self.board, validMove, self.score =...
def get_subvolumes_reaction_rate_sum(self) -> ndarray: """ Returns a 2D array of reaction rates for each subvolume. :return: ndarray """ return self.get_subvolumes_reaction_rates().sum(axis=2) def get_subvolumes_total_rate(self) -> ndarray: """ Returns a 2D array ...
The code simulates a reaction-diffusion process by handling events from a priority queue. It updates visualizations, processes reactions or diffusion events based on probability, executes reactions by modifying molecule counts, and adjusts diffusion rates. It recalculates event timings and updates the queue for affecte...
def step(self, loop_count: int): print(f"{loop_count} : {self.matrix.get_total_molecules_count()}") for i in range(len(self.species)): ims[i].set_data(self.matrix.underlying_matrix[:, :, i]) next_event: SubVolume = self.event_queue.extract_min() if next_event is None: ...
def clear_cache(self): self.subvolumes_diffusion_rates = None self.subvolumes_reaction_rates = None self.subvolumes_next_event_times = None def get_subvolumes_next_event_times(self) -> ndarray: """ Returns the time of the next event. :return: float """ if ...
The code initializes an event queue by iterating through subvolumes, checking if their next event time is positive, and inserting active subvolumes into the queue with their coordinates, diffusion rates, reaction rates, and next event times.
def initialize(self): self.clear_cache() for x in range(self.get_subvolumes_next_event_times().shape[0]): for y in range(self.get_subvolumes_next_event_times().shape[1]): if self.get_subvolumes_next_event_times()[x, y] > 0.0: self.event_queue.insert( ...
def clear_screen(): os.system("cls") def display_rate(): print( ''' +======================+ || List of FX Rate || +======================+ ''' ) for entry in fxRateRepository.get_fx_rate().get("currencies"): print("-" * 20) print("+ {} ...
This code displays a menu for a FOREX application, allowing users to view all exchange rates, add new rates, update existing rates, or delete rates. It captures user input and directs the program to the corresponding function (display_rate, add_rate, update_rate, delete_rate) based on the selection, with conditional ch...
def display_menu(): print("\t-----FOREX APP-----") print("\t[1] Display all fx rates.") print("\t[2] Add new rate") print("\t[3] Update existing rate") print("\t[4] Delete existing rate") selection = input("Enter choice: ") if selection == "1": clear_screen() display_rat...
def filelabel(self): """ Give a label to files associated with this backlight model. """ f = "backlight-model-" f += "-".join([f"{len(self.data[k])}{k}" for k in self.data]) if self.label is not None: f += "-" + self.label return f def rprs_actual(self...
This code performs Markov Chain Monte Carlo (MCMC) sampling to infer parameters of a model (likely related to astrophysical data analysis, such as exoplanet transit light curves with spots). It initializes walkers with random parameters, runs the MCMC for a specified number of steps, saves results, and identifies the m...
def sample(self, nburn=5000, nsteps=5000, nwalk=100, remake=False): """ Run an MCMC to sample from the probability distribution for TLSE parameters. Parameters ---------- nburn : int The number of steps to skip. nsteps : int The number of ...
def pop_stack_to_D() -> str: return "\n".join([load_stackpointer_to_A(), "D=M"]) def load_stackpointer_to_A() -> str: return "\n".join([decrement_stackpointer(), "A=M"]) def increment_stackpointer() -> str: """ "Returns the code for incrementing the stack pointer""" return "\n".join(["@SP", "M=M+1", ""]...
This function generates assembly code for a comparison operation. It creates labels, uses conditional jumps based on the input command, and sets the stack's top value to 0 or -1 depending on the comparison result, then increments the stack pointer.
def write_compare(command: str) -> str: jump = "J" + command.upper() global label_count label_count = label_count + 1 return "\n".join( [ pop_stack_to_D(), load_stackpointer_to_A(), "D=M-D", f"@LABEL.{label_count}", f"D;{jump}", ...
def pop_stack_to_D() -> str: return "\n".join([load_stackpointer_to_A(), "D=M"]) def load_segment(segment: str, index: int) -> str: return "\n".join( [ f"@{segment}", "D=M", f"@{index}", "A=D+A", ] ) def increment_stackpointer() -> str: ""...
The function generates assembly code for pushing or popping values from specific memory segments (e.g., temp, pointer, static) in a virtual machine. It constructs instruction sequences based on the command type ("push" or "pop"), memory segment, and index, using helper functions to manipulate the stack and registers. T...
def write_pushpop(command: str, segment: str, index: int) -> str: match command: case "pop": if segment == "temp": return "\n".join( [ f"@R{5 + int(index)}", "D=A", f"@R{5 + int(index)}"...
def pop_stack_to_D() -> str: return "\n".join([load_stackpointer_to_A(), "D=M"]) def load_stackpointer_to_A() -> str: return "\n".join([decrement_stackpointer(), "A=M"]) def increment_stackpointer() -> str: """ "Returns the code for incrementing the stack pointer""" return "\n".join(["@SP", "M=M+1", ""]...
The function `write_arithmetic` generates assembly code instructions for arithmetic operations on a stack-based virtual machine. It maps input commands like "add", "sub", "neg", "and", "or", "not", and comparison operators to corresponding assembly instructions, handling each case by returning a sequence of operations ...
def write_arithmetic(command: str) -> str: match command: case "add": return "\n".join( [ pop_stack_to_D(), load_stackpointer_to_A(), "M=D+M", increment_stackpointer(), ] )...
def get_s1_idx(nhash): #import pdb; pdb.set_trace() goal = floor(nhash % S1_LEN) print(f"- goal=0x{(goal & 0xffffffff):x}") s = goal % (NUM_SYLLABLES+1) print(f"- s=0x{(s & 0xffffffff):x}") n = goal // (NUM_SYLLABLES+1) - 1 print(f"- gn=0x{(n & 0xffffffff):x}"); print(f"- nhash=0x{(n&0x...
The function generates a string by computing the CRC32 hash of an integer `n`, then using successive divisions of the hash by predefined lengths (`S1_LEN`, `S2_LEN`, etc.) to retrieve indices from four functions (`get_s1_idx`, `get_s2_idx`, etc.). These indices are concatenated into a final string and returned.
def robot_named_n(n): nhash=crc32c(n.to_bytes(4, 'big')) print(f"robot_named_n n=0x{n:x} nhash=0x{nhash:x}") l = [] l.append(get_s1_idx(nhash)); nhash //= S1_LEN l.append(get_s2_idx(nhash)); nhash //= S2_LEN l.append(get_s3_idx(nhash)); nhash //= S3_LEN l.append(get_s4_idx(nhash)); nhash //=...
def createPath(): # create directories os.makedirs(pathHeaderNodes) os.makedirs(pathHeaderRelations) os.makedirs(pathNodes) os.makedirs(pathRelations) def createEpsNodes(): for k in [1,2,3,4]: tempEps = eps(k) epsSingletonNodes.append(tempEps) def createRiskGroups(): #low, me...
The code generates epsilon-related data structures (paths, nodes, risk groups, combinations) and exports them to CSV, measuring execution time and printing generated epsilon combination IDs for verification.
def createAll(): tic = time.time() createPath() createEpsNodes() createRiskGroups() createRsCombinations() createEpsilonCombination() createEdgeOnts() writeToCSV() toc = time.time() # timer print("--- %s seconds ---" % (toc - tic)) for element in epsCombNodes: pri...
def collectBets(self): self.setPrizeEligibilities() self.betAmount = 0 for p in self.playersInGame(): self.pot += p.betting p.setChips(-p.betting) p.resetBet() p.label.config(text=p.name + '\n chips: ' + str(p.chips)) def handIsLive(self): ...
The main task of the code is to conclude a game hand by collecting bets, incrementing the hand count, checking game state conditions, dealing necessary cards (flop, fourth, fifth), determining winners, and returning the list of winners. It handles both live and non-live hand scenarios, ensuring proper card setup and wi...
def endHand(self): self.collectBets() self.hands += 1 if self.handIsLive(): if not self.nextRoundIsPlayable(): if self.threeCardFlop == []: self.setThreeCardFlop() if self.fourthCard == None: self.setFourthCard()...
def collectBets(self): self.setPrizeEligibilities() self.betAmount = 0 for p in self.playersInGame(): self.pot += p.betting p.setChips(-p.betting) p.resetBet() p.label.config(text=p.name + '\n chips: ' + str(p.chips)) def setActivePlayer(self, orde...
The method `endRound` manages a game round's progression by collecting bets, setting active/end players, and sequentially dealing cards (three-card flop, fourth, fifth) based on current state. It returns a stage indicator (0-3) to signal round progression or hand termination.
def endRound(self): self.collectBets() self.setActivePlayer(self.getStartingPlayerOrder()) self.setEndPlayer(self.getStartingPlayerOrder()) if self.threeCardFlop == []: self.setThreeCardFlop() return 0 elif self.fourthCard == None: self.setFour...
def parseArgs(): parser = argparse.ArgumentParser() parser.add_argument("--args", nargs='?', default=None, help="Argument, default: None") args = parser.parse_args() return args.args def getFuncList(filename): # if file eixst if not os.path.isfile(filename): return None ...
The code's main task is to execute a greedy optimization experiment on a list of functions from "fn.txt" using an original binary file ("original.bc"), calculate performance improvements (speedups), and save results including final speedup metrics, function-specific relative speedups in "greedy_result.txt", and detaile...
def main(): arg = parseArgs() FN_FNAME = "fn.txt" ORI_BC_FNAME = "original.bc" fn_list = getFuncList(FN_FNAME) if not fn_list: print("Function list (fn.txt) is empty or does not exist") return if not os.path.isfile(ORI_BC_FNAME): print(ORI_BC_FNAME + " does not exist")...
def download_file(url, dst_path): """ Download a file. This function was copied from https://note.nkmk.me/python-download-web-images/ . Parameters ---------- url: string A download URL to the benchmarking data of the i-th algorithm. dst_path: path A path to save the download...
The code post-processes experimental data from the noiseless BBOB function set by downloading algorithm performance data, calculating function evaluations to reach targets, ERT (Expected Runtime), and SP1 values, ranking optimizers, and generating ECDF proportions. It handles data extraction, metric computation, and re...
def run(): """ Post-processing experimental data obtained on the noiseless BBOB function set """ # Extract the algorithm name and the url link to data bbob_suite = 'bbob' exdata_dir_path = './{}_exdata'.format(bbob_suite) os.makedirs(exdata_dir_path, exist_ok=True) # For the noi...
def get_id(message: Message): if message is None: return -1, -1 return message.chat.id, message.message_id def get_user_from_message(message: Message) -> User: chat_id, _ = get_id(message) name = get_user_name(message) username = message.from_peer.username return User(None, str(chat_id),...
This function processes incoming messages by checking if they contain text or non-text content. It retrieves or creates a user in the database based on the chat ID, determines if the message is a command (starting with "/"), and routes the message to appropriate handlers for commands, text, or non-text content.
def handle_update(update: Update): if update.message is not None: message: Message = update.message chat_id, _ = get_id(message) user = db.get_user(chat_id) if user is None: db.add_user(get_user_from_message(message)) if message.text is not None: if ...
def print_all_data(): # Print all customers print(f"{ORANGE}Customers:{RESET}") for customer in session.query(Customer).all(): print(f" {GREEN} {customer}{RESET}") # Print all restaurants print(f"{ORANGE}\nRestaurants:{RESET}") for restaurant in session.query(Restaurant).all(): ...
The main task of the code is to handle user commands for managing a customer database. It performs actions like viewing all data, searching customers by username, creating customers with orders, adding orders, deleting orders, and viewing specific customer orders based on input parameters. Each conditional branch execu...
def main(view, search, create_customer, add_order, delete_order, view_orders): if view: print_all_data() elif search: customer = session.query(Customer).filter_by(username=search).first() if customer: print(f"{GREEN}Customer found:{RESET}") print(f"{GREEN}{custome...
def make_tree(directory): backup = os.getcwd() os.chdir(directory) tree = build_branch('') build_path(tree, '') os.chdir(backup) return tree def make_toc(node, ext, short_index): toc = ['**Table of Contents**\n'] depth = node.depth() for n in node: if n is not node: ...
The function processes a directory tree to generate structured markdown content with table of contents, edit links, anchor points, and hierarchical headings, then organizes the output into a list of sections for documentation or website generation.
def build_md_main(directory, ext, repo, root, short_index, **settings): tree = make_tree(directory) id_map = [] for node in tree: id_map.append((node.id, node)) for n in tree: n.content = make_toc(n, ext, short_index) + n.content for n in tree: n.content.insert(0, ...
def show_game_title(self) -> None: """Prints the game title at the start of the game.""" title = "Welcome to my card game. Developed by Bc. Matej Kopecky.\n" print(title) def get_players_fast(self): """Get default players without user input.""" p1 = Player("Matej", 23, self._ctu_...
The code initializes a card game by creating specific card types (stop and draw-two cards), setting up players based on the 'settings' parameter (normal/fast), creating game decks, distributing cards to players, and initiating the game. It handles game setup, player configuration, and starts the gameplay process.
def __init__(self, ctu_v: ctu, settings = "normal") -> None: #Some rules stop_num = "A" self._stop_cards = [Card(s, stop_num, ctu_v) for s in ctu_v.card_suits] #self._cards = [Card(s, n, ct) for s in suits for n in numbers] draw_two_num = 7 self._draw_tw...
def PB1(): ''' "Interfata" pentru prima problema, unde utilizatorul introduce datele si obtine rezulatul dorit prin divesre subprograme ''' test_get_largest_prime_below() n = int(input("Introduceti valoarea numarului: ")) rez = get_largest_prime_below(n) print(f"Rezultatul functiei [get_larg...
The main task of the code is to provide a menu-driven interface where users select an option (1-4) to execute specific functions (PB1, PB14, PB5) or exit. It continuously prompts for input, processes the choice, and terminates when option 4 is selected. Invalid inputs trigger an error message.
def main(): while True: optiune = int(input("Introduceti problema dorita aici: ")) if optiune == 1:#Problema aleasa din prima jumatate PB1() elif optiune == 2:#Problema aleasa din a doua jumatate PB14() elif optiune == 3:#Problema in plus PB5() ...
def assignment_complete(self, assignment): """ Return True if `assignment` is complete (i.e., assigns a value to each crossword variable); return False otherwise. """ return True if len(assignment) == len(self.crossword.variables) else False def select_unassigned_variable(self, a...
The main task of the code is to implement a backtracking search algorithm to solve a crossword puzzle by assigning words to variables (clues) while ensuring constraints are satisfied. It recursively selects unassigned variables, tries possible values, checks consistency, applies inference to prune invalid domains, and ...
def backtrack(self, assignment): """ Using Backtracking Search, take as input a partial assignment for the crossword and return a complete assignment if possible to do so. `assignment` is a mapping from variables (keys) to words (values). If no assignment is possible, return No...
def enforce_node_consistency(self): """ Update `self.domains` such that each variable is node-consistent. (Remove any values that are inconsistent with a variable's unary constraints; in this case, the length of the word.) """ for var in self.domains: # Takin...
The code solves a Constraint Satisfaction Problem (CSP) by enforcing node and arc consistency to reduce the search space. It first ensures each variable's domain adheres to unary constraints (`enforce_node_consistency`), then removes inconsistent values across variable pairs via the AC3 algorithm. Finally, it uses back...
def solve(self): """ Enforce node and arc consistency, and then solve the CSP. """ self.enforce_node_consistency() self.ac3() return self.backtrack(dict())
def embedded_corefs(corefs): embed = False res = None for t in corefs: if (t[0] <= t[2] and t[1] > t[3]) or (t[0] < t[2] and t[1] >= t[3]): embed = True elif (t[2] <= t[0] and t[3] > t[1]) or (t[2] < t[0] and t[3] >= t[1]): embed = True else: res =...
The function `apply_split_policy` determines optimal split points in source and target sentences based on coreference information to avoid breaking coreference links. It evaluates embedded coreferences, antecedent-mention gaps, and multiple coreference events, prioritizing splits that maintain coherence while adhering ...
def apply_split_policy(idx, src, tgt, coref_dict, args): split_code = 0 min_segment_tokens = args.min_length[0]//2 if coref_dict is not None and idx in coref_dict: if args.verbose: print(' ###################################################') print(' *** coref_dict[{}]: {...
def create_label_vector(dataset, ontology_by_id): """ Returns given dataset with some label fields. """ labels = [] label_ids = [] label_names = [] sound_ids = [] for node_id, obj in dataset.items(): label_ids.append(node_id) label_names.append(ontology_by_id[node_id]['n...
The main task of the code is to process multiple datasets by computing statistical aggregations of audio embeddings, clustering audio samples based on similarity matrices, and saving clustering results, features, and evaluation metrics for visualization. It iterates through embedding types, calculates mean features, ge...
def statistical_agg_main(datasets, ontology_by_id): #========= original pipelines ======================================= for dataset in datasets: sound_ids, true_labels, label_ids, label_names = create_label_vector(dataset['dataset'], ontology_by_id) for embedding_name, embedding_folder in EMB...
def doCmd(cmd): encoding = 'latin1' printLongLine() #This functions executes and dispplays the output of the command print('doCmd():', cmd) cmd = cmd.encode(encoding) + b'\n' subpro.stdin.write(cmd) subpro.stdin.flush() #just show the first 5 lines for repeat in range(0, 90): ...
The main task of the code is to iterate through a list of dates (ListCWA), set each date as a variable using TSO commands, submit a JCL job for processing, extract date components (day, month, year), reformat them into a standardized date string (YYYYMMDD), and prepare this date for subsequent use, likely in exporting ...
def compareFiles(): for i in range(len(ListCWA)): # Set the CWA date used for Job run cmd = 'String("TSO CALL \'TDEAAPP.CREDIT.LNKBA.TDEB(ARTDATE)\' ")' + 'String("\'")' + 'String("' + ListCWA[i] + '")' + 'String("\'")' doCmd(cmd) cmd = 'Enter()' doCmd(cmd) checkRes...
def doCmd(cmd): encoding = 'latin1' printLongLine() #This functions executes and dispplays the output of the command print('doCmd():', cmd) cmd = cmd.encode(encoding) + b'\n' subpro.stdin.write(cmd) subpro.stdin.flush() #just show the first 5 lines for repeat in range(0, 90): ...
The main task of the code is to automate the submission of two production transfer jobs (PRODFOY and PRODVDR) for Germany's PROD and Baseline Test environments. It navigates a system interface to input environment codes, transfer options, and specific file names (e.g., TPRGPPL.TESTCASE.MCD#2021.FOYER and .VDR), submits...
def importRelease(): # Submit the PRODFOY job for the foyer file cmd = 'String("TSO PRODFOY FILE")' doCmd(cmd) cmd = 'Enter()' doCmd(cmd) # Insert the PROD environment for Germany cmd = 'String("PDEU")' doCmd(cmd) # Insert the Baseline Test environment for Germany cmd = 'Strin...
def importRelease(): # Submit the PRODFOY job for the foyer file cmd = 'String("TSO PRODFOY FILE")' doCmd(cmd) cmd = 'Enter()' doCmd(cmd) # Insert the PROD environment for Germany cmd = 'String("PDEU")' doCmd(cmd) # Insert the Baseline Test environment for Germany cmd = 'Strin...
The main task of the code is to automate a release process by repeatedly submitting TSO jobs (FDXDOS and DB2#RELS) for each entry in ListCWA. It imports release data, sets a CWA date, submits jobs, checks their success (RC=00), and iterates through all entries. The loop ensures sequential job execution and validation f...
def runRelease(): # reimport the foyers and vendors importRelease() i = 0 while runs > i: # Set the CWA date used for Job run cmd = 'String("TSO CALL \'TDEAAPP.CREDIT.LNKBA.TDEB(ARTDATE)\' ")' doCmd(cmd) cmd = 'String("\'")' + 'String("' + List...
def runFdxdos(): # create pop-up screen to ask for how many events FDXDOS will run window = Tk() window.title('Establish the number of events to run') # specify size of window. window.geometry("920x250") # Create label l = Label(window, text = "Please select from below how many CWA based e...
This code automates mainframe operations by connecting to a system, logging in with user credentials, navigating menus, submitting jobs (e.g., TDEBQSM, PRODFOY), transferring files (FOYER, VDR), executing baseline/release scripts, and comparing results. It interacts with s3270.exe to handle terminal sessions, input com...
def main(): #Main print("Hello, world!") runFdxdos() print("Opening s3270.exe") print("Sending the command ") #s3270 command: Connect(172.21.2.135) cmd ="Connect(172.21.2.135)" doCmd(cmd) #s3270 cmd: Wait the screen to show something cmd = "Wait(3270mode)" doCmd(cmd) ...
def _delete_closing_message(self) -> http.client.HTTPResponse | None: closing_message_id = self.__settings.last_message_id if closing_message_id is not None: with contextlib.suppress(urllib.error.URLError): url = f'{self.__base_url}/deleteMessage' request_data...
The main task of the code is to securely send credentials and formatted password information to a specified chat, with optional archiving. It constructs messages from input parameters, escapes/formatting text, sends them to a primary chat, and duplicates to an archive chat if enabled. Error handling for HTTP issues is ...
def keep(self, password_: password.Password, credentials: str, note: str = None) -> None: try: self._delete_closing_message() credentials_message = f'{credentials}\n\n{note or ""}'.rstrip('\n') self._send_message(credentials_message, self.__settings.chat_id) forma...
def check_game_over(self): return self.__has_collided_with_wall() or self.__has_collided_with(self.segments[1:], 5) def __get_heading(self, index: int): return self.segments[index].heading() def __get_segment_position(self, index: int): return self.segments[index].position() def __segments_follo...
This code moves a game object's head in the current direction, updates its position based on the heading (0°, 90°, 180°, 270°), and triggers segment following. It checks if the game is over before proceeding, then adjusts the head's coordinates according to the heading and speed, finally updating movement speed for the...
def move_forward(self): if not self.check_game_over(): previous_heading = self.__get_heading(0) previous_position = self.__get_segment_position(0) self.__segments_follow() match previous_heading: case previous_heading if previous_heading == 0: ...
def read_corr(csv_file): """Read corr results in a csv file""" results = [] with open(csv_file, 'r') as infile: for line in infile: terms = line.rstrip().split(",") if terms[0] == 'l': continue results.append(CorrRes(terms)) return results def ...
The function `fitp2` reads correlation data from a file, prepares fitting data within specified x-range limits, and generates a plot and JSON file containing the best-fit results for a "p2" model. It processes input data, performs fitting, and outputs visualization and structured data for analysis.
def fitp2(corr_file, prefix, xmin, xmax): """Fit p2""" corr_results = read_corr(corr_file) fitdata = prepare_fitting_data(corr_results, xmin, xmax) plot_file = prefix + "_best_fit.svg" json_file = prefix + "_best_fit.json" plot_fit(fitdata, plot_file, json_file)
def read_corr(csv_file): """Read corr results in a csv file""" results = [] with open(csv_file, 'r') as infile: for line in infile: terms = line.rstrip().split(",") if terms[0] == 'l': continue results.append(CorrRes(terms)) return results def ...
The main task of the code is to fit models to correlation data, generate best-fit plots, and save parameter results in a CSV file. It reads correlation data, processes it with specified x-ranges, extracts model parameters, and writes them to a structured output file while creating visualizations for analysis.
def fitp2(corr_file, prefix, xmin, xmax): """Fit p2""" corr_results = read_corr(corr_file) fitdatas = FitDatas(corr_results, xmin, xmax) if fitdatas.get("all"): best_fit_plot_file = prefix + "_best_fit.svg" plot_fit(fitdatas.get("all"), best_fit_plot_file) all_results = sorted(fit_...
def takeTurn(self, move): if isinstance(move, str): chessMove = chess.Move.from_uci(move) pieceMoved = self.board.piece_at(chessMove.from_square) if pieceMoved.piece_type == chess.PAWN and (chessMove.to_square in SQUARES[0:8] or chessMove.to_square in SQUARES[56:64]): ...
This code implements a turn-based chess game loop where a human player (white) and an AI engine (black) alternate moves. It handles user input validation, executes moves, switches turns, and lets the AI search for optimal moves while displaying progress stats. The loop continues indefinitely until externally terminated...
def play(self): self.turnColor = chess.WHITE while True: print(self.board) if self.turnColor == chess.WHITE: usrMove = input("Type Move: ") if (usrMove == "back"): continue try: self.takeTurn(...
def addPath(g: nx.Graph, path, path_cap): for i in range(0, len(path)-1): g[path[i]][path[i+1]]['cap'] += path_cap def pathCost(g: nx.Graph, path): max_cap = pathCapacity(g, path) flow_with = nx.maximum_flow(g, path[0], path[-1], capacity='cap')[0] flow_without = maxFlowWoPath(g, path, max_cap) ...
The code calculates the total cost of a set of paths in a graph, considering both individual path costs and penalties for overlapping edges between paths. For each path, it temporarily adds it to the graph, computes its cost, then removes it. It then adds a penalty of 100 per common edge between every pair of paths. Th...
def groupCost(g: nx.Graph, paths): cost = 0 for path in paths.keys(): addPath(g, path, paths[path]) cost += pathCost(g, path) removePath(g, path, paths[path]) ks = list(paths.keys()) for i in range(len(ks)-1): for j in range(i+1, len(ks)): cost += 100 * common...
def pathCost(g: nx.Graph, path): max_cap = pathCapacity(g, path) if max_cap == 0: return -1 flow_with = nx.maximum_flow(g, path[0], path[-1], capacity='cap')[0] flow_without = maxFlowWoPath(g, path, max_cap) #print(f'path: {path}, overload cost: {(flow_with - flow_without - max_cap)*100//ma...
The function `balanceCapacities` allocates capacity along paths in a graph to meet a required capacity (`req`). It iteratively selects the path with the minimum cost, assigns the minimum of its available capacity and the remaining required capacity, updates the graph’s capacities, and removes the path from the list. If...
def balanceCapacities(g: nx.Graph, paths, req): ret = {} cap = 0 while paths != []: if (cap == req): break path = min(paths, key=lambda x: pathCost(g, x)) pc = pathCapacity(g, path) ret[tuple(path)] = min(pc, req-cap) cap += ret[tuple(path)] remove...
def getNextPath(g: nx.Graph, candidates): global mf ret = min(candidates, key=lambda x: pathCost(g, x)) return ret def pathCost(g: nx.Graph, path): global mf max_cap = pathCapacity(g, path) if max_cap == 0: return -1 flow_with = mf flow_without = maxFlowWoPath(g, path, max_cap) ...
This function computes a set of paths in a graph to meet a specified capacity requirement between a source and target node. It uses maximum flow analysis to check feasibility, iteratively selects paths with optimal capacity, adjusts capacities to meet the demand, and removes used paths from the graph. The result is a d...
def findPaths(g: nx.Graph, fr, to, cap_req=1): global mf mf = nx.maximum_flow(g, fr, to, capacity='cap')[0] if cap_req > mf: print("Denied: no sufficient paths") return {} capacity, cost = 0, 0 paths = {} candidates = list(nx.all_simple_paths(g, fr, to)) req_met = False ...
def addPath(g: nx.Graph, path, path_cap): for i in range(0, len(path)-1): g[path[i]][path[i+1]]['cap'] += path_cap def getNPaths(g: nx.Graph, fr, to, path_num: int): graph = copy.deepcopy(g) size = graph.number_of_nodes() max_node = size+1 edges = list(graph.edges) for a, b in edges: ...
This function finds up to 'req' edge-disjoint paths in a graph from 'fr' to 'to', balancing capacities iteratively. It first checks if the requested paths exceed the max flow. If not, it repeatedly finds new paths, adjusts capacities, and stores valid paths until meeting the requirement or exhausting possibilities. The...
def findPaths(g: nx.Graph, fr, to, req = 10): mf = nx.maximum_flow(g, fr, to, capacity='cap')[0] if req > mf or req == 0: return {} p = 3 ret = {} pr_paths = [] paths = [0] while ret == {} and pr_paths != paths: for k in ret.keys(): addPath(g, k, ret[k]) ...
def getTitle(self, task_str = None): """Method to get the title of article in the xml doc. The task_str is a command to only return the column header f the method and will be used in the CVS file creation.""" #print("\t [+] getTitle()") if task_str == "headerCall": return "Title" #title:tag, get child.text c...
This method generates a list of column headers for structured data by sequentially calling specific getTitle() methods (e.g., for title, abstract, PMID) and appending manually added headers ("Keyword", "Counts"). It ensures headers appear in the same order as their corresponding data fields, maintaining consistency for...
def getTitlesOfCols(self): """Method to call each of the information gathering methods to determine what the headers of the information should be called. Each method (i.e., getTitle()) has a task that will only return the header name. Note, be sure have header names in the order of the data.""" # We are appending t...
def getTitle(self, task_str = None): """Method to get the title of article in the xml doc. The task_str is a command to only return the column header f the method and will be used in the CVS file creation.""" #print("\t [+] getTitle()") if task_str == "headerCall": return "Title" #title:tag, get child.text c...
The main task of the code is to search for specified keywords in document abstracts, collect document details (title, abstract, PMID, etc.), and return these details along with found keywords and their counts if any keywords are present. If no keywords are found, it returns None.
def getInformationOfKwInDocs(self): """A Method to locate the keywords in the document abstracts. If any keyword is found, return all details to program""" # print("getInformationOfKwInDocs()") #print("\n\t Searching abstract: {} \n".format(self.abstract_str)) # Get the details of the current article; used la...
def get_dataset(args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD transform = transforms.Compose([ transforms.Resize(256, interpolation=PIL.Image.BICUBIC), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean, std) ]) dataset = da...
The main task of the code is to load a pre-trained Vision Transformer (ViT) model, freeze its parameters, and perform feature analysis (attention and SVD) on a dataset using the model's encoder. It loads a checkpoint, configures the model for inference on GPU/CPU, and processes data via a DataLoader to extract and anal...
def main(args): device = torch.device( 'cuda') if torch.cuda.is_available() else torch.device('cpu') model = vits.__dict__['vit_base'](num_classes=0) for p in model.parameters(): p.requires_grad = False model.eval() model.to(device) dataset = get_dataset(args) data_loader = ...
def _formatter(data_format, fh, handler): fmtr_class = getattr(formatter, data_format, None) if fmtr_class is None: click.echo("Unknown format '{}'".format(data_format)) sys.exit(1) return fmtr_class(fh, handler) def _input_fh(in_file): return open(in_file, 'r') def print_bulk_summaries(...
This function creates users in bulk from an input file by formatting data, queuing user creation actions via an API connection, executing the queue, and reporting results. It processes each user's attributes, handles empty domains, and prints summaries of completed actions and errors.
def user_create_bulk(ctx, input_format, in_file): """Create users in bulk from an input file""" fmtr = _formatter(input_format, _input_fh(in_file), InputHandler('user_create_bulk')) umapi_conn = ctx.obj['conn'] queue = ActionQueue(umapi_conn) for user in fmtr.read(): if user['domain'] == ''...
def _formatter(data_format, fh, handler): fmtr_class = getattr(formatter, data_format, None) if fmtr_class is None: click.echo("Unknown format '{}'".format(data_format)) sys.exit(1) return fmtr_class(fh, handler) def _input_fh(in_file): return open(in_file, 'r') def print_bulk_summaries(...
This function deletes users in bulk from an input file (organization/identity directory) by parsing the file with a formatter, queuing delete actions (soft/hard) via UMAPI, executing them, and reporting results. It processes each user's email and hard_delete flag, uses an action queue for batch processing, and outputs ...
def user_delete_bulk(ctx, input_format, in_file): """Delete users in bulk from input file (from org and/or identity directory)""" fmtr = _formatter(input_format, _input_fh(in_file), InputHandler('user_delete_bulk')) umapi_conn = ctx.obj['conn'] queue = ActionQueue(umapi_conn) for user in fmtr.read(...
def _formatter(data_format, fh, handler): fmtr_class = getattr(formatter, data_format, None) if fmtr_class is None: click.echo("Unknown format '{}'".format(data_format)) sys.exit(1) return fmtr_class(fh, handler) def _input_fh(in_file): return open(in_file, 'r') def print_bulk_summaries(...
The main task of the code is to perform bulk user updates by reading data from an input file in a specified format, queuing update actions via an API connection, executing them, and reporting completed updates along with any errors. It processes each user record, batches updates, and provides summary feedback on the op...
def user_update_bulk(ctx, input_format, in_file): """Update users in bulk from input file""" fmtr = _formatter(input_format, _input_fh(in_file), InputHandler('user_update_bulk')) umapi_conn = ctx.obj['conn'] queue = ActionQueue(umapi_conn) for user in fmtr.read(): queue.queue_update_action(...
def _formatter(data_format, fh, handler): fmtr_class = getattr(formatter, data_format, None) if fmtr_class is None: click.echo("Unknown format '{}'".format(data_format)) sys.exit(1) return fmtr_class(fh, handler) def _input_fh(in_file): return open(in_file, 'r') def print_bulk_summaries(...
This function creates multiple groups in bulk from an input file. It processes the input using a formatter, queues group creation actions via an API connection, executes them, and reports completion status along with any errors.
def group_create_bulk(ctx, input_format, in_file): """Create groups in bulk from an input file""" fmtr = _formatter(input_format, _input_fh(in_file), InputHandler('group_create_bulk')) umapi_conn = ctx.obj['conn'] queue = ActionQueue(umapi_conn) for group in fmtr.read(): queue.queue_group_c...
def _formatter(data_format, fh, handler): fmtr_class = getattr(formatter, data_format, None) if fmtr_class is None: click.echo("Unknown format '{}'".format(data_format)) sys.exit(1) return fmtr_class(fh, handler) def _input_fh(in_file): return open(in_file, 'r') def print_bulk_summaries(...
This function updates multiple groups in bulk using data from an input file. It parses the input with a formatter, queues group update actions via an API connection, executes them, and prints summaries of completed updates and errors.
def group_update_bulk(ctx, input_format, in_file): """Update groups in bulk from input file""" fmtr = _formatter(input_format, _input_fh(in_file), InputHandler('group_update_bulk')) umapi_conn = ctx.obj['conn'] queue = ActionQueue(umapi_conn) for group in fmtr.read(): queue.queue_group_upda...
def _formatter(data_format, fh, handler): fmtr_class = getattr(formatter, data_format, None) if fmtr_class is None: click.echo("Unknown format '{}'".format(data_format)) sys.exit(1) return fmtr_class(fh, handler) def _input_fh(in_file): return open(in_file, 'r') def print_bulk_summaries(...
This function deletes multiple groups in bulk by reading group names from an input file, formatting them, queuing deletion actions via an API connection, executing the operations, and reporting completion status along with any errors. It uses a formatter to parse input, an action queue to manage deletions, and outputs ...
def group_delete_bulk(ctx, input_format, in_file): """Delete groups in bulk from input file""" fmtr = _formatter(input_format, _input_fh(in_file), InputHandler('group_delete_bulk')) umapi_conn = ctx.obj['conn'] queue = ActionQueue(umapi_conn) for group in fmtr.read(): queue.queue_group_dele...
def seedranges(seedsline): seeds = [] start = -1 nums = list(int(s) for s in seedsline.split(" ") if s.strip() != "") for n in nums: if start == -1: start = n else: seeds.append((start, start+n-1)) start = -1 # print(len(seeds)) return seeds de...
The code processes input data to parse seed ranges, applies a series of mutations (soil, fertilizer, water, light, temperature, humidity, location) to these seeds, and outputs each seed's transformed value along with the minimum result. It reads input lines, categorizes them into steps, cleans and mutates seed ranges, ...
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "input", nargs="?", default="-", metavar="INPUT_FILE", type=argparse.FileType("r"), help="path to the input file (read from stdin if omitted)") parser.add_argument( "output"...
def basic_search_view(self, request, form, search_query=None): """ Produce view for the basic search """ if not search_query: search_query = form.cleaned_data["query"] else: # Set the form query input to be equal to the search query, for # mor...
This function handles search requests by determining whether to use advanced or basic search views. It processes form data, checks request methods (GET/POST), validates forms, and redirects to appropriate views (basic/advanced) or exports results. It also displays search forms or results based on query parameters and f...
def search_dispatcher(self, request): """ Takes in searches and sends them to the advanced or basic view """ advanced = request.GET.get("advanced", False) # Build the form from the POST data if request.method == "POST": form = st_forms.SearchForm(request.POST) else: ...
def init(pop, popSize): for i in range(0, popSize): indiv = Chromosome() indiv.full(0) pop.append(indiv) def evalPop(pop, trainInput, trainOutput): for indiv in pop: computeFitness(indiv, trainInput, trainOutput) def selection(pop): pos1 = random.randrange(len(pop)) pos2 ...
The code implements a generational genetic programming algorithm to evolve a solution over multiple generations. It initializes a population, evaluates fitness using training data, iteratively selects individuals, applies mutation to generate offspring, replaces the population, and re-evaluates until the specified gene...
def GP_generational(popSize, noGenerations, trainIn, trainOut, maxDepth): global MAX_DEPTH MAX_DEPTH = maxDepth pop = [] init(pop, popSize) evalPop(pop, trainIn, trainOut) for g in range(0, noGenerations): popAux = [] for k in range(0, popSize): M = selection(pop) ...
def init(pop, popSize): for i in range(0, popSize): indiv = Chromosome() indiv.full(0) pop.append(indiv) def evalPop(pop, trainInput, trainOutput): for indiv in pop: computeFitness(indiv, trainInput, trainOutput) def selection(pop): pos1 = random.randrange(len(pop)) pos2 ...
The code implements a steady-state genetic programming algorithm to evolve a program (e.g., a tree) that minimizes error on given training data. It initializes a population, iteratively selects individuals, applies mutation to generate offspring, evaluates their fitness, and replaces the current best solution if the of...
def GP_steadyState(popSize, noGenerations, trainIn, trainOut, maxDepth): global MAX_DEPTH MAX_DEPTH = maxDepth pop = [] init(pop, popSize) evalPop(pop, trainIn, trainOut) for g in range(0, noGenerations): for k in range(0, popSize): M = selection(pop) off = mutati...
def compute_deflection(num_samples, summaries, gen): res = np.empty(num_samples) for i in range(num_samples): res[i] = fem_compliance_i(gen, summaries, i) return res def compute_load(num_samples, summaries, gen): res = np.empty(num_samples, dtype = int) for i in range(num_samples): r...
The code defines a function `analysis` that computes four metrics—deflection, load, vf error, and fm—using input parameters `num_samples`, `summaries`, and `gen`, then returns these computed values as a tuple.
def analysis(num_samples, summaries, gen): d = compute_deflection(num_samples, summaries, gen) l = compute_load(num_samples, summaries, gen) vf = compute_vf_error(num_samples, summaries, gen) fm = compute_fm(num_samples, gen) return d, l, vf, fm
def order_list(num_samples, num_folder): lst = np.empty(num_samples, dtype = int) s = [] for i in range(num_folder): s.append(str(i)) s.sort() for i in range(num_samples): lst[i] = int(s[i]) return lst def pre_process_summaries(dict_array, lst = None): for...
The function `topodiff_analysis` processes and analyzes generated images against summaries. It orders samples, preprocesses summaries, loads generated images from a file, applies thresholding to binarize pixel values, and executes an analysis comparing the processed data. The core task involves evaluating generated ima...
def topodiff_analysis(num_samples, num_folder, summaries, gen_dir): lst = order_list(num_samples, num_folder) summaries = pre_process_summaries(summaries, lst) gen = np.load(gen_dir + f"samples_{num_samples}x64x64x1.npz")["arr_0"] gen[gen < 127] = 0. gen[gen >= 128] = 255. return analysis(num_...
def basic_filitering(self): """ Basic Filtering """ print(f'number of Cells BEFORE Basic Filtering : {self.adata.n_obs}') sc.pp.filter_cells(self.adata, min_genes=self.filter_cells_min_genes,) #min_genes=self.over_n_genes_bycounts print(f'Filtering cells pp.filter_cells(adata, min_cells...
This method preprocesses single-cell RNA-seq data by resetting to raw counts, applying quality control filters, normalizing, identifying highly variable genes (HVGs), regressing out technical factors, performing PCA/UMAP, Leiden clustering, and evaluating clustering quality via silhouette scores. It includes data norma...
def PP(self): """ adsctl_gex.PP() doc string to add later""" sc.logging.print_header() print(f'############################################################################# # reset self.adata to raw counts') self.adata=self.adata_raw_counts.copy() # reset self.adata to raw count...
def init(self): self.init_controls() self.hide_all_controls() def add_pages_to_ui(self, pages): self.stackDetail.add(self.cameraView) def add_videos_to_ui(self, videos): video_rows = self.mainViewModel.get_video_rows() video_pages = self.mainViewModel.get_video_pages() fo...
The main task of the code is to initialize UI components when shown by creating a MainViewModel instance, retrieving pages and videos from it, and dynamically adding them to the user interface. The method initializes the view, sets up data binding through the view model, and populates the UI with page and video element...
def on_show(self, _): self.init() self.mainViewModel = MainViewModel(self) self.add_pages_to_ui(self.mainViewModel.get_pages()) self.add_videos_to_ui(self.mainViewModel.get_videos())