dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def move_random(self): # random move human player kalo waktu habis random.seed(timer()) pawns_position = [] for i in range(self.board_size): for j in range(self.board_size): if self.halma.board[i][j].kind == self.human_player: pawns_position.appen...
This function updates a countdown timer, decrementing every second until the time limit is reached. If time runs out, it triggers bot movement based on predefined behavior, checking game mode to determine movement logic. It continuously schedules itself to run again, updating the timer display until a winner is decided...
def update_timer(self): if self.time_limit != 0 and not self.winner: time_left = self.time_limit - floor(timedelta(seconds=timer() - self.timer_start).total_seconds()) if time_left >= 0: self.var_timer.set(time_left) self.master.after(1000, self.update_tim...
def get_tile_color(self, x, y): # selang-seling warna tile home_info = self.halma.get_home_info(x, y).kind if home_info == 1: return TILE_COLORS_RED[(x + y) % 2] elif home_info == 2: return TILE_COLORS_GREEN[(x + y) % 2] return TILE_COLORS[(x + y) % 2] def update...
This code initializes and configures a Halma game GUI, setting up the board with tiles, handling user interactions, and preparing game parameters like board size, mode, and time limits. It binds mouse events to tiles, initializes game state variables, and starts either human vs bot or bot vs bot gameplay based on selec...
def start_game(self): self.board_size = self.var_board_size.get() self.mode = self.var_mode.get() self.time_limit = self.var_time_limit.get() self.human_player = 3 if self.mode == GAME_MODE[2] else self.var_human_player.get() self.bot_player = 2 if self.human_player == 1 else 1 ...
def reshape_signal_canonical(signal): """Convert the signal into a canonical shape for use with cochleagram.py functions. This first verifies that the signal contains only one data channel, which can be in a row, a column, or a flat array. Then it flattens the signal array. Args: signal (array): The sou...
The function `generate_subband_envelopes_fast` computes subband envelopes (cochleagrams) of a time-domain signal using provided frequency filters. It optimizes performance by employing `rfft` for real-valued signals and manually computing the Hilbert transform to avoid redundant FFT/IFFT calls. Optional zero-padding an...
def generate_subband_envelopes_fast( signal, filters, padding_size=None, fft_mode="auto", debug_ret_all=False ): """Generate the subband envelopes (i.e., the cochleagram) of the signal by applying the provided filters. This method returns *only* the envelopes of the subband decomposition. The signal can b...
def reshape_signal_batch(signal): """Convert the signal into a standard batch shape for use with cochleagram.py functions. The first dimension is the batch dimension. https://github.com/mcdermottLab/pycochleagram/blob/master/pycochleagram/cochleagram.py Args: signal (array): The sound signal (waveform) in...
The function generates cochleagrams (subband envelopes) from an audio signal using an ERB (Equivalent Rectangular Bandwidth) filterbank. It decomposes the input signal into subbands via filtering, then optionally applies downsampling and nonlinearity (e.g., dB scaling) to the envelopes. The output depends on `ret_mode`...
def cochleagram( signal, sr, n, low_lim, hi_lim, sample_factor, padding_size=None, downsample=None, nonlinearity=None, fft_mode="auto", ret_mode="envs", strict=True, **kwargs ): """Generate the subband envelopes (i.e., the cochleagram) of the provided signal. ...
def update_selections_focus_buttons(self): """ code that transfers selected options and focused buttons from this view to product_component_selectors.js file """ self.call('setSelectedSizeColorQty', self.selected_size, self.selected_color, self.component_quantity) self.call('focu...
This method sets the component's size and color for rendering new selections, updates related UI elements, checks if the component is in a bag, and toggles detail visibility if not already shown.
def set_size_color(self, color, size): """ sets the size and color on the component for rendering new selections """ self.selected_size = size self.selected_color = color self.selected_rgba = self.rgba_colors[self.selected_color] self.update_selections_focus_butt...
def XOR(): for i in range(18): p[i] ^= key[i % 14] def subkeys(): k = 0 data = 0 for i in range(9): temp = encryption(data) p[k] = temp >> 32 k += 1 p[k] = temp & 0xFFFFFFFF k += 1 data = temp def encrypt_text(text): text_bytes = text.encode('u...
The code's main task is to encrypt and decrypt user input using a cipher (via XOR and subkeys functions), measure encryption/decryption times in milliseconds, and display the encrypted data in hexadecimal format along with the decrypted result. It tests cryptographic performance by timing both processes and outputs the...
def driver(): XOR() subkeys() encrypt_data = input("Masukkan Kalimat: ") start_time = time.time() encrypted_data = encrypt_text(encrypt_data) end_time = time.time() encryption_time_ms = (end_time - start_time) * 1000 print("Encrypted data : ", encrypted_data.hex()) print("Encryptio...
def encryption(data): L = data >> 32 R = data & 0xFFFFFFFF for i in range(16): L ^= p[i] L1 = func(L) R ^= L1 L, R = swap(L, R) L, R = swap(L, R) R ^= p[16] L ^= p[17] encrypted = (L << 32) ^ R return encrypted def encrypt_file(input_file_path, output_f...
The main task of the code is to encrypt and decrypt a file using a custom cryptographic algorithm. It initializes a key schedule by XORing key values, generates subkeys through iterative encryption, and applies these to encrypt the input file into a binary file. The encrypted file is then decrypted back to a text file,...
def driver(): input_file_path = "test.txt" encrypted_output_path = "OutputV4/encrypted_file.bin" decrypted_output_path = "OutputV4/decrypted_file.txt" # Key schedule initialization for i in range(18): p[i] ^= key[i % 14] # Generate subkeys k = 0 data = 0 for i in range(9): ...
def handshake(self): """3 steps:""" """1. SEND REQUEST""" if self.running: self.logger.log(LogTypes.INF, 'Handshake started') self.udp.send(PacketTypes.REQ) self.udp.update_source_port() """2. WAIT FOR PARAMETERS""" counter = 0 PARAMETERS_TRI...
(The main task of the code is to receive data via UDP, establish a handshake with the sender to retrieve vital parameters, receive packets, write the received data to a file, and handle errors like ConnectionResetError. It initializes a UDP socket, performs a three-step handshake, checks if the receiver is active, writ...
def run(self): self.logger.log(LogTypes.SET, 'Receiver has started') with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as self.socket: self.socket.setblocking(False) # socket does not have an address yet, so init with port 0 self.udp = Udp.Udp(self.socket, 0, sel...
def create_sql_table(con): """ Will create the SQL table "scores" if it doesn't already exist in the database with open connection con Parameters ---------- con : SqLite3 Connection Connection to open database. Returns ------- None """ cur = con.cursor() cur....
The main task of the code is to download and score audio recordings between specified dates, processing one day at a time to avoid download limits. It connects to an API, loads a model, and updates a SQLite database with scores or positions, depending on command-line arguments. The function handles daily recording quer...
def process_all_recordings(args): """ Download and score all the audio recordings between the specified dates args.start_date and args.end_date. This is done one day at a time to avoid limits on the maximum number of downloads Parameters ---------- args : dictionary Command l...
def LogContactDate(): try: #declare runLog as global tempLog = "" #variable for Seeing if a date has already been logged dateLogged = False #Create Workbook and Sheet workbook = load_workbook(filename=argExcel_Filename) sheet = workbook.active ...
The main task of the code is to execute different operations based on the `argTaskType` parameter. It initializes global variables with input arguments, then dispatches tasks: processing Excel data, editing Word documents, renaming screenshots, or copying files. It accumulates and returns log messages from these operat...
def runToolbox(_globWordTemplate, _argExcel_Filename, _argWord_FileDIR, _argNumPerMonth, _argDateScreen, _argInitialContactTime, _argResponseTime, _argPerson, _argTaskType, _argMonthYear, _argScreenshotDIR): #Assign Global Variables Through Swift Code #Connect with Global Variables global globWordTemp...
def speak(text): engine.say(text) engine.runAndWait() def reminder(): speak("What hour do you want to set a reminder") userH = int(input("What hour do you want to set a reminder\n")) speak("What minute do you want to sea a reminder") userM = int(input("What minute do you want to sea a reminder\n...
This code defines a voice assistant function `query()` that processes user commands to perform tasks like providing current time, searching Wikipedia, opening websites, retrieving chemical formulas, executing basic math operations, managing files/folders, controlling applications, and responding to greetings/personal q...
def query(): print('Please input a command ') command = input().lower() if 'time' in command: time = datetime.now().strftime("%I:%M %p") speak(time) elif 'who is' in command: speak('Searching Wikipedia sir...') query = command.replace("jarvis", "") resul...
def process_submission() -> dict: with open(file='submission.json') as file: data = json.load(file) # convert string to list try: data['categories'] = data['categories'].split(', ') except KeyError: exception_writer(error=Exception('No categories provided'), name='categories', e...
The function processes an issue update by first handling a submission, validating a GitHub URL to extract owner and repository names, and then using these along with the submission data to process the GitHub URL.
def process_issue_update() -> None: # process submission file submission = process_submission() # check validity of provided GitHub url git_owner, git_repo = check_github(data=submission) process_github_url(owner=git_owner, repo=git_repo, submission=submission)
def get_folds(X, y, k): """ Divides the data and labels to k folds :param X: the data :param y: the labels :param k: amount of folds :return: batches and labels, where batches[i] is the i'th data fold and labels[i] is the i'th label fold which matches batches[i] """ m = X.shape[0] ...
The code performs cross-validation for the RBF Soft SVM algorithm to identify the optimal lambda (λ) and sigma (σ) parameters. It splits data into `k` folds, iterates through all combinations of λ and σ, trains the model on `k-1` folds, validates on the remaining fold, and calculates the average error. The combination ...
def cross_validation_rbf(X, y, k, ls, sigmas): """ Performs cross validation for the RBF Soft SVM algorithm :param X: the data :param y: the labels :param k: amount of folds :param ls: list of values to check for lambda parameter :param sigmas: list of values to check for sigma parameter ...
def get_levels(self): vertices = self.get_vertices() for vertex in vertices: curr_key = vertex.get_key() arr = self.levels.get(vertex.get_depth(),[]) for data_vertex in vertex.get_data_connections(): neighbour_key = data_vertex.get_key() ...
The code's main task is to compute and return the hierarchical positions of nodes in a tree structure. It initializes the root node, sets depths, organizes nodes into levels, orders them hierarchically, and reverses the final positions using 'flip'. This is typically used for tree layout algorithms like BFS or DFS trav...
def get_position(self): self.set_root_vertex_by_key(0) self.initialise_depth() self.get_levels() self.order_levels() return flip(self.positions)
def iterate_through_node(self,curr_node,current_x,current_y,previous_node): #crx = curr position of node # returns rightmost x self.positions[curr_node.get_key()] = (current_x,current_y) curr_line_segment = (self.positions[previous_node.get_key()],self.positions[curr_node.get_key()]) self.line_s...
The code's main task is to compute and adjust the positions of nodes in a tree or graph structure. It initializes the root vertex, sets node depths, traverses nodes to determine levels, orders these levels, and adjusts the positions using `adjustByRow` and `flip` functions for layout optimization. The result is a struc...
def get_position(self): self.set_root_vertex_by_key(0) self.initialise_depth() self.iterate_through_node(self.get_root_vertex(),0,0,self.get_root_vertex()) self.get_levels() self.order_levels() return adjustByRow(flip(self.positions))
def hide_widgets(*widgets): for widget in widgets: widget.grid_forget() def calculate_points(answer): global point_counter if answer[0] == "q1": if answer[1] == "s1": global credits point_counter += credits / -4 elif answer[1] == "s2": if answer[2] == "op1": point_counter -= 1 elif answer[2] ==...
This code creates a GUI question interface asking about residency preferences with three options (Private, Shared, None). When an option is selected, it hides the question, updates a score, and proceeds to the next step. The main task is to capture user input for a specific question and trigger score calculation and na...
def pg_ques12_s1(): ### Question 12: Section 1 ### # Question title q12_s1_text = tk.Label(main_frame, text="Q12S1: Any specific preferences for residency?", font=question_text_font) q12_s1_text.grid(row=1, column=0, columnspan=6) # Top left option q12_s1_op1 = tk.Button(main_frame, text="Private", font=main_te...
def hide_widgets(*widgets): for widget in widgets: widget.grid_forget() def calculate_points(answer): global point_counter if answer[0] == "q1": if answer[1] == "s1": global credits point_counter += credits / -4 elif answer[1] == "s2": if answer[2] == "op1": point_counter -= 1 elif answer[2] ==...
This function creates a GUI question asking "Were you previously in residence?" with "Yes" and "No" buttons. Selecting an option hides the question, records points via calculate_points, and navigates to the next question (pg_ques1_s3) by updating the interface.
def pg_ques1_s2(): # Question title q1_s2_text = tk.Label(main_frame, text="Q1S2: Were you previously in residence?", font=question_text_font) q1_s2_text.grid(row=1, column=0, columnspan=6) # Top left option q1_s2_op1 = tk.Button(main_frame, text="Yes", font=main_text_font, height="10", width="30", comma...
def hide_widgets(*widgets): for widget in widgets: widget.grid_forget() def calculate_points(answer): global point_counter if answer[0] == "q1": if answer[1] == "s1": global credits point_counter += credits / -4 elif answer[1] == "s2": if answer[2] == "op1": point_counter -= 1 elif answer[2] ==...
This function creates a GUI question interface asking how many courses the user is taking, provides four numeric options (2.0+, 1.5, 1.0, 0.5), and upon selection, hides the question, records the choice via a points calculation, then navigates to the next question (pg_ques3_s1). It manages UI layout and user interactio...
def pg_ques2_s2(): # Question title q2_s2_text = tk.Label(main_frame, text="Q2S2: How many courses are you\n currently taking in the upcoming term?", font=question_text_font) q2_s2_text.grid(row=1, column=0, columnspan=6) # Top left option q2_s2_op1 = tk.Button(main_frame, text="2.0+", font=main_text_fon...
def hide_widgets(*widgets): for widget in widgets: widget.grid_forget() def calculate_points(answer): global point_counter if answer[0] == "q1": if answer[1] == "s1": global credits point_counter += credits / -4 elif answer[1] == "s2": if answer[2] == "op1": point_counter -= 1 elif answer[2] ==...
This code creates a GUI question interface asking if a mental disability is persistent/prolonged, offering "Yes" and "No" buttons. Selecting either hides the question, records the choice via calculate_points(), and advances to the next question (pg_ques8_s3). It handles user input for a psychological assessment or surv...
def pg_ques8_s2(): # Question title q8_s2_text = tk.Label(main_frame, text="Q8S2: Is your mental\n disability persistent or prolonged?", font=question_text_font) q8_s2_text.grid(row=1, column=0, columnspan=6) # Top left option q8_s2_op1 = tk.Button(main_frame, text="Yes", font=main_text_font, height="5", ...
def hide_widgets(*widgets): for widget in widgets: widget.grid_forget() def calculate_points(answer): global point_counter if answer[0] == "q1": if answer[1] == "s1": global credits point_counter += credits / -4 elif answer[1] == "s2": if answer[2] == "op1": point_counter -= 1 elif answer[2] ==...
This function displays a question about campus job interest via a GUI, offering "Yes" and "No" buttons. Selecting either hides the question, logs the choice, and advances to the next question (pg_ques12_s1()), forming part of a step-by-step survey or quiz system.
def pg_ques11_s2(): # Question title q11_s2_text = tk.Label(main_frame, text="Q11S2: Would you be interested in\n pursuing a job opportunity on campus?", font=question_text_font) q11_s2_text.grid(row=1, column=0, columnspan=6) # Top left option q11_s2_op1 = tk.Button(main_frame, text="Yes", font=main_text...
def calculate_points(answer): global point_counter if answer[0] == "q1": if answer[1] == "s1": global credits point_counter += credits / -4 elif answer[1] == "s2": if answer[2] == "op1": point_counter -= 1 elif answer[2] == "op2": point_counter += 1 elif answer[1] == "s3": if answer[2] ==...
This function validates user input as a numeric value between 0 and 40 (exclusive) with 0.5 increments. If valid, it triggers calculations, hides UI elements, and advances to the next question. If invalid, it sets an error flag to display an error message.
def input_verify(user_input): global credits, print_error try: credits = float(user_input) if credits <= 40 and credits > 0 and credits % 0.5 == 0: calculate_points(["q1", "s1", "box"]) hide_widgets(q1_s1_text, q1_s1_box_title, q1_s1_box, q1_s1_box_button, q1_s1_box_error) pg_ques1_s2() prin...
def _open_map_search(self): print('1') img_search= cv.imread('./Targets/UI/OnMap/search.png',0) img_search2= cv.imread('./Targets/UI/Others/search_for_target.png',0) while True: print('2') sleep(1) if(self._inMap()== True): print('3') ...
The main task of the code is to dispatch troops in a game by detecting UI elements via image recognition, interacting with the screen (e.g., clicking coordinates), and handling retries or fallbacks like opening maps/searching for forces. It checks for attack buttons, navigates menus, selects formations, and confirms tr...
def _dispach_troops(self): imagen_list_attack=self.img.get_imagen_list('./Targets/UI/Combat/Attack/') #img_search2= cv.imread('./Targets/UI/Others/search_for_target.png',0) res = False tryAgain=0 #looking for Go or Attack Botton while True: if self.img.isaImgT...
def reset(self): self.car.x = self.screen_width / 2 + 40 self.car.y = self.screen_height - 250 self.car.angle = -10 state = np.array( [self.car.x, self.car.y, self.car.acceleration, self.car.angle] ) return state def render(self, mode="human"): self.d...
This code trains a deep Q-learning agent to control a car in a Pygame simulation. It initializes the agent, loads a pre-trained model if available, and runs episodes where the agent takes actions, receives rewards, and updates its neural network. The loop renders the environment, tracks total rewards, and saves the mod...
def run(self): clock = pygame.time.Clock() fps = 30 running = True episode = 0 agent = Agent(state_size=4, action_size=5, seed=42) # Initialize the deep Q-learning agent\ if os.path.exists('agent_parallel.pth'): agent.load_m...
def readInput(path): return np.matrix([[int(i) for i in row] for row in open(path, "r").read().split('\n')]) def getLowPoints(matrix): lowPoints = [] for row in range(matrix.shape[0]): for column in range(matrix.shape[1]): if isLocalMinimum(np.array([row,column]),matrix=matrix): ...
The code's main task is to solve a basin size problem by reading a matrix from a file, identifying low points (local minima), and calculating the size of basins formed around these points. The function `solve` orchestrates these steps: `readInput` loads the matrix, `getLowPoints` finds local minima, and `getBasinSize` ...
def solve(path): matrix = readInput(path) lowPoints = getLowPoints(matrix) return getBasinSize(lowPoints,matrix)
def _init_variables(): # Capturing video video = cv2.VideoCapture(VIDEO_SOURCE) # Initializing the HOG person detector hog = cv2.HOGDescriptor() hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) tracker = None jump_counter = JumpCounter() return hog, jump_counter, tracker,...
The main task of the code is to process video frames in an infinite loop, tracking objects using a tracker and HOG features, counting jumps based on bounding box changes, displaying annotated frames with jump counts, and exiting on 'q' key press, followed by resource cleanup.
def main_loop(): hog, jump_counter, tracker, video = _init_variables() # Infinite while loop to treat stack of image as video while True: # Reading frame(image) from video check, frame = video.read() if frame is None: break box, tracker = _get_tracker_get_box(f...
def _get_size(height): """ Determines the size of the grid for the given height map. """ Lx = 0 Ly = 0 for (x,y) in height: Lx = max(x+1,Lx) Ly = max(y+1,Ly) return Lx,Ly def height2circuit(height, log=False, eps=1e-2): """ Converts a dictionary of heights (or brightn...
The function applies partial swaps between two quantum circuits derived from input height maps, using a specified fraction. It combines the circuits, applies the swaps, calculates resulting probabilities, and converts them back into height maps, returning the modified height maps with logarithmic decoding if enabled.
def swap_heights(height0, height1, fraction, log=False, ): """ Given a pair of height maps for the same sized grid, a set of partial swaps is applied between corresponding qubits in each circuit. Args: height0, height1 (dict): Dictionaries in which keys are coordinates for point...
def _image2heights(image): """ Converts an rgb image into a list of three height dictionaries, one for each colour channgel. """ Lx,Ly = image.size heights = [{} for j in range(3)] for x in range(Lx): for y in range(Ly): rgb = image.getpixel((x,y)) for j in ra...
The function `swap_images` applies partial swaps between corresponding qubits in two same-sized RGB images, modifying their color channels based on a given fraction of swap gates. It converts images to height data, swaps portions of each channel using `swap_heights`, and reconstructs new images from the modified height...
def swap_images(image0, image1, fraction, log=False): """ Given a pair of same sized grid images, a set of partial swaps is applied between corresponding qubits in each circuit. Args: image0, image1 (Image): RGB encoded images. fraction (float): Fraction of swap gates to apply. ...
def notify(self, title, message): # Notifications are currenly only working on macOS if sys.platform == 'darwin': self.background_thread(self.notify_command, [title, message]) def background_thread(self, target, args_list): args = () for arg in args_list: args += ...
The code synchronizes data between a SNES Classic device and local storage by pulling Retroarch/SNES saves, updating local copies, generating game ID mappings, and pushing changes if modifications are enabled. It monitors connectivity, handles iCloud preservation on macOS, and notifies users of sync status, terminating...
def start(self): self.notify(title='RetroSync Startup', message=f'Now starting Data Sync...') RUNNING = False time_in = time.time() initial_time = time_in while True: if self.terminate: self.notify(title='RetroSync Offlin...
def get_customers_sorted_by_score(self, customers: CUSTOMERS) -> CUSTOMERS: """ Get list of Customers sorted by ascending score. Parameters ---------- customers : CUSTOMERS List of Customers to be sorted. Returns ------- CUSTOMERS ...
The code initializes a balance class by filtering unavailable customer success agents, sorting both available customer success agents and customer lists by score, and identifying the customer success agent with the most customers to manage assignments efficiently.
def __init__( self, customer_success: CUSTOMERS, customers: CUSTOMERS, customer_success_away: list[int], ) -> None: """ Initialize balance class. Parameters ---------- customer_success : CUSTOMERS List of Customers Success in compa...
def _Load_FilePCK(file_name): with open(file_name, 'rb') as fp: obj = pickle.load(fp) return obj def _Standardize_Data(data): sc = StandardScaler() stdData=[] for matrix in data: stdData.append( sc.fit_transform(matrix) ) return np.array(stdData) def _Get_SummarizationMatrix(in...
The main task of the code is to process a new dataset by loading input and label data, standardizing the input features, generating a summarization matrix, classifying labels, and exporting the processed data (X, y) to a PCK file for subsequent use in machine learning tasks.
def Process_NewDataSet(inputsDir, labelsDir): sampledInputs = _Load_FilePCK(inputsDir) inputs_Scaled = _Standardize_Data(sampledInputs) sampledLabels = _Load_FilePCK(labelsDir) X = _Get_SummarizationMatrix(inputs_Scaled) y = _Clasify_Labels(sampledLabels) _ExportData_ToPCK(X, y) return ...
def _Load_FilePCK(file_name): with open(file_name, 'rb') as fp: obj = pickle.load(fp) return obj def _Standardize_Data(data): sc = StandardScaler() stdData=[] for matrix in data: stdData.append( sc.fit_transform(matrix) ) return np.array(stdData) def _Get_SummarizationMatrix(in...
The function Load_DataSet loads input and label datasets from specified directories. If the ready datasets fail to load, it processes original data by standardizing inputs, generating summary matrices, classifying labels, and exporting processed data. The main task is to ensure dataset availability by prioritizing pre-...
def Load_DataSet(inputsDir = DatasetPath.InputsReady, labelsDir = DatasetPath.LabelsReady): #if given specific files to load, it will do it #if not given parameters, it will try to load the ready ones #if there are not ready ones, or there is any other problem, it will load and process the very original one...
def clear(): """Executes clear (Linux) or cls (Windows).""" if IN_COLAB: return if platform.system() == 'Windows': subprocess.run(['cls'], shell=True) else: subprocess.run(['clear']) def print_separator(char: str, style: str = ''): """Prints `char` until it fills the term...
The code clears the terminal, then displays a centered, styled title and subtitle (if provided) surrounded by separators. It combines the global `title` and `subtitle` variables, adding a delimiter if both exist, and formats them with color and bold text using terminal width for centering.
def print_title(subtitle: str = '', separator: str = '=', style: str = '[cyan]'): """Calls `clear` then prints global var `title` (if not empty) and `subtitle` between two separators. """ clear() if len(title) > 0 and len(subtitle) > 0: subtitle = ' | ' + subtitle print...
def do_beam(self): best = BestHeap(self.beam_size * self.beam_expansion) # heuristic to leave room for diversity print("Generating candidates") #TODO: use a DataLoader to score in minibatches candidates = list(self.data) for candidate in tqdm(candidates, "scoring"): ...
The code performs iterative beam search processing by repeatedly expanding the beam (via `do_beam`) and summarizing results until no more data remains. It then returns the top `max_out` scores from the final evaluation.
def run(self, max_out:int=100): while self.data.longest_left() > 0: self.do_beam() self.summarize_results() out = self.final_scores(max_out) return out
def initialize_parameters(dim): w = np.random.randn(dim, 1)*0.01 b = 0 return w, b def gradient_descent(w, b, X, Y, iterations, learning_rate): costs = [] for i in range(iterations): grads, cost = propagate(w, b, X, Y) #update parameters w = w - learning_rate * grads...
The code trains a linear model using gradient descent on given training data, evaluates it on test data, saves the learned weights, and prints prediction accuracy for both training and test sets. It initializes parameters, performs optimization, predicts labels, and calculates accuracy by comparing predicted vs actual ...
def model(train_x, train_y, test_x, test_y, iterations, learning_rate): #print("the shape of x[0]: ",train_x.shape[0]) w, b = initialize_parameters(train_x.shape[0]) parameters, costs = gradient_descent(w, b, train_x, train_y, iterations, learning_rate) w = parameters["w"] b = parameters["b"] ##...
def init_thing(one_thing): w = np.random.randn(one_thing,1) * 0.01 b = 0 return w,b def gradient_descent(w,b,X,Y,iterations, learning_rate): costs = [] for i in range(iterations): #print("the shape of the weights inside the gradient_d: ", w.shape) grads,cost = propagate(w,b,X,Y) ...
The code trains a linear regression model using gradient descent on provided training data, evaluates it on both training and test sets by predicting outputs, calculates accuracy via mean absolute error, and returns the cost history. It initializes weights/bias, performs gradient descent iterations, shuffles data, and ...
def model(train_x,train_y, test_x,test_y,iterations, learning_rate): #init the weights and biasees print("the shape of tran_x: ",train_x.shape) w,b = init_thing(train_x.shape[0]) print("int the model weights: ",w.shape) print("the shape of the weights: ",w.shape) params, costs = gradient_descent...
def generate_rocrate(notebook: Path, metadata: Path) -> ROCrate: crate = ROCrate() add_notebook(crate, notebook, metadata) return crate def create_temporary_crate_file(crate: ROCrate) -> Path: temp_dir = Path(TEMP_DIR) temp_dir.mkdir(parents=True, exist_ok=True) crate.write(temp_dir) return...
The function generates an ROCrate from a Jupyter notebook and metadata file, writes it to a temporary file, reads the content, and embeds it into the notebook's metadata using a specified key. It then cleans up temporary files. The main task is to integrate structured metadata (ROCrate) into a Jupyter notebook for prov...
def update_notebook_metadata(notebook: Path, metadata: Path) -> None: """Creates and embeds an rocrate in the metadata of a jupyter notebooks Parameters: notebook: The path of a jupyter notebook metadata: A metadata file containing author information """ crate = generate_rocrate(notebo...
def get_notebooks(dir: Path) -> List[Path]: files = [Path(file) for file in os.listdir(dir)] is_notebook = lambda file: file.suffix == NOTEBOOK_EXTENSION return list(filter(is_notebook, files)) def update_notebook_metadata(notebook: Path, metadata: Path) -> None: """Creates and embeds an rocrate in the ...
The main task of the code is to process Jupyter notebooks in a specified directory by updating their metadata using a provided metadata.json file. It parses command-line arguments for the target directory and metadata file, retrieves all notebooks, updates each notebook's metadata, and finally creates a root crate stru...
def main(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument("dir", type=Path, help="The directory to act on") parser.add_argument( "metadata", type=Path, help="An metadata.json file containing some defaults for author information", ) args = parse...
def readLines(data_with_key): lines = data_with_key.strip().split(splitter) return [unicodeToAscii(line) for line in lines] def train(category_tensor, input_line_tensor, target_line_tensor): criterion = nn.NLLLoss() learning_rate = 0.0005 target_line_tensor.unsqueeze_(-1) hidden = rnn.initHidde...
The code trains a neural network (RNN) model using input data and a specified category, saving the trained model and training progress. It processes incoming POST requests, validates required parameters, prepares training data, initializes the RNN, trains it over 100,000 iterations, logs training status, and stores the...
def post(self, request): global all_categories global n_categories global splitter global rnn try: data = request.data["data"] category = request.data["category"] splitter = request.data["splitter"] except KeyError: res = ...
def readBenchmarkFile(benchmark_file): if not os.path.isfile(benchmark_file): logger.error(f'Benchmark file @ {benchmark_file} does not exist') return None try: with open(benchmark_file, 'r') as fd: return dotmap.DotMap(json.load(fd)) except Exception as e: logge...
The code runs a benchmark by compiling and executing configurations, checking build success, logging results, and outputting final sequences. It initializes problem sizes, attempts an initial build, and if successful, performs optimistic optimization across source files, logging success/failure status and final sequenc...
def runBenchmark(benchmark_file): benchmark = readBenchmarkFile(benchmark_file) logger.info(f'Start benchmark {benchmark.name}') benchmark_path = os.path.dirname(benchmark_file) success = False seqs = getFinalSeq(benchmark) problemsizes = {x.path:0 for x in benchmark.source_files} success, ...
def readBenchmarkFile(benchmark_file): if not os.path.isfile(benchmark_file): logger.error(f'Benchmark file @ {benchmark_file} does not exist') return None try: with open(benchmark_file, 'r') as fd: return dotmap.DotMap(json.load(fd)) except Exception as e: logge...
The main task of the code is to execute a benchmark by compiling and running configurations of source files, tracking sequences and problem sizes. It first attempts an initial build; if successful, it performs optimistic optimization across all source files, moves executables to 'initial' and 'final' stages, and logs r...
def runBenchmark(benchmark_file): benchmark = readBenchmarkFile(benchmark_file) logger.info(f'Start benchmark {benchmark.name}') benchmark_path = os.path.dirname(benchmark_file) success = False seqs = {x.path:[] for x in benchmark.source_files} problemsizes = {x.path:0 for x in benchmark.source...
def readBenchmarkFile(benchmark_file): if not os.path.isfile(benchmark_file): logger.error(f'Benchmark file @ {benchmark_file} does not exist') return None try: with open(benchmark_file, 'r') as fd: return dotmap.DotMap(json.load(fd)) except Exception as e: logge...
The code executes a benchmark process by reading a benchmark file, compiling and running configurations, logging success/failure status, and recording execution sequences. It first attempts an initial build; if successful, it proceeds with optimistic optimization, copies the initial executable, and runs all configurati...
def runBenchmark(benchmark_file): benchmark = readBenchmarkFile(benchmark_file) logger.info(f'Start benchmark {benchmark.name}') benchmark_path = os.path.dirname(benchmark_file) success = False seqs = {x.path:[] for x in benchmark.source_files} problemsizes = {x.path:0 for x in benchmark.source...
def trajUnfitScore(self,traj): """Fitness score of a trajectory is comprised of: 1) Trajectory has to be smooth. Distance of each intermediate state with prev and next 2) Obstacle should be avoided by each state. Obstacle cost is the sum of obs cost of all intermediate points of all link...
The main task of the code is to generate an initial population for an evolutionary algorithm. It starts by adding a trajectory with its fitness score to the population, then supplements it with randomly generated individuals to reach the specified population size, combining both into a complete initial population for o...
def generateInitialPopulation(self): population = [] fs = self.trajUnfitScore(self.traj) self.push_heap(population, (fs, self.traj)) random_population = self.generateRandomPopulation(self.population_size-1) return population+random_population
def selection(self,population): return heapq.nsmallest(int(self.population_size/2),population) def pairing(self,population): ## Assumes that the population is sorted parents = [[population[x][2],population[x+1][2]] for x in range(len(population)//2)] return parents de...
The main task of the code is to generate the next generation in a genetic algorithm by selecting individuals, pairing them to produce offspring, mutating the fittest candidates, and supplementing with random individuals to maintain diversity. It sorts selected individuals, applies crossover to create offspring, filters...
def next_generation(self,population): selected_population = self.selection(population) sel_pol_num = len(selected_population) selected_population.sort() parents = self.pairing(selected_population) offsprings = [self.mating(parents[x]) for x in range(len(parents))] unmutat...
def removeEps(CFG:CFG): CFG.produksi = CFG.produksi nullable = set() n_bef = -1 while (n_bef != len(nullable)): n_bef = len(nullable) for LHS in list(CFG.produksi.keys()): toBeDeleted = set() for RHS in CFG.produksi[LHS]: if (len(RHS) == 1 and RHS[...
The code simplifies a context-free grammar (CFG) by sequentially removing epsilon productions (removeEps), unit productions (removeUnit), and useless symbols (removeUseless). This reduces the CFG to its minimal form, eliminating redundant rules and non-generative elements, enhancing efficiency for analysis or processin...
def simplifyCFG(CFG:CFG): removeEps(CFG) removeUnit(CFG) removeUseless(CFG)
def simplifyCFG(CFG:CFG): removeEps(CFG) removeUnit(CFG) removeUseless(CFG) def nextAvailable(var,variabel): # mencari variabel baru dari list variabel yang ada. # produksi variabel dimulai menaikkan char terakhir hingga 'Z', # jika masih ada maka tambah karakter baru, lakukan hingga tidak ada ...
This code converts a Context-Free Grammar (CFG) into Chomsky Normal Form (CNF). It simplifies the CFG by removing epsilon/unit productions, replaces terminals in multi-symbol productions with new variables, and recursively splits productions with more than two symbols into binary rules. The process ensures all producti...
def CFGtoCNF(CFG : CFG): simplifyCFG(CFG) for LHS in CFG.produksi: CFG.produksi[LHS] = list(CFG.produksi[LHS]) for i in range(len(CFG.produksi[LHS])): CFG.produksi[LHS][i] = list(CFG.produksi[LHS][i]) newVar = nextAvailable("AA",CFG.variabel) for LHS in list(CFG.produksi.keys...
def getConfigkey(configname): findrecord = {} findrecord['name'] = configname result = mongo.db.configuration.find_one(findrecord) if result == None: return "0" else: return result['value'] def getHashMetaOnline(url): logging.info("Starting getHashMetaOnline from %s" % url) try: res = requests.get(url) b...
The main task of the code is to periodically synchronize up-to-date CVE data from NVD by checking the last update timestamp, downloading and importing new/modified CVE entries via hash comparison, and maintaining sync status in configuration. It ensures data freshness by exiting if outdated, avoids redundant updates, a...
def updateCVEOnline(): logging.info("Starting update CVE Online") # 1. check last syntime, if over 8 days, the process will be exit lastupdated = getConfigkey("lastupdated") if lastupdated == "0": logging.error("Please synchronize data from NVD first!") return 0 lastupdateobj = datetime.datetime.strptime(lastu...
def create_nerf(coarse_model_state=None, fine_model_state=None): embedder_pts = Embedder(max_encoding_resolution=10) embedder_dirs = Embedder(max_encoding_resolution=4) coarse_model = NeRF(input_ch_pts=embedder_pts.output_dim, input_ch_views=embedder_dirs.output_dim) if coarse_model_state is not None: ...
The code renders a video using a Neural Radiance Field (NeRF) model by loading the latest checkpoint, setting up camera transformations for a spiral trajectory, rendering frames with rays, and compiling them into an MP4 file. It processes image dimensions, generates view angles, and outputs a 30fps video of the scene f...
def render_video(): ckpts_paths = [] for f in os.listdir(ckpts_dir): if f.endswith('.tar'): ckpts_paths.append(f) ckpt = torch.load(os.path.join(ckpts_dir, ckpts_paths[-1])) nerf = create_nerf(ckpt['coarse_state'], ckpt['fine_state']) data = load_data() down_sample_factor...
def load_data(): splits = ['train', 'val', 'test'] metas = {} for split in splits: with open(os.path.join(args.data_dir, 'transforms_{}.json'.format(split)), 'r') as fp: metas[split] = json.load(fp) images = [] camera_to_world_transformations = [] counts = [0] for split...
The code trains a Neural Radiance Field (NeRF) model by optimizing coarse and fine networks using random ray sampling from training images. It computes MSE loss between rendered and target RGB values, applies Adam optimization with learning rate decay, and periodically saves model checkpoints. The process iterates over...
def train(): data = load_data() images = data['images'] camera_to_world_transformations = data['camera_to_world_transformations'] h, w, focal = data['hwf'] split_train, split_val, split_test = data['splits'] intrinsic_camera_transformation = create_intrinsic_camera_transformation(h, w, focal) ...
def check_Pse_arguments(fastas,method,nctype,weight,kmer,lamadaValue): #os.chdir('C:/Users/Administer/Desktop/DeepAc4C-master/') #if not os.path.exists("input.fasta"): # print('Error: the input file does not exist.') # sys.exit(1) if not 0 < weight < 1: print('Error: the weight factor ...
The code generates three types of pseudo-sequence feature encodings (PseKNC, SCPseDNC, SCPseTNC) for DNA sequences using specified parameters, then saves the resulting feature matrices into separate CSV files for subsequent analysis or machine learning tasks.
def Pse_feature(fastas): import sequence_read_save import check_parameters # PseKNC my_property_name, my_property_value, lamada_value, weight, kmer = check_Pse_arguments(fastas,"PseKNC","DNA",0.1,3,10) encodings = make_PseKNC_vector(fastas, my_property_name, my_property_value, lamada_value, we...
def get_methods(class_ref): methods = [ method for method in dir(class_ref) if not method.startswith("__") or "__init__" in method ] method_dict = {} for method in methods: method_dict[method] = {"params": {}} method_ref = getattr(class_ref, method) m_src ...
This code implements an evolutionary algorithm to generate a population of candidates for a given target class, using NSGA-II principles. It iteratively selects, breeds, and mutates candidates, maintaining an archive of top performers based on Pareto front ranks and sparsity. The process yields evolving populations to ...
def generate(self, target_class: type) -> List[AbstractCandidate]: ################################### ### IMPLEMENT YOUR SOLUTION HERE ## ################################### POP_SIZE = 40 ARCHIVE_PERCENTAGE = 0.2 MUTATION_RATE = 0.2 archive_size = int(POP_SIZE *...
def updateScreenShot(self): scr = numpy.array(self.sct.grab(self.dimensions)) self.scr = scr[:,:,:3] self.scr_gray = cv2.cvtColor(scr, cv2.COLOR_BGR2GRAY) self.master.after(500, self.updateScreenShot) def loadMapNeedles(self): for map in self.maps: # read the needles ...
The code automates in-game tasks by periodically executing actions like updating screenshots, detecting and interacting with objects (e.g., chests, spells), managing monster upgrades, spawning drones, logging positions, checking for defeat, and closing modals. It runs loops with specific intervals (every 0.5s, 4s, 30s,...
def startLoops(self): # update screenshot self.updateScreenShot() # loadMapNeedles self.loadMapNeedles() # check for a flying chest self.findAndClickChest() # every 4 seconds try and upgrade all monsters self.upgradeMonsters() # spawn d...
def createWidgets(self): self.debug("Create Widgets") #create buttons self.loadMarkersBtn = tk.Button(self) self.loadMarkersBtn["text"] = "Load Map Markers" self.loadMarkersBtn["command"] = self.loadMap self.loadMarkersBtn.grid(column=1, row=0) self.set...
The code initializes a GUI application by setting up a window with a specific size, creating and arranging widgets, loading necessary data (needles), and starting event loops to enable the application's functionality. The main task is to configure the graphical interface and prepare the application for interaction.
def __init__(self, master=None): tk.Frame.__init__(self, master) self.master.geometry('400x850') self.pack() self.createWidgets() self.loadNeedles() self.startLoops()
def _write_message(message: str) -> None: global _output_queue # pylint: disable=global-statement,invalid-name asyncio.run_coroutine_threadsafe(_output_queue.put(message), asyncio.get_event_loop()) def _create_will_display_payload(deck_info: dict, button_index: int, page: int, event: str = 'willAppear') -> dic...
This function handles changes to MD data by validating JSON input, updating button action settings in the material deck, and sending a formatted message with the updated payload.
def md_data_changed(button_index: int, text: str) -> None: """ Handles when data is changed within the md data box. """ try: json.loads(text) except Exception: # pylint: disable=broad-except return page = deck_api.get_page(_deck_id) button_state = deck_api._button_state(_de...
def _create_will_display_payload(deck_info: dict, button_index: int, page: int, event: str = 'willAppear') -> dict: init_data = copy.deepcopy(deck_info['init_data']) init_data['context'] = _to_context(button_index, page) init_data['size'] = {'columns': DECK_COLUMNS, 'rows': DECK_ROWS} init_data['event']...
This function unloads MaterialDeck buttons by sending 'willDisappear' events. It retrieves button configurations for a specified page, generates event payloads with deck data, resets button states, and transmits JSON-formatted messages to notify of button unloading. The process ensures proper cleanup of MaterialDeck bu...
def _unload_md_buttons(page: int) -> None: """ Reads the buttons configured for use with MaterialDeck and sends willDisappear events. """ if _deck_id not in deck_api.state: return button_states = deck_api.state[_deck_id]['buttons'] for button_index, button_info in button_states.get(page...
def _write_message(message: str) -> None: global _output_queue # pylint: disable=global-statement,invalid-name asyncio.run_coroutine_threadsafe(_output_queue.put(message), asyncio.get_event_loop()) def _create_command_payload(action: str, event: str, button_index: int, page: int) -> dict: return { ...
This function handles key release events by generating a JSON command payload containing action details (e.g., 'keyUp') and sending it to an output queue. It retrieves button state data from a deck API, extracts material deck information, and constructs the payload with key, page, and action type before serializing it ...
def key_up_callback(deck_id: str, key: int, state: bool) -> None: """ Handles key up events by sending the necessary information to the output queue. """ if state: log.warning('Released callback called while the state boolean is true') button_state = deck_api._button_state(deck_id, deck_api....
def _create_command_payload(action: str, event: str, button_index: int, page: int) -> dict: return { 'action': action, 'event': event, 'context': _to_context(button_index, page), 'payload': { 'coordinates': { 'column': button_index % DECK_COLUMNS, ...
This function handles changing the action type for a specific button on a Material Deck device. It updates button configurations, sets new commands based on the provided action, and triggers UI updates. If no action is provided, it resets the button and sends a disappearance event. The function interacts with global st...
def md_action_changed(button_index: int, action: str) -> None: """ Handles changing the type of action Material Deck listens for. """ global _ui # pylint: disable=global-statement,invalid-name button_state = deck_api._button_state( # pylint: disable=protected-access _deck_id, deck_...
def _create_will_display_payload(deck_info: dict, button_index: int, page: int, event: str = 'willAppear') -> dict: init_data = copy.deepcopy(deck_info['init_data']) init_data['context'] = _to_context(button_index, page) init_data['size'] = {'columns': DECK_COLUMNS, 'rows': DECK_ROWS} init_data['event']...
This function loads MaterialDeck button configurations for a specified page, generates command payloads for each button, and sets them on the deck API. It processes button states, creates initialization data, and executes a shell script to configure button commands, then logs the initialization data.
def load_md_buttons(page: Optional[int] = None) -> None: """ Reads the buttons configured for use with MaterialDeck and sends willAppear events. """ if _deck_id not in deck_api.state: return if page is None: page = deck_api.get_page(_deck_id) button_states = deck_api.state[_dec...
def _unload_md_buttons(page: int) -> None: """ Reads the buttons configured for use with MaterialDeck and sends willDisappear events. """ if _deck_id not in deck_api.state: return button_states = deck_api.state[_deck_id]['buttons'] for button_index, button_info in button_states.get(page...
This function handles page transitions by unloading markdown buttons from the previous page and loading buttons for the new page, ensuring UI consistency during navigation.
def _on_page_changed(old_page: int, new_page: int) -> None: _unload_md_buttons(old_page) load_md_buttons(new_page)
def checkSkipCounter(): if (oSkipCounter.get() >= 4): disableAll() oGameOver.set(1) oMessage.set("Start a New Game!") messagebox.showinfo(title="End of Game", message="It's a tie! No player can make another move. Please start a new game.") def checkWinner(): if (oGameOver.get() =...
This function handles a player's move in a domino game by validating the chosen domino, determining placement direction (front/back), updating the game board, checking for a win, disabling controls, advancing to the next player's turn, and triggering the computer's move. It manages turn logic, skip counters, and user i...
def placeDown(): if (oGameOver.get() == 1): return if(oPlayerChoice.get()==-1): # Check skip counter oSkipCounter.set(oSkipCounter.get() + 1) checkSkipCounter() else: oSkipCounter.set(0) val = GAMEBOARD.hands[0].list1[oPlayerChoice.get()].val opt = GAMEBOARD.i...
def checkWinner(): if (oGameOver.get() == 1): return if (GAMEBOARD.hands[0].valDomCnt == 0): disableAll() messagebox.showinfo(title="Congratulations!", message="You won this game! You're too good!!\nClick 'Start Game' for a new game.") oGameOver.set(1) elif(GAMEBOARD.hands[1]...
This function handles the computer's first move in a domino game by updating the game state, processing the move, updating the UI, and transitioning to the next player's turn. It checks game-ending conditions, updates the board, and manages turn progression, ensuring proper game flow after the computer's action.
def getCompFirstMove(): if (oGameOver.get() == 1): return oStartGame.set(0) move = 66 player = GAMEBOARD.turn canvas = playerRC if (player == 1): canvas = playerLC elif (player == 2): canvas = playerUC oMessage.set(GAMEBOARD.names[player] + " has made a move!") ...
def reset(): gameBoardC.delete(ALL) playerDC.delete(ALL); playerRC.delete(ALL); playerUC.delete(ALL); playerLC.delete(ALL) oDom1.set(""); oDom2.set(""); oDom3.set(""); oDom4.set(""); oDom5.set(""); oDom6.set(""); oDom7.set(""); oName0.set(""); oName1.set(""); oName2.set(""); oName3.set("") oMessage....
The function `startGame` initializes a domino game by resetting the game state, dealing dominoes to players, updating the graphical interface to display each player's hand, and determining the starting player. It handles turn initialization, enables player interaction, and sets up UI elements like messages and buttons....
def startGame(DC, LC, UC, RC, gameC): reset() GAMEBOARD.getNames() setNames() GAMEBOARD.deal() # Deal dominoes to each player window.update(); time.sleep(1.5) GAMEBOARD.drawDeal(0, DC) displayPlayerOptions() window.update(); time.sleep(0.7) GAMEBOARD.drawDeal(1, LC) window.update...
def findSend(fogNode,request): return findTrans(fogNode,request)+findPropogation(fogNode,request) def findProcess(fogNode,request): return findQueueing(fogNode,request)+findExe(fogNode,request) def findreturn(fogNode,request): return 0
The code defines a function `find_TEstimate` that calculates an estimate by summing the results of three sub-functions: `findSend`, `findProcess`, and `findreturn`, each evaluating different aspects of handling a request at a fog node. The main task is to aggregate these components to estimate total time, cost, or reso...
def find_TEstimate(fogNode,request): return findSend(fogNode,request)+findProcess(fogNode,request)+findreturn(fogNode,request)
def findEInit(fogNode,request): return 18 def findEQueueing(fogNode,request): return 0.11 + findEExe(fogNode,request) + findESend(fogNode,request) def findEExe(fogNode,request): return fogNode.power * findExe(fogNode,request) def findESend(fogNode,request): return 100 * findSend(fogNode,request)
(The function calculates the estimated value (EEstimate) by subtracting the sum of queueing, execution, and sending times from the initial estimate (EInit) for a fog node handling a request.)
def find_EEstimate(fogNode,request): return findEInit(fogNode,request)-(findEQueueing(fogNode,request) + findEExe(fogNode,request) + findESend(fogNode,request))
def try_search( keyword = '' ): search_tweet_task = st.SearchTweetsTask( all_words = keyword ) output_jl_tweets = st.JsonLineFileRawOutput( 'crawler/Tweets/' + keyword + '_tweets.jl' ) output_jl_users = st.JsonLineFileRawOutput( 'crawler/Tweets/' + keyword + '_users.jl' ) # output_print = st.PrintRawOut...
The code's main task is to search for tweets using a keyword, check if a file exists locally, and fetch/persist tweets if the file is missing. It recursively ensures the file is created via `try_search`, then parses the data into a structured list of posts using `json_parser`, returning the list of tweets for further p...
def search_tweets( keyword = 'midjourney', tweet_count = 3 ): if ( path.exists( "crawler/Tweets/" + keyword + '_tweets.jl' ) ): print( 'stweet, search_tweets: file exists.' ) pass else: print( 'stweet, search_tweets: file does not exist.' ) try_search( keyword ) return se...
def parser_keyword( keyword_str ): # given a keyword string, returning a valid url keywords part. keyword_list = keyword_str.lower().strip().split() # lower: url only accepts lowercase. # strip: remove whitespaces at the head and tail of string. # split: extract each keyword from string. # print...
The crawler_pipeline function retrieves PubMed articles for a specified keyword by crawling multiple pages, storing results in a file if not already present, and returning the list of articles. It uses global variables for the search URL and article count, and processes each page's HTML to extract article data, either ...
def crawler_pipeline( page_count = 1, default_keyword_str = 'Myotonic Dystrophy' ): # send crawler with a given keyword and return first 10 searching result. global SEARCH_URL_PREFIX global ARTICLE_COUNT ARTICLE_COUNT = 0 article_list = [] page_str = '&page=' searching_str = parser_keyw...
def _findSmallest(self, start_node): # returns node object at smallest topographical location in subtree # with head at input node start_node node = start_node while node.left_child: node = node.left_child return node def _swapNodes(self, node1, node2): assert...
This function removes a node with two children by swapping it with its in-order successor (the smallest node in the right subtree), then removes the original node as a leaf or branch based on its height.
def _swapWithSuccessorAndRemove(self, node): # this removes a node with 2 children successor = self._findSmallest(node.right_child) self._swapNodes(node, successor) assert (node.left_child is None) if node.height == 0: self._removeLeaf(node) else: ...
def search(self, key): """ Search a AVLNode satisfies AVLNode.value = key. if found return AVLNode, else return None. """ return self._dfsSearch(self.root, key) def _removeLeaf(self, node): # this removes a node that has no children parent = node.parent if...
The main task of the code is to delete a node with a specified value from a tree structure. It searches for the node, decrements the node count if found, and handles three cases: removing a leaf node, a node with one child, or a node with two children by swapping with its successor. The function returns True if the nod...
def delete_value(self, key): # deletes a node by value lookup; # returns False if no node with value "key" is found, True otherwise # first find the node attached to the value, "key" node = self.search(key) if node is not None: # a node with value "key" has been found ...
def count_tree(root): if root is None: return 0 count = 1 if root.left is not None: count = count + count_tree(root.left) if root.right is not None: count = count + count_tree(root.right) return count def get_height(root): if root is None: return -1 return max...
This function provides a menu-driven interface for interacting with a tree data structure, allowing users to count nodes, calculate height, generate files with tree contents or depth-specific words, compute word similarities, or exit. It measures and displays operation runtimes, differentiates between AVL and RB trees ...
def tree_functionalities(tree): while True: # Give user operation options operation = input("\n [a]: Print the number of nodes in the tree\n"+ " [b]: Print the height of the tree\n"+ " [c]: Generate a file containing all the words in the tree\n" + ...
def populate_AVL(filename): file = open(filename, "r", encoding="utf8") tree = AVLTree() for line in file: current = line.strip().split(" ") # For each line in the file, if the word starts with an alphabetic # character, insert the word and embedding in a node within the tree ...
The code allows users to select between AVL or Red-Black Trees to populate with GloVe word embeddings from a file. It measures the time taken to build each tree, handles file not found errors by prompting for a custom path, and executes tree operations. The loop continues until the user exits, providing error handling ...
def read_glove_file(): glove_filename = "glove.6B.50d.txt" while True: try: # Ask user the operation they want to perform tree_pref = input("What type of tree would you like to work with?\n" + " [1]: AVL Tree\n [2]: Red-Black Tree\n" + ...
def quick_fill(grid, n_rows, n_cols): ''' If there are squares with only one possible value, fill them in and return the grid Parameters: -------------- grid: list A list of lists representing a sudoku board n_rows: int The number of rows in each square n_cols: int The number of columns in each square ...
The function `solve` attempts to solve a Sudoku grid using a two-step approach: first applying a "quick fill" technique to fill obvious cells, then using a recursive backtracking solver if needed. It tracks the number of iterations and identifies which cells were filled during solving. The function returns the solved g...
def solve(grid, n_rows, n_cols): ''' Solve function for Sudoku coursework. Comment out one of the lines below to either use the random or recursive solver Parameters: -------------- grid: list A list of lists representing a sudoku board n_rows: int The number of rows in each square n_cols:...
def add_voter(cursor,name,surname,index): cursor.callproc('new_voter', (index,name,surname)) odp = cursor.fetchone() return odp[0] def fetchdate(mess): ans = "y" while ans != "n": string = input(mess) if len(string) > 3: sep = string[2] else: ...
This function provides a menu-driven interface for managing an election system, allowing users to add voters (with validation for index numbers), create elections (with date and numeric input checks), publish results, or access other options. It loops until the user selects "Exit" (option 5), handling input validation ...
def commitee(cursor): ans = 0 while ans != "5": ans = input("\n What do you want to do? \n 1. Add a voter \n 2. Add election \n 3. Publish results \n 4. Other options \n 5. Exit\n") if ans == "1": print("Please enter voters data") name = input("name: ") ...
def logging_in(cursor): ans = input("What do you want to do?: \n 1) Log in \n 2) Exit\n" ) while ans != "2": if ans == "1": user = input("Username:") password = getpass.getpass("Password:") type = check(user,password,cursor) if type == "commit...
The main task of the code is to establish a database connection, authenticate a user via username/password, and execute role-specific operations (committee or voter) using PostgreSQL. It handles user login verification, role determination, and delegates tasks to corresponding functions while ensuring proper connection ...
def main(): #establishing the connection user = input("Username: ") password = getpass.getpass("Password: ") conn = psycopg2.connect( database="election", user=user, password=password, host='127.0.0.1', port= '5432' ) conn.autocommit = True #Creating a cursor cursor = conn.curs...
def send(value: int, sender: str, dest: list[str]): for d in dest: idx = index_node(d) if idx != None: messages_to_send[idx].append((value, sender)) else: messages_to_send[-1].append((value, sender)) def clear_messages_to_send(): global messages_to_send messag...
The function `push_button` processes a sequence of messages generated by a broadcaster, tracking the cumulative counts of "low" and "high" signals. It initializes counts, iteratively processes messages, updates counts based on new signals, and terminates when no further messages remain, returning the final low and high...
def push_button(): send(LOW, "button", ["broadcaster"]) low_count, high_count = 1, 0 while(True): messages_to_process = messages_to_send.copy() clear_messages_to_send() for i in range(len(messages_to_process[:-1])): if messages_to_process[i] != []: process...
def send(value: int, sender: str, dest: list[str]): for d in dest: idx = index_node(d) if idx != None: messages_to_send[idx].append((value, sender)) def clear_messages_to_send(): global messages_to_send messages_to_send = [[] for _ in range(len(MODULES))] def process(messages_to_...
This code simulates a button press in a node network. It sends a LOW signal to a "button" broadcaster, then processes messages in a loop. It checks if any node with value -1 receives a message matching the input 'value', updating its count. The loop continues until no messages remain, ensuring all message processing co...
def push_button(nodes: dict[str: int], value: int, count: int): send(LOW, "button", ["broadcaster"]) while(True): messages_to_process = messages_to_send.copy() clear_messages_to_send() for i in range(len(messages_to_process)): if messages_to_process[i] != []: ...
def ejection_phase_dynamic_matrix(self, t): """ :param t: time (s) :return: A matrix for filling phase """ el = self.elastance(t) del_dt = self.elastance_finite_difference(t) return [[del_dt/el, 0, 0, -el], [0, -1/(self.R1*self.C2), 1/(self.R1*self...
Your return The code computes time derivatives of cardiac state variables (ventricular/atrial/arterial pressure, aortic flow) by selecting the appropriate dynamic matrix (ejection/filling/isovolumic phase) based on conditions involving pressure comparisons and flow sign. It uses matrix multiplication with phase-specifi...
def get_derivative(self, t, x): """ :param t: time :param x: state variables [ventricular pressure; atrial pressure; arterial pressure; aortic flow] :return: time derivatives of state variables """ # Seperate state-variables from inputted state x1, x2, x3, x4 = x[...
def get_calendar_service(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: fl...
The code retrieves calendar events for a specified week (or current week if unspecified), filters them, and outputs the results either to a Slack channel or standard output. It accepts parameters for the target date, calendar email, and Slack destination. The task involves parsing arguments, handling timezones, fetchin...
def main(): parser = argparse.ArgumentParser(description='Get calendar events for a week.') parser.add_argument('--date', type=str, help='Date to use for the week (YYYY-MM-DD format)', default=None) parser.add_argument('--email', type=str, help='Email address of the calendar to view', default=None) pars...
def add(a, b): return a[0]+b[0], a[1]+b[1] def line_intersection(a, b, c, d): t = cross(sub(b, a), sub(d, c)) if(eq(t, 0)): return -1 p = cross(sub(b, c), sub(d, c)) q = cross(sub(d, c), sub(a, c)) return div(t, add(mult(p, a), mult(q, b))) def div(s, a): return a[0]/s, a[1]/s def neq(a,b): return ...
The code calculates the intersection of two line segments. It first checks if lines are parallel, then verifies if the computed intersection point lies on both segments using dot products and distance checks. If valid, it returns the squared distance from the first segment's start point to the intersection; otherwise, ...
def intersect(line1, line2): a, b = line1 c, d = line2 b = add(a, b) d = add(c, d) inter = line_intersection(a,b,c,d) if inter == -1: # We have parallel lines inter = div(2, add(a, c)) if neq(cross2(a, inter, b), 0) or neq(cross2(c, inter, d), 0): return -1 ...
def action_enemies(self, obj): answer = obj.interact(self.hero, self.map.enemies) if answer == 0: self.working = False else: for message in answer: self.notify(message) self.draw_map.draw_map(), self.interface.draw_interface(), self.info.draw_info(...
The code checks if the hero's movement (with correction) collides with enemies, doors, or items. If an enemy or door is hit, respective actions are triggered and the method returns False. If an item is hit, its action is called. The interface and info are updated, then True is returned unless a collision stops movement...
def action(self, correction): for obj in self.map.enemies: if [self.hero.pos[0] + correction[0], self.hero.pos[1] + correction[1]] == obj.pos: self.action_enemies(obj) return False for coord in self.map.objects["doors"]: if [self.hero.pos[0] + corr...
def draw_ground(self, work_surface, surface_size): ground = create_sprite(os.path.join("texture", "ground.png"), self.size) for coord_x in range(0, math.ceil(surface_size[0] + 1), self.size): for coord_y in range(0, math.ceil(surface_size[1] + 1), self.size): work_surface.bli...
The main task of the code is to render a game map by scaling the original map size, creating a surface for the map, drawing ground, trees, doors, enemies, items, and the hero, then blitting the rendered map onto the game window at a calculated position to display the game scene.
def draw_map(self): self.map_size = [self.map.map_size[0] * self.size, self.map.map_size[1] * self.size] self.map_screen = pygame.Surface((self.map_size[0], self.map_size[1])) self.draw_ground(self.map_screen, self.map_size) self.draw_trees(self.map.objects['trees'], self.map_screen) ...
def getS(X, L, mu, s_penalty): mu = float(mu) s_penalty = float(s_penalty) s_penalty2 = s_penalty * mu C = np.subtract(X, L, out=None) S = SoftThresholdMatrix(C, s_penalty2) S_l1norm = np.sum(np.abs(S)) return S, s_penalty2 * S_l1norm def getL(X, S, mu, L_penalty): mu = float(mu) L_p...
The function performs Robust Principal Component Analysis (RPCA) to decompose input matrix $ X $ into low-rank ($ L $), sparse ($ S $), and error ($ E $) components. It iteratively optimizes these matrices using alternating projections, with penalties controlling sparsity and rank constraints. Convergence is checked vi...
def RPCA(X, Lpenalty=-1, Spenalty=-1, verbose=True): X = np.array(X).astype('float64').copy() m, n = X.shape # Penality parameters if (Lpenalty == -1): Lpenalty = (1.4) / np.sqrt(min(n, m)) if (Spenalty == -1): Spenalty = (1.4) / np.sqrt(max(n, m)) # Convergence condition ...
def check_keydown_events(event, game_settings, screen, ship, bullets): """Checks for keydown events from the user""" if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_q: sys.exit() # ...
The function checks for user input events (keyboard and mouse) to handle game actions such as quitting, controlling the ship, firing bullets, and initiating gameplay via the play button. It processes events like KEYDOWN, KEYUP, and MOUSEBUTTONDOWN, delegating specific actions to other functions for further processing.
def check_events(game_settings, screen, stats, sb, play_button, ship, aliens, bullets): """Checks for events from mouse and keyboard""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(...
def check_fleet_edges(game_settings, aliens): """Respond appropriately if any aliens have reached an edge""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(game_settings, aliens) break def check_aliens_bottom(game_settings, stats, sb, screen, ship, ...
The function `update_aliens` updates alien positions, checks if the alien fleet reaches the screen edge or bottom, detects collisions between the ship and aliens, and triggers responses like `ship_hit` if a collision occurs. It ensures aliens move dynamically, monitors game-ending conditions (e.g., aliens reaching the ...
def update_aliens(game_settings, stats, sb, screen, ship, aliens, bullets): """Checks if fleet is at an edge, and updates all positions of the alien fleet""" check_fleet_edges(game_settings, aliens) aliens.update() #Checks to see if any aliens are at the bottom of the screen check_aliens_bottom(gam...
def readGrid(filename): #print('In readGrid') grid = [] with open(filename) as f: for l in f.readlines(): grid.append([int(x) for x in l.split()]) f.close() #print 'Exiting readGrid' return grid def uninformedSearch(grid, start, goal, searchType): current = Node(star...
The code reads a grid from a file, takes user inputs for start/goal coordinates, and performs an uninformed search (BFS or DFS) to find a path. It then outputs the grid with the computed path. The main task is to execute a chosen search algorithm on a grid to determine a route from a specified start point to a goal poi...
def Main(): grid = readGrid('grid.txt') print(grid) start_x = int(input("Starting point (x value): ")) start_y = int(input("Starting point (y value): ")) start = [start_x, start_y] goal_x = int(input("Goal point (x value): ")) goal_y = int(input("Goal point (y value): ")) goa...
def readGrid(filename): #print('In readGrid') grid = [] with open(filename) as f: for l in f.readlines(): grid.append([int(x) for x in l.split()]) f.close() #print 'Exiting readGrid' return grid def informedSearch(grid, start, goal, searchType): #current = Node(start...
The code's main task is to perform an A* search (searchType = 1) on a grid loaded from 'grid.txt' to find a path from the start position [0,0] to the goal [9,9]. It reads the grid, executes the informed search algorithm, and outputs the resulting grid with the identified path. The `expandCount` variable tracks explorat...
def Main(): grid = readGrid('grid.txt') print(grid) #Greedy Search: searchType = 0 #A*: searchType = 1 searchType = 1 start = [0, 0] goal = [9, 9] global expandCount #path = breadthFirstSearch(grid, start, goal) path = informedSearch(grid, start, goal, s...
def load_wiki_data(self, bs=70): trn_path = self.dataset_path / f'{self.lang}.wiki.train.tokens' val_path = self.dataset_path / f'{self.lang}.wiki.valid.tokens' tst_path = self.dataset_path / f'{self.lang}.wiki.test.tokens' for path_ in [trn_path, val_path, tst_path]: assert ...
The code trains a language model (LM) using a learner object, loading data and initializing the model with optional pretrained weights. It trains the LM for a specified number of epochs, adjusting learning rates and weight decay based on whether pretrained weights are used. The training involves freezing and unfreezing...
def train_lm(self, num_epochs=20, data_lm=None, bs=70, true_wd=False, drop_mult=0.0, lr=5e-3): data_lm = self.load_wiki_data(bs=bs) if data_lm is None else data_lm learn = self.create_lm_learner(data_lm, drop_mult=drop_mult) learn.true_wd = true_wd #try: # learn.load("lm_best...
def load_cls_data(self, bs, **kwargs): if self.dataset_dir.name == 'imdb': return self.load_cls_data_imdb(bs, **kwargs) else: assert self.tokenizer is Tokenizers.MOSES, "XNLI does not support other tokenizers than Moses" return self.load_cls_data_old_for_xnli(bs, **kw...
The main task of the code is to train a classifier model using a pre-trained language model, with options to fine-tune the LM, apply weight decay, and adjust learning rates. It loads classification data, trains the LM if needed, creates a classifier learner, freezes/unfreezes layers in stages, and performs multi-phase ...
def train_cls(self, num_lm_epochs, unfreeze=True, bs=40, true_wd=True, drop_mul_lm=0.3, drop_mul_cls=0.5, use_test_for_validation=False): data_clas, data_lm = self.load_cls_data(bs, use_test_for_validation=use_test_for_validation) if self.need_fine_tune_lm: self.train_lm(num_lm_epochs...
def drop_useless_columns(df): """ Removes irrelevant or non-correlated columns (s.t "hotel_id", "customer_nationality") that were not expected to significantly impact cancellation predictions. :param df: Dataframe, Design matrix of regression problem :return: df """ df = df.drop(columns=DROP...
The main task of the code is to preprocess a regression dataset by removing irrelevant columns, adding new features, converting categorical variables to dummy variables, and transforming boolean columns into binary values to prepare the data for modeling.
def preprocess_data(df): """ preprocess the data: - Removes irrelevant or non-correlated columns - Introduces new features - Converts categorical variables into dummy variables - Transforms true/false columns into binary values :param df: Dataframe, Design matrix of regression problem :r...
def drop_useless_columns(df): """ Removes irrelevant or non-correlated columns (s.t "hotel_id", "customer_nationality") that were not expected to significantly impact cancellation predictions. :param df: Dataframe, Design matrix of regression problem :return: df """ df = df.drop(columns=DROP...
The function preprocesses a regression dataset by removing irrelevant columns, adding new features, converting categorical variables to dummy variables, and transforming boolean columns into binary values to prepare the data for modeling.
def preprocess_data(df): """ preprocess the data: - Removes irrelevant or non-correlated columns - Introduces new features - Converts categorical variables into dummy variables - Transforms true/false columns into binary values :param df: Dataframe, Design matrix of regression problem :r...
def clean_data_classifiers(df = pd.read_csv("1/code/agoda_cancellation_train.csv"), train=True, cols_train=None): """ cleans the data and preprocess it :return: """ np.random.seed(0) df = preprocess_data(df) if not train: df = df.reindex(columns=cols_train, fill_value=0) if trai...
The main task of the code is to train a classifier on cleaned training data (excluding the 'h_booking_id' column) and evaluate feature importance using the trained model. It prepares data, fits a classifier, and assesses how features contribute to predicting cancellation outcomes, likely for model interpretation or opt...
def task_3(): X_cancel_train, y_cancel_train = clean_data_classifiers(train=True) X_cancel_train = X_cancel_train.drop(columns=["h_booking_id"]) regr = classifier_fit(X_cancel_train, y_cancel_train) feature_evaluation(X=X_cancel_train, y=y_cancel_train, model=regr)
def launchGame(): #subprocess.Popen(["vba", "-4", "POKEMONRED98.GB"]) FNULL = open(os.devnull, 'w') subprocess.Popen(["vba", "POKEMONRED98.GB"], stdout = FNULL, stderr = FNULL) def getWindowID(): proc = subprocess.Popen(["xdotool", "search", "--name", "VisualBoy"], stdout=subprocess.PIPE) ID = 0...
The main task of the code is to test the "left" key functionality in a game by launching the game, loading a specific scenario ("BEGINNING.sgm"), simulating a left key press, and recording the action as a GIF for verification or debugging.
def testLeft(): launchGame() time.sleep(1) ID = getWindowID() time.sleep(1) loadGame("BEGINNING.sgm", ID) hitKeyAndRecord(ID, KEYS["left"], "Left.gif")
def create_layer_optimizers(model,lr, momentum, weight_decay): l3_params = [] l2_params = [] l1_params = [] for name, param in model.named_parameters(): if name.startswith('linear'): pass elif name.startswith("layer3"): l3_params.append(param) elif n...
The function `client_train` trains a client's model in a federated learning setup, supporting both traditional training and knowledge distillation. It initializes or loads a ResNet or VGG model, manages learning rate scheduling, and handles incremental learning. The code trains the model over specified epochs, logs met...
def client_train(per_client_output_avg, per_client_act_avg, per_client_layers_avg, per_client_grads_avg, per_client_target_avg, per_client_activation_avg, per_client_tot_output_avg, client,round_n, mod,normalization,dataset,depth,lr, momentum, weight_decay, writer, save_path, t_round, lr_next, train_lo...
def get_class_images(loader, seen_id): incremental_step_images_ids = [] for ind in range(len(loader.dataset.indices)): if loader.dataset.dataset.targets[loader.dataset.indices[ind]] == seen_id: incremental_step_images_ids.append(ind) incremental_step_images=loader.dataset.dataset.data...
This function creates an incremental dataloader by combining original dataset samples with exemplar samples from previous steps. It calculates required exemplar counts per class, constructs exemplar sets via `construct_exemplar_set`, and merges them with initial data. The resulting dataloader uses SubsetRandomSampler o...
def incremental_dataloader_creation(loader_init, dataset_init, seen_ids, exemplar_classes, batch_size, transform, exemplar_size, model, exemplar_ids_prev, incremental_step): if exemplar_classes>0: class_size = exemplar_size // exemplar_classes classes_list= [...
def random_split(n_clients, trainSet, splits, total_len, mode, list_server): split_tr = [] split_ev = [] for i in range(n_clients): if np.mod(i, 2) == 0: split_tr.append(int(np.floor(len(trainSet) * splits[i]))) split_ev.append(int(np.floor(len(trainSet) * splits[n_clients...
The function creates client-specific training and validation subsets from a dataset, either randomly or non-IID, based on the 'partition' parameter. It adjusts dataset splits according to 'mode' (distillation vs. others), generates data loaders, and returns training/validation data, labels, and server-side validation s...
def client_subset_creation(partition,trainSet,splits,n_clients,beta, batch_size, mode, common_dataset_size): if mode == 'distillation': total_len= int(len(trainSet)*(1-common_dataset_size)) list_server=[int(len(trainSet)*common_dataset_size)] else: list_server = [int(len(trainSet...
def update_all_readings(): """ Updates local storage data to new data received over TCP, Then formats as floats to store locally :rtype: None """ # Clear all storage data storage_log.clear() # Get temperature and precipitation data (big buffer size to handle a long list of data) ra...
The function handles web requests by sending a command to a storage server to retrieve all data, updates the system's readings, refreshes the GUI plot on the webpage, and returns the updated HTML template to display the new data visualization.
def handle_request(): """ This function is called whenever a post or get request is sent from the webpage Sends a message to storage server to send all data available, then updates readings and subsequently the GUI Plot in webpage :return: Template from hello_world() """ sentence = "give al...
def verificar_eventos_keydown(event, ai_settings,pantalla,nave,balas): """Responde a las pulsaciones de las teclas""" if event.key == pygame.K_RIGHT: nave.moving_right = True elif event.key == pygame.K_LEFT: nave.moving_left = True elif event.key == pygame.K_SPACE: fuego_bala(ai_...
The main task of the code is to handle user inputs in a Pygame game by detecting keyboard presses/releases, mouse clicks, and quitting events. It updates game state by delegating actions to functions like verificar_eventos_keydown, verificar_eventos_keyup, and check_play_button, which manage ship movement, shooting, an...
def vericar_eventos(ai_settings,pantalla,estadisticas,marcador,play_button,nave, aliens,balas,): """Responde a las pulsaciones de teclas y los eventos del raton""" #Con el ciclo for detectamos todos los eventos(teclado o raton) que suceden dentro de pygame for event in pygame.event.get...
def check_fleet_edges(ai_settings, aliens): """Responde de forma apropiada si algun alien llega a un borde""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings,aliens) break def nave_golpeada(ai_settings,estadisticas,pantalla,marcador,nave,...
The function updates alien positions, checks for collisions between the player's ship and aliens, and verifies if aliens have reached the screen's bottom, triggering responses like ship damage or game-over conditions.
def update_aliens(ai_settings,estadisticas,pantalla,marcador,nave,aliens,balas): """Comprueba si la flota esta al borde y actualiza las posiciones de todos los aliens de la flota""" check_fleet_edges(ai_settings,aliens) aliens.update() #Busca colisiones de nave-alien if pygame.sprite.spritecoll...
def get_prompt(self, batch_size, device, dtype=torch.half): prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device) past_key_values = self.prefix_encoder(prefix_tokens).type(dtype) past_key_values = past_key_values.view( batch_size, self.prefix_s...
This code defines the forward pass of a transformer model, handling input embeddings, attention masks, and position embeddings (Alibi or RoPE). It processes inputs, generates attention masks, manages past key values for caching, and runs through the encoder. The method returns hidden states, attention outputs, and cach...
def forward( self, input_ids, position_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.BoolTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None, inputs_embeds: Optional[torch.Tensor] = N...
def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, system_prompt = None): inputs = tokenizer.build_inputs(query, history=history, system_prompt=system_prompt) inputs = inputs.to(self.device) return inputs def build_stream_inputs(self, tokenizer, query: str, hist...
This method generates text responses incrementally using a language model, handling conversation history and streaming outputs. It constructs input tensors, applies logits processing, and yields partial results with updated history and optional past key values for efficient generation.
def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, system_prompt=None, past_key_values=None, max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, return_past_key_values=False, **kwargs): if history is ...
def find_winner(board, length=4): """ Checks the board for any winning streaks :param board: active game board :param length: Length of streak searching for. A win is 4 in a row :return: None if no winner, or the winning piece if there is one. """ for row in range(ROWS): for column i...
The code implements the **Minimax algorithm with alpha-beta pruning** to determine the optimal move in a game (e.g., Connect Four). It evaluates possible future game states by recursively exploring the game tree, prioritizing moves that maximize the current player's advantage while minimizing the opponent's. Alpha-beta...
def alpha_beta(board, depth, alpha, beta, max_player): """ Minimax algorithm with alpha-beta pruning to decide which move is the best. :param board: active game board :param depth: number of moves to look ahead :param alpha: high cutoff for maximizing player :param beta: low cutoff for minimizin...
def checkMissing(param): if param is None: raise ValueError(f"Missing required '{param[0]}' parameter") def checkType(param, check): if not isinstance(check, type): if check[0] is LIST_TYPES: result = isinstance(param[1], LIST_TYPES) if not np.all(result): ...
This function validates input parameters for a statistical model, ensuring correct types, ranges, and constraints. It checks K, data structure, model type, known class labels, and other settings, raising errors for invalid values, NaNs, or incompatible configurations. It also verifies initialization methods, dimension ...
def _T_hddc_control(params): K = ('K',params['K']) checkMissing(K) checkType(K, (INT_TYPES)) checkRange(K, lower=1) data = ('data', params['data']) checkMissing(data) checkType(data, (skfda.FDataBasis, dict)) if isinstance(data[1], skfda.FDataBasis): checkType(('data', data[1]...