dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def queue(self, dat): ''' Add data to queue, wait execution :param dat: 8-bit data, first 4 bit is D7-D4, Last 4 bit is NC, E, RW, RS :return: ''' dat = dat & 0xF0 dat |= self.BK dat |= self.RS self.bufs.append(dat | 0x04) # enabl...
This code initializes an I2C-connected LCD display by scanning for the device, configuring its settings (function set, display on/off, entry mode), and sending initialization commands to prepare the display for operation. It uses queued byte buffers for efficient I2C communication and executes commands like function se...
def __init__(self, i2c): # board definition # P0: RS # P1: R/W # P2: E # P3: -- # P4-P7: DB4-DB7 self.i2c = i2c print('(Re)Initializing...') scan_result = i2c.scan() while not scan_result: print("Cannot Locate I2C Device") ...
def SDF(max_steering, k):#Steering_Distribution_Function, abs(x)**(1/k) half_range = int((DISCRETE_RANGE-1)/2) positive_steering = np.zeros(half_range) for i in range(half_range): positive_steering[i] = max_steering*((i+1)/half_range)**k negative_steering = positive_steering*(-1) steering_ca...
The code initializes a ROS node for real-time intersection detection and autonomous navigation using the Dynamic Window Approach (DWA). It processes camera images, subscribes to sensor data, and employs a matplotlib plot for visualization. The DWA algorithm calculates optimal steering and velocity commands based on det...
def main(): global fig, histo plt.style.use('dark_background') fig, ax = plt.subplots(figsize=(4,4)) ax.set_title("Intersection") ax.set_xlabel("Angle") ax.set_ylabel("Histogram") discrete_steering = SDF(max_steering = 200, k=2) histo, = ax.plot(discrete_steering, np.zeros((dis...
def __get_player_in_game(self, target_player: Player) -> Optional[Player]: for player in self.players: if player.name == target_player.name: return player return None def __is_player_connected(self, target_player: Player) -> bool: for player in self.players: ...
This function handles new player connections by validating authentication, managing existing players, checking game capacity, and initializing game setup. It accepts a connection, verifies the 'want connect' message, stores the player, checks for duplicates, handles reconnections, and starts the game if both players ar...
def connect_new_player(self, player_connection, addr) -> None: logging.debug(f'Accepted a connection from {addr}') if player_connection.recv(1024) != b'want connect': player_connection.close() return player_connection.sendall(b'connected') player_data = player_c...
def enteringUsername(self, driver): usernameFieldXPath = '//*[@id="i0116"]' usernameNextButtonXPath = '//*[@id="idSIButton9"]' driver = self.waitForElementToAppear(usernameFieldXPath, driver) driver = self.waitForElementToBeClickable(usernameNextButtonXPath, driver) usernameFi...
The main task of the code is to automate a login process for a room booking system using Selenium. It initializes a Chrome browser with specific options, navigates to a booking URL, handles username/password input, 2FA selection, OTP entry, and accesses a room schedule page. The code also includes steps to manage brows...
def login(self): # Options options = uc.ChromeOptions() options.user_data_dir = "c:\\temp\\profile" options.add_argument('--user-data-dir=c:\\temp\\profile2') options.add_argument('--incognito') options.add_argument('--no-first-run --no-service-autorun --password-stor...
def getTimeSlot(self): # Get the timeSlot from the current screencapture with their exact coordinates imgWidth = self.calendarImg.shape[1] pixelOffset = 15 boxLeft = self.dateCoordinate[0] boxTop = self.dateCoordinate[1] boxHeight = self.dateCoordinate[2] time...
The main task of the code is to prepare data for room availability analysis by processing a calendar image. It checks if the image is valid, extracts time slots, crops room names, performs OCR on room names (correcting errors), generates room names, and organizes room slot coordinates. These attributes are set to enabl...
def prepareRoomAnalysis(self): # Generate all the required attributes for the functioning of getRoomAvailability Method if (type(self.calendarImg) == type(np.array([]))): if not ( self.calendarImg.size == 0 or self.dateCoordinate == None ): # Get timeslot for the timetable...
def getRoomId(self, roomName): # get the room id from the roomSlot Array for i in range(0, len(self.roomSlot)) : if roomName == self.roomSlot[i][0]: return i def cropRoomSlotFromImg(self, img, boundingBox): # Crop room slot from img with the provided bounding box ...
The code extracts a room's availability by cropping its section from an image, then checks each time slot's status to generate a list of time-slot availability pairs.
def getRoomAvailability(self, roomName): roomId = self.getRoomId(roomName) roomBoundingBox = self.roomSlot[roomId][1] roomImg = self.cropRoomSlotFromImg(self.calendarImg, roomBoundingBox) roomAvailability = [] for i in range(0, len(self.timeSlot)): timeSlotName =...
def portionImageByArea(self, img, portionHeightCorrector=0, portionWidthCorrector=0): rowsImg = [] areaImg = [] rowDivision = PORTION_HEIGHT_DIVISOR + portionHeightCorrector colDivision = PORTION_WIDTH_DIVISOR - portionWidthCorrector for i in range(0, rowDivision): ...
This function identifies the coordinate and dimensions of a date in a screenshot. It first splits the image into portions by area, analyzes them to detect the date, and returns coordinates if found. If unsuccessful, it performs a narrowed search on the original image. If neither method finds the date, it returns defaul...
def findCropDateCoordinateByArea(self, screencaptureImg): dateId = -1 imgPortions = self.portionImageByArea(screencaptureImg) dateId, left, top, height, width = self.analyzeAllImgPortions(imgPortions) if dateId != -1: return left, top, height, width # if we could...
def simulation(k, exponent, m_planet , sigma_value): sim = rebound.Simulation() sim.integrator = "WHFast" sim.units = ('yr', 'AU', 'Msun') sim.add(m=1) m_array = m_final(m_planet, sigma_value) a_array_final = a_final(m_array, k, exponent) e_array_final = e_final(a_array_final) for i in...
The code simulates planetary system dynamics by running multiple trials with randomized parameters (k, exponent, mass, sigma). It calculates collision frequencies, their standard deviation, and MMR (Mean Motion Resonance) statistics. Results are log-transformed for analysis, with outputs including frequency distributio...
def MMR_sim(k_lower, k_upper, expoent, m_planet, sigma_value, num): MMR_result_array = [] MMR_result_collide = [] for i in range(int(num)): sim = simulation(k = rand(k_lower, k_upper), exponent = expoent, m_planet = m_planet , s...
def simulation(k, exponent, m_planet , sigma_value): sim = rebound.Simulation() sim.integrator = "WHFast" sim.units = ('yr', 'AU', 'Msun') sim.add(m=1) m_array = m_final(m_planet, sigma_value) a_array_final = a_final(m_array, k, exponent) e_array_final = e_final(a_array_final) for i in...
The code runs multiple simulations (`num` times) with random parameters (`k` between `k_lower` and `k_upper`), computes collision frequency data from each, and analyzes the statistical distribution (frequency count and standard deviation). It outputs results for given planet mass, sigma, and exponent values, aiding in ...
def MMR_sim_collide(k_lower, k_upper, expoent, m_planet, sigma_value, num): MMR_result_array = [] for i in range(int(num)): sim = simulation(k = rand(k_lower, k_upper), exponent = expoent, m_planet = m_planet , sigma_value = sigma_v...
def initialize_optimizer(self): with tf.variable_scope('GAN_Optimizer'): with tf.variable_scope('Optim'): self.optim = tf.train.AdamOptimizer(learning_rate=ln_rate, beta1=0.0, beta2=0.99, epsilon=1e-8, name='d_optim') # was 0.5, 0.9 print('Solver Configured') def build_model(...
This code initializes a class instance by setting input data (img, label), configuring an optimizer, constructing a model using the data, and generating model statistics. The __init__ method prepares the model for training or analysis by linking data, optimization settings, and model architecture.
def __init__(self, img, label): self.img = img self.label = label self.initialize_optimizer() self.build_model(img, label) self.model_stats()
def addPadding(text):#Add padding to the datas using PKCS5 spec. pad_len = 16 - (len(text) % 16) text += pad_len * chr(pad_len) return [text,pad_len] def nsplit(s, n):#Split a list into sublists of size "n" return [s[k:k+n] for k in range(0, len(s), n)] def generate_subkey(plaintext,secretkey): # Gene...
This code encrypts plaintext using a secret key with padding, block splitting, and multiple rounds of encryption. It checks if plaintext length is a multiple of 16, adds padding if needed, splits input into 8-byte blocks, generates subkeys, and applies 8 rounds of encryption per block. The result, subkeys, and padding ...
def encrypt(self,secret_key,plaintext): res="" if len(plaintext)%16!=0: plaintext,self.pad_len=addPadding(plaintext) self.ispadding=True self.pswd=secret_key self.inputtext=plaintext blocks=nsplit(self.inputtext,8) round_encrypted_result=None ...
def nsplit(s, n):#Split a list into sublists of size "n" return [s[k:k+n] for k in range(0, len(s), n)] def reverse_round(plaintext,subkey): round_key="" plaintext_R=plaintext[:4] plaintext_L=plaintext[4:] #converting strings to bit arrays round_key_bit_array=string_to_bit_array(subkey)...
The main task of the code is to decrypt a given plaintext using a series of reversed cryptographic rounds. It splits the input text into 8-character blocks, applies reverse_round operations iteratively with provided round keys, concatenates the decrypted blocks, and finally removes padding based on the specified pad_le...
def decrypt(self,keys,pad_len,plaintext): res="" self.roundkeys=keys self.inputtext=plaintext blocks=nsplit(self.inputtext,8) round_decrypted_result=None for block in blocks: roundtext=block for j in range(7,-1,-1): round_decrypted_...
def train_epoch(self, model, loader, optimizer, criterion, progress_bar, epoch): running_loss = 0.0 model.train() for i, (data, target_values, condition_mask) in enumerate(loader): optimizer.zero_grad() predictions, loss = self.train_batch(model, data, target_values, c...
(The code trains a neural network model using training and validation data loaders, optimizing with a given criterion and optimizer. It employs early stopping based on validation loss patience, adjusts learning rate via ReduceLROnPlateau, tracks metrics like MAE and whiteness, logs results with WandB if enabled, and sa...
def train(self, model, train_loader, valid_loader, optimizer, criterion, n_epoch, patience=10, lr_patience=10, fps=30): model = model.to(self.device) criterion = criterion.to(self.device) if self.wandb_logging: wandb.watch(model, criterion) best_valid_loss = ...
def optimize_batch(self, local_batch, local_batch_labels): pred = self.forward(local_batch, local_batch_labels) loss = self.MCLoss(pred) self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.detach().item() def print_loss(self, epoch): LLs=...
This code trains a neural network model over a specified number of epochs, optimizing its parameters using provided data and labels. It monitors loss values, checks for NaNs, and evaluates progress every 100 epochs by computing scores and storing intermediate predictions/qzx values for visualization. Training stops ear...
def optimize(self, epochs, data, labels, score=None, channel=None, *args, **kwargs): self.train() # Inherited method which sets self.training = True self.epochs = [0, epochs] loss_value=[] self.Toplot=[] for epoch in range(epochs): loss = self.optimize_...
def optimize_batch(self, local_batch, local_batch_labels): pred = self.forward(local_batch, local_batch_labels) loss = self.MCLoss(pred) self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.detach().item() def print_loss(self, epoch): LLs=...
The code trains a model over specified epochs using a dataloader, optimizing batch data with `optimize_batch`, tracking loss values, checking for NaNs, and evaluating scores. It prints losses periodically, breaks early if a score threshold is met, and logs predictions/qzx values for visualization. Finally, it switches ...
def optimize(self, epochs, dataloader, score=None, channel=None, *args, **kwargs): self.train() # Inherited method which sets self.training = True self.epochs = [0, epochs] loss_value=[] self.Toplot=[] for epoch in range(epochs): for i, Data in enumerate...
def generate_real_samples(dataset, n_samples): ix = randint(0, dataset.shape[0], n_samples) X = dataset[ix] y = ones((n_samples, 1)) return X, y def generate_fake_samples(g_model, latent_dim, n_samples): x_input = generate_latent_points(latent_dim, n_samples) X = g_model.predict(x_input) y =...
The code trains a GAN by alternating between updating the discriminator with real and fake samples, and the generator via the GAN model. It iterates over epochs and batches, trains discriminator on real data, then on generated fake data, then trains the generator using latent vectors. Periodic performance summaries are...
def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=500, n_batch=128): bat_per_epo = int(dataset.shape[0] / n_batch) half_batch = int(n_batch / 2) for i in range(n_epochs): for j in range(bat_per_epo): X_real, y_real = generate_real_samples(dataset, half_batch) ...
def usage(self): print ( 'Usage: ' + sys.argv[0] + ' -p <purpose> ' + ' -e <experience> ' + ' -b <budget> ' \ + ' -o <origin> ' + ' --outbounddate <departure date - yyyy-mm-dd> ' \ + ' --arrivaldate <arrival date - yyyy-mm-dd>' + ' --adults <no. of passengers> ' ) def send...
The code processes user inputs to recommend a travel destination based on purpose, experience, and budget. It validates required parameters, constructs flight search parameters, and handles errors by logging and sending messages to a server. If successful, it retrieves flight data and sends the recommended destination ...
def runfromserver(self, argdict): self.tlogger.info("Running 'runfromserver' function...") #temp hardcode adults = "1" arrivaldate = "" country = "US" currency = "USD" flightparams = {} destination = "" flightdata = "" errormsg = "" if (...
def check_ros_running(): try: rostopic.get_topic_class('/rosout') return True except: print('WARNING: Unable to detect rosmaster. Is rosmaster running?\n') return False def kill_node(node_name, quiet): print("Killing node: {}".format(node_name)) # sanity check: is this a...
This code defines a command-line tool for managing ROS (Robot Operating System) nodes and messages. It provides subcommands to kill nodes, drop messages on topics, unregister publishers/subscribers/services, and isolate nodes by unregistration. The tool checks ROS status, handles arguments via argparse, and executes ac...
def main(): ros_running = check_ros_running() parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() parser.add_argument('--version', action='version', version='0.0.1') parser.add_argument('-i', '--ignore_rosmaster_state', action='store_true', \ ...
def find_stars(self): """Find stars in the image used to initalise the PSF object. Returns ------- peaks[ok] (pyplot.figure): Information associated with each of the acceptable measured peaks. stars[ok] (list): Contains all the measured COGs for the accep...
The code generates an empirical Point Spread Function (PSF) from an image by detecting stars, filtering them by magnitude, centering and measuring their profiles, stacking acceptable objects, and saving the resulting PSF. It also optionally visualizes and saves dominant star stamps for validation, ensuring accuracy thr...
def measure_psf(self): """Employ the functions defined above to measure an empirical PSF from an image.""" # Find the stars. peaks, stars = self.find_stars() # Only use stars of a particular magnitude. ok = (peaks['mag'] > self.config['MAG_MAX']) & ( peaks['mag'] < self.config[...
def get_part(sock): while True: data, addr = sock.sock.recvfrom(BUFF_SIZE) packet = pickle.loads(data) if is_valid(packet): sock.sock.sendto(make_packet('ack'), addr) return packet['payload'] else: sock.sock.sendto(make_packet('nack'), addr) def is...
The function `recv` receives data via a socket by first retrieving a header, then collecting payload packets until a 'fin' signal is received. It merges the payload parts, constructs a packet with the header and payload, validates it using a checksum, and sends an 'ack' or 'nack' response accordingly. The validated pay...
def recv(sock): # get header info header = get_part(sock) # get pakets first = get_part(sock) while True: part = get_part(sock) if part == 'fin': break # merge pakets first += part # chek merged to header cksm paket = { 'cksm' : header...
def parse_coefs(K, N): return get_tau_mat(get_U_mat(K, N)) def get_coefs(x, q, r, tau, z=10): combinatorial_term = get_combinatorial_term(x, r, q, z=z) residual_term = get_residual_term(x, r, q, tau) result = combinatorial_term + residual_term return np.exp(result) def get_sample_error(...
This function calculates the average error of a model's predictions across a dataset. It iterates through each sample in X and Y, computes prediction coefficients using parameters R, Q, and parsed coefficients from K, then accumulates the per-sample error. Finally, it returns the mean error over all samples by dividing...
def get_dataset_error(K, X, Y, R, Q): N = X.shape[1] parameters = R, Q, parse_coefs(K, N) error = 0 for i in range(len(X)): x, y = X[i], Y[i] coefs = get_coefs(x, *parameters) error += get_sample_error(x, y, coefs) error /= X.shape[0] return error
def parse_coefs(K, N): return get_tau_mat(get_U_mat(K, N)) def get_coefs(x, q, r, tau, z=10): combinatorial_term = get_combinatorial_term(x, r, q, z=z) residual_term = get_residual_term(x, r, q, tau) result = combinatorial_term + residual_term return np.exp(result) def get_sample_error(...
The function `get_error_by_X` computes the error between predicted values (derived from input data `x` and parameters `K`, `R`, `Q`) and actual values `y` using a set of coefficients. It processes input data to calculate a sample error, which is returned as the result.
def get_error_by_X(x, y, K, R, Q): N = x.shape[0] parameters = R, Q, parse_coefs(K, N) coefs = get_coefs(x, *parameters) error = get_sample_error(x, y, coefs) return error
def parse_coefs(K, N): return get_tau_mat(get_U_mat(K, N)) def get_coefs(x, q, r, tau, z=10): combinatorial_term = get_combinatorial_term(x, r, q, z=z) residual_term = get_residual_term(x, r, q, tau) result = combinatorial_term + residual_term return np.exp(result) def get_concetrations...
This function predicts concentration values for each sample in dataset X using parameters R, Q, and coefficients derived from E. It iterates through each sample, computes model coefficients with get_coefs(), then calculates predicted concentrations with get_concetrations(), storing results in pred_y.
def predict_dataset(X, E, R, Q): parameters = R, Q, parse_coefs(E, X.shape[1]) pred_y = np.zeros(X.shape) for i in range(len(X)): x = X[i] coefs = get_coefs(x, *parameters) pred_y[i] = get_concetrations(x, coefs) return pred_y
def handle_withdraw_response(self, amount: int, customer_request_id): self.balance -= amount message_received = MessageReceived(interface="withdraw") response_result = ResponseResult(status="success") message_received.result.CopyFrom(response_result) self.propagate_withdraw(amo...
The main task of the code is to process customer banking requests (withdraw, deposit, propagate_withdraw, propagate_deposit) by updating logical clocks, logging events with timestamps and transaction details, and generating responses. It uses thread safety (locks) to ensure atomic operations, serializes events to a sha...
def MsgDelivery(self, request, context): lock = Lock() with lock: response = MsgDeliveryResponse(id=self.id) for request_element in request.request_elements: self.local_clock = ( max(self.local_clock, request_element.logical_clock) + 1 ...
def check_eaten(gui_board,board, snake:Snake, food:Food): if snake.head[0] == food.x and snake.head[1] == food.y: #print(snake.points) #increase snakelength by 1 grow_snake(gui_board,board,snake) #update food food.update() snake.ate_food = True def update_snake(gui_bo...
The main task of the code is to update the game state by checking collisions (food/eaten self), updating the snake's position based on direction, redrawing food on the GUI, and updating the board. It returns flags indicating if the game ended or if the snake collided with itself.
def update_all(snake:Snake, board:Board, gui_board,food:Food, direction): check_eaten(gui_board,board,snake, food) end = board.check_end(snake) eat_self = snake.eat_self() update_snake(gui_board, board, direction, snake) draw_food(gui_board, food) board.update(snake, food) return end,eat_se...
def board_fill(gui_board, board: Board): py.display.update() for i in range(0, board.x): for j in range(0,board.y): py.draw.rect(gui_board, black, (i*swidth, j*sheight, swidth, sheight)) py.draw.rect(gui_board, dark_grey, (i*swidth+1, j*sheight+1, swidth-1, sheight-1)) py.dis...
The code implements a reinforcement learning agent for a Snake game using a DQN approach. It initializes game elements, trains the agent via experience replay, and uses a GUI for rendering. The agent explores (epsilon-greedy) and decays exploration over epochs, updating its neural network with batched experiences from ...
def GUI(): testing = False if testing: epsilon = 0 agent = Agent(load=True) else: epsilon = 1.0 agent = Agent() epsilon_decay = 0.995 min_epsilon = 0.01 #agent initialization buffer = ReplayBuffer(20000) moves = 10000 #angle_norm = 180 ...
def get_random_point(self): if random.randint(0, 100) > self.goalSampleRate: rnd = [random.uniform(self.minrand, self.maxrand), random.uniform(self.minrand, self.maxrand), random.uniform(-math.pi, math.pi) ] else: # goal point sampli...
The main task of the code is to perform path planning using a randomized algorithm (likely RRT) in a 2D space with obstacles. It iteratively generates random points, connects them to the nearest nodes in a tree structure, checks for collisions with obstacles, and dynamically adjusts the tree (rewiring) to find a feasib...
def Planning(self, animation=True): """ Pathplanning animation: flag for animation on or off """ self.nodeList = [self.start] for i in range(self.maxIter): if(i%10==0): print("Planning path",i) for e in pygame.event.get(): ...
def reset(): global count screen.fill(white) #init_obstacles(GAME_LEVEL) init_circular_obstacles() count = 0 def fitSpline(points) -> object: pts = np.array(points) #print("points",pts.T) #pts = np.delete(pts,-1) #print("x = ",pts.T[:][0]) x1 = pts.T[:][0] y1 = pts.T[:][1] ...
This code implements a Rapidly-exploring Random Tree (RRT) algorithm for path planning in a 2D environment using Pygame. It allows users to set a start and goal point, builds a tree of nodes to navigate obstacles, detects when the goal is reached, and optimizes the path using a spline. The visualization displays node e...
def main(): global count initPoseSet = False initialPoint = Node(None, None) goalPoseSet = False goalPoint = Node(None, None) currentState = 'init' nodes = [] reset() path = [] while True: if currentState == 'init': pygame.display.set_caption('Select St...
def mybag_predict(eula): vec = my_bag_of_words(text_prepare(eula) , WORDS_TO_INDEX, DICT_SIZE) output = classifier_mybag.predict([vec])[0] return "EULA acceptable" if output == 1 else "EULA unacceptable" def tfidf_predict(eula): vec = tfidf_vectorizer.transform([text_prepare(eula)]) output = classif...
The code defines a `predict` function that selects and executes a text classification model based on the input `model_name`. It routes the input `eula` text to either `mybag_predict` (Bag of Words), `tfidf_predict` (TF-IDF), or `bert_predict` (BERT) functions, returning the respective model's prediction result. The mai...
def predict(model_name, eula): if model_name == "Bag of word": return mybag_predict(eula) elif model_name == "TD-IDF": return tfidf_predict(eula) elif model_name == "BERT": return bert_predict(eula)
def draw_board(self): self.draw_background() self.draw_lines() pygame.display.update() def move_agents(self): for agent in self.alive_agents: prev_pos = agent.pos if not agent.move(): continue x, y = (prev_pos[0] * self.size, ...
The main task of the code is to initialize and run a game loop that continuously updates and renders a game world. It draws the board, handles quit events, moves game agents, redraws them each frame, and maintains a target frame rate using a clock. The loop ensures real-time interaction and visual updates until the use...
def start_world(self): self.draw_board() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() self.move_agents() self.draw_agents() self.fpsClock.tick(FPS)
def move_ast(self): # Randomly move ast around. for ast in self.ast: speed = random.randint(1, 5) direction = Vec2d(1, 0).rotated(self.ob_body.angle + random.randint(-2, 2)) ast.velocity = speed * direction def move_mover(self): speed = random.randint(20, 200)...
This code processes an action to control an object's movement in a game environment, updates physics simulation, renders the screen with scores, checks for collisions, calculates a reward based on sensor readings, and returns the reward and state for reinforcement learning. It handles turning, movement, rendering, coll...
def frame_step(self, action): if action == 0: # Turn left. self.ob_body.angle -= .2 elif action == 1: # Turn right. self.ob_body.angle += .2 # Move ast. if self.num_steps % 100 == 0: self.move_ast() #print("WITh") # Move mover. ...
def minimap2(fq1, fq2, ref, path='minimap2', nthread=3, report=1e5): """ Wrapper for minimap2 for processing paired-end read data. :param fq1: str, path to FASTQ R1 file (uncompressed or gzipped) :param fq2: str, path to FASTQ R2 file (uncompressed or gzipped); if None, treat fq1 as a...
The main task of the code is to align sequencing reads (from FASTQ files) to a reference genome using minimap2, then analyze the alignment to compute mutation frequencies and coverage at each nucleotide position. It returns two dictionaries: one for mutation frequencies and one for coverage, both keyed by position. The...
def process(fq1, fq2, ref, nthread, binpath, limit): """ Main function :param fq1: str, path to FASTQ R1 or single file :param fq2: str, path to FASTQ R2 file, or None if single FASTQ :param ref: str, path to reference FASTA file :param nthread: int, number of threads to run minimap2 :p...
def temp_fastq(count=1): if count == 1: return NamedTemporaryFile(delete=False, suffix='.fastq') elif count > 1: return [NamedTemporaryFile(delete=False, suffix='.fastq') for _ in range(count)] else: return None def censor(original_file, bad_cycles_reader, censored_file, use_gzip=Tru...
This function trims paired-end FASTQ files by removing adapter/primer sequences using specified reference data. It handles gzip-compressed inputs, writes trimmed outputs to given paths, and optionally filters out bad cycles from a CSV. Temporary files are cleaned up afterward.
def trim(fq1, fq2, out1, out2, badfile=None, use_gzip=True, datadir=os.getcwd()): """ :param fq1: str, path to first FASTQ file :param fq2: str, path to second FASTQ file :param datadir: str, path to directory containing adapter and primer FASTAs :param out1: str, path to write first trimmed FAS...
def estimateDepth(rgb_mix): depth_temp = doubleestimate(rgb_mix, 384, 768) return depth_temp def estimateMatte(image): # convert image to PyTorch tensor im = Image.fromarray(image) im = im_transform(im) # add mini-batch dim im = im[None, :, :, :] # resize image for input im_b, im_c...
This function processes an input image to compute depth, disparity, and 3D points. It initializes camera parameters, converts the image to a PyTorch tensor, estimates disparity and matte, normalizes disparity, applies filters, calculates depth from disparity using focal length, and stores results like depth maps, 3D po...
def process_load(npyImage, objSettings): objCommon['fltFocal'] = 1024 / 2.0 objCommon['fltBaseline'] = 40 objCommon['intWidth'] = npyImage.shape[1] objCommon['intHeight'] = npyImage.shape[0] tenImage = torch.FloatTensor(numpy.ascontiguousarray( npyImage.transpose(2, 0, 1)[None, :, :, :].ast...
def replace_lemmas(text): doc_text = nlp(text.lower()) modified = "" for token in doc_text: if token.lemma_ in dictionary: modified += str(token.lemma_) + " " else: modified += str(token) + " " return modified def preprocess(text): index = -1 word_to_swap = "" root = "" doc_text...
The code parses mathematical expressions from text by processing tokens, replacing lemmas and numbers, tracking positions, and extracting dependencies/nouns using spaCy. It constructs a structured parsing result containing tokens, their dependencies, and associated nouns, handling numerical replacements for accurate re...
def get_math_parsing(text): modified_string = replace_lemmas(text) modified_string = preprocess(modified_string) modified = replace_numbers(modified_string) modified_string = modified["modified_string"] modified_positions = modified["modified_positions"] doc_text = nlp(modified_string) # displacy.re...
def get_available_letters(letters_guessed): ''' letters_guessed: list (of letters), which letters have been guessed so far returns: string (of letters), comprised of letters that represents which letters have not yet been guessed. ''' string_to_return = '' Alphabet = ['a','b','c','d','e','...
The main task of the code is to implement an interactive Hangman game where the user guesses letters of a secret word. The game provides feedback on guesses, tracks remaining attempts, and allows a single hint (using '*') to display matching words from a wordlist. It enforces rules like penalizing vowels with double gu...
def hangman_with_hints(secret_word): ''' secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should s...
def w_alpha(t,omega,tau,c): """ Weighting function for each point at a given omega and tau; (5-3) in Foster (1996) Parameters ---------- t : array-like times of observations omega : float angular frequency in radians per unit time. tau : float time shift in sam...
The function computes the Weighted Wavelet Transform (WWZ) and its amplitude (WWA) for observed data `y` at specified wavelet scale $\omega$ and shift $\tau$. It uses basis functions from `func_list`, evaluates their contributions, and applies a Gaussian envelope decay factor `c`. If `exclude=True`, it returns zero whe...
def WWZ(func_list,f1,y,t,omega,tau,c=0.0125,exclude=True): """ Calculate the Weighted Wavelet Transform of the data `y`, measured at times `t`, evaluated at a wavelet scale $\omega$ and shift $\tau$, for a decay factor of the Gaussian envelope `c`. Adapted from (5-11) in Foster (1996) Parameter...
def _get_custom_actions(self) -> dict[str, dict[str, Any]]: return {} def _get_actions(self) -> dict[str, dict[str, Any]]: actions = {} actions["undo_filters"] = { "obj": v.Icon(children=["mdi-filter-remove"]), "tooltip": "Undo all filters", } actions["mul...
This code initializes a data table interface with features like filtering, selection, pagination, and UI components using ipyvuetify and Polars. It sets up event handlers, manages column displays, and integrates interactive elements for data manipulation and visualization in a Jupyter environment.
def __init__( self, df: pl.LazyFrame = pl.LazyFrame(), *, title: str | None = None, item_key: str | None = None, columns_repr: dict[str, pl.LazyFrame] = {}, columns_to_hide: list[str] = [], show_actions: bool = True, **kwargs: Any, ): s...
def release_yes(valve): send(valveOnDict[valve]) send(valveOnDict[7]) send(valveOffDict[8]) messagebox.showinfo("Droplet Released", "Released droplet %s. Transferring to merging" % valve) def release_no(valve): send(valveOnDict[valve]) send(valveOffDict[7]) send(valveOnDict[8]) messagebo...
The function manages a sequential droplet release process based on the current release number (releaseNum). It disables the button, checks conditions (c1-c4) to determine if a droplet is released, updates the release count, modifies the button text, and resets the system after all four droplets are released. It also sh...
def release_samples(releaseNum, btn, btn_text,c1,c2,c3,c4): btn.config(state='disabled') if releaseNum.get() == 1: if(c1 == 1): release_yes(6) else: release_no(6) releaseNum.set(2) #incrementing num btn_text.set("Release Droplet 5") elif releaseNum.g...
def map_with_index(func, data, desc=None, progress_bar=True): if progress_bar: it = enumerate(tqdm(data, desc=desc, unit="nodes", miniters=1)) else: it = enumerate(data) return [[func(i, j, item) for j, item in enumerate(row)] for i, row in it] def merge_equal_height_nodes(self, node_grid):...
The main task of the code is to construct a graph from a height map by creating nodes, setting their borders, connecting adjacent nodes, merging nodes with equal heights, and organizing them into a sorted linked list for efficient traversal or processing.
def __init__(self, height_map: List[List[float]]): print("Creating graph") self.node_grid = map_with_index(self.to_node, height_map, "Creating nodes") map_with_index(self.set_border, self.node_grid, "Setting border") map_with_index(self.connect_node, self.node_grid, "Connecting nodes") ...
def found_empty_cells(seed): """ Check all the cells in the given seed to make sure that none of the cells are empty. """ # first make a map of the seed seed_map = region_map(seed) # count the number of regions in the map num_regions = np.amax(seed_map) # examine each region for i in range(num_regio...
The function `uniform_asexual` generates a new seed via bit-flipping mutation of a parent seed, replacing the least fit individual in the population. It ensures the new seed has no empty cells, updates its properties (ID, fitness, birth type), and replaces the worst-performing seed in the population. The new seed's his...
def uniform_asexual(candidate_seed, pop, n, next_unique_ID_number): """ Create a new seed by randomly mutating an existing seed. The new seed is generated by selecting a parent seed and flipping bits in the parent. The size of the seed does not change; it is uniform. """ # The most fit member of the tourn...
def found_empty_cells(seed): """ Check all the cells in the given seed to make sure that none of the cells are empty. """ # first make a map of the seed seed_map = region_map(seed) # count the number of regions in the map num_regions = np.amax(seed_map) # examine each region for i in range(num_regio...
The function generates a new seed by mutating an existing parent seed through bit-flipping, resizing (growing/shrinking), and checks validity. If invalid, it defaults to uniform reproduction. It replaces the least fit seed in the population with the new mutated seed, updates its history, stores it, and returns the upda...
def variable_asexual(candidate_seed, pop, n, max_seed_area, next_unique_ID_number): """ Create a new seed by randomly mutating, growing, and shrinking an existing seed. The new seed is generated by selecting a parent seed and randomly flipping bits, removing rows and columns, or adding ...
def calc_fitness(self, overlap_penalty=50, time_between_classes=15, time_buffer = 10): """Short summary. Args: time_buffer (type): Description of parameter `time_buffer`. Defaults to 10. overlap_penalty (type): Descr...
The main task of the code is to iteratively optimize a population of schedules using genetic algorithms over multiple epochs. It crossbreeds top-performing schedules, applies mutations, and selects survivors to form new generations, aiming to improve fitness metrics (e.g., minimizing penalties for overlaps or time gaps...
def evolve(self,n_epochs = 5, fix_pop_size=5, cross_breed_top_n = 3, n_mates = 1, n_room_swap = 3, mutation_bounds = 10, time_buffer = 15, overlap_penalty = 5, time_between_classes = 10, stop_threshold=.005,stop_calls_threshold=10,verbose=False): """Ma...
def _invokeRequestVoteRPV(self): print("Invoking Election by Node {0}".format(self.id)) # vote for itself # loop the nodes and call the RequestVoteRPC vote = Vote() self.mutexForAppendEntry.acquire() self.state = State.CANDIDATE self.currentTerm = self.currentTer...
This code implements a timeout mechanism for a distributed node in a consensus algorithm. It handles follower state by checking for heartbeats, initiating leader elections if none are received, and managing timeout-based re-elections. In leader state, it periodically sends heartbeats to other nodes. The code uses rando...
def timeout(self): while True: randomTimeout = random.randint(4, 8) if self.state == State.FOLLOWER: print("Chosen timeout for node {0} is {1}".format(self.id, randomTimeout)) logging.debug("Chosen timeout for node {0} is {1}".format(self.id, randomTimeout...
def tmdb_title_search(keyword): """Finds an actor in the TMDB database.""" response = requests.get( "https://api.themoviedb.org/3/search/movie?api_key=" + api_key + f"&language=en-US&query={keyword}&page=1&include_adult=false" ) mov = response.json() return package_tmdb_data(...
The function `tmdb_discover` fetches movie data from The Movie Database (TMDb) API using the Discover endpoint, allowing filtering by actor, genre, release year, or title. It constructs a request URL with parameters like `with_people` (actor ID), `with_genres` (genre ID), and `primary_release_year`, then retrieves and ...
def tmdb_discover(actor=None, title=None, genre=None, year=None, page=1): if title: return tmdb_title_search(title) reqString = ( "https://api.themoviedb.org/3/discover/movie?api_key=" + api_key + f"&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&...
def acceleration(self, ego_vehicle: ControlledVehicle, front_vehicle: Vehicle = None, rear_vehicle: Vehicle = None) -> float: """ Compute an acceleration command with the Intelligent Driver Model. The acceleration is chosen so as to...
The main task of the code is to compute a vehicle's longitudinal acceleration for speed control, considering neighboring vehicles, lane changes, and physical constraints. It calculates acceleration using Krauss model, adjusts for target lane conditions, applies acceleration limits, and incorporates friction, rolling re...
def speed_control(self, target_speed: float) -> float: # Longitudinal: Krauss front_vehicle, rear_vehicle = self.road.neighbour_vehicles(self, self.lane_index) acc = self.acceleration(ego_vehicle=self, front_vehicle=front_vehicle, r...
def soloMidgameScore(brd, tkn): score = 0 for i in range(64): if brd[i]==tkn: score += 0.075*gameEval[i]+(-5+2*(brd.count('.')<=36)+5*(brd.count('.')<=20))*0.17 #if not 'xo'[tkn=='x'] in {brd[0], brd[7], brd[56], brd[63]}: #idea: make this dependent on which corners have been taken (ex. 0 and 7 ...
The main task of the code is to determine the optimal move for a player in a game (likely Tic-Tac-Toe or similar) by combining heuristic evaluations, midgame analysis with alpha-beta pruning, and endgame strategies. It uses iterative deepening to explore deeper search levels while respecting time constraints, updates t...
def best_strategy(self, board, player, best_move, still_running, time_limit): t = process_time() score = soloMidgameScore(board, player)-soloMidgameScore(board, 'xo'[player=='x']) mM,oM = len(findMvs(board, player)), len(findMvs(board, 'xo'[player=='x'])) print(f'Current evaluation: {round(score...
def aStar(start, goal): if start == goal: return [start] openSet = [(calcDist(start,goal), 0, start, None)] #estimate, cumulative distance, station, parent closedSet = {} timeSinceUpdate = time.time() updateInterval = (calcDist(start, goal)/10000)**2 #updates canvas based on how far away goal is ...
The code executes the A* algorithm to find a path between two stations (`start` and `goal`), then visualizes the result on a canvas. It updates a GUI label to display the path length and details, clears previous UI elements, and draws the path using the `closedSet` from the A* output. The main task involves pathfinding...
def doAStar(): start = startG.get() goal = goalG.get() canvas.create_rectangle(890, 460, 1210, 580, outline='white', fill='white') label1 = Label(root) label1.config(text=f'\nFinding a path from \n {start} to {goal}\n') label1.config(font=('helvetica', 15)) label1.config(bg='white') canv...
def url_helper(self, path): return "http://localhost:8080" + path def auth_header(self): token = self.get_jwt_token() return {"Authorization": f"Bearer {token}"} def parse(self, obj): if isinstance(obj, dict): return sorted((k, self.parse(v)) for k, v in obj.items()) ...
The test function verifies that the API endpoint for retrieving store data by ID returns a successful HTTP 200 response with valid JSON content. It checks the response structure, including the store's name, status, ID, and menu items, against an expected format to ensure correctness and proper data formatting.
def test_eats_storeId(self): res = requests.get( self.url_helper("/eats/00001"), headers=self.auth_header(), ) json_data = res.json() assert res.status_code == 200 assert res.headers["content-type"] == "application/json" assert self.parse(json_data...
def url_helper(self, path): return "http://localhost:8080" + path def auth_header(self): token = self.get_jwt_token() return {"Authorization": f"Bearer {token}"} def parse(self, obj): if isinstance(obj, dict): return sorted((k, self.parse(v)) for k, v in obj.items()) ...
This test verifies that the GET request to retrieve order details by order ID returns a 200 status code, valid JSON content-type, and matches the expected data structure containing order_id, status, store_id, and item details.
def test_eats_order_orderId(self): res = requests.get( self.url_helper("/eats/order/000011"), headers=self.auth_header(), ) json_data = res.json() assert res.status_code == 200 assert res.headers["content-type"] == "application/json" assert self.pa...
def optimal_eta_hinge(train_data, train_labels, validation_data, validation_labels): eta_power = np.arange(-5,6) eta_score = np.zeros(11) for i in range(11): eta_score[i] = cross_validation_hinge(train_data, train_labels, validation_data, validation_labels,pow(10.0,eta_power[i]),1,1000) ...
The function `test_hinge` evaluates a Support Vector Machine (SVM) using the hinge loss. It determines optimal hyperparameters (learning rate `eta_0` and regularization parameter `C`) via cross-validation on training and validation data. It then trains the model using Stochastic Gradient Descent (SGD) with these parame...
def test_hinge(train_data, train_labels, validation_data, validation_labels, test_data, test_labels): eta_0 = optimal_eta_hinge(train_data,train_labels, validation_data, validation_labels) c = optimal_C_hinge(train_data,train_labels, validation_data, validation_labels, eta_0) w = SGD_hinge(train_data,train_...
def optimal_eta_log(train_data, train_labels, validation_data, validation_labels): eta_power = np.arange(-5,6) eta_score = np.zeros(11) for i in range(11): eta_score[i] = cross_validation_log(train_data, train_labels, validation_data, validation_labels,pow(10.0, eta_power[i]),1000) # pl...
The main task of the code is to evaluate the performance of a logistic regression model trained via stochastic gradient descent (SGD) on a given dataset. It determines the optimal learning rate using training and validation data, trains the model with 20,000 iterations, and outputs the test accuracy. The function also ...
def test_log(train_data, train_labels, validation_data, validation_labels, test_data, test_labels): eta_0 = optimal_eta_log(train_data,train_labels, validation_data, validation_labels) w = SGD_log(train_data,train_labels,eta_0,20000) # plt.imshow(np.reshape(w, (28, 28)), interpolation="nearest") # plt.s...
def helper(): mnist = fetch_openml('mnist_784', as_frame=False) data = mnist['data'] labels = mnist['target'] neg, pos = "0", "8" train_idx = numpy.random.RandomState(0).permutation(np.where((labels[:60000] == neg) | (labels[:60000] == pos))[0]) test_idx = numpy.random.RandomState(0).permutatio...
The code loads training, validation, and test datasets using a helper function, then evaluates two models—likely SVM with hinge loss and logistic regression with log loss—on these datasets. It executes testing functions for both models and prints the results.
def test(): train_data, train_labels, validation_data, validation_labels, test_data, test_labels = helper() test_hinge(train_data, train_labels, validation_data, validation_labels, test_data, test_labels) test_log(train_data, train_labels, validation_data, validation_labels, test_data, test_labels)...
def greyscale(): img = Image.open('head.jpg') px = img.load() sz = img.size for i, j in product(range(sz[0]), range(sz[1])): px[i, j] = get_grey(px[i, j]) img.save('greyscale_result.jpg') img.close() return sz def halftone(num): img = Image.open('greyscale_result.jpg') px = ...
The main task of the code is to render a halftone image through an iterative process. It initializes parameters, generates a grayscale image (via `greyscale()`), then iterates 15 times to refine the halftone image using the `start()` function. Each iteration updates the `sites` data structure and increments a counter (...
def main(): num = 0 avg = EPSILON + 1 # GRAYSCALE SECTION print('RENDERING GREYSCALE IMAGE ... ') sz = greyscale() # HALFTONE SECTION print('RENDERING HALFTONE IMAGE ... ') halftone(num) sites = get_sites() for i in range(15): sites = start(sites, sz, num) num +...
def _parse_args(self, args, n_user, n_item, adj_entity, adj_relation, user_item_adj): # [entity_num, neighbor_sample_size] self.adj_entity = adj_entity self.adj_relation = adj_relation self.n_iter = args.n_iter self.batch_size = args.batch_size self.n_neighbor = args.nei...
The code initializes a recommendation system model by parsing arguments, constructing input layers, building a graph-based neural network with user-item-entity-relation data, and setting up training components. It prepares for tasks like collaborative filtering or knowledge graph embedding, leveraging pre-trained weigh...
def __init__(self, args, n_user, n_item, n_entity, n_relation, adj_entity, adj_relation, user_item_adj, pretrain=None): self.pretrain = pretrain self._parse_args(args, n_user, n_item, adj_entity, adj_relation, user_item_adj) self._build_inputs() self._build_model(n_user, n_item, n_entity...
def _step(self, action: Optional[int], player: Spaceship) -> None: """Takes a single step for one player.""" # If action is None, do not move (Currently only used for human_player) if action is None: return assert isinstance(action, int) and action in range( # type: ignore ...
This function processes a game step for two players, applying the given action to player1, determining the opponent's move for player2, updating game state, calculating rewards based on winners, and returning the new observation, reward, termination status, and empty info. It supports bot and human player interactions ...
def step(self, action: Optional[int]) -> Tuple[torch.Tensor, float, bool, Dict]: """Action should be an integer 0-5 for all bot moves, None is made available for the human player as it is too difficult to control otherwise.""" self._step(action, self.player1) opponent_move = self.oppon...
def send(self, msg): self.messageHandler.write(msg) def receive(self): message = self.messageHandler.read() self.log(message) return message def handleError(self, message): self.currentState = State.Start self.previousState = State.Error self.log(f"--Error: {mess...
This code handles user login by checking credentials against a stored password file. It prompts for username/password, verifies them against entries in "pass.password", sets user/admin status if matched, and transitions to signup if no account exists. Errors are handled for invalid inputs or file issues.
def login(self): self.send("Do you have an account(y/n)") response = self.receive() if response == "y": # Get us the login information loginfile = open("pass.password", "r") self.send("Please enter your username") username = self.receive() ...
def write(self): self.send("Please enter the file you would like to write to\nfollowed by what you want to write:") file = self.receive() text = self.receive() try: file1 = open(f"{file}.txt", "a") file1.write(f"{text}\n") message = f"Written {text} t...
The main task of the code is to determine state transitions based on message prefixes. It converts messages to lowercase, checks if they start with specific keywords ("echo", "write", "read", "logs", "active", "add"), and updates the object's state accordingly. Admin-only commands require authentication. If valid, it r...
def stateCheck(self, message): message = message.lower() if message.startswith("echo") and self.currentState != State.Echo: self.previousState = self.currentState self.currentState = State.Echo return "Moving to Echo" elif message.startswith("write") and self...
def zero_to_one_based_index(x): return x + 1 if x < 0 else x - 1 def compute_normal(vertex1, vertex2, vertex3): # Vector 1 ax = vertex2[0] - vertex1[0] ay = vertex2[1] - vertex1[1] az = vertex2[2] - vertex1[2] # Vector 2 bx = vertex3[0] - vertex1[0] by = vertex3[1] - vertex1[1] bz =...
This function reads an OBJ 3D model file, parsing vertices, texture coordinates, normals, and faces. It combines vertex attributes into a unified list, generates triangle indices, and organizes meshes by material. It handles material switches, loads MTL files, and stores each mesh as a tuple of (material_id, vertex_dat...
def read_obj_file(filename): global mesh_list vertex_positions = [] texture_coordinates = [] normals = [] combined_vertices = [] vertex_to_index = {} triangle_index_list = [] current_texture_id = -1 with open(filename, 'r') as f: for line in f: if line[0] == '#'...
def create_qsub(name= "",nodes = "", cores = 16, queue = "q_residual", path =""): file_name_out = name +".out" file_name_sh = path + "/qsub_fhi.sh" THIS_FOLDER = os.path.dirname(os.path.abspath(__file__)) complete_path = os.path.join(THIS_FOLDER,path) print("Creating :" + file_name_sh) text = ["!/bin/bash \n"...
The main task of the code is to automate the setup and execution of a computational job by generating input files, configuring resource allocation, and submitting a job script. It creates a shell script for job scheduling, prepares control and geometry files, reads molecular geometry data, and initiates the calculation...
def create_unique_run(original_filename = "", name= "",nodes = "", cores = 16, queue = "q_residual", path ="", vdw = False): filename_sh = create_qsub(name= name,nodes = nodes, cores = cores, queue = queue, path =path) create_control_in(path=path, vdw=vdw ) matrix = read_geometry_nextstep(filename=original_filena...
def generate_atom (atoms=[],r_min = 2.0,r_max = 7,num_decimals =4,dist_min =2, dist_max =7): condition =0 #print("r_max ", r_max, " dist_max", dist_max) if atoms == [] : at1 =[0,0,0] else : temporal_atom = None num_atoms = len(atoms) while condition ==0: rand...
The code generates a cluster of specified atoms (default: Au) with customizable parameters (size, radii, distances) and creates associated computational files (geometry, XYZ coordinates, shell scripts, control files) for simulation tasks. It returns "Done" upon completion.
def create_cluster(size =55, atom="Au",path ="", R_min = 2.0,R_max = 7,Num_decimals =4,Dist_min =2, Dist_max =7,cores =16, vdw = False): cluster =[] Size = size Atom = atom Path_cluster= path print("size : ", Size , "atom : ",Atom,"r_max",R_max ,"dist = ", Dist_max ) for i in range(int(size)): at=generate_atom...
def recenter_cluster(filename = ""): matriz = read_geometry_nextstep(filename=filename) center_monoatomic = [round(sum([float(x[i]) for x in matriz])/(len(matriz)),4) for i in range(3)] recentered_matrix_num = [[round(float(x[i]) - center_monoatomic[i],4)for i in range(3)] for x in matriz] recentered_matrix = [[st...
This code merges two cluster matrices by recentering, rotating, ordering, and cutting/splicing them based on a percentage, then saving the resulting geometry to a file.
def Mating( file1 , file2, percentage_cut=50, filename_mated="", path=""): matrix= recenter_cluster(file1) matrix2= recenter_cluster(file2) rotated_matrix = rotate_matrix_over_xyz(matrix) rotated_matrix_2 = rotate_matrix_over_xyz(matrix2) ordered_matrix = order_matrix(rotated_matrix) ordered_matrix_2 = order_matr...
def Cluster_size(N=55, R_ws=1.44): ##Revisar bibliografia de esto dist_max = round(2 * R_ws* math.pow(int(N) , 1/3), 4) print("For ", N , "atoms distance is : ", dist_max) return dist_max def create_folder( name ="Au_6", path ="", add =0): count = add original_name = name original_path = path directory_name =...
The function generates atomic cluster structures of a specified size and element, using given radial and distance parameters. It creates a directory to store the generated clusters, utilizing multiple cores for computation, and returns the directory path. The process involves calculating cluster size, creating folders,...
def create_files(Size = 55, Atom = "Au", Path ="", r_min = 2.0,r_max = 7,num_decimals =4,dist_min =2, dist_max =7,cores =16, vdw = False): atom = Atom size = Size path = Path dist_max = Cluster_size(Size, R_ws= 1.44) #directory_name =create_directory(size, atom, path) directory_name = create_folder(name=Ato...
def Pool_size(N= 55): ##Revisar bibliografia de esto pool = int(math.pow(int(N),2/3)) return pool def Cluster_size(N=55, R_ws=1.44): ##Revisar bibliografia de esto dist_max = round(2 * R_ws* math.pow(int(N) , 1/3), 4) print("For ", N , "atoms distance is : ", dist_max) return dist_max def create_files(Size = 5...
The main task of the code is to generate a pool of directories containing atomic cluster configurations, then filter and return only those directories that contain a specific shell script (`shforrunning.sh`). It uses parameters like cluster size, atom type, and distance thresholds to create directories, checks each for...
def create_pool(N= 55, atom = "Au", path = "", R_min = 2.0, Num_decimals =4, Dist_min= 2 ,generation =0, cores = 16, vdw = False): pool_size = Pool_size(N) dist = Cluster_size(N) directories =[] for x in range(pool_size): directory= create_files(Size = N, Atom = atom, Path = path, r_min = R_min ,r_max = dist ,num...
def select_mutate_or_mate(percentage_of_mating): float_mating = percentage_of_mating /100 random_number = random.random() response ="" if random_number <= float_mating: response ="Mate" else: response ="Mutate" return response def Mate(data_last_step= "", path = "", name="", core...
This function decides whether to perform mutation or mating based on a given percentage. If mating is selected (80% chance), it calls the 'Mate' function; otherwise, it invokes 'Mutate'. Both operations use shared parameters like input data, path, computational cores, and atomic properties. The choice between mutation/...
def Mutate_or_mate(data_last_step= "", path = "", name="", cores =16, file_energies="", Atom ="Au", Size=52,percentage_of_mating = 80, vdw = False): mutate_or_mate= select_mutate_or_mate(percentage_of_mating=percentage_of_mating) if mutate_or_mate =="Mate": Mate(data_last_step= data_last_step, path = path, name="",...
def create_folder( name ="Au_6", path ="", add =0): count = add original_name = name original_path = path directory_name =original_name directory_path = original_path +"/"+ directory_name answer = "not changing answer" if count != 0: directory_path = original_path+"/" + directory_name + "_" + str(count) ...
The function `create_all_files` generates directories for atomic structures, saves their paths in a text file, creates associated Python scripts, and prepares a job submission file for batch processing. It organizes file structures, handles computational parameters, and facilitates parallel execution on a cluster. The ...
def create_all_files(Size =55, Atom ="Au", Path ="", Cores ="16", Node= "g1", queue = "q_residual", vdw = False): path_master = create_folder(name=Atom+str(Size), path= Path) print("Path :", path_master) dirs = create_pool(N= Size, atom = Atom, path =path_master, R_min = 2.0, Num_decimals =4, Dist_min= 2 ,generation...
def check_convergence_pool_first_step( file_dirs ="", Atom = "Au", Size = 52, path ="",cores= 16 ): name = Atom + str(Size) directories = read_files(file_dirs) Energies =[] Converged = [] Normalized_energies =[] for x in directories: #print("currently in ", x) converged = False energy =0 converged , e...
The function `complete_cicle_mutation` processes atomic data (e.g., Au atoms in a cluster of size 52) by first checking convergence using `check_convergence_pool_first_step`, then performing mutation operations via `Mutate` and `Cicle_mutation` to iteratively refine structural or energetic properties. It uses parallel ...
def complete_cicle_mutation(file_dirs ="", Atom = "Au", Size = 52, path ="",cores= 16 , vdw = False): file_energies, data_last_step = check_convergence_pool_first_step( file_dirs =file_dirs, Atom = Atom, Size = Size, path =path,cores=cores ) Mutate(data_last_step= data_last_step, path = path, name="{}+{}".format(Atom...
def _resolve_hostname(self, hostname): """Checks whether the hostname is resolvable or not.""" try: socket.gethostbyname(hostname) except socket.error as e: logger.warning("Encountered error while resolving hostname %s: %s", hostname, e) return 0 retu...
The code renews a TLS certificate for a configured service hostname by validating the hostname, ensuring infrastructure setup, checking ingress routing, generating the certificate, and handling errors by cleaning up ingress configurations if renewal fails.
def _on_renew_certificate_action(self, event): """Renew the certificate for the currently configured service-hostname.""" hostname = self.model.config["service-hostname"] if not hostname: raise CertbotK8sError("service-hostname is not set.") if not self._resolve_hostname(ho...
def _secret_exists(self, secret_name): """Checks whether the given secret exists in Kubernetes.""" self.k8s_auth() api = _core_v1_api() secrets = api.list_namespaced_secret(namespace=self._namespace) return secret_name in [s.metadata.name for s in secrets.items] def _resolve_hos...
The function ensures a TLS certificate is generated and stored as a secret for a given hostname if it doesn't already exist. It checks if the hostname is valid, resolves it, verifies Ingress Route accessibility, and generates the certificate if all checks pass. If issues arise, it updates the unit status to blocked or ...
def _ensure_certificate(self, event, hostname): if not hostname: # Nothing to do. return # We're creating secrets based on the requested service-hostname. If it already exists, # we don't have to anything. secret_name = "%s-tls" % _SECRET_NAME_REGEX.sub("-", host...
def _refresh_charm_status(self, container=None): """Updates the Charm status. If the Pebble layer is not yet ready, the Charm status will be set to Waiting. If the Charm was not configured with an email to be used by certbot, the Charm status will be set to Blocked. If the user ...
The main task of the code is to handle configuration changes in a Juju charm, specifically reacting to updates in the "service-hostname" setting. It defers events to allow ingress route updates, sets up Ingress Routes for HTTP challenges, ensures SSL certificates are configured, and handles permission errors by notifyi...
def _on_config_changed(self, event): """Refreshes the service config.""" is_active = self._refresh_charm_status() if not is_active: return # If the service-hostname config option changed, we need to defer the event, so the # ingress relation data has a chance to get ...
def EM(self, X, mu1, sigma1, mu2, sigma2, T, alpha=ALPHA, changeAlpha=False): T -= 1 if T < 0: # T = num of iterations left, base case return mu1, sigma1, mu2, sigma2, alpha # E-step phi1 = stats.norm.pdf(X, mu1, sigma1) phi2 = stats.norm.pdf(X, mu2, sigma2) ...
The code fits a Gaussian Mixture Model (GMM) and Hidden Markov Model (HMM) to input scores. It computes statistical parameters (means, sigmas) via EM for two Gaussian components, applies Baum-Welch to refine HMM transition matrices and initial states, and saves model parameters (mu, sigma, alpha, trans_mat, pi) to a fi...
def fit(self, scores, file_name, T_GMM=10, T_HMM=5): dataMean = np.mean(scores) dataSigma = np.std(scores) threshold = np.percentile(scores, 100 * (1 - ALPHA)) scores2 = scores[np.argwhere(scores > threshold)].transpose()[0] data2Mean = np.mean(scores2) data2Sigma = np.st...
def download_s3_object(client, bucket, file_name): current_date = datetime.today().strftime('%Y-%m-%d') object_key = f"poi-api/{current_date}/{file_name}" with open(f"/tmp/{file_name}", "wb") as file: client.download_fileobj(Bucket=bucket, Key=object_key, Fileobj=file) return "Successfully dow...
The main task of the code is to process a list of geographical records by analyzing nearby points of interest (POIs) within specified distances (1, 3, 5 km). It aggregates data for predefined categories (e.g., amenities, services) and generates statistics (counts, ratings, hours). The results are compiled into a DataFr...
def main(record_ls): # Initialise output output = [] # Initialise S3 client client = boto3.client("s3") # Load POI DF download_s3_object(client, "stonehenge-fyp", "full_poi_results.csv") poi_df = pd.read_csv("/tmp/full_poi_results.csv") # Function configurations target_distance = ...
def load_data(input_path): # Loads promoter and negative sequences from the input_path. # DO NOT modify this function. promoter_sequences, negative_sequences = [], [] with open(input_path) as f: for line in f: seq, clazz = line.strip().split() if clazz == "1": ...
The code evaluates Markov models of varying order (k=1 to 5) for classifying promoter vs. negative sequences. It trains models on training data, computes accuracy on training and validation sets, and returns accuracy lists. The goal is to determine the optimal Markov order for sequence classification by comparing perfo...
def main(): train_promoter_sequences, train_negative_sequences = load_data(TRAIN_DATA) val_promoter_sequences, val_negative_sequences = load_data(VAL_DATA) train, val = [], [] for k in range(1, 6): states, promoter_transition_matrix = train_markov_model(train_promoter_sequences, k) _, n...
def get_data(): with open("problem_5_data.txt") as f: rolls = f.readline().strip() return [int(r) for r in rolls] def run_baum_welch(rolls, thres): # return: # - 2 x 2 transition probability matrix # - 6-dimensional array containing emission probabilities for dice 1 # - 6-dimensiona...
The main task of the code is to apply the Baum-Welch algorithm to train Hidden Markov Models (HMMs) on different subsets of roll data and output the resulting transition and emission probabilities. Part A processes the full dataset with a specific initial log-likelihood value, while Part B uses the first 1000 rolls wit...
def main(): rolls = get_data() # Part A print("Part A") transition_matrix_A, emission_1_A, emission_2_A = run_baum_welch(rolls, -178400) print_parameters(transition_matrix_A, emission_1_A, emission_2_A) print("") # Part B print("Part B") transition_matrix_B, emission_1_B, emission_...
def pressKey(self, key): self.pressed=key self.pressedStart=globalClock.getFrameTime() self.game.keyPressed(key) def createArrows(self): self._2DleftArrow="../textures/left_arrow.png" self._2DupArrow="../textures/up_arrow.png" self._2DrightArrow=("../textures/right_arrow....
The code initializes and starts a dance game by processing music data, setting up arrow key controls, loading sound effects, and scheduling tasks for game mechanics like arrow movement, miss detection, score tracking, and camera effects. It configures event handlers, initializes game state variables, and begins the dan...
def createDance(self,path): self.game = musicGameCore.DanceGame(self, path,self.difficultyLevel) self.FULLSCORE, self.arrows = self.game.processMusic() self.accept('arrow_down', lambda: self.pressKey('h')) self.accept('arrow_right',lambda: self.pressKey('l')) self.createArrows() ...
def createDefaultMusicList(): # check if the file is created if os.path.isfile('musicGameData.txt'): print('here') file=open('musicGameData.txt','r') else: file=open('musicGameData.txt','w') file.write('Rather Be\n') file.write('../musi...
This code initializes a Panda3D application by setting up the engine, loading music files, configuring GUI panels for options, and playing background music. It creates a music list, sets difficulty to 'easy', and displays the options panel. The BGM is loaded and played from a specified audio file.
def __init__(self): # Basic initialization of panda3D engine ShowBase.__init__(self) self.songButtonList=[] self.createDefaultMusicList() self.loadMusicScores() self.difficultyLevel='easy' self.configureGUIPanels() self.displayPanel('options') ...
def read_stages(csvpath): csvpath = Path(csvpath) assert ( csvpath.is_file() and csvpath.suffix == ".csv" ), "File does not exist or is not a csv file" skiprow = get_rows(csvpath) df = pd.read_csv(csvpath, skiprows=skiprow) for s in __STAGES: df[s] = df["Stage"] == s return d...
This function converts an EDF file into individual HDF5 files for each mouse, applying normalization and optionally computing FFT/STFT for EEG signals. It validates inputs, extracts channel data, splits labels, and saves processed signals with metadata, while handling light-dark cycles and filtering EMG/LOC channels ba...
def convert_edf_file( edfpath: Path, numsofsamples: int, csvlist: list, windowsize: int = 4, normalization=True, saveEMG=False, saveLOC=False, lighton=9, calculate_fft: bool = False, calculate_stft: bool = False, ): """ Take the edffile and split each individual mice into...
def border_if_winner(team, winner, final=True): if final == True: if team == winner: return {'border':"2px MediumSeaGreen solid", 'borderRadius': '20%', } elif winner == 'TIE': return {'border':"2px GoldenRod solid", 'borderRadiu...
The function `display_game` generates a dynamic layout for displaying sports game details, including team information, date, time, venue, and user predictions. It constructs a responsive Dash component structure with team visuals, prediction tooltips, and formatted game data, returning a styled `dbc.Row` for rendering ...
def display_game(row, idx, rankings, team_summ, preds=True): game_date = datetime.strptime(row['game_date'], "%Y-%m-%d").strftime("%m/%d/%Y") # game_time = pd.to_datetime(row['game_time']).tz_convert('US/Eastern').strftime("%I:%M %p %Z") game_time = pd.to_datetime(row['game_time']).tz_convert('...
def end_row(): return [dbc.Row( [ html.Div('', style={'width':'10%'}), html.Div('', style={'textAlign':'center', 'height':'1vw', 'justify':'center', 'borderBottom':".5px outset rgba(255,255,255,.2)", 'width':'80%', 'borderBottomWidth':'light'}), html.Div(...
The main task of the code is to generate a UI layout displaying upcoming week's game data, team rankings, and user predictions. It initializes a layout, retrieves team rankings, checks for user-added results, iterates through game scores to build dynamic game displays, and returns a structured layout containing game in...
def display_upcoming_week(user, scores, season=season, week=week, user_df=user_df, df_teams=df_teams, USER_LIST=USER_LIST): # Start Layout score_layout = end_row() ## Get Rankings rankings, team_summ = team_rankings(df_teams, week=week, season=season) ## Check if User ...
def end_row(): return [dbc.Row( [ html.Div('', style={'width':'10%'}), html.Div('', style={'textAlign':'center', 'height':'1vw', 'justify':'center', 'borderBottom':".5px outset rgba(255,255,255,.2)", 'width':'80%', 'borderBottomWidth':'light'}), html.Div(...
The main task of the code is to generate a layout displaying historical game scores and related information for a specific week and season. It retrieves team rankings and summaries, iterates through game scores, and constructs a structured layout by combining game displays and additional game details, returning the fin...
def display_historical_week(scores, season=season, week=week, user_df=user_df, df_teams=df_teams, USER_LIST=USER_LIST): # Start Layout score_layout = end_row() ## Get Rankings rankings, team_summ = team_rankings(df_teams, week=week, season=season) for idx, row...
def iterateChildrenInvisble(obj): removeInvisbleObjects(obj) for child in obj.GetChildren(): iterateChildrenInvisble(child) def cleanMaterials(): mats = doc.GetMaterials() materials = [] for x in mats: string = x.GetName() if string.find(".") != -1: string = x.Ge...
The main task of the code is to process 3D objects by removing invisible elements, standardizing material names by eliminating invalid characters, and adding UVW tags for texture and lighting while removing redundant texture tags. It iterates through objects, cleans data, and finalizes with a "Done" confirmation.
def main(): #Remove Invisble Objects for obj in doc.GetObjects(): iterateChildrenInvisble(obj) #Create a unique name for the materials and remove unorthodox characters cleanMaterials() #Add UVW tags (one for texture and other on for light)and Removed usless Texture t...
def create_linear_hyperparameter_sets(): hyperparameter_sets = list() hyperparameter_sets.append((None, None)) hyperparameter_sets.append(("l1", None)) hyperparameter_sets.append(("l2", None)) hyperparameter_sets.append(("elasticnet", 0.25)) hyperparameter_sets.append(("elasticnet", 0.5)) h...
The function `create_model` trains a specified machine learning model (linear, forest, neural, SVM, tree, or boost) using cross-validation. It generates hyperparameter sets, trains the model with `learn_model`, evaluates performance via MSE, and returns the trained model, optimal hyperparameters, and cross-validated pr...
def create_model(args, seed, X, y, checkpoint_file=""): np.random.seed(seed) if seed else None # train a model if args.model == "linear": hyperparameter_sets = create_linear_hyperparameter_sets() model, hyperparameters, kfold_y_hat = learn_model(X, y, args.k, hyperparameter_sets, build_line...
def _find_other_point(self, point: Point): point.mark = True self._paint() msgb.showinfo("Information", "Please select other point to calculate equation.") for but in self._buttons.winfo_children(): but.config(state="disable") but.unbind("<ButtonPress-1>") ...
This code selects the closest geometric object (point, line, or polygon) to a mouse event, then displays a context menu with actions specific to the selected object, such as calculating area, finding relations, or removing the object.
def _selector(self, event): selected = None for point in self.data["points"]: if point.x - 3 <= event.x and point.x + 3 >= event.x and point.y - 3 <= event.y and point.y + 3 >= event.y: selected = point break if not selected: for line in s...
def divisor(x,y): nx,dx=x[0],x[1] ny,dy=y[0],y[1] new_n,new_d=nx*dy,dx*ny return simplifier([new_n,new_d]) def do_for_all(f,s): '''calculate f(x) for all x in s, return new set''' return [f(x) for x in s] def multier(x,y): nx,dx=x[0],x[1] ny,dy=y[0],y[1] new_n,new_d=nx*ny,dx*dy r...
This function adjusts coefficients of two lists (c1, c2) by scaling c2's elements using the ratio of their first elements, then substitutes these scaled values into c1's elements. It generalizes to equations with any number of variables by focusing on the first variable's coefficient ratio, returning modified coefficie...
def cut_one(c1,c2): ''' return 2 new lists of coefficient with one variable cut''' '''This is a generally applicable function no matter how many variable an equation has''' fractor=divisor(c1[0],c2[0]) q=do_for_all(lambda x: multier(fractor,x),c2) return [substier(c1[i],q[i]) for i in range(0,len(c1...
def cut_one(c1,c2): ''' return 2 new lists of coefficient with one variable cut''' '''This is a generally applicable function no matter how many variable an equation has''' fractor=divisor(c1[0],c2[0]) q=do_for_all(lambda x: multier(fractor,x),c2) return [substier(c1[i],q[i]) for i in range(0,len(c1...
The code solves a system of equations by calculating two results (ans1, ans2) using algebraic operations on input coefficient lists c1 and c2. It first processes the lists with cut_one, then computes ans2 via division of a negated value by e. Ans1 is derived by combining coefficients, applying negation, multiplication,...
def calculate(c1,c2): '''c1,c2 are two lists of coefficient''' new_list=cut_one(c1,c2) c=negativer(new_list[2]) e=new_list[1] ans2=divisor(c,e) ans1=divisor(negativer(adder(c1[2],multier(c1[1],ans2))),c1[0]) return [ans1,ans2]
def get_value(c,v): '''get value of one variable when the value of other variables all known''' '''c--->list of coefficients; v--->list of variable values''' '''Be aware that the variable corresponding to coefficient of c[-1] is always 1''' others=c[1:] compose=[multier(others[i],v[i]) for i in rang...
The code recursively solves a system of linear equations represented by coefficient lists in `s`. It processes each equation step-by-step, reducing the problem size with `slash_one`, and combines results using `get_value` to compute solutions. The function returns evaluated solution values and associated variables, han...
def final_calculator(s): ''' s is a set with this formality: s=[c1,c2,c3......] where c means a list of coefficients in each func if equation has n variables, then len(c) should be n+1 ''' if len(s)==1: return [get_value(s[0],[[1,1]]),[1,1]] else: new_s=slash_one(s) v...
def generate_risset_beat(sound_array, repetitions=4, octaves=3): samples = sound_array.copy() # resample (remap time) time_mesh, time_speed, loop_counts = compute_time_mesh(len(samples), repetitions, octaves) samples = samples[time_mesh] M = len(samples)//octaves samples = apply_fade_window(sa...
The main task of the code is to generate a Risset beat from an audio file by processing its waveform with specified repetitions and octaves, normalizing the data, tiling the output, saving the result as a new WAV file, and playing it. The process involves reading audio data, applying a Risset beat algorithm, adjusting ...
def main(): src = "assets/example.wav" repetitions = 2 octaves = 4 fs, data_int16 = wavfile.read(src) data = data_int16.copy() / (2 ** 15 - 1) # half time # data = np.repeat(data, 2, axis=0) samples = generate_risset_beat(data, repetitions, octaves) # repeat x4 and save sampl...
def herz2octave(hz): C3 = 440 * 2 ** (-9 / 12) offset = 3 - np.log2(C3) res = np.log2(hz) + offset res[res < -1] = -1 res[np.isinf(res)] = -1 return res def linreg_ransac_1d(X1d, y, RESIDUAL_THRESHOLD=None, show_plot=True, plot_xlabel="", plot_ylabel=""): assert len(X1d.shape) == 1, "Support...
The code analyzes a chirp sound by computing its Short-Time Fourier Transform (STFT) to extract frequency-time characteristics. It identifies dominant frequency components, converts them to octaves, and applies RANSAC regression to fit a linear model (removing outliers). Using this model, it maps time-frequency relatio...
def fit_sweep(x, fs): # COMPUTE SHORT-TERM FOURIER TRANSFORM fr_zxx, ts_zxx, Zxx = scipy.signal.stft(x, fs=fs, window='hann', nperseg=2048, boundary='zeros', padded=True, axis=-1) Sxx = abs(Zxx)**2 # PLOT SPECTROGRAM TO VISUALLY APRECIATE THE CHIRP SOUND # plt_spectrogram(fr[::10], ts[::10], Zxx[::...
def GridPositionsIn2d(xBox,yBox,NParticles,debug=False): """ Returns two arrays of x- and y-positions for NParticles in the interval xBox = [xmin,xmax) or xBox * [0,1), if xBox is a float or integer yBox = [xmin,xmax) or xBox * [0,1), if xBox is a float or integer """ n = np.ceil(np.sqr...
The function generates an NVT Molecular Dynamics (MD) trajectory for a Lennard-Jones (LJ) system using the Velocity Verlet algorithm. It simulates particles with specified masses in a 2D box at a given temperature, initializing configurations either from a provided state or a grid. Velocities are periodically reset to ...
def Generate_LJ_NVT_MolecularDynamics_Trajectory(d,m,LBox,kT,run_time, starting_configuration=[], time_step = 0.01, number_of_time_steps_between_stored_configurations=100, ...
def set_background(self, html: str): """sets the background of the html document randomly. there is a chance that the background is just a gradient or an image from the 'background' folder. this functionality works only if there is the '/*#bodyStyle*/' placeholder inside a style tag of y...
The code generates images from an HTML template by replacing specified tags with random elements (table, text, headline), then returns four image types in a JSON object: regular (full HTML render), table (black background with white table), table_lines (black with white table lines), and cell (black with white table ce...
def load_template(self): """generate image based on your template and parameters. returns the images in a json object: {'regular': regular_img, 'table': table_img, 'table_lines': table_lines_img, 'cell': cell_img} regular = the regular image of the html doc table = everything is ...
def resize_image(img, target_width=3840): im = cv2.resize(img, dsize=(target_width, int(img.shape[0] * target_width / img.shape[1])), interpolation=cv2.INTER_NEAREST) return im def generate_patches_from_image(im_ori, patch_width=608, offsets=np.array(((-2, 0),...
This code processes an input image using a detection model to identify objects, specifically focusing on the PERSON_LABEL. It resizes the image, generates patches for analysis, runs object detection on these patches, and visualizes or saves the detected results. The function either displays the processed image with det...
def run_test_image(net, meta, show=0, PERSON_LABEL=0): im_ori = cv2.imread("images/test.jpg") im_ori = resize_image(im_ori) patch_boxes = None if patch_boxes is None: patch_boxes = generate_patches_from_image( im_ori) det_results = detect_patches(im_ori, patch_boxes, net, meta,l...
def resize_image(img, target_width=3840): im = cv2.resize(img, dsize=(target_width, int(img.shape[0] * target_width / img.shape[1])), interpolation=cv2.INTER_NEAREST) return im def generate_patches_from_image(im_ori, patch_width=608, offsets=np.array(((-2, 0),...
The main task of the code is to detect and visualize "person" objects in video frames using a neural network. It processes each frame by generating patches, performing object detection, and drawing results. Detected frames are saved to an output directory, with periodic progress updates.
def run_video_detection(args, datadir, outputdir, video_name, net, meta): PERSON_LABEL = None for i in range(meta.classes): if meta.names[i] == b"person": PERSON_LABEL = i patch_boxes = None print("Processing video: {}".format(video_name)) out_frames_path = os.path.join(outputdir...
def runCircuit(self, qbit_init_string): '''create one instance of a noisy ciruit and then calculate its density matrix First, initialize the circuit in one particular basis state given by binary. Then, call consTtructCircuitRealisation to add (noisy) gates to the circuit. Finally, get th...
This function computes the average density matrices (DMs) from multiple quantum circuit samples, calculates their fidelity compared to ideal states as a reward, and returns the averaged DMs (observation), average reward, and a non-terminal status. It iterates over input states, samples DMs, averages them, and evaluates...
def getSampledBigRho(self): '''The main observation function: when run, gets the density matrices for each of several sample realisations. It then compares these to the ideal, and determines the reward. Reward = Fidelity of sample-averaged DMs compared to ideal ...
def parse_scratchpad(): global scratchpad_file scratchpad = {"windows": []} if Path(scratchpad_file).exists(): scratchpad = json.load(open(scratchpad_file, "r")) scratchlist = [] for win_id in scratchpad["windows"]: # validation, if not found, window does not exist anymor...
This function manages a scratchpad's window visibility by cycling through windows when none are visible, hiding the current visible window, reordering it in the list, and updating the scratchpad state. It ensures only one window is visible at a time, appending the hidden window to the list and saving changes.
def show_scratchpad(): scratchpad = parse_scratchpad() scratchlist = scratchpad["windows"] if len(scratchlist): visible_id = scratchpad.get("visible", None) if visible_id is None: next_win_id = unshift(scratchlist) for win in scratchlist: hide_window(w...
def get_focused_window_id(throw=True): win_id = get_id_from_filtered(filter(focused=True)) if win_id is None or not isinstance(win_id, (int, str)): raise RuntimeError(f"Unable to fetch focused window ID: {win_id}") return win_id def toggle_window_to_scratchpad(win_id, floating): scratchpad = par...
The code toggles the focused window to a scratchpad and hides it if successful. It retrieves the focused window's ID, attempts to move it to the scratchpad with the 'floating' parameter, and hides the window if the toggle succeeds.
def toggle_to_scratchpad(floating): win_id = get_focused_window_id() if toggle_window_to_scratchpad(win_id, floating): hide_window(win_id)
def __get_next_ssnum(): global UNIQUE_SSNUM returnVal = UNIQUE_SSNUM UNIQUE_SSNUM = UNIQUE_SSNUM + 1 return returnVal def __get_next_unique_name(): global UNIQUE_NAME returnVal = UNIQUE_NAME UNIQUE_NAME = increment_str(UNIQUE_NAME) return UNIQUE_NAME def __get_random_manager(): retur...
The main task of the code is to generate 70,000 employee records and 30,000 combined employee-student records by writing structured data fields (SSN, name, manager, department, integers) to global file objects `EMPLOYEE` and `STUDENT`, using helper functions to populate random or sequential values.
def __generate_Employee(): global EMPLOYEE global STUDENT i = 0 while i < 70000: EMPLOYEE.write(str(__get_next_ssnum())) EMPLOYEE.write("\t") EMPLOYEE.write(__get_next_unique_name()) EMPLOYEE.write("\t") EMPLOYEE.write(__get_random_manager()) EMPLOYEE.writ...
def __get_next_ssnum(): global UNIQUE_SSNUM returnVal = UNIQUE_SSNUM UNIQUE_SSNUM = UNIQUE_SSNUM + 1 return returnVal def __get_next_unique_name(): global UNIQUE_NAME returnVal = UNIQUE_NAME UNIQUE_NAME = increment_str(UNIQUE_NAME) return UNIQUE_NAME def __get_random_course(): return...
The code generates 70,000 student records, each containing a student number, unique name, random course, and random grade, writing them to a file with tab-separated values and line breaks. It uses helper functions to generate data fields and closes the file after completion.
def __generate_Student(): global STUDENT i = 0 while i < 70000: STUDENT.write(str(__get_next_ssnum())) STUDENT.write("\t") STUDENT.write(__get_next_unique_name()) STUDENT.write("\t") STUDENT.write(str(__get_random_course())) STUDENT.write("\t") STUDENT...
def __open_files(): global EMPLOYEE global STUDENT global TECHDEPT if not os.path.exists(DATA_PATH): os.makedirs(DATA_PATH) if os.path.exists(DATA_PATH+"/employee.tsv"): os.remove(DATA_PATH+"/employee.tsv") if os.path.exists(DATA_PATH+"/student.tsv"): os.remove(DATA_PAT...
The code's main task is to initialize file operations and generate data for Employees, Students, and the Tech department by sequentially calling private functions to open files and create corresponding records or structures.
def generate(): __open_files() __generate_Employee() __generate_Student() __generate_Techdept()
def test(P): Q = solve_Q(P) redundancy = CoI(Q) / np.log(2) print('Redundancy:', redundancy) unique_1 = UI(Q, cond_id=1) / np.log(2) print('Unique1', unique_1) unique_2 = UI(Q, cond_id=0) / np.log(2) print('Unique2', unique_2) synergy = CI(P, Q) / np.log(2) print('Synergy', synergy) ...
The code computes lower and upper bounds for information-theoretic quantities involving variables X1, X2, and Y. It calculates mutual information, conditional entropy, and disagreement metrics using probability distributions from input P, derives lower bounds for conditional mutual information and disagreement, and com...
def get_bounds(P): r, u1, u2, s = test(P) # print ('r=', r, 'u1=', u1, 'u2=', u2, 's=', s, 'total=', r+u1+u2+s) all_p = get_quantities(P) Py_given_x1 = all_p['Py_given_x1'].squeeze(axis=1) Py_given_x2 = all_p['Py_given_x2'].squeeze(axis=0) diff = np.zeros((Py_given_x1.shape[0], Py_given_x2.shap...
def GetP_Q(): primeList=[0,0] while(primeList[0] == primeList[1]): for i in range(0, 2): n = sympy.randprime(2, 2**8) primeList[i] = n return primeList[0], primeList[1] def Calculate_e(phi_n): e = 2 while(e < phi_n): if GCD...
The function `client_send` encrypts a user-input message using RSA-like parameters (p, q, n, e, φ(n)), ensuring the message's maximum ASCII value is less than n. It generates keys, encrypts the message, and sends the encrypted result along with public key components (e, n, φ(n)) to a server in a single encoded packet.
def client_send(): while True: x = f'{alias}: ' message = f'{input("")}' p, q = GetP_Q() while Choice == 0: p=poriginal q= qoriginal break n = p * q print(p) print(q) phi_n = (p-1)* (q-1) e = Ca...