dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def getImagePosition(image: str, confidence=0.9, grayscale=True): try: pos = pyautogui.locateCenterOnScreen( image, confidence=confidence, grayscale=grayscale ) return pos except pyautogui.ImageNotFoundException: return None def moveAndClick(pos: pyautogui.Point): ...
This code automates in-game tasks by detecting images and performing actions like clicking, scrolling, and item collection based on configuration settings. It initializes logging, checks enabled features, and runs a loop to gather items, claim rewards, use boosts, and open gifts/containers. The script stops if no funct...
def farm(config: Config, runtimeVariables: RuntimeVariables): global ENABLE_SCRIPT # Check what is enabled in the script configuration. If there is nothing enabled, # the script will not do anything so there is no point in running. if True not in set(vars(config).values()): logger.info( ...
def get_average_re_over_time(self, t_range): """ Averages the reynolds number value over a range o times :param t_range: range o start and end time frame :return: ixjxk array """ all_time_list = self.__time_list t_start, t_end = t_range filtered_time_list ...
The main task of the code is to compute starting positions for clustering (k-means) by analyzing averaged and scaled Reynolds number data over a specified time range. It calculates mean/standard deviation, generates weighted position values, and derives initial cluster positions using these parameters. The function ret...
def get_all_starting_points(self, t_range, re_range, k_means): """ :param t_range: range of time used to computing average :param re_range: range of reynolds numbers :param k_means: number of clusters used in k means :return: list of all starting points """ avera...
def __get_closest_time_step_index(self, re_time): closest_time_step_value = min(self.__time_list, key=lambda x: abs(x - re_time)) closest_time_step_index = np.where(self.__time_list == closest_time_step_value)[ 0 ][0] return int(closest_time_step_index) def run_ode(self, time...
The function `start_ode` executes ODE simulations for each time point in `self.__time_list`, retrieves results via `run_ode`, and combines forward and reverse integration outcomes if `reverse_integration` is True. It stores aggregated results in `self.__time_results`, filters streams by length, and returns the modified...
def start_ode(self, reverse_integration=True): """ :param reverse_integration: :return: """ for t_start in self.__time_list: time_step_index = self.__get_closest_time_step_index(t_start) all_results = self.run_ode(time_step_index) if reverse...
def aw_init(): print("Wait aw9523b reset...") aw_write(AW9523B_REG_SOFT_RST, 0x0) devid=aw_read(AW9523B_REG_ID) print("DevID: ", hex(devid)) # aw_write(AW9523B_P0_CONF_STATE, 0) # aw_write(AW9523B_P1_CONF_STATE, 0) aw_write(AW9523B_P0_LED_MODE, 0x00) aw_write(AW9523B_P1_LED_MODE, 0x00) aw_write(AW9523B_REG_GL...
The main task of the code is to automate GPIO testing by repeatedly powering on a specific pin (P1_0) for random durations (10-40 seconds), then turning it off and re-testing all GPIOs. It initializes GPIOs, runs initial tests, and enters an infinite loop to cycle through power-on/wait/power-off/test cycles, ensuring c...
def aw_autotest(): # reset all gpio aw_init() # auto test each gpio aw_test() counter=0 while 1: rand = random.randint(10,40) aw_write(P1_0, 255) print("Power on", counter, " waiting... ", rand, "seconds") time.sleep(rand) aw_write(P1_0, 0) # time.sleep(3) aw_test() counter = counter + 1 return
def check_keydown_events(event, ai_settings, screen, ship, bullets): '''Check when the key is pushed down''' # Checks what kind of key is being pushed down and acts on it if event.key == pygame.K_d: ship.moving_right = True elif event.key == pygame.K_a: ship.moving_left = True elif e...
The function `check_events` processes user input events in a game, handling key presses (KEYDOWN/KEYUP), mouse clicks (MOUSEBUTTONDOWN), and quit actions (QUIT). It delegates key-specific actions to `check_keydown_events` and `check_keyup_events`, and triggers game-start logic via `check_play_button` when the play butt...
def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets): '''this will check if there are any keypresses in the game''' # For each event(action) performed, check each of these statements for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()...
def check_fleet_edges(ai_settings, aliens): '''respond if any of the aliens have touched the bounds''' for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets): ...
This function updates alien positions, checks for collisions with the player's ship, and detects if aliens reach the screen bottom. It first checks if aliens hit screen edges, updates their positions, then detects ship-alien collisions to trigger a ship hit response. Finally, it checks if any aliens have reached the sc...
def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets): '''check if the aliens are at an edge, then update the positions of all aliens in the fleet''' check_fleet_edges(ai_settings, aliens) aliens.update() # look for alien -> ship collisions if pygame.sprite.spritecollideany(ship,...
def build_IN(self, train_batch, *, sample_weight=1.0): """ build_IN learns a new Info-Fuzzy Network on a given training window :param train_batch: current training window :param sample_weight: weight of sample """ # Reset the information known to the classifier s...
The code updates an Info-Fuzzy Network by splitting nodes in the final layer to adapt to new attributes in the training data. It replaces the last layer with new nodes, teaches them using the training batch, and iteratively splits nodes to refine the network structure. The process involves updating parent-child relatio...
def update_IN(self, train_batch, *, sample_weight=1.0): """ update_IN updates an Info-Fuzzy Network on a given training window by spliltting the nodes on the final layer of the current network by splitting on attributes not included in the network :param train_batch: current training win...
def build_IN(self, train_batch, *, sample_weight=1.0): """ build_IN learns a new Info-Fuzzy Network on a given training window :param train_batch: current training window :param sample_weight: weight of sample """ # Reset the information known to the classifier s...
The main task of the code is to train an Incremental Network (IN) model on a single instance while detecting concept drift. If no drift is detected, it updates the network incrementally; if drift is detected, it rebuilds the IN. The process involves calculating training/validation errors, adjusting window sizes dynamic...
def learn_one(self, x, y, *, sample_weight=1.0): """Train the model on instance x and corresponding target y. Parameters ---------- x Instance attributes. y Class label for sample x. sample_weight Sample weight. Returns ...
def sync_at_init(self): n_models = len(self.model_list) filter_banks = {} for k,v in self.model_list[0].state_dict().items(): if 'filter_bank' in k: filter_banks[k] = v for i in range(n_models): self.model_list[i].load_state_dict(copy.deep...
The main task of the code is to initialize an Agent by configuring parameters, creating multiple models with different fractions, syncing filter banks, loading checkpoints, and logging model details. It sets up device settings, parses arguments, generates model instances based on specified fractions, and prepares the a...
def __init__(self, *args): super(Agent, self).__init__() print('Init Agent {} and making models...'.format(args[2])) self.args = args[0] # args should contain slim rate self.ckp = args[1] self.my_id = args[2] self.crop = self.args.crop self.device = torch.device(...
def generateHeader(self): tmp = "Created by " + self.creator + "\r\n" tmp += "\r\n" tmp += "Copyright © " + str(datetime.datetime.now().year) + " " + self.company + ". All rights reserved.\r\n" tmp += self.disclaimer return self.generateMultilineComment(tmp) def generateFileHisto...
This code generates a C/C++ source file template with standard headers, macros, and function stubs based on the provided module name and mode. It creates a structured file including includes, preprocessor directives, section placeholders, and specific functions like 'main' or 'Init/Deinit' for non-main modules.
def generateCFile(self,moduleName,moduleDescription): tmp = self.generateHeader() if self.cppMode: tmp += self.generateFileHistory(moduleName.lower() + ".cpp",moduleName,moduleDescription) tmp += "#define __" + moduleName.upper() + "_CPP__\r\n\r\n" else: tmp...
def connectToSolr(): global coreName global URL if checkSolrCoreExistance(URL,coreName)==0: #################### Create new core connection = urlopen(URL+'admin/cores?action=CREATE&name='+coreName+'&instanceDir=./&config=solrconfig.xml&dataDir=data') response = json.load(connection) def Get...
The code handles AJAX POST requests to process Solr queries, returning JSON data based on 'list', 'count', or 'detail' types. It parses incoming JSON, executes Solr searches, and sends structured responses. For non-AJAX POSTs or GETs, it renders a template.
def home(request): if request.method == 'POST': #FeatureReq=request.POST.get('FeatureReq') #data = json.loads(FeatureReq) print("okay") #POST goes here . is_ajax is must to capture ajax requests. Beginner's pit. if request.is_ajax(): #Always use get on request...
def browse(self,id): self.file,_ = QtGui.QFileDialog.getOpenFileName(self, 'choose the image', os.getenv('HOME') ,"Images (*.png *.xpm *.jpg)" ) if self.file == "": logger.info("no file has been chosen to be open") pass #error when upload img1 before img2 #set...
This function connects GUI elements to their respective functions in a PyQt/PySide application. It links menu actions to window creation and image browsing, attaches combo box text changes to Fourier transform handling and mode updates, sets default selections, and connects sliders to update functions. Logger statement...
def connect_func(self): self.actionNew_Window.triggered.connect(self.newwindow) self.actionImage1.triggered.connect(lambda: self.browse(0)) self.actionImage2.triggered.connect(lambda: self.browse(1)) logger.info("open buttons are connected to their functions successfully") ...
def create_album(self, **extra_params): params = { 'name': self.get_next_album_name(), 'rating': 3, 'release_date': datetime(2014, 6, 1), 'purchase_date': datetime(2014, 6, 2), } params.update(extra_params) if 'artists' in params: ...
This test verifies that the `with_tracks_about_love` method correctly filters albums containing tracks with titles including the word "love". It creates two albums, adds one track about love to the first album, and checks that only that album is returned by the filtered query.
def test_06_albums_with_tracks_about_love(self): album1 = self.create_album() album2 = self.create_album() self.create_track(title='All you need is love', album=album1) self.create_track(title='Yesterday', album=album2) self.assertItemsEqual( [album1], Al...
def default_venv_name(file_name): """ @brief Default name for a venv """ abs_ = os.path.abspath(file_name) return abs_.replace(os.path.sep, "_").replace(".", "_").strip("_") def create_if_not_exist(venv_name): """ @brief Create a venv if it does not exist """ if not isvenv(venv_name)...
This function executes a Python script within a specified virtual environment, automatically creating the environment if it doesn't exist. It associates files with environments via configuration, locates the virtual environment's Python interpreter, and runs the script with provided arguments. Verbose mode displays the...
def python(venv_name, file_name, *args, verbose=True, **kwargs): """ @brief Run a Python file in a virtual environment """ if file_name is None and venv_name is None: raise click.UsageError("Require venv name or file name") if venv_name is None: venv_name = config.get( c...
def get_track_names(): playlist = get_playlist_info() track_names = [] for song in range(len(playlist['items'])): track_names.append(playlist['items'][song]['track']['name']) return track_names def get_track_artists(): playlist = get_playlist_info() track_artists = [] ...
The main task of the code is to gather track names, artists, and song lyrics, process lyrics into word counts, and populate a structured table with this data using the `setupSongTable` function, likely for organizing music-related information in a database or dataset.
def main(): track_names=get_track_names() track_artists=get_track_artists() song_lyrics = get_lyrics() word_counts_list = word_count(song_lyrics) setupSongTable(track_names, track_artists, song_lyrics, word_counts_list)
def _create_placeholders(self): self.input = tf.placeholder(shape=[None, self.num_visible], dtype=tf.float32, name="input") self.mask = tf.placeholder(shape=[None, self.num_visible], dtype=tf.float32, name="mask") def _create_varia...
This code initializes a neural network model, setting up placeholders for input/output data, creating model variables, and defining a training operation. It initializes a TensorFlow session and prepares the model for training with RBM-like parameters (visible units, hidden units, and sampling steps).
def __init__(self, num_visible, num_hidden, k, session): self.num_visible = num_visible self.num_hidden = num_hidden self.k = k self._create_placeholders() self._create_variables() self.train_op = self._train_op() self.sess = session init = tf.global_vari...
def make_IndexList(n1,n2,nLayers,mirror=False): ## Assuming always even number of layers if (nLayers%2!=0): print("Please enter an even number of layers") return indList=np.zeros(nLayers) if mirror==0: indList[0]=1 else: indList[0]=1e300 #1e309 is infinity in python indList[...
The code simulates light propagation through layered media, calculating transmission/reflection responses across angular frequencies. It constructs refractive index (nL) and thickness (dL) lists based on input parameters, then computes solutions for 1000 frequency points between wmin and wmax. The function returns freq...
def solution_rightwave(n1,n2,d1,nLayers,chirp=False,mirror=False,isTList=[]): ##nLayers is the number of layers in indexList d2=d1*n1/n2 #nLayers=10 #nL=[1,n1,n2,n1,n2,1] nL=make_IndexList(n1,n2,nLayers,mirror) #dL=[d1,d2,d1,d2] if chirp: dL=make_chirplist(d1,d2,n1,n2,nLayers-2,chir...
def poisson_1sided_interval(n,beta,limit="upper"): if limit=="upper": return poisson_interval(n,beta)[1] else: return poisson_interval(n,beta)[0] def disc_powerA(muB_,sigmaDiscovery_=5): xc = sps.poisson(muB_).ppf(sps.norm.cdf(sigmaDiscovery_)) ## critical value muS = np.linspace(0,25,2...
The function `get_critical` computes a list of critical values (`muS`) based on input parameters in `paramDict`. For each entry, it selects a calculation method (A1, A2, B1, B2) and applies corresponding statistical functions (`poisson_1sided_interval`, `disc_powerA`, `upper_limitB`, `discovery_powerB`) using parameter...
def get_critical(paramDict): """ paramDict - dictionary of input choices returns corresponding list of critical values """ muS = np.zeros(len(paramDict)) beta = 0.2 for i,keys in enumerate(paramDict): choice = paramDict[keys][0] time = paramDict[keys][2] bgd = p...
def n_vs_eV(kappa=1e-11,fDM=1,hitRate=0.75,area=AREA_DEFAULT,time=1): ''' area in units of cm^2 time in units of days returns energy,number of events ''' m,rate_curve = rate.get_rate(kappa) N = rate_curve*(m*area*time) return m,N def get_critical(paramDict): """ paramDict - dicti...
The code processes user inputs for experimental parameters, computes critical values (kappa) for different sensor configurations and plot types, and generates log-log plots comparing detection thresholds (kappa) against particle mass (eV/c²). It saves computed data and visualizes results for various sensor options, bac...
def main(argv): #--- default values mu = 0 bgd = 0 time = 1 choices = [] percentile = 1 labelDict = { "A1": "Option A, Upper Limit", "A2": "Option A, Discovery Power", "B1": "Option B, Upper Limit ", "B2": "Option B, Disco...
def create_parent_segments(self, mother_coords: tuple[int, int, int], father_coords: tuple[int, int, int]) -> tuple["WireSegment", "WireSegment"]: """ Returns the origin and destination segment of a wire """ mother_segment = WireSegment(None, mother_coords) father_segment = WireSegment(None, fa...
This function determines the shortest path between two points (mother and father) using a pathfinding algorithm. It employs an open/closed list system to explore segments, assigns costs to potential paths, and avoids cycles. The goal is to connect the two points with the lowest total cost, returning the wire path if su...
def draw_wire(self, mother: "Gate", father: "Gate"): """ Determines the shortest path between two points and draws the wire """ # Create lists which keep track of checked and not-checked possible segments open_list = [] closed_list = [] next_segments = [] # Initialize m...
def __memory_control(self,pos,spot): if len(self.memory) == self.memory_size: self.memory.pop() tmp = spot.reward.type if spot.reward is not None else 0 self.memory.insert(0,tmp) def __take(self,r): p = self.__calculate_take(r) take = np.random.choice(np.array([1,0]),...
The code's main task is to manage an agent's interaction with rewards and stock in an environment. It first processes possibilities and rewards via memory control, then attempts to pick up a reward if none is held. If a reward is picked up, it moves, then drops the reward if possible, updating its state and resetting t...
def action(self,posibilities,rewards): self.__memory_control(posibilities,rewards) if self.stock is None: for r,i,j in rewards: result = self.__take(r) if result == 1: r.is_taken = True self.stock = r ...
def __memory_control(self,pos,spot): if len(self.memory) == self.memory_size: self.memory.pop() tmp = spot.reward.type if spot.reward is not None else 0 self.memory.insert(0,tmp) def __take(self,r): p = self.__calculate_take(r) take = np.random.choice(np.array([1,0]),...
The main task of the code is to perform a backup action by taking a reward, moving to a new position, and then dropping the reward if possible. It first checks if the agent has no stock, then selects a reward to take. After moving, if holding a reward, it attempts to drop it, updating the reward's state and the agent's...
def action_backup(self,posibilities,rewards): self.__memory_control(posibilities,rewards) if self.stock is None: for r,i,j in rewards: result = self.__take(r) if result == 1: r.is_taken = True self.stock = r ...
def __memory_control(self,pos,spot,rewards): for r in rewards: if len(self.memory) == self.memory_size: self.memory.pop() self.memory.insert(0,r.type) for i in range(8-len(rewards)): self.memory.insert(0,0) def __take(self,r): p = self.__calcul...
The code manages an agent's actions in a multi-agent system, handling cooldowns, pheromone signals, reward collection, and item delivery. It checks for waiting states, processes memory, interacts with requesting agents, collects rewards (if none are held), and moves/drops items based on environment interactions and phe...
def action(self,posibilities,spot,rewards,agents_asking): if self.waiting: self.w_counting = self.w_counting + 1 if self.w_counting <= 20 else 0 if self.w_counting == 21: self.waiting = False else: self.__memory_control(posibilities,spot,rewards) ...
def getClassStrength(stream): # cluster URL clusterURL = "mongodb+srv://"+credentials.MONGODB_USERNAME+":"+credentials.MONGODB_PASSWORD+"@attendanccedb.vkkyk.mongodb.net/?retryWrites=true&w=majority" # setup connection with cluster myCluster = MongoClient(clusterURL,tls=True,tlsAllowInvalidCertificates=...
The main task of the code is to process a POST request for recording student attendance. It parses subject codes and attendance lists, converts them into a structured log format, and stores the data in MongoDB. If a duplicate record exists, it displays a message; otherwise, it writes the data to a file. The function ul...
def attendance(request): if request.method == "POST": subjectCode = request.POST["subjectCode"] attendanceList = request.POST["attendanceList"] try: attendanceList = list(map(int,attendanceList.split(','))) except: attendanceList = list(map(int,attendanceList....
def __setup_file(self, input): if input == None: return sys.stdin else: return open(input, 'r') def __get_exclusions(self): # check if correct file version is input if "1" in self.input.readline(): print("Input is version 1, concord4.py expected versio...
The code initializes a class to process input data by setting up files, retrieving exclusions and phrases, organizing input elements, formatting concordances, and outputting results. It structures input data, manages text processing parameters, and prepares formatted output through a series of internal methods, culmina...
def __init__(self, input=None, output=None): self.input = self.__setup_file(input) self.output = output self.exclusions = self.__get_exclusions() self.phrases = self.__get_phrases() self.keys_n_indicies = self.__organize_input() self.concord = self.__format_concord() ...
def identify_functional_groups(mol): marked = set() #mark all heteroatoms in a molecule, including halogens for atom in mol.GetAtoms(): if atom.GetAtomicNum() not in (6,1): # would we ever have hydrogen? marked.add(atom.GetIdx()) #mark the four specific types of carbon atom for patt in ...
The code processes a dataset by reading text and SMILES files, splits lines, generates functional group labels from SMILES, tokenizes processed sentences, and creates masked input-output pairs for training. It handles text encoding, label masking, and calculates average lengths for source and target sequences.
def __init__(self, tokenizer, file_path, max_length): assert os.path.isfile(file_path), f"Input file path {file_path} not found" print (f'Creating features from dataset file at {file_path}') #import ipdb; ipdb.set_trace() #bos_tok = tokenizer.bos_token eos_tok = tokenizer.eos_tok...
def spectrumPlot(integrals, molecule, maxC, returnSpectra=False, xmin=-1000, xmax=8000): FCData = loadFCF(integrals, molecule, maxC) print("Loading complete") zero = [0 for i in range(len(list(FCData[0].keys())[0]))] values = [zero+zero] integralZeroZero = get0Integral(molecule) probs = [integra...
The function compares complete and combined NMR spectra for a molecule using specified methods. It generates a complete spectrum from the first integral, combines spectra via 'legacy' or 'independent' methods, then compares results. The task involves analyzing spectral differences based on integration and partial data,...
def comparePartialComplete(integrals, partials, moleculeName, maxCs, method, maxCPlot=-1): completeSpectra = spectrumPlot(integrals[0], moleculeName, maxCs[0], True) if method == 'legacy': combinedSpectra = combineSpectra(integrals[1], partials, moleculeName, maxCs[1], maxCPlot, True) elif method ==...
def weight_variable(shape): initial= tf.truncated_normal(shape, stddev=.05) return tf.Variable(initial) def bias_variable(shape): initial=tf.constant(0.1, shape=shape) return tf.Variable(initial) def Inception_layer1(intensor, outshapes): shape = intensor.get_shape().as_list() #first bit Ia_...
This code defines and trains a 3D convolutional neural network with Inception modules for multi-output regression. It uses batch normalization, data augmentation, and alternating training strategies. The model minimizes mean squared errors for three outputs, validates periodically, and saves the best-performing models ...
def model(train_xs,train_ys,validation_xs,validation_ys,step,batchS,record_low,optimizer): #specify placeholders for tensorflow in the shape of our input data xs=tf.placeholder(tf.float32, [None,40,40,105], name='Xinput') #ys=tf.placeholder(tf.float32, [None,1], name='Yinput') ys1=tf.placeholder(tf.fl...
def slide_up(self): self.transpose() score = self.slide_left() self.transpose() return score def slide_right(self): self.reflect_horizontal() score = self.slide_left() self.reflect_horizontal() return score def slide_down(self): self.transpose() ...
The code applies a sliding action (up, right, down, left) to a game board based on the given opcode. It returns the reward from the action or -1 if the opcode is invalid, indicating an illegal move.
def slide(self, opcode): """ apply an action to the board return the reward of the action, or -1 if the action is illegal """ if opcode == 0: return self.slide_up() if opcode == 1: return self.slide_right() if opcode == 2: retur...
def daclen(primes): return [dac(primes[j])[1] for j in range(len(primes))] def batchstart(batchsize): B = len(batchsize) return [sum(batchsize[:j]) for j in range(B)] def batchstop(batchsize): B = len(batchsize) return [sum(batchsize[:j+1]) for j in range(B)]
The function computes the maximum values of `daclen(primes)` for each batch defined by `batchsize`, returning a list of these maxima. It divides the `daclen(primes)` array into batches using `batchstart` and `batchstop` indices, then calculates the maximum in each batch.
def maxdaclen(primes,batchsize): B = len(batchsize) return [max(daclen(primes)[j] for j in range(batchstart(batchsize)[b], batchstop(batchsize)[b])) for b in range(B)]
def daclen(primes): return [dac(primes[j])[1] for j in range(len(primes))] def daccost(n): return xDBL+xADD+n*xADD def batchstart(batchsize): B = len(batchsize) return [sum(batchsize[:j]) for j in range(B)] def batchstop(batchsize): B = len(batchsize) return [sum(batchsize[:j+1]) for j in range(B)]
The function `eachdac` calculates the sum of costs for a specific batch `b` by iterating over a subset of elements in `primes`, determined by `batchstart` and `batchstop`, and applying the `daccost` function to each element in that batch. It returns the aggregated cost for the selected batch.
def eachdac(primes,batchsize,b): B = len(batchsize) D = daclen(primes) return sum(daccost(D[j]) for j in range(batchstart(batchsize)[b], batchstop(batchsize)[b]))
def div(primes): return inv(primes)+M def elligator(primes): return S+M+M+M+S+M+M+sqrt(primes) def maxdac(primes,batchsize,b): B = len(batchsize) M = maxdaclen(primes,batchsize) return daccost(M[b]) def eachdac(primes,batchsize,b): B = len(batchsize) D = daclen(primes) return sum(daccost(D[j]) ...
This function computes a weighted sum of multiple operations on primes, using coefficients from the input dictionary x. It initializes a total (mults) by adding results from div(), elligator(), and clear2 operations. Then, for each batch element, it accumulates contributions from maxdac(), eachdac(), and isog() functio...
def mults(x,primes,batchsize): B = len(batchsize) mults = 0 mults += div(primes) mults += x['elligator']*elligator(primes) mults += x['clear2']*clear2 for b in range(B): mults += x['maxdac',b]*maxdac(primes,batchsize,b) mults += x['eachdac',b]*eachdac(primes,batchsize,b) mults += x['isog',0,b]*i...
def qw(s, returnTuple=False): ''' mimics perl's qw function usage: qw('a b c') will yield ['a','b','c'] returnTuple: return a tuple if true, otherwise return list ''' if returnTuple: return tuple(s.split()) else: return s.split() def get(self, key): ''' get the annot...
This function applies ADSP ranking to genetic consequence types (transcript, regulatory_feature, intergenic), reorders them by severity using OrderedDict, and stores the newly ranked consequences in the object's attributes. It retrieves each consequence type's data, applies ADSP-specific ranking, and compiles the resul...
def adsp_rank_and_sort_consequences(self): ''' applies ADSP ranking to consequence, re orders the array and and saves newly ordered list ''' conseqTypes = qw('transcript regulatory_feature intergenic') adsp_ranked_consequences = {} # Use OrderedDict; this way adsp_ranked_...
def get_entropy(labels): assert isinstance(labels, np.ndarray) vals = np.unique(labels) val_count = count_items(labels, vals) total = len(labels) entropy = 0 for count in val_count: entropy -= (count/total) * np.math.log2(count/total) return entropy def get_cond_entropy(feature, labe...
This code initializes a decision tree node by selecting the feature with maximum mutual information for splitting, recursively creating child nodes for each feature value (if max_depth allows), and preparing label data for majority voting at leaf nodes.
def __init__(self, max_depth, train): self._children = {} self._split_attr_idx = None self._split_attr = None self._max_depth = max_depth # add a new node if max-depth is not reached if max_depth > 0: num_feat = train.data.shape[-1] - 1 label_ent ...
def calc_probability_factor(self, prediction): """Buy more, the more confident we are it is a buy. Sell more, the more confident we are it is a sell.""" return prediction.probability ** 2 def calc_correlation_factor(self, trade, portfolio, prediction): """ Buy more if it is a diversifyin...
The function calculates an ideal incremental value by multiplying four factors: probability, correlation, weight, and total, each derived from the input parameters prediction, trade, and portfolio. It combines these factors to determine a weighted ideal value for decision-making.
def calc_ideal_incremental_value(self, prediction, trade, portfolio): probability_factor = self.calc_probability_factor(prediction) correlation_factor = self.calc_correlation_factor(trade, portfolio, prediction) weight_factor = self.calc_weight_factor(trade, portfolio, prediction) total_...
def load_data(use_data=None): data_load = np.load('dataset/'+use_data+str('.npy')) scalar = MinMaxScaler() #data_load[:, 0:-1] = scalar.fit_transform(data_load[:, 0:-1]) print(data_load.shape) return np.asarray(data_load).astype(float) def StreamClientData(data,num_clients=10,client_initial="c"): ...
The code's main task is to process streaming data for federated or individual client learning. It loads and preprocesses data, splits it into client streams, initializes prototypes, and executes either federated stream learning (FedStream), individual client stream processing (ClientsStream), or single-stream learning ...
def run(run_type="FedStream"): # load dataset data_load = load_data(use_data=dataset) if (data_load[:, -1] == 0).any(): print('Okay') else: print('Label Transformation') data_load[:, -1] = data_load[:, -1] - 1 print(np.unique(data_load[:,-1])) if run_type == "FedStre...
def _updateColours(self, accentColour): for img in self._appIcons: self._appIcons[img] = self.colourise(self._appIcons[img], accentColour) for img in self._taskbarIcons: self._taskbarIcons[img] = self.colourise(self._taskbarIcons[img], accentColour) for text in self._menu...
This code updates the game display by adjusting colors based on configuration, handling ambient effects, rendering the background, managing UI elements for different screens (face, home, settings, etc.), drawing interactive elements like a red circle at the mouse position, and ensuring the display updates at the specif...
def update(self): '''Updates the display. To be called at the end of every game loop''' accentColour = ut.getConfig('accentcolour') if self._currentColour != accentColour: self._updateColours(accentColour) #Ambience if ut.getConfig('ambientblink'): sel...
def apex_vf_path(self, guidelines=False, color=False): if len(self.sources) > 1: raise ValueError("Only one source supported") source = self.sources[0] if ( (source.is_glyphs and len(source.gsfont.masters) < 2) or source.is_ufo or (source.is_design...
This method constructs variable-related data structures by processing guidelines and variants based on configuration settings. It first builds apex VF paths for each guideline, then generates color variables if enabled, and finally creates variant-specific VFs by iterating through variants and guidelines. The process c...
def build_all_variables(self): if not self.config.get("buildVariable", True): return # Build apex VF for guideline in self.guidelines: self.recipe[self.apex_vf_path(guideline)] = self.variable_steps( guideline ) + [{"operation": "hbsubset", "a...
def isEnabled(): return helper.sdCardEnabled def isCardPresent(): if helper.sdCardCD is None: return isInitialized() and isEnabled() isPresent = helper.sdCardCD.value if not isPresent: clearInitFlag() return isPresent def isInitialized(): return helper.sdCardInitialized def in...
The code checks if the system is enabled, a card is present, and not yet initialized. If so, it initializes the system. It then returns a boolean indicating whether the system is fully ready (enabled, card present, and initialized).
def isReady(): if isEnabled() and isCardPresent() and not isInitialized(): init() return isEnabled() and isCardPresent() and isInitialized()
def clearInitFlag(): helper.sdCardInitialized = False if helper.sdCardVfs is None: return storage.umount(helper.sdCardVfs) helper.sdCardVfs = None helper.sdcard = None def isInitialized(): return helper.sdCardInitialized def init(): if isInitialized(): return # Make cer...
The code's main task is to enable or disable SD card functionality by updating the `sdCardEnabled` flag. If disabled, it clears an initialization flag; if enabled and not already initialized, it triggers initialization. The function ensures proper state management for SD card operations, handling both activation and de...
def setEnable(val): if val == helper.sdCardEnabled: return helper.sdCardEnabled = val if not val: clearInitFlag() if val and not isInitialized(): init()
def isCardPresent(): if helper.sdCardCD is None: return isInitialized() and isEnabled() isPresent = helper.sdCardCD.value if not isPresent: clearInitFlag() return isPresent def isEnabled(): return helper.sdCardEnabled def isReady(): if isEnabled() and isCardPresent() and not i...
The main task of the code is to update display and log items with SD card status, including presence detection, enabled status, disk space (total/free), and file count. It clears dictionary values, checks card readiness, calculates storage metrics using os.statvfs, counts files, formats data for display, and handles er...
def update(): # Clear dictonary values helper.clearDictionaryValues(dispItems.sdcard) helper.clearDictionaryValues(logItems.sdcard) gc.collect() cardPresent = isCardPresent() dispItems.sdcard["cardPresent"]["value"] = \ "Present" if cardPresent else "Not Present" logItems.sdcard["c...
def isReady(): if isEnabled() and isCardPresent() and not isInitialized(): init() return isEnabled() and isCardPresent() and isInitialized() def isInitialized(): return helper.sdCardInitialized def clearInitFlag(): helper.sdCardInitialized = False if helper.sdCardVfs is None: retur...
The main task of the code is to append provided text to a file on an SD card, using an LED to signal writing activity. It checks system readiness and initialization status before attempting to write, handles errors by clearing the initialization flag, and ensures proper LED state management during file operations.
def writeToFile(fileName, text): if not isReady(): return if not isInitialized(): return filefullpath = "/sd/{}".format(fileName) try: with open(filefullpath, "a") as f: # turn on LED to indicate we're writing to the file if helper.sdCardLED is not None...
def round_2(self): self.cont_players = self.players[:] if self.decision == "f": self.cont_players.remove(self.main_player) elif self.decision == "b": self.main_player.set_bet_amount(self.bet_amount) Player.set_community_cards( (self.deck.pull_card(), ...
This function handles user decisions in a game interface, managing GUI elements for betting, checking, or folding. It validates bet amounts against the player's balance, updates the interface, and triggers subsequent game rounds (round_2, round_3, round_4) based on the decision.
def valid_decision(self, decision): self.gui_link.fold_button.pack_forget() self.gui_link.check_button.pack_forget() self.gui_link.bet_button.pack_forget() if decision == "b": self.gui_link.bet_label.pack() self.gui_link.bet_entry.pack() self.gui_link....
def get_relevant_transcript_entries(transcript_data, filename_regex): found_entries = [] for entry in transcript_data["translated_results"]: if is_match(entry['filename'],regex=filename_regex): found_entries.append(entry) return found_entries def is_multi_speaker(entry): ...
The code translates a transcript file into audio by filtering relevant entries using a regex pattern. It processes each entry, pausing for 2 seconds before generating audio: single-speaker entries are handled directly, while multi-speaker entries are split into segments for individual processing.
def translate(source_file, filename_regex): with open(source_file, 'r') as file: transcript_data = json.load(file) relevant_entries = get_relevant_transcript_entries(transcript_data, filename_regex) logging.debug(f"relevant_entries: {relevant_entries}") for entry in relevant_entries: ...
def is_square(matrix): for i in matrix: if(len(matrix) != len(i)): return False return True def try_make_col_canon(matrix, col_i): col = matrix[col_i] if(check_col_only_at_below(col, col_i)): return matrix for row_i in range(col_i): if(row_i != col_i and...
The function converts a square matrix into a canonical basis form by iteratively canonicalizing columns, applying field transformations, sorting, and scaling. It ensures linear independence by checking for non-zero entries below the diagonal and raises errors for non-square matrices or linear dependencies.
def try_make_canon_basis(matrix): if(not is_square(matrix)): raise ValueError("Matrix is not nxn") for col_i in range(len(matrix)): matrix = try_make_col_canon(matrix, col_i) matrix = field_transform(matrix) tmp = sort_matrix(matrix) if(t...
def preamble(env): return f"""You are an expert at Reversi (also known as Othello). We are playing on a board that is {env.dim}-by-{env.dim}. We use standard Othello notation where rows are numbered from top to bottom by 1 to {env.dim}, and columns are indicated from left to right by 'a' through '{max_col(env.dim)}...
The function generates a prompt for a model by combining a preamble with example interactions from a replay, then queries the model to determine an accurate move based on the current game state, using historical examples to inform the decision.
def accurate_move_query(model, replay, turn, shots=0, example_replay=None): prompt = preamble(replay.state_before_turn(turn)) messages = [] ex_turns = [] for shot in range(shots): while(True): ex_turn = random.randrange(len(example_replay.actions) - 1) if ex_turn in ex_tu...
def preamble(env): return f"""You are an expert at Reversi (also known as Othello). We are playing on a board that is {env.dim}-by-{env.dim}. We use standard Othello notation where rows are numbered from top to bottom by 1 to {env.dim}, and columns are indicated from left to right by 'a' through '{max_col(env.dim)}...
The function constructs a prompt for a model by combining a preamble, example interactions from a replay buffer, and a current query prompt based on the environment and legal moves, then queries the model to generate a response with a token limit.
def greedy_visual_query(model, env, legal_moves, shots=0, replay=None): prompt = preamble(env) messages = [] for shot in range(shots): turn = shot*3 + 2 messages += example_greedy_visual_conversation(replay, turn) messages.append(greedy_visual_prompt(env, legal_moves)) return query(m...
def board_visualization(env): black_char = 'X' if env.curr_player == BLACK else 'O' white_char = 'X' if env.curr_player == WHITE else 'O' return f"""A representation of the board follows. Empty squares are denoted by '.', your pieces are denoted by 'X', and your opponent's by 'O'. Columns and rows are label...
The code generates a prompt for a game, providing the current board state (visual or descriptive), lists legal moves, and requests an explanation of which opponent's pieces each move would flip, aiding decision-making in a turn-based strategy game.
def move_prompt(env, legal_actions, visualize=False): state_prompt = board_visualization(env) if visualize else board_description(env) return f"""{state_prompt} It is your turn. Here are your legal moves: {poslist2str(legal_actions)}. Explain which of your opponent's pieces will be flipped by each legal move...
def board_visualization(env): black_char = 'X' if env.curr_player == BLACK else 'O' white_char = 'X' if env.curr_player == WHITE else 'O' return f"""A representation of the board follows. Empty squares are denoted by '.', your pieces are denoted by 'X', and your opponent's by 'O'. Columns and rows are label...
The function generates a prompt describing the current game state and legal moves, asking the user to identify which move(s) flip the most pieces. It returns a formatted string that includes either a visual or textual board description, lists available moves, and requests analysis of piece-flipping outcomes, prioritizi...
def greedy_prompt(env, legal_actions, visualize=False): state_prompt = board_visualization(env) if visualize else board_description(env) return f"""{state_prompt} It is your turn. Here are your legal moves: {poslist2str(legal_actions)}. Describe which pieces will be flipped by each of these legal moves. Then,...
def preamble(env): return f"""You are an expert at Reversi (also known as Othello). We are playing on a board that is {env.dim}-by-{env.dim}. We use standard Othello notation where rows are numbered from top to bottom by 1 to {env.dim}, and columns are indicated from left to right by 'a' through '{max_col(env.dim)}...
The function `move_query` generates a query for a model by constructing a prompt and conversation history. It incorporates example interactions from a replay buffer, appends a prompt for the current move decision, and returns the model's response, enabling decision-making in an environment with specified legal moves.
def move_query(model, env, legal_moves, shots=0, replay=None, visualize=False): prompt = preamble(env) messages = [] for shot in range(shots): turn = shot*3 + 2 messages += example_move_conversation(replay, turn, visualize) messages.append(move_prompt(env, legal_moves, visualize)) re...
def preamble(env): return f"""You are an expert at Reversi (also known as Othello). We are playing on a board that is {env.dim}-by-{env.dim}. We use standard Othello notation where rows are numbered from top to bottom by 1 to {env.dim}, and columns are indicated from left to right by 'a' through '{max_col(env.dim)}...
The function `greedy_query` constructs a prompt for a language model by combining a preamble, example conversations from a replay buffer, and a greedy decision-making prompt based on the environment and legal moves. It then queries the model to generate a response, using historical examples to guide the model's decisio...
def greedy_query(model, env, legal_moves, shots=0, replay=None, visualize=False): prompt = preamble(env) messages = [] for shot in range(shots): turn = shot*3 + 2 messages += example_greedy_conversation(replay, turn, visualize) messages.append(greedy_prompt(env, legal_moves, visualize)) ...
def preamble(env): return f"""You are an expert at Reversi (also known as Othello). We are playing on a board that is {env.dim}-by-{env.dim}. We use standard Othello notation where rows are numbered from top to bottom by 1 to {env.dim}, and columns are indicated from left to right by 'a' through '{max_col(env.dim)}...
The function `legal_query` constructs a prompt and message history for a legal reasoning task using a specified number of example interactions (`shots`), then queries a model to generate a response. It aggregates example conversations from `replay`, appends a final legal prompt, and returns the model's output with a to...
def legal_query(model, env, shots=0, replay=None, visualize=False): prompt = preamble(env) messages = [] for shot in range(shots): turn = shot*3 + 2 messages += example_legal_conversation(replay, turn, visualize) messages.append(legal_prompt(env, visualize)) return query(model, promp...
def page1(self): if self.db.init: self.frames[2].reinitFrame(self.ir['SessionInfo']['Sessions'][self.ir['SessionNum']]['SessionType']) # DRS if self.db.DRS: if self.ir['SessionInfo']['Sessions'][self.ir['SessionNum']]['SessionType'] == 'Race': self.db.DR...
The code renders a racing game's Heads-Up Display (HUD) using Pygame, handling user input, updating visual elements based on in-game data (like gear, track position, warnings), and displaying dynamic information such as lapping cars, engine alerts, and session flags. It manages multiple UI pages, renders graphical indi...
def render(self): try: t = time.perf_counter() if self.db.DDUrunning and self.db.StartDDU and not self.BDisplayCreated: RenderMain.screen = pygame.display.set_mode(self.resolution, pygame.NOFRAME) self.BDisplayCreated = True for event in pyga...
def print_welcome_message(self): welcome_message = dedent(''' Hi, I am your Training Assistant, and I will help you achieve your goals. First, lets collect some information about you and your Gym environment so I can bring you the most effective way to help you rock inside the Fitness wo...
The code's main task is to initialize a training program by first displaying a welcome message, then gathering trainee data, and finally constructing a training routine based on that data. This sequence sets up the necessary components for the program's operation.
def start(self): self.print_welcome_message() self.collect_trainee_data() self.build_routine()
def get_model(): encoder_name = 'timm-efficientnet-b0' model = smp.Unet( encoder_name=encoder_name, encoder_weights=None, in_channels=2, classes=2, ) model_name = 'unet_timm-efficientnet-b0_12.09_fold_2.pth' model.load_state_dict(torch.load(ASSETS_DIRECTORY / mode...
The code loads a pre-trained model, processes a list of chip IDs by generating predictions for each, and saves the results as TIFF files in a specified directory. It handles model setup, input validation, and batch processing with progress tracking.
def main(): print("Loading model") # Explicitly set where we expect smp to load the saved resnet from just to be sure torch.hub.set_dir(ASSETS_DIRECTORY / "torch/hub") model = get_model() print("Finding chip IDs") chip_ids = get_expected_chip_ids() if not chip_ids: print("No input i...
def export_VTK(self, n): """ Export the fluid field to VTK. """ x = np.linspace(0, lx, lx) y = np.linspace(0, ly, ly) z = np.linspace(0, lz, lz) grid_x = np.linspace(0, lx, lx) grid_y = np.linspace(0, ly, ly) grid_z = np.linspace(0, lz, lz) ...
This code simulates a physical process over a specified number of steps, periodically exporting simulation data to VTK files. It updates fluid dynamics parameters (psi, force, velocity), handles collisions, and performs streaming operations. The loop increments the step counter until reaching max_step, ensuring systema...
def run(self, max_step=20000): while self.step[None] < max_step: if (self.step[None]) % vtk_dstep == 0: self.export_VTK(self.step[None] // vtk_dstep) print( "Export No.{} vtk at step {}".format( self.step[No...
def force_vec(self, local_pos) -> parameters.f32_vec3d: force_vec = ti.Vector([0.0, 0.0, 0.0]) local_psi = Intra_psi(self.rho_1[local_pos]) for i in ti.static(range(3)): for s in ti.static(range(1, Q)): neighbor_pos = self.periodic_index(local_pos + self.e_xyz[s]) ...
The code implements a collision operation in a lattice Boltzmann method (LBM) simulation. It updates distribution functions for non-solid particles within specified bounds using either MRT (matrix-based) or BGK (relaxation-time) operators. For MRT, it transforms collision functions via matrix multiplication and relaxat...
def collision(self): for I in ti.grouped(self.collide_f_1): if I.x < lx and I.y < ly and I.z < lz and self.IS_SOLID[I] == 0: self.force_1[I] = self.force_vec(I) self.v_1[I] = self.velocity_vec(I) if ti.static(MRT): """MRT operator...
def export_VTK(self, n): x = np.linspace(0, lx, lx) y = np.linspace(0, ly, ly) z = np.linspace(0, lz, lz) grid_x = np.linspace(0, lx, lx) grid_y = np.linspace(0, ly, ly) grid_z = np.linspace(0, lz, lz) X, Y, Z = np.meshgrid(x, y, z, indexing="ij") gridToVT...
The code simulates a process (e.g., lattice Boltzmann method) by iterating up to `max_step`, calculating porosity, exporting VTK files at intervals (`vtk_dstep`), and updating the simulation state via `collision()`, `streaming()`, and `post_collision()` methods.
def run(self, max_step=1000): print("The number of solid nodes is ", nb_solid) print("Porosity = {:.3f}".format(1 - nb_solid / (lx * ly * lz))) self.export_VTK(self.step[None] // vtk_dstep) while self.step[None] < max_step: if (self.step[None]) % vtk_dstep == 0 an...
def get_domain(link: str) -> str: domain = urlparse(link).hostname parts = domain.split('.') if len(parts) > 2: domain = '.'.join(parts[-2:]) return domain def scrape(link: str) -> PageContent: scraper = get_scraper(link) return scraper.scrape(link) def generate_hash(link: str) -> st...
The code reads URLs from a log file, filters out processed/skipped links, sorts remaining URLs by domain, then scrapes each URL's content and saves the data as YAML files in a specified directory.
def main(): links = [] with open('links.log', 'r') as f: links = f.readlines() pending_links = [link.strip() for link in links if link and not "$DONE$" in link] pending_links = [link.strip() for link in pending_links if link and not "$SKIP$" in link] print(pending_links[:10]) pending_...
def get_document_by_hash(hash: str, session: Optional[Session] = None): if session: document = session.exec(select(Document).where(Document.hash == hash)).first() else: with Session(get_engine()) as session: document = session.exec( select(Document).where(Document.has...
This function creates or updates a document in a project by uploading a file from a specified path. It validates the organization and project, checks file existence, computes a hash, and ensures no duplicate content exists. If overwriting, it deprecates the existing document and increments the version. Otherwise, it cr...
def create_document_by_file_path( organization: Organization = None, project: Project = None, file_path: str = None, url: Optional[str] = None, file_version: Optional[int] = 1, file_hash: Optional[str] = None, overwrite: Optional[bool] = True, session: Optional[Session] = None, ): if...
def covarianceList(aList,bList): m=meanList(aList) m2=meanList(bList) covariance=sumList([(a-m)*(b-m2) for a,b in zip(aList,bList)])/(len(aList)-1) return covariance def varianceList(aList): variance = sumList((i - meanList(aList))**2 for i in aList) / (len(aList)-1) return variance def meanList...
The code calculates the coefficients (intercept `b0` and slope `b1`) for a linear regression model using a training dataset. It extracts `x` and `y` values, computes their means, covariance, and variance, then derives `b1` as covariance divided by variance, and `b0` as the mean of `y` minus `b1` times the mean of `x`. ...
def coefficients(trainingDatasetList): x = [item[0] for item in trainingDatasetList] aList = [] for i in x: aList.append(float(i)) y = [item[1] for item in trainingDatasetList] bList = [] for i in y: bList.append(int(i)) b1 = covarianceList(aList,bList) / varianceList(aList)...
def init_layers() -> None: onboard = machine.Pin("LED", machine.Pin.OUT) onboard.off() for pin in LAYER: machine.Pin(pin, machine.Pin.OUT) for x in range(4): for z in range(4): machine.Pin(GRID_3D[x][z], machine.Pin.OUT) def clear_leds() -> None: for x in range(4):...
The code initializes LED layers, clears LEDs, generates a color-specific LED pattern, displays it in a loop controlled by 'endFlagger', then clears LEDs again. The main task is to display and control LED patterns based on input color and termination flag.
def innerprogram(COLOUR :str, endFlagger) -> None: # Main program init_layers() clear_leds() led_pattern = get_led_pattern(COLOUR) prog_loop(led_pattern, endFlagger) clear_leds()
def get_delta_time(self): dt = perf_counter() - self.last_time dt *= s.DELTA_FPS # wanted fps self.last_time = perf_counter() return dt def event_handler(self): for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() quit() ...
The code defines a `tick` method that drives a game loop by handling events, updating the game state with delta time, limiting frames per second (FPS), rendering the game, and marking new data as loaded.
def tick(self): dt = self.get_delta_time() # LOCAL CLIENT GAME LOOP self.event_handler() self.clock.tick(s.FPS) self.update(dt) self.draw() self.new_data_loaded = True
def display_menu(): """Prints the menu to screen.""" print(HELP_TEXT) def get_command() -> str: """ Accepts input command from reading and validates it, returning it if valid. :returns: valid command to be parsed by main() """ while True: command = str(input("$ ")) if not co...
The main task of the code is to manage a reading database by allowing users to view, add, delete, or modify entries through a command-line interface. It initializes a dictionary with predefined entries, displays a menu, and processes user commands in a loop until an exit command is received. The program handles viewing...
def main(): # initialize readings dict readings = { "Kirk Van Houten": "Can I Borrow A Feeling?", "Lucifer": "Necronomicon", "Edgar Allan Poe": "Could You Be Loved? The Bob Marley Story" } print("Welcome to the reading database.") display_menu() # tell the user what their op...
def display_menu(): """Prints the menu to screen.""" print(HELP_TEXT) def get_command() -> str: """ Accepts input command from user and validates it, returning it if valid. :returns: valid command to be parsed by main() """ while True: command = str(input("$ ")) if not comma...
The main task of the code is to manage a user database via a command-line interface, allowing users to view, add, delete entries, or exit. It initializes a predefined user dictionary, displays a menu, and processes commands in a loop. Functions handle specific actions, with 'exit' terminating the program. Invalid comma...
def main(): # initialize users dict users = { "xXxbubbafrumpstreestumpxXx": "Bobby Hill", "mrbillohno": "Connor Chuckles", "jimvarney66": "Ernest Worrell" } print("Welcome to the user database.") display_menu() # tell the user what their options are # main program loop ...
def display_menu(): """Prints the menu to screen.""" print(HELP_TEXT) def get_command() -> str: """ Accepts input command from user and validates it, returning it if valid. :returns: valid command to be parsed by main() """ while True: command = str(input("$ ")) if not comma...
The main task of the code is to manage a simple email database by initializing it if non-existent, reading user data from a file, and allowing users to view, add, or exit via a terminal menu. It maintains a username-to-email mapping in a dictionary, processes commands, and persists changes to the database file.
def main(): # check if database file exists; if not, make one with the sample entry db_path = pathlib.Path('./db.txt') if not db_path.exists(): with db_path.open(mode="w") as db: db.writelines(SAMPLE_ENTRY) # from the db file, read the usernames and emails and store them in a dict ...
def grammar3(shot): dic={} for ispos in shot.objects["text_is"]: boolean1=False for babapos in shot.objects["text_baba"]: if babapos==[ispos[0],ispos[1]-1]: boolean1=True thing="baba" for wallpos in shot.objects["text_wall"]: if wallpos==[ispos[0],ispos[1]-1]: boolean1=True thing="wall" ...
The main task of the code is to move objects containing "you" upward in a game state by iterating through directional and regular objects, applying position updates via `push2`, and checking win conditions using `win3`. It modifies the game state (`shot`), adjusts object positions, and sets a win flag if applicable.
def up(shot): dic=grammar3(shot) for dicitem in dic.items(): if dicitem[1].issuperset({"you"})==True: for dirobjs in shot.dir_objects.items(): if dirobjs[0]==dicitem[0]: for dirobjpos in dirobjs[1]: result=push2(shot,dirobjpos[0],dirobjpos[1]-1,"u",dic) if result==False: continue ...
def grammar3(shot): dic={} for ispos in shot.objects["text_is"]: boolean1=False for babapos in shot.objects["text_baba"]: if babapos==[ispos[0],ispos[1]-1]: boolean1=True thing="baba" for wallpos in shot.objects["text_wall"]: if wallpos==[ispos[0],ispos[1]-1]: boolean1=True thing="wall" ...
The main task of the code is to move objects and directional objects downward in a game state, checking for valid movements using `push2`. If successful, it updates positions and applies grammar rules, then checks for a win condition. The function modifies the game state (`shot`) by adjusting object positions and setti...
def down(shot): dic=grammar3(shot) for dicitem in dic.items(): if dicitem[1].issuperset({"you"})==True: for dirobjs in shot.dir_objects.items(): if dirobjs[0]==dicitem[0]: for dirobjpos in dirobjs[1]: result=push2(shot,dirobjpos[0],dirobjpos[1]+1,"d",dic) if result==False: continue ...
def grammar3(shot): dic={} for ispos in shot.objects["text_is"]: boolean1=False for babapos in shot.objects["text_baba"]: if babapos==[ispos[0],ispos[1]-1]: boolean1=True thing="baba" for wallpos in shot.objects["text_wall"]: if wallpos==[ispos[0],ispos[1]-1]: boolean1=True thing="wall" ...
The code processes a game state (`shot`) by moving objects or the player ("you") leftward, updating positions via `push2`, and checks for a win condition using `win3`. It modifies the game state by adjusting coordinates, applies grammar rules (`grammar3`, `grammar4`), and returns the updated state with a win flag if ap...
def left(shot): dic=grammar3(shot) for dicitem in dic.items(): if dicitem[1].issuperset({"you"})==True: for dirobjs in shot.dir_objects.items(): if dirobjs[0]==dicitem[0]: for dirobjpos in dirobjs[1]: result=push2(shot,dirobjpos[0]-1,dirobjpos[1],"l",dic) if result==False: continue ...
def grammar3(shot): dic={} for ispos in shot.objects["text_is"]: boolean1=False for babapos in shot.objects["text_baba"]: if babapos==[ispos[0],ispos[1]-1]: boolean1=True thing="baba" for wallpos in shot.objects["text_wall"]: if wallpos==[ispos[0],ispos[1]-1]: boolean1=True thing="wall" ...
The main task of the code is to simulate a rightward movement in a game by checking grammar rules, updating object positions, and determining a win state. It iterates through objects, applies directional shifts using `push2`, updates positions if valid, and checks for a win via `win3` after processing. The function mod...
def right(shot): dic=grammar3(shot) for dicitem in dic.items(): if dicitem[1].issuperset({"you"})==True: for dirobjs in shot.dir_objects.items(): if dirobjs[0]==dicitem[0]: for dirobjpos in dirobjs[1]: result=push2(shot,dirobjpos[0]+1,dirobjpos[1],"r",dic) if result==False: continue ...
def addTextEdit(root, row, label, longLabel, value, hintText, narrow = False): row, labelTop = addLabel(root, row, label, longLabel, narrow) text = tk.Entry(root, textvariable = value) text.grid(column=1, row=row, columnspan=2, sticky=tk.EW) if hintText: rna_ttp = CreateToolTip(labelTop, hintTex...
This function creates a GUI panel for inputting experiment parameters, including fields for experiment name, amplicon names, editing tool selection, sequencing design, and sequence-specific settings. It adds "Process" and "Cancel" buttons to initiate or abort the experiment, using Tkinter widgets and layout configurati...
def createLeftPanel(root, ctx, topRoot): global params row = 0 root.columnconfigure(0, weight=0) root.columnconfigure(1, weight=100) root.columnconfigure(2, weight=0) root.columnconfigure(3, weight=0) # Sequence Name hintText = """Optional suffix to append to the report name. Only alphan...
def getClearFrame(root): for widget in root.winfo_children(): widget.destroy() return root def createLeftPanel(root, ctx, topRoot): global params row = 0 root.columnconfigure(0, weight=0) root.columnconfigure(1, weight=100) root.columnconfigure(2, weight=0) root.columnconfigure(3...
The code sets up a GUI experiment interface by dividing the window into two panels: a left panel for controls/configurations and a scrollable right panel for displaying/experiment data. It clears the root frame, initializes global parameters, creates structured frames with specific layouts, and populates panels with ex...
def executeExperiment(root, ctx, experiment): getClearFrame(root) global params params = experiment frame1 = tk.Frame(root) frame1.place(relx=0.0, rely=0.0, relheight=1.002, relwidth=0.466) frame1.configure(relief='groove') frame1.configure(borderwidth="2") frame1.configure(relief="groo...
def readWords(ham_loc, spam_loc): # Ham and spam email numbers ham_count = len(os.listdir(os.getcwd()+ham_loc)) spam_count = len(os.listdir(os.getcwd()+spam_loc)) # For every file read the message break it down to single words (no duplicates of words) and update the dictionaries for fname in os.li...
This code implements a decision tree classifier using the ID3 algorithm to classify emails as spam or ham. It calculates accuracy, error, precision, recall, and F1 score by training on provided training data, testing on a validation set, and evaluating performance metrics based on classification results.
def init(ham_train, spam_train, test, validation): ham_count, spam_count, most_imp = readWords(ham_train, spam_train) total_count = ham_count + spam_count ham_freq = ham_count / total_count spam_freq = spam_count / total_count ent = entropy(ham_count, spam_count) entrop.append(ent) root = ...
def log_info(self, message: str, col: int = colour.LIGHTBLUE_EX) -> None: self._print('[INFO]', message, col) return def log_error(self, message: str) -> None: self._print('[ERR]', message, colour.LIGHTRED_EX) return def print_online_users(self) -> None: print(f'\n{colour.CYAN}<-...
The main task of the code is to handle client-server communication for a user session, processing packets related to login, logout, registration, inventory management, and user interactions. It sends user data, receives server responses, updates user state (e.g., authentication, inventory, online users), and manages ac...
def _handle_connection(self, sock: socket, packet: Packet) -> None: if packet.id == packets.client_login: username: str = input('Username: ') # newline to space from menu password: str = getpass() print() # Print new line to split from.. everything packet.pack_da...
def print_main_menu(self) -> None: print('', # Print a space at the top of menu. f'{colour.CYAN}<- {colour.YELLOW}Main Menu {colour.CYAN}->', sep='\n' ) if not self.is_online: # *** Not logged in. *** print( '1. Login', '2. Reg...
The main task of the code is to manage a game loop for a user interface, handling login/logout, inventory management, online user interactions, and privilege-based commands. It processes user choices to perform actions like logging in, registering, adding bottles, taking shots, viewing ledgers, and admin functions (pla...
def _gameLoop(self) -> None: while True: self.print_main_menu() choice_count: int = 2 if self.is_online: if self.user.privileges & privileges.USER_PERMS: choice_count += 6 if self.user.privileges & privileges.ADMIN_PERMS: choice_count += 2 ...
def _reshape_input_torch(tensor: torch.Tensor) -> typing.Tuple[torch.Tensor, _I, _I, int, int]: if tensor.dim() == 4: b, c, h, w = tensor.size() elif tensor.dim() == 3: c, h, w = tensor.size() b = None elif tensor.dim() == 2: h, w = tensor.size() b = c = None else...
This function resizes a 2D image tensor using specified scaling factors or target sizes, supporting interpolation (cubic, etc.) and downsampling methods. It handles input reshaping, kernel selection, antialiasing, and output reconstruction, ensuring compatibility with PyTorch tensors while preserving data types and dim...
def _image_resize_torch(tensor: torch.Tensor, scale_factor: typing.Optional[float] = None, sizes: typing.Optional[typing.Tuple[int, int]] = None, kernel: typing.Union[str, torch.Tensor] = "cubic", sigma: float = 2, ...
def _fspecial_gaussian_torch(window_size: int, sigma: float, channels: int): """PyTorch implements the fspecial_gaussian() function in MATLAB Args: window_size (int): Gaussian filter size sigma (float): sigma parameter in Gaussian filter channels (int): number of input image channels ...
The function computes the NIQE (Natural Image Quality Evaluator) score by comparing statistical features of image patches to a reference Gaussian model. It processes the input tensor with Gaussian filters, extracts MSCN features at multiple scales, fits a multivariate Gaussian to distorted patches, and calculates the m...
def _fit_mscn_ipac_torch(tensor: torch.Tensor, mu_pris_param: torch.Tensor, cov_pris_param: torch.Tensor, block_size_height: int, block_size_width: int, kernel_size: int = 7, ...
def callUsageError(error: str, program=None): if program is None: print(Fore.YELLOW + "Usage: \n" " PROGRAM CALL -- ./hl.py FILE_PATH RUN_MODE \n" " ...
The function parses command-line arguments, validates the file path, and executes either simulation or compilation based on the specified mode ("sim" or "com"), returning an exit code. It checks argument count, file existence, and mode validity, raising errors for invalid inputs.
def argv_parser(argv): exit_code = 1 if len(argv) != 3: callUsageError("BAD ARGUMENTS ERROR!") program_info, argv = uncons(argv) if not checkFilePath(argv[0]): callUsageError("FILE_PATH ERROR", program_info) file_path, argv = uncons(argv) if argv[0] == "sim": exit_code...
def movePanda(self, pos): """ Given The Position of the Panda (End_Effector_Part) Move The Panda/Joints to reach the location """ # Move Panda Body self.bullet_client.submitProfileTiming("IK") orn = self.bullet_client.getQuaternionFromEuler(self.finder_orientation) jointPoses = self.bullet_client.cal...
The code defines a `step` method for a robotic arm (Panda) to control its movement and gripper actions across multiple states, including initialization, moving, grasping, releasing, and idle. It adjusts the gripper height using a weighted average, updates the robot's position, and triggers specific actions like fine co...
def step(self, gripper_error=False): alpha_change_gripper_height = lambda x: ALPHA * self.gripper_height + (1.0-ALPHA)* x # alpha_change_gripper_height = lambda x: x if self.state == PandaState.INIT: self.pos = np.zeros(3) self.gripper_height = alpha_change_gripper_height(MOVE_HEIGHT) self.pos[2] = s...
def outOfBounds(self): for i in range(len(self.inits)): if abs(self.inits[i][0])>0.55 or abs(self.inits[i][1])>0.55: return True return False def collision(self): if self.explicit: return self.explicitCollision() return self.coll def goalReached(se...
The main task of the code is to determine if a terminal state is reached by checking if the agent is out of bounds, collides, or has reached the goal. It returns True when any of these conditions are met, indicating the end of the current state or episode.
def isTerminal(self): if self.outOfBounds(): # print("OUTOFBOUNDS") return True if self.collision(): #print("COLL") return True if self.goalReached(): # print("GOAL") return True return False
def outOfBounds(self): for i in range(len(self.inits)): if abs(self.inits[i][0])>0.55 or abs(self.inits[i][1])>0.55: return True return False def collision(self): if self.explicit: return self.explicitCollision() return self.coll def goalReached(se...
The code defines a reward function that returns -1 for out-of-bounds or collision, 10 for reaching the goal, twice the partial goal value if a partial goal is reached, and 0 otherwise. Its main task is to calculate an agent's reward based on environmental conditions in a reinforcement learning context.
def getReward(self): if self.outOfBounds(): return -1 if self.collision(): return -1 if self.goalReached(): return 10 if self.partialGoalReached()[0]: return 2*self.partialGoalReached()[1] return 0
def solomonEncoder(message: list, blockLen: int, isWord:bool = False) -> list: if isWord: temp = [] for letter in message: temp.append(ord(letter)) #find ASCII code for a symbol, convert string to array of numbers message = temp codeLen = blockLen-len(message) #length of ad...
The code tests a Solomon encoding/decoding process by validating message length, encoding the input, optionally corrupting it, decoding, and comparing results. It checks if the message length is valid, encodes using `solomonEncoder`, corrupts data if specified, then decodes with `solomonDecoder`, printing original and ...
def test(message, blockLen, isWord: bool = False, toCorrupt: bool = False, numberOfCorruptions: int = 0): #check valid messagelength if len(message) >= blockLen: print("MessageLength must be greater than message") return #encode message and print resulting encoded message encod...
def cycle(s): """ Yield elements of s cyclically """ n = 0 while True: yield s[n%len(s)] n += 1 def draw_simplex(S, colours): """ Draw the simplex S in the colour given by the colour generator colours. """ # Put the vertices of the simplex in an array for plotting, ...
The code implements the Nelder-Mead simplex algorithm to minimize a function `func(x)` starting from an initial guess `x0`. It constructs an initial simplex, iteratively updates it via reflection, expansion, contraction, or shrinkage based on function evaluations, and terminates when simplex vertices or function values...
def neldermead(x0, func, tolx=1e-3, tolf=1e-3, Niter=1000, draw=True, interact=True): """ Nelder Mead optimisation of func(x) using the Nelder-Mead simplex algorithm. Arguments --------- x0 Initial guess (vector/list) func The function to be minimised. func(x) should ...
def _train_step(self, batch): """Train model one step.""" # parse batch vqidx, aux, mel, prompt, y, xlens, prompt_lens = batch vqidx = vqidx.to(self.device) mel = mel.to(self.device) aux = aux.to(self.device) prompt = prompt.to(self.device) vqvec = torch.c...
The main task of the code is to perform one epoch of model training. It iterates through training data batches, executes training steps, checks logging/evaluation/save intervals (on rank 0), handles early termination if training finishes, updates epoch counters, logs progress, and sets distributed sampler epochs for sh...
def _train_epoch(self): """Train model one epoch.""" for train_steps_per_epoch, batch in enumerate(self.data_loader["train"], 1): # train one step self._train_step(batch) # check interval if self.config["rank"] == 0: self._check_log_interv...
def create_table4_C1(options, table4_full): table4 = [] table4_format = [] for i in range(len(options)): if i == 0: if options[i] == 1: table4.append(table4_full[0:3]) continue else: table4.append(table4_full[3:6]) ...
The main task of the code is to classify a user's health status based on their responses to 11 questions about menstrual patterns, lifestyle, and family medical history. It uses predefined fuzzy logic tables (table2, table4_full_c1) to map answers to risk categories (VHR, HR, R) and calculate a classification result (c...
def classification_C1(choices): global decision_matrix global weight options = choices questions = [ "Are you getting periods regularly (on time)?", "What is the typical length of your menstrual cycle?", "What is the usual duration of the flow?", "How heavy would you say...
def create_table4_Crest(options, table4_full): table4 = [] table4_format = [] for i in range(len(options)): if i == 0: if options[i] == 5: table4.append(table4_full[0:3]) continue elif options[i] == 4: table4.append(table4_full...
The main task of the code is to classify responses to psychological screening questions into categories like anxiety, social phobia, and body image issues using a structured scoring system. It processes user answers, applies fuzzy logic, and returns classification results (crest) and indices (crest_indicies) indicating...
def classification_Crest(choices): global weight global decision_matrix options = choices questions = [ # C2 "How often did you feel tired out for no good reason?(D)", "How often did you feel nervous?(A)", "How often did you feel so nervous that nothing could calm you do...
def get_straight_course(self, dl): ax = [0.0, 30.0] ay = [0.0, 1.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) return cx, cy, cyaw def initialize_obstacles(self,NUM_OF_OBSTACLES): coordinateX=[] coordinateY=[] ...
The main task of the code is to execute a Model Predictive Control (MPC) path-following algorithm along a straight-line trajectory. It generates a reference path, initializes obstacles, sets an initial state, and runs the controller to track the path while avoiding obstacles. The code then visualizes the planned path, ...
def main_only_mpc(self): print("I am gonna follow a stright line ") dist_step= 1 path_planning = False path_x,path_y,path_yaw = self.get_straight_course(dist_step) ox,oy,velX,velY = self.initialize_obstacles(0) initial_state= State(self.gem_pos_x , self.gem_pos...
def get_straight_course(dl): ax = [0.0, 24.0] ay = [0.0, 1.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) return cx, cy, cyaw def initialize_obstacles(NUM_OF_OBSTACLES): coordinateX=[] coordinateY=[] velX =[] velY =[] for i in...
The code simulates a path tracking task using an MPC controller on a straight course with obstacles. It initializes a path, sets up obstacles, defines an initial state, and runs the controller to track the path. The results are visualized by plotting the reference path and the vehicle's tracking trajectory.
def main_only_mpc(): print("i am here") dist_step= 1 path_planning = False #path_x,path_y,path_yaw = get_right_turn(dist_step) #path_x,path_y,path_yaw = get_forward_course(dist_step) path_x,path_y,path_yaw = get_straight_course(dist_step) ox,oy,velX,velY = initialize_obstacles(0) ...
def optimal_solution(sort_list): sorted_list = quickSort(sort_list) # returns the median. return sorted_list[int(len(sort_list) / 2)] def sum_of_distances(list_sum): sumOfDistances = 0 list_final = quickSort(list_sum) optimal = optimal_solution(list_final) for i in range(0, len(list_final)):...
The main task is to determine the optimal location for a food truck by analyzing distances from a file. It uses Quick Sort and Quick Select algorithms to compute the optimal position, comparing their execution times and results. The code reads input data, processes distances, calculates the optimal point, and prints th...
def main(): # read the file if len(sys.argv) < 3: with open(sys.argv[-1], 'r') as f: distances = f.readlines() distances_list = [] for string in distances: distances_truck = string.rstrip('\n').split(" ") distances_list.append(int(dista...
def pil2pixmap(self, im:Image.Image)->QPixmap: # function to convert pil image to pyqt pixmap r, g, b, a = im.split() im = Image.merge("RGBA", (b, g, r, a)) data = im.tobytes("raw", "RGBA") qim = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32) pixmap = QPixmap.fromImag...
The main task of the code is to update the system's state using the RK4 numerical method, refresh the graphical display with the new state, and update the status based on the updated state variables. It performs a time-step simulation, visualizes results in real-time, and synchronizes UI elements with the current syste...
def timeout(self): self.x = self.rk_solver.RK4(self.x,self.u,self.tau) self.canvas.setPixmap(self.pil2pixmap(self.draw())) self.update_status(self.x,self.u)
def pil2pixmap(self, im:Image.Image)->QPixmap: # function to convert pil image to pyqt pixmap r, g, b, a = im.split() im = Image.merge("RGBA", (b, g, r, a)) data = im.tobytes("raw", "RGBA") qim = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32) pixmap = QPixmap.fromImag...
This code initializes and executes a Dynamic RRT (Rapidly-exploring Random Tree) path planning algorithm. It creates a planner instance, generates a path to a target, and if successful, traces back the path nodes. It then simulates the path using RK4 integration, updates the system state, visualizes each step, and mana...
def start_dyn_rrt(self): self.is_rrt_started = True rrt_planner = DynRRTPlanner.DynRRTPlanner(self.world_size,self.target,self.obstacles,self.dynamics,self.x,self.max_steer,self.max_velocity,self.tau,1000) target_node = rrt_planner.rrt() if target_node is not None: transition...
def write(csvFile, row): writer = csv.writer(csvFile) writer.writerows([row]) def noisy_circle(size, radius, noise): img = np.zeros((size, size), dtype=np.float64) # Circle row = np.random.randint(size) col = np.random.randint(size) rad = np.random.randint(30, max(30, radius)) draw_circ...
The main task of the code is to generate a training dataset of noisy circular images. It creates `PIC_NUM` images of size `PICTURE_SIZE` with random noise levels, saves each as a `.npy` file and PNG image, and logs parameters (row, column, radius) in a CSV file. The dataset is stored in specified directories, with each...
def train_set(): number_of_images = PIC_NUM picture_size = PICTURE_SIZE max_radius = picture_size // 2 level_of_noise = NOISE_CREATE with open("train_set.csv", 'w', newline='') as outFile: header = ['NAME', 'ROW', 'COL', 'RAD'] write(outFile, header) for i in range(number_o...
def noisy_circle(size, radius, noise): img = np.zeros((size, size), dtype=np.float64) # Circle row = np.random.randint(size) col = np.random.randint(size) rad = np.random.randint(30, max(30, radius)) draw_meta(img, row, col, rad) # Noise img += noise * np.random.rand(*img.shape) re...
The code evaluates a circle detection model's performance on noisy images by comparing detected circles with ground-truth parameters using IoU (Intersection over Union). It iterates through validation images, generates noisy circles, detects them with a pre-trained model, and records IoU scores. If detection accuracy e...
def main(): results = [] model_name = f'saved_models/{MODEL_NAME}' best_count = 0 for i in range(PIC_NUM_VALIDATE): params, img = noisy_circle(PICTURE_SIZE, PICTURE_SIZE // 2, NOISE_TEST) detected = find_circle(img, model_name) result = iou(params, detected) if (params[0]...
def extract_Params(star): starname = starfinder(star) mh = float(MH_finder(star))+0.0 lg = float(Logg_finder(star)) tef = float(Teff_finder(star)) return starname, tef, mh, lg def estimate_snr_from_flux(star_spectrum,points): ## WARNING: To compare SNR estimation between different spectra, they ...
The code determines astrophysical parameters (teff, logg, MH, etc.) of a star using spectral analysis. It resamples the star's spectrum, iterates over linemasks to analyze specific spectral regions, and computes best-fit parameters via synthetic spectra. Results, including uncertainties and chi-square metrics, are stor...
def parameters(star): starname,t, m, l = extract_Params(star) #getting template parameters from spectrum name star_spectrum = ispec.read_spectrum(folder + star) #opening normalized spectra star_params = [starname,0,0,0,0,0, 'ASPCAP'] #Resample spectrum wavelengths = np.arange(np.min(star_s...
def board(): grid = [] for line in open("game_file.txt", "r"): row = [int(cell) for cell in line.split() if cell != ''] grid.append(row) return grid def draw_square(x, y, color): left, top = x * size, y * size if color != WHITE: pygame.draw.rect(screen, WHITE, (top - 1, left ...
The code displays a dynamically updating game board with randomly colored cells, cycling through generations. It initializes a board, iterates over rows/columns to draw cells with random colors (or white for non-1 cells), updates the board state, and refreshes the display every 0.5 seconds to create an evolving visual ...
def game_display(rows): this_gen = board() user_choice = '' #while user_choice != 'x': while True: #color = random.choice(COLORS) for x in range(rows): for y in range(rows - 1): color = random.choice(COLORS) cell = this_gen[x][y] ...
def total_weight(m): """Return the total weight of m, a planet or mobile. >>> t, u, v = examples() >>> total_weight(t) 3 >>> total_weight(u) 6 >>> total_weight(v) 9 """ if is_planet(m): return size(m) else: assert is_mobile(m), "must get total weight of a mob...
The main task of the code is to calculate torque by multiplying the total weight at the end of an arm by the length of the arm. It uses the `total_weight` function to determine the weight at the arm's end and the `length` function to get the arm's length, then returns their product as torque.
def torque(arm): return total_weight(end(arm)) * length(arm)
def read_threads(self): if self.login(): try: # create gmail api client service = build('gmail', 'v1', credentials=self.creds) self.service_obj = service threads = service.users().threads().list(userId='me', labelIds=['INBOX']).execute(...
The code's main task is to process threads by reading and cleaning their messages, aggregating each thread's messages into a single string, classifying them as SPAM or not using a classifier, and flagging SPAM threads. The process iterates through all threads, utilizing the classifier collectively to determine spam sta...
def run(self): """ 1. Read the threads, and get all the messages inside threads and the clean them up 2. Run the messages in a thread collectively through the classifier(to build ...)TODO, 3. Flag the Thread either as SPAM or None SPAM, 4. Repeat for all the thraeds. """ ...
def disaster_distribution(self, deck: int): dis_left = self.num_disasters_left() + self.num_catastrophes_left() if dis_left == 0: return {0: 1.0} no_dis_prob = select_prob(0, 5, dis_left, deck) one_dis_prob = select_prob(1, 5, dis_left, deck) redeal_prob = 1 - no_dis_...
This function calculates the probability distribution of damage values for diamond, cross, moon, and total damage types based on a given deck, link configuration, and reduction factor. It considers both disasters and catastrophes, their probabilities, and their damage outputs, aggregating results into distributions tha...
def damage_distribution( self, deck: int, links: Tuple[int, int, int], reduction: int = 0, ): diamond_link, cross_link, moon_link = links diamond_damage: Dict[int, float] = defaultdict(lambda: 0.0) cross_damage: Dict[int, float] = defaultdict(lambda: 0.0) ...
def get_distance(coord: np.ndarray) -> np.ndarray: d_theta = np.pi - np.abs(np.pi - np.abs(coord[:, 1]-coord[:, np.newaxis, 1])) distance = np.cosh(coord[:, 0]) * np.cosh(coord[:, np.newaxis, 0]) distance -= np.sinh(coord[:, 0]) * np.sinh(coord[:, np.newaxis, 0]) * np.cos(d_theta) with warnings.catch_wa...
The code generates heatmaps to visualize the impact of moving a specific vertex in a graph on routing scores. It compares initial and modified configurations by recalculating metrics (greedy closest neighbor, routing scores) across positions within a disk, plotting the difference as a heatmap. The function also overlay...
def vertex_move_improvement_heatmap(path, moved_vertex, resolution=64): subplot_titles=[ 'a) ', 'b) ' ] fig = make_subplots( rows=1, cols=2, subplot_titles=subplo...
def get_initial_crop_demand_data(self): cropList=[] InAcres=[] mycursor = mydb.cursor() mycursor.execute("select CropType, Acerage from demanddata GROUP BY CropType") for row in mycursor: cropList.append(str(row[0])) InAcres.append(str(r...
This code sets up a GUI for a crop management application, initializing widgets like text editors, buttons, combo boxes, and data tables. It configures layouts, connects UI elements to functions, and prepares for data retrieval and display. The interface includes sections for crop status, market data, seed information,...
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1375, 815) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.textEdit_cropstatus = QtWidgets.QTextEdit(self.centralwidget) self....