dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _check_edge_collision(self): """Adds point and resets ball if there is a collision with the edge""" if not self.ball_out: # Ball goes out on the right side: AI gains a point if self.rect.left >= self.screen_rect.right: self.pong_game.ai_points += 1 ...
The main task of the code is to check for collisions in a game environment by calling three methods: edge collision, paddle collision, and wall collision. This ensures proper interaction handling between game objects and boundaries/paddles, likely in a physics-based or arcade game simulation.
def _check_all_collisions(self): self._check_edge_collision() self._check_paddle_collision() self._check_wall_collision()
def update_robot_status(self, status): """ Updates robot status :param status: :return: """ self.robot_status = status def think_decisions(self): """ Thinks of the optimal path before starting mission :return: """ # tree = self.grow...
The code manages a robot's operational states in a loop, checking its status (IDLE, READY, IN_MISSION, etc.) and performing corresponding actions like logging, decision-making, mission execution, charging requests, or F-measure restoration. It maintains a 1 Hz loop using `rospy.Rate(1)` to handle state transitions and ...
def run_operation(self): """ Among the feasible areas, pick randomly the next area to monitor :return: """ rate = rospy.Rate(1) while not rospy.is_shutdown(): if self.robot_status == self.IDLE: pu.log_msg(self.robot_id, 'Robot idle', self.debu...
def show_pause_menu(self): self.paused = True self.menu = MenuScene('Paused', 'Highscore: %i' % self.highscore, ['Continue', 'New Game']) self.present_modal_scene(self.menu) def tile_for_touch(self, touch): touch_pos = self.root_node.point_from_scene(touch.location) for t in self.tiles: if t.frame.contains...
This code handles touch events by checking if the touch is in the bottom-left corner to trigger a pause menu, ensuring no tile is already selected, locating the touched tile, playing a sound effect, and selecting the tile if valid.
def touch_began(self, touch): if touch.location.x < 48 and touch.location.y > self.size.h - 48: self.show_pause_menu() return selected = [s for s in self.tiles if s.selected] if selected: return t = self.tile_for_touch(touch) if t: sound.play_effect('ui:click2') self.select_from(t)
def move_paddle(self): dx = self.paddle_target - self.paddle.position.x if abs(dx) > paddle_speed: dx = paddle_speed * cmp(dx, 0) self.paddle.position += dx, 0 def update_all_balls(self): for ball in list(self.balls): ball.update_effects() # Update in multiple steps, so a ball cannot pass through a bri...
The code's main task is to update game elements in a loop: move the paddle, update all balls' positions, handle power-ups, check if all balls are lost to trigger a loss, and verify if all bricks are cleared to signal level completion. It manages game state transitions and interactions between components like paddles, b...
def update(self): self.move_paddle() self.update_all_balls() self.update_powerups() if not self.balls: self.ball_lost() if not self.bricks: self.level_finished()
def get_cosine_autosimilarity(an_array): """ Computes the autosimilarity matrix with the cosine similarity function. The cosine similarity function is the normalized dot product between two bars, i.e.: .. math:: s_{x_i,x_j} = \\frac{\\langle x_i, x_j \\rangle}{||x_i|| ||x_j||} Parameters ...
The function `switch_autosimilarity` computes an autosimilarity matrix for a given input array using specified similarity measures. It supports three methods: cosine similarity (normalized dot product), covariance/autocorrelation (centered feature dot product), and RBF (exponential of negative Euclidean distance). Para...
def switch_autosimilarity(an_array, similarity_type, gamma=None, normalize=True): """ High-level function to compute the autosimilarity of this matrix. Expects a matrix of shape (Bars, Feature representation). Computes it with different possible similarity function s_{x_i,x_j} (given two bars denoted ...
def read_navigation_subsystem(data: str) -> List[str]: navigation_subsystem = data.split('\n') return navigation_subsystem def discard_corrupted_lines(navigation_subsystem: List[str]) -> List[str]: uncorrupted_lines = [line for line in navigation_subsystem if find_first_illegal_character(line, '') is None]...
The code processes a navigation subsystem's data by discarding corrupted lines, calculating completion scores for remaining incomplete lines, and returning the median of these scores as an integer. It reads input data, filters valid lines, computes scores, and determines the middle value. Your return
def get_part_2_answer(data: str) -> int: navigation_subsystem = read_navigation_subsystem(data) incomplete_lines = discard_corrupted_lines(navigation_subsystem) line_completion_scores = [calculate_line_completion_score(line) for line in incomplete_lines] middle_score = int(np.median(line_completion_scor...
def read_hydrothermal_vents(data: str) -> List[Vent]: hydrothermal_vents = [] for vent in data.split('\n'): coordinates = vent.split(' -> ') vent_start = tuple(int(c) for c in coordinates[0].split(',')) vent_end = tuple(int(c) for c in coordinates[1].split(',')) hydrothermal_ven...
Your return The main task of the code is to count the number of coordinates where two or more horizontal or vertical hydrothermal vents overlap. It processes input data by filtering horizontal/vertical vents, counting occurrences per coordinate, and returning the count of coordinates with multiple overlapping vents.
def get_part_1_answer(data: str) -> int: hydrothermal_vents = read_hydrothermal_vents(data) horizontal_and_vertical_vents = get_horizontal_and_vertical_vents(hydrothermal_vents) vents_per_coordinate = count_vents_per_coordinate(horizontal_and_vertical_vents) coordinates_with_multiple_vents = get_coordin...
def read_hydrothermal_vents(data: str) -> List[Vent]: hydrothermal_vents = [] for vent in data.split('\n'): coordinates = vent.split(' -> ') vent_start = tuple(int(c) for c in coordinates[0].split(',')) vent_end = tuple(int(c) for c in coordinates[1].split(',')) hydrothermal_ven...
The code processes hydrothermal vent data to count how many coordinates have multiple vents. It reads vent data, tallies occurrences per coordinate, identifies coordinates with multiple vents, and returns their count. The main task is to determine the number of overlapping vent coordinates in the input data. Your retur...
def get_part_2_answer(data: str) -> int: hydrothermal_vents = read_hydrothermal_vents(data) vents_per_coordinate = count_vents_per_coordinate(hydrothermal_vents) coordinates_with_multiple_vents = get_coordinates_with_multiple_vents(vents_per_coordinate) return len(coordinates_with_multiple_vents)
def initialize_population(population=POPULATION,popsize=POPSIZE): for i in range(popsize): chromosome = np.random.choice([1,0], size=(GENES*GENES),p=[0.5,0.5]) population.append(chromosome) return population def evaluate_population(population,period): selected_parents = [] for itr in pop...
The code implements a genetic algorithm to evolve a population of solutions over multiple generations. It initializes a population, evaluates and selects parents, applies crossover and mutation operations to generate offspring, and iterates for a specified number of generations. The process stops early if the populatio...
def genetic_algorithm(period=2,crossover_rate=0.2,mutation_rate=0.6,generations=2): population = initialize_population() selected_parents = population for i in range(generations): selected_parents = evaluate_population(population,period) if len(selected_parents) < 10: return selec...
def fetch_logs_in_range(w3, rule, block_range): filter_params = get_filter_params(rule, block_range) logs = w3.eth.get_logs(filter_params) return logs def get_address_from_log(rule, log): if rule["addressTopicIndex"] is not None: addressTopic = log.topics[rule["addressTopicIndex"]] retur...
The code monitors Ethereum blocks using `w3`, processes logs based on given `rules`, checks if users are registered in `r`, and stores encounters with a probability-based filter. It iterates through block ranges, handles registered users, and pauses when no new blocks are found.
def monitor(w3, r, rules): prev_block_number = w3.eth.block_number # prev_block_number = 21192556 while True: current_block_number = w3.eth.block_number block_number = min(current_block_number, prev_block_number + MAX_BLOCK_RANGE) print(f"fetching logs in range {prev_block_number}.....
def add_section(self, partOfcode): return f"""<section>{partOfcode}</section>""" def Tailwin_Operation(self, html): # Change The colors Colored_html = self.Tailwin_Random_Color_changer(html) # Change the images Image_Changed = self.change_images(Colored_html) return Imag...
The main task of the code is to generate a web page by concatenating UI sections (Menu, hero, about, cards, footer) processed via Tailwin_Operation, wrapping them in a base template with `BaseCode`, and applying text transformations via `change_Text` to produce the final output.
def create_page(self): self.code = '' # create code...... self.code = self.code + \ self.add_section(self.Tailwin_Operation(self.Menu)) self.code = self.code + \ self.add_section(self.Tailwin_Operation(self.hero)) self.code = self.code + \ se...
def Lambda_psi_func(self, psi, psif): return psi-psif def dLambdadpsi0_func(self, psi0, psi0f): #return 1./(1.-psi0+psi0f) return 1. def phi_psi_func(self, psi, psi0f, sfe): Lambda = self.Lambda_psi_func(psi,psi0f) phi = self.phi_Lambda_func(Lambda, sfe) return phi def dLambdadphi_func(self, phi, sfe, Mcrit...
The function computes the derivative of `dpdpsi0` with respect to `psi0`, using interpolation and normalization. It calculates `Lambda` and `phi` values, their derivatives, and combines them to determine `dpdpsi0` for indices where `psi0 > psi0f`. If normalization (`norm`) is zero, it applies a delta function approxima...
def dpdpsi0_func(self, psi0, psi0f, sfe): dpdpsi0 = np.zeros(len(psi0)) ipsi0f= np.argmin(np.absolute(psi0-psi0f)) dlogpsi0 = np.log10(psi0[1])-np.log10(psi0[0]) isub = np.where(psi0>psi0f)[0] Lambda = self.Lambda_psi_func(psi0[isub],psi0f) dLambdadpsi0 = self.dLambdadpsi0_func(psi0,psi0f) phi = se...
def phi_psi_func(self, psi, psi0f, sfe): Lambda = self.Lambda_psi_func(psi,psi0f) phi = self.phi_Lambda_func(Lambda, sfe) return phi def sigmaF_func(self,psi0, phi, psi0f): sigmaL = self.sigmaL_func(phi) #Weighting function to avoid overshoot below 'field flux' W1 = special.erf((np.log(psi0)-np.log(psi0...
This function computes a convolution integral of dpdpsi0 with a function derived from psi_space, sigmaF, and dpdx_func. It calculates dpdpsi by iterating over psi_space values, evaluating the integrand dpdpsi0 * dpddpsi / psi0, and applying numerical integration (trapz) for each point. The sigmaF array, determined by p...
def convolve_psi(self,dpdpsi0, psi0,psi0f, sfe, iflg=False,extinct=False): psi_space = psi0 dpdpsi = np.zeros(len(psi0)) if not extinct: phi = self.phi_psi_func(psi0, psi0f, sfe) sigmaF = self.sigmaF_func(psi0, phi, psi0f) sigmaF[np.where(psi0<psi0f)] = self.sigmaFf else: sigmaF= self.sigmaFf...
def tff_func(self, rhog): return np.sqrt(3*np.pi/(32.*self.G*(rhog*self.MSun/self.pc**3.)))/self.Myr def ssfrff_func(self, mach=None,sig_rho=None, qvir=None): if mach==None: mach=self.mach if qvir==None: qvir = self.qvir if sig_rho==None: sig_rho = self.sig_rho_func(mach) """ssfrff = 0.014*(qvi...
This function calculates the fragmentation fraction (fcoll) using input parameters or object attributes, computes derived values like tff, tsn, and tff2d, normalizes fcoll to ensure it does not exceed 1, and returns fcoll or additional intermediate values based on the 'rvals' argument.
def fcoll_func(self, mach=None, omega0=None, rho0=None, rvals='fcoll'): if mach==None: mach =self.mach if omega0==None: omega0 = self.omega0 if rho0==None: rho0=self.rho0 tff = self.tff_func(rho0) ssfrff = self.ssfrff_func(mach) tsn = self.tsn mean_tfb = self.tfb_fcoll_func(1.0, tff, tsn) tf...
def ssfrff_func(self, mach=None,sig_rho=None, qvir=None): if mach==None: mach=self.mach if qvir==None: qvir = self.qvir if sig_rho==None: sig_rho = self.sig_rho_func(mach) """ssfrff = 0.014*(qvir/1.3)**(-0.68)*(mach/100.)**(-0.32) erf_arg = (sig_rho**2 -np.log(0.68*qvir**2*mach**4))/(2.**1.5*si...
The function calculates star formation efficiency (SFE) by combining parameters like free-fall time (tff), star formation rate (ssfrff), and snap time (tsnap). It uses surface density, mass, and time-scale conversions to derive SFE via a formula involving efb (feedback-limited efficiency) and einc (snap-limited efficie...
def sfe_func(self, x, sigma0=None, omega0=None, mach=None,rho0=None, ssfrff=None, Q=None, tsnap=10.0): if sigma0==None: sigma0=self.sigma0 if omega0==None: omega0= self.omega0 if mach==None: mach= self.mach if rho0==None: rho0 = self.rho0 if Q==None: Q =self.Q if ssfrff==None: ssfrff = s...
def dpdchi1_func(self, chi_d, x, sfe): #Step 1: define phi dummy array phi_dd = np.logspace(-3, 4, 400) #Step 2: define gamma dummy array gamma_dd = np.logspace(-4, 4,500) #Step 3: get chi(gamma, phi) and also dchi/dphi at each Lambda phi_mg, gamma_mg = np.meshgrid(phi_dd, gamma_dd, indexing='ij') ...
The function `dpdpsi0ext_func` computes the derivative of a probability distribution (`dpdpsi0`) by integrating over parameters `chi` and `phi`, involving numerical methods and truncation. It processes input arrays (`psi0`, `x`, `sfe`), truncates the PDF below a threshold (`psi0f`), generates a `chi` range, and iterati...
def dpdpsi0ext_func(self, psi0, psi0f, x, sfe, convolve=True): dpdpsi0 = np.zeros(len(psi0)) #Step 1: truncate PDF below psi0f ipsi0f= np.argmin(np.absolute(psi0-psi0f)) dpsi0 = psi0f-psi0[ipsi0f-1] isub = np.where(psi0>psi0f)[0] #Step 2: Establish a phi for each chi, Lambda #(Chi range a bit arbit...
def get_h0(self): sigma0=self.sigma0 rho0 = self.get_rho0() self.h0 = sigma0/(2.*rho0) return self.h0 def tildesfe_func(self, MMC, sigma0=None, omega0=None, mach=None,rho0=None, ssfrff=None, Q=None, tsnap=10.0): if sigma0==None: sigma0=self.sigma0 if omega0==None: omega0= self.omega0 if mach==None...
This function calculates the field flux (F0f) by integrating the initial cluster mass function (ICMF) over spatial and mass scales, incorporating extinction effects and normalization factors. It determines the mean separation of star-forming regions, computes extinction correction terms, and derives the final flux usin...
def F0f_func(self): #get scale height of galactic disc h0 =self.get_h0() #Calculate the mean cluster radius MMC_space = np.logspace(-5, 10, 100) sfe = self.tildesfe_func(MMC_space) #Define phispace by MMC_space phispace = MMC_space*sfe/self.Mcrit #Get ICMF (un-weight by phi) dpdphi = self.dpdphi_f...
def xc_gamma_func(self, gamma,x): return x*(1.+gamma**2.)**(5./2.) def dpdx_func(self, x, sig=None, mulnx=None, mach=None): if mach==None: mach=self.mach if sig==None: sig = self.sig_rho_func(mach) if mulnx==None: mulnx = -0.5*sig**2. dpdx= 1./(np.sqrt(2.*np.pi)*sig*x)*np.exp(-((np.log(x)-mulnx)**...
The code computes the probability distribution $ pS $ by integrating over $ \phi $ for given $ \psi_0 $, using interpolated $ \gamma $ values and precomputed functions. It normalizes the integral of $ \phi $-dependent terms to derive $ pS $ for each $ \psi_0 $, returning the normalized probabilities.
def pSphi0_func(self, psi0,x,sfe, psi0f): phi_dd = np.logspace(-5,5,100) gamma_dd = np.logspace(-5,5,1000) phi_mg, gamma_mg = np.meshgrid(phi_dd, gamma_dd, indexing ='ij') psi0ext = self.psi0ext_phi_gamma_func(phi_mg, gamma_mg, x, sfe, psi0f) gamma_func = interpolate.interp2d(phi_mg, psi0ext, gamma_m...
def get_rho0(self, Q=None, sigma0=None, omega0=None): if sigma0==None: sigma0=self.sigma0 if omega0==None: omega0 = self.omega0 rho0 = 3.*(omega0/self.Myr)**2./(np.pi*self.G*self.Q**2.) self.rho0 = rho0*self.pc**3./self.MSun return self.rho0 def get_mach(self,sigma0=None,Q=None,omega0=None): if ...
This code initializes a class with astrophysical constants and parameters for star formation modeling, setting up variables related to gravity, feedback, and stellar dynamics. It configures initial conditions, computes derived quantities like density and Mach number, and sets limits for star-forming region masses. The ...
def __init__(self, sigma0, Q, omega0, mach=None, rho0=None, qvir = 1.3,tsn = 3., Mcrit=1e3, MMCmin=10.0, mumass=0.5, timeit=False, Lcrit=8e38, oname='sbeclass_instance'): self.initialize=True self.time=timeit pi = np.pi self.G = 6.67e-11 # units: m**3 kg**-1 s**-2 self.MSun = 1.989e30 # units: kg self.pc =...
def rhog_rhost_func(self, rhost): rhog_space = np.logspace(-20, 20, 2000) x_space = rhog_space/self.rho0 rhost_space = rhog_space*self.sfe_func(x_space) rhog_rhost_func_interp = interpolate.interp1d(np.log10(rhost_space), np.log10(rhog_space)) return 10.**rhog_rhost_func_interp(np.log10(rhost)) def sfe_fu...
This function computes the derivative of a physical quantity (F) with respect to density (y) and a parameter (ψ) using interpolation, convolution, and normalization. It processes input density arrays (rho_st) and f_fuv values, calculates gas density ratios, star formation efficiency (sfe), and gradients. Depending on ψ...
def d2Fdydpsi_func(self,rho_st,f_fuv, ext=False, convolve=True, phi_res=500, rfact=16.0, PFL=1e-20): rho0=self.rho0 rho_g = self.rhog_rhost_func(rho_st) x = rho_g/rho0 sfe = self.sfe_func(x) xd2pdxdpsi = np.zeros((len(x),len(f_fuv))) #Get value of x (gas over density) from rho_st x = rho_st/(sfe*rho0) ...
def dpdx_func(self, x, sig=None, mulnx=None, mach=None): if mach==None: mach=self.mach if sig==None: sig = self.sig_rho_func(mach) if mulnx==None: mulnx = -0.5*sig**2. dpdx= 1./(np.sqrt(2.*np.pi)*sig*x)*np.exp(-((np.log(x)-mulnx)**2.)/(2.*sig**2.)) return dpdx def sfe_func(self, x, sigma0=None, o...
The main task of the code is to compute and visualize a 2D probability distribution function (PDF) of stellar density (rhost) and FUV flux (fuv), normalizing and plotting the derived 2D PDF using logarithmic scales. It calculates grid values, processes the data with optional convolution, generates a heatmap with contou...
def plot_d2Fdydpsi(self,convolve=True,xlims = [-6.,4.5], ylims = [-.2,5.0],phlab=None, enclab=None, pmin = 1e-3, pmax = 1.1e-1, extinct=False, resx=100, resy=1000, sl=False, plot=True,interactive=True): if type(xlims)==type(None) or type(ylims)==type(None): rho_ = self.rho0 mach_ = self.mach x_tmp = np.lo...
def _validateDocObj(docobj): ret = [] for identifier in docIds: if identifier in docobj: ret.append(identifier) return ret def _getDocCollection(): client = _connect() db = client["NEWS_ANALYZER"] # Name of Database documents = db["Documents"] # Name of Collection retur...
This function updates a document in a collection using provided identifiers and update parameters. It validates input identifiers, constructs a query with user credentials and IDs, updates the document if matching records exist, and returns the modified document if successfully updated.
def updateDocument(username, idObj, update): # Validate that this json object has the correct identifiers for a query ids = _validateDocObj(idObj) # If no valid identifiers are passed, return None if not ids: return None # Add valid identifiers to query query = dict() query["Delete...
def dy_dx(state, args): Jacobian = np.zeros((2*len(args[0]), len(state))) ARGS = [(i, state, args) for i in range(len(state))] jac_column_pool = multiprocessing.Pool() result_arr = jac_column_pool.map(dy_dx_col, ARGS) jac_column_pool.close() jac_column_pool.join() result_arr.reverse() ...
The function `LeastSquares` performs a **least squares optimization** to refine an initial state estimate (`state_est`) by minimizing weighted residuals derived from observational data. It sets bounds for parameters (position, velocity, fragmentation, time offsets) and uses the `least_squares` solver with a Jacobian (`...
def LeastSquares(state_est, args): ''' Where the magic happens ''' logger = logging.getLogger('trajectory') # Bounds for the least squares minimisation pe = 40e3; ve = 5e3; n_frag = args[6] # 40km pos err, 5km/s vel err state_lb = state_est.copy(); state_lb[:3] -= pe; state_lb[3:6] -= ve; ...
def FirstApprox(ObsTables, kwargs): ''' Using SLLS code to best optimise the trajectory then generate X0_est, where X0_est = [x0, y0, z0, vx0, vy0, vz0, beta0, sigma0] ''' logger = logging.getLogger('trajectory') # Calculate a first radient approximation logger.debug('Calculating ini...
The code's main task is to estimate an object's trajectory using observational data by iteratively refining the solution. It first computes an initial approximation of the state, then removes problematic observations through sanity checks. After applying least squares optimization to determine the trajectory (positions...
def main_using_table(ObsTables, kwargs): logger = logging.getLogger('trajectory') # First approximation [state_est, args, slls_args] = FirstApprox(ObsTables, kwargs) # Catch the dodgy events with some sanity checks kept_obs = np.ones(len(ObsTables)).astype(bool) '''''' obs_to_remo...
def residuals(state, args): [UV_obs, ang_err, v_loc, v_sign] = [args[0], args[1], args[7], args[8]] Pos_est = f(state, args) UV_est = Pos_est / norm(Pos_est, axis=0) v_mag = np.sqrt(1 - state[2]**2 - state[3]**2) UV_rad = np.hstack((state[2:v_loc+2],v_sign*v_mag, state[v_loc+2:])).reshape(...
The function `SLLS` performs nonlinear least squares optimization to estimate the position and radiant vector of an object using camera data. It minimizes residuals between observed and predicted values, computes uncertainties via covariance matrices, and returns triangulated positions, cross-track errors, and metadata...
def SLLS(state0, args, eci_bool=False): """experimental version using scipy optimise instead of custom equations""" [ang_err, Camera_pos, Times_jd, Times_err, NumberTimePts] = args[1:6] # Create the first approximation of x, where X0=[x1,y1,z1,ra_geo,dec_geo,L2,L3,...,Ln] # Include a scaling facto...
def run_cmd(cmd): """Runs a command and returns stdout""" return subprocess.run(cmd, stdout=subprocess.PIPE).stdout.decode('utf-8') def run_zeek_on_files(path, filenames): for f in filenames: if not f.endswith('.zeek'): continue path = path.replace(pkg_script_dir + "/", "") ...
The code sets up Zeek to generate ReST documentation files for Sphinx by configuring environment variables, walking directories to identify Zeek scripts, running Zeek on these files, adjusting file order for special scripts, fixing reference links in generated RST files, and creating a package index for documentation o...
def setup(app): """Zeek will run and generate the ReST files, which Sphinx will then convert to HTML.""" if 'ZEEK_DISABLE_ZEEKYGEN' in os.environ: del os.environ['ZEEK_DISABLE_ZEEKYGEN'] os.environ['ZEEK_ALLOW_INIT_ERRORS'] = "1" zeekpath = pkg_script_dir zeekpath += ":" + run_cmd(['zeek-c...
def update_position(self): if self.has_created_position(): self.log.silly('Position updated') self.position['closed'] = True position = self.client.futures_position_information(symbol=self.config.market) if float(position[0]['entryPrice']) > 0: sel...
The code continuously monitors time intervals to check for updates in position data, candlestick data, and logs. When updates are detected, it triggers position updates, closes positions if conditions are met, notifies via logging, and handles errors with exception tracking. The loop ensures real-time monitoring and ex...
def listener(self): while True: try: now = datetime.datetime.now() if self.interval_check_position.is_update(now): self.update_position() if self.has_created_position() and self.position['closed']: self.c...
def parse_args(): parser = argparse.ArgumentParser( description='Switch between environments in Solidity.' ) parser.add_argument( "path", help="Specify a path to a file or root of a directory containing a `contracts` (immediate) subdirectory." ) parser.add_argument( '...
The main task of the code is to parse command-line arguments, process specified files based on given parameters (comment, environment), handle changes generated from file processing, and manage errors by capturing exceptions, printing error details, and re-raising them for further handling.
def main(): try: args = parse_args() setVerbosity(args.silent, args.verbose) # filenames fns = get_fns(args.path) changes = process_fns(args.comment, args.env, fns) process_changes(changes) except Exception as e: print ('An error ocurred:\n%s' % repr(e)) ...
def createCorpus(stopwords, filename): file = open(filename) j = json.load(file) corpus = [] data_length = len(j[u'data']) #442 for data in tqdm(range(data_length)): paragraph_length = len(j[u'data'][data][u'paragraphs']) #66 for paragraph in range(paragraph_length): #...
The code processes a JSON dataset to analyze linguistic features in questions and their contexts by comparing verb and noun counts between questions and corresponding paragraphs, likely for a question-answering or NLP task. It loads a corpus, iterates through data entries, and uses functions to compute linguistic stati...
def main(): stop_words = set(stopwords.words('english')) # stop_words.union(set(string.punctuation)) corpus = createCorpus(stop_words, "training_sample.json") #print (corpus) #print ("=---=-------") file = open("training_sample.json") j = json.load(file) predictions = {} #id:value ...
def init_slots(): """ Initialize the slots dict """ slots = {} for i in range(configuration.number_runners): slots[i] = True return slots def count_cases(indexes: list): global total_count if len(indexes) == configuration.k: if not increasing_indexes(indexes): ...
The main task of the code is to generate and execute test files simultaneously while tracking progress and execution statistics. It initializes test slots, counts test cases, removes existing scripts, recursively generates new tests, logs success, and writes detailed statistics (total tests, progress, execution time) t...
def execute_and_generate_test(): """ Generate and execute at same time the tests """ global count, total_count, slots, initial_timestamp initial_timestamp = datetime.datetime.fromtimestamp(time.time()) slots = init_slots() count_cases([]) sources.generate_scripts.remove_scripts() rec...
def get_random_file_from_directory(directory, excluded_color=None): """ Returns a random file from the specified directory, considering color. """ files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] if excluded_color is not None and np.any(excluded_color): files...
The code recommends an outfit by selecting random items from categories like Topwear and Bottomwear, ensuring color compatibility between consecutive items. It checks color complementarity, avoids repeating colors, and compiles a cohesive outfit, handling unavailable items by marking them as 'No items available'. The f...
def recommend_outfit(): categories = ['Topwear', 'Bottomwear', 'Shoes', 'Watches'] base_directory = 'd:/test/' outfit = {} last_color = None for category in categories: directory = os.path.join(base_directory, category) file = get_random_file_from_directory(directory, excluded_color...
def _clocking(self, limit, vector): """ Performs clocking for all registers (r1, r2, r3 and r4) :param limit: number of clocking cycles :param vector: either the session key or the frame counter. In each cycle a bit is XORed to the first position. ...
The main task of the code is to generate a key stream using the A5/2 algorithm. It initializes registers with a session key and frame counter via XOR operations, sets specific register bits, runs predefined cycles to discard initial output, and finally generates a 228-cycle key stream. The function returns a pair of ke...
def get_key_stream(self, save_register_states=False, generate_only_send_key=False): """ Performs the following steps: 1. Run A5/2 for 64 cycles and XOR the session key into the registers 2. Run A5/2 for 22 cycles and XOR the frame counter into the ...
def analyse(file): print("\n" + "="*28 + "\n\tGame Stats\n" + "="*28) print("Save File: {}\n".format(file)) with open(file, "r") as filehandler: data = json.load(filehandler) print("Total moves:\t{}".format(len(data[3]))) print("Pieces taken:\t{}".format(len(data[1]))) print("A...
The main task of the code is to analyze multiple chess game files, generate individual heat maps for each game, combine moves from all games into an averaged board state, and produce an aggregated heat map. It also analyzes a single standalone game and creates its heat map, likely for visualizing move patterns or strat...
def main(): analyse("saves/game1.chess") analyse("saves/game2.chess") analyse("saves/game3.chess") analyse("saves/game4.chess") heat_map_file("saves/game1.chess", "stats/game1.png") heat_map_file("saves/game2.chess", "stats/game2.png") heat_map_file("saves/game3.chess", "stats/game3.png") ...
def make_board(): squares = {} # populate with every chess square for x in range(0, 8): for y in range(0, 8): squares[(x, y)] = 0 return squares def heat_map_file(file, save): # "file" is open dir with open(file, "r") as filehandler: data = json.load(filehandler) ...
The main task of the code is to generate heatmaps for chess game files in a directory. It processes 50 files, creating individual heatmaps (e.g., 1.png) and stacking their move data into a cumulative board state. Finally, it generates an aggregated heatmap (avg.png) representing the combined move patterns from all 50 g...
def main_pgn(dir): all_pgn = make_board() for i in range(1, 51): heat_map_file("{}/{}.chess".format(dir, i), "{}/{}.png".format(dir, i)) all_pgn = stack_moves_file(all_pgn, "{}/{}.chess".format(dir, i)) heat_map(all_pgn, "{}/avg.png".format(dir))
def setup(self) -> None: self.output_dir.mkdir(exist_ok=True) session_maker = setup_db() self.session = session_maker() self.browser_manager = BrowserManager(clean_process=not self.skip_process_clean) logging.basicConfig( level=logging.INFO, format="%(asct...
The code's main task is to execute a scraping process by first setting up necessary components, then scraping URLs of boards, followed by scraping data from those boards. It ensures proper cleanup by closing the session in a `finally` block to handle resources safely.
def run(self) -> None: try: self.setup() board_urls = self.scrape_board_urls() self.scrape_boards(board_urls) finally: if self.session is not None: self.session.close()
def create_provenance_id(provenance_id): provenance_definition = { "provenance": { "provenance_type": "user", "record_id": provenance_id, "name": "test_api_outside", "metadata": { "contact_information": { "email": "uqrpo@exa...
The main task of the code is to register a dataset by parsing command-line arguments, loading dataset details from a JSON file, creating a provenance ID, and synchronizing metadata with a specified data catalog. The script processes input parameters, reads dataset information, registers it, and updates metadata in the ...
def main(): """Main function """ global DCAT, PROVID parser = argparse.ArgumentParser(description='Register a dataset') parser.add_argument('FILE', help='dataset details file') parser.add_argument('DATA_CATALOG_URL', help='data catalog url', defau...
def angle_between(self, v1, v2): # Returns the angle between the vectors v1 and v2 in radians v1_u = self.unit_vector(v1) v2_u = self.unit_vector(v2) # clip limits the unit vectors: -1 to 1 # arccos is the arcosine of the vectors. Tha angle between them return np.arccos(n...
The main task of the code is to generate a sweeping path for a polygon by calculating geometric properties (slope, angle, translation) between two vertices, creating inner/outer polygon boundaries, determining directional movement (left/right), and outputting the path for visualization and file storage. It uses vector ...
def get_path(self): # Gets the vector that corresponds to the point. # Distance along the x-axis is x2 - x1 # Distance along the y-axis is y2 - y1 self.delta_x = (self.vertex_2[0] - self.vertex_1[0]) self.delta_y = (self.vertex_2[1] - self.vertex_1[1]) self.vertex_vector...
def monte_carlo(b: Goban.Board, nb_try: int): """ Returns board score on average according to random games. """ board_score = 0 for _ in range(nb_try): board_score += random_game(b) board_score /= nb_try return board_score def evaluate_board_score(b: Goban.Board) -> float...
This function combines alpha-beta pruning with Monte Carlo simulations to evaluate a board's score. It recursively explores legal moves, applying alpha-beta pruning to limit search depth. At terminal states or max depth, it randomly selects between Monte Carlo evaluation (via `monte_carlo`) and direct board scoring. Th...
def alpha_beta_monte_carlo(b: Goban.Board, max_depth=0, alpha=-math.inf, beta=math.inf, maximizing=True, depth=0, p=0.2, nb_try=100) -> float: """Alpha-Beta with Monte Carlo Returns: float: The score of the current board. """ if depth >= max_depth or b.is_game_over(): r = random.Random...
def motorOff(self,motor): self.motorOn(motor,"f",0) def motorOn(self,motor, direction, speed): #cap speed to 0-100% if (speed<0): speed = 0 elif (speed>100): speed=100 if self.board_type=="pico": motorReg = self.MOT_REG_BASE + (2 * (motor - 1)...
This function controls a robot's left turn by setting motor directions. If the board is 'pico', it activates motor B in reverse and motor A forward to turn left, then pauses. For other boards, it sets both motors to the same speed and pauses. The 'speed' parameter adjusts rotation speed, while 'delay' determines turnin...
def left(self,speed=50,delay=0.5): """ Move the robot forward by rotating both motors the same direction. This relies on the robot motors being wired the same way @param speed is how quickly it rotates @param delay is how long the robot will turn right for """ if "pico" i...
def motorOff(self,motor): self.motorOn(motor,"f",0) def motorOn(self,motor, direction, speed): #cap speed to 0-100% if (speed<0): speed = 0 elif (speed>100): speed=100 if self.board_type=="pico": motorReg = self.MOT_REG_BASE + (2 * (motor - 1)...
The code defines a `right` method to turn a robot right by controlling motor directions. It checks the robot's board type: for "pico", it sets motor B forward and motor A reverse; otherwise, it applies equal negative throttle to both motors. The `speed` parameter determines rotation speed, and `delay` specifies how lon...
def right(self,speed=50,delay=0.5): """ Move the robot forward by rotating both motors the same direction. This relies on the robot motors being wired the same way @param speed is how quickly it rotates @param delay is how long the robot will turn left for """ if "pico" i...
def getDoc(e) : trainImg = cv.imread(e) trainImg = cv.cvtColor(trainImg, cv.COLOR_BGR2GRAY) e = re.split('\\\\',e) m = e.pop() e = "\\".join(e) doc_desc_dict[m] = detector.detectAndCompute(trainImg,None) return e def get_Match_Keys(doc_desc_dict, logo_desc_dict) : for doc_filename, doc_d...
The code processes an input list to match document and logo descriptors, filters relevant keys, tests homography for geometric alignment, and generates an output using matched features. It retrieves document data, identifies matching keys between descriptor dictionaries, refines logo matches, selects optimal keys, vali...
def implement(l) : e = getDoc(l) get_Match_Keys(doc_desc_dict , logo_desc_dict) get_Logo_Match_Dict(match_keys) get_good_keys(match_keys) homography_Test(final_matches) p = op(final_matches,logo_parent_dir , e , doc_desc_dict , match_keys ,logo_desc_dict , output_dir) return p
def calc_sfn(sfn, vort, dx, dy, max_iterations=200): """ Calculates the stream function `sfn` from the equation $\nabla^2 \psi = - \omega$. This uses the Jacobi method to find the solution. """ temp = np.zeros_like(sfn) sfn[:] = 0.0 D = 2.*(1./dx**2 + 1./dy**2) for k in range(max_iteratio...
The code simulates natural convection in a 2D incompressible fluid using a vorticity-stream function approach. It initializes a grid, sets parameters (Prandtl and Rayleigh numbers), and evolves the flow by solving the Navier-Stokes equations via finite differences. The simulation updates vorticity and temperature field...
def main(): # Parameters nx = 64 ny = 64 lx = 1. ly = 1. Pr = 10 # CHANGEME to get different physics (Prandtl number) Ra = 1e6 # CHANGEME to get different physics (Rayleigh number) dx = lx/nx dy = ly/ny dt = 0.5*min(dx,dy)**2/(4*Pr) # CHANGEME if you change nx or ny and the si...
def conv2d(inputs, filters, name, kernel_size = 3, strides = 1, padding='same', bias=False, dilation_rate = 1, trainable = True, activation = None, reuse = False): return tf.layers.conv2d(inputs, filters = filters, kernel_size = kernel_size, padding...
The code defines a ResNet-32 inference function that processes input tensors through a series of residual blocks with increasing filter sizes (16 → 32 → 64) and stride adjustments for downsampling. It applies batch normalization, ReLU activation, and global average pooling, culminating in a fully connected layer output...
def inference(input_tensor_batch, n, reuse): with tf.variable_scope('resnet32',reuse = reuse) as scope: conv0 = tf.nn.relu(tf.layers.batch_normalization(conv2d(input_tensor_batch, 16, 'conv0', kernel_size=3, strides=1),training=True)) #pool0 = tf.nn.max_pool(conv0, [1,3,3,1], [1,2,2,1], paddi...
def query_to_video_id(self, q): """Gets the video id from a youtube query. Uses youtube data api. Args: q (str): youtube query, eg. name of a song. Returns: (str): youtube video id. """ res = requests.get("https://www.googleapis.com/youtube/v3/...
This function processes a YouTube video query to download an MP3 file. It converts the query to a video ID, extracts a download URL and file size, then downloads the MP3 with a slight size adjustment. If any step fails, it prints an error and aborts.
def process_video_name(self, video_name): """Take a youtube query and download a .mp3 file of a first result. Args: video_name (str): youtube query. """ video_id = self.query_to_video_id(video_name) if not video_id: print(f"Could not find a video {video_...
def parse_config(): global conf with open("mqtt-agent.yaml", 'r') as stream: try: conf = yaml.load(stream, Loader=yaml.SafeLoader) except yaml.YAMLError as exc: print(exc) print("Unable to parse configuration file mqtt-agent.yaml") sys.exit(1) if not 'name' in conf: # use h...
The main task of the code is to read temperature, pressure, and humidity data from a BME280 sensor, then periodically transmit this data to MQTT and InfluxDB servers based on configuration settings, while handling test modes, errors, and sensor initialization. It also includes chip ID/version checks and ensures proper ...
def main(): global conf, mqtt_client, mqtt_state_topic parse_config() if args.test: conf.pop( 'mqttServer', None ) conf.pop( 'influxServer', None ) if 'mqttServer' in conf: init_mqtt() if 'influxServer' in conf: init_influx() (chip_id, chip_version) = readBME280ID() print( "Chip ID ...
def get_game_state(self): return self.board.status def pos2label(self, pos): """ Change the screen position to the label on the board. """ pos = tuple([p - tl for p, tl in zip(pos, self.top_left)]) if (pos[0] < 0 or pos[0] > self.side_length or pos[1] < 0 or ...
The main task of the code is to handle player interactions in a game via mouse events. It processes mouse motion to update the board state, detects mouse clicks to finalize moves, manages player turns, tracks time, and checks for valid actions or game-ending conditions like no available moves. Exceptions are raised for...
def _handle_player_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEMOTION: try: if self.get_game_state()[self.board.enum[self.last_lab...
def _time_out(self): """ Gets the time left, return true if no time left. """ if pygame.time.get_ticks() - self.prev_action_time > self.time_left[self.cur_player]: return True return False def _display_game_over(self): """ Display 'GAME OVER' on the sc...
The method determines if the game has ended by checking timeout or available moves. If timed out, it sets the winner as the opponent of the current player. If no moves remain, it declares the winner based on scores (player 1 or -1). It then displays the game-over message and returns True if the game ended; otherwise, r...
def game_over(self): if self._time_out(): self.winner = -1 * self.cur_player self._display_game_over() return True elif len(self._get_available_actions()) > 0: return False else: if self.scores[1] > self.scores[-1]: se...
def _update_time_left(self): """ Update the time left to the time left on the screen on date. """ if pygame.time.get_ticks() - self.prev_action_time > self.time_left[self.cur_player] % 1000: self.time_left[self.cur_player] -= pygame.time.get_ticks() - self.prev_action_time ...
This code processes a game step by updating time/scores, handling player actions, rendering the board, and managing exceptions. It updates game state, displays visuals, and re-raises errors for invalid actions or no available moves, ensuring consistent game state updates before exceptions.
def step(self, dt): self._update_time_left() self._display_scores_and_time_left() try: self._handle_player_events() self._update_scores() self.board.draw_board(self.screen) self.board.draw_pieces(self.screen) self._display_scores_and_t...
def devStrTm(cadena, inicio, fin): try: if inicio not in cadena: return '' str = cadena.split(inicio)[1] if not fin == '': str = str.split(fin)[0] return str except: return '' def devHtml(cadena, etiqueta, cortar = False): tempcad = devStrTm(ca...
The function `devinfoacu` parses weather data from an XML string, extracting temperature, wind conditions, and extended forecasts. It processes HTML elements to retrieve textual and symbolic weather information, including temperature, wind direction, and daily weather summaries. Conditional logic based on `extendido` a...
def devinfoacu(xmlstring, extendido): try: t2 = devStrTm(xmlstring, '>', '<').strip() lacondicion = devStrTm(xmlstring, '<div class="right txt-tight">', '</div>').replace('<br />', '\n').replace('\n ', '\n') arrcon = lacondicion.split('\n') if len(arrcon) > 1: t12 = arrco...
def pondebug(loque, etipo = 0): pass def haywheather(): rethay = False try: if config.misc.spazeinfobarmeteo.value: rethay = True else: rethay = False return rethay except: rethay = True try: if devtipo() == 0: numero =...
The function `getBoolean` determines a boolean value based on the presence of weather-related data (`haywheather`, `hayinfowheather`) and the object's type (`self.type`). It sets `self.poll_interval` and inverts the result if the type is `WFNOEXIST`. If service info is absent, it returns `False` (or `True` for `WFNOEXI...
def getBoolean(self): ret = False service = self.source.service self.png = None info = service and service.info() if not info: ret = False if self.type == self.WFNOEXIST: ret = not ret return ret else: pondeb...
def devarchivo(): if devtipo() == 0: return 'wf_spz.xml' else: return 'wf_forespz.xml' def pondebug(loque, etipo = 0): pass def devtipo(): try: return config.plugins.spzWeatherPlugin.default.value except: return 0 def devinfoacu(xmlstring, extendido): try: ...
This function parses weather data from an XML file, extracts current conditions, forecasts, and location details, and returns structured information including temperature, humidity, wind, icons, and extended forecasts based on the 'extendido' flag.
def devinfowheather(extendido): try: f = open('/tmp/' + devarchivo(), 'r') rettemp = f.read() f.close() except: pondebug('devinfowheater ERROR') return ('', '', '', '', '', '', '', '', '', '', '') if devtipo() == 1: return devinfoacu(rettemp, extendido) s...
def haytp(): ret = True try: ret = config.misc.spazeinfobartp.value except: pass return ret def cargasat(self, tipo, sixml = True): if tipo < 1 or tipo > 6: return else: if tipo == 1: sixml = False if not self.seg_plano...
This function generates a textual representation of service information based on the `self.type` value, handling cases like service names, CAM module status, satellite positions, service numbers, and ECM data. It checks conditions, reads files, and constructs formatted strings for display, returning the result as a str...
def getText(self): if len(self.tv_list) == 0: if haytp(): self.cargasat(self.type) elif haynum(): self.cargasat(self.type, False) service = self.source.service info = service and service.info() if not info: return '' ...
def haywheather(): rethay = False try: if config.misc.spazeinfobarmeteo.value: rethay = True else: rethay = False return rethay except: rethay = True try: if devtipo() == 0: numero = config.plugins.spzWeatherPlugin.entriesc...
The function `cargaDatos` retrieves and formats weather data based on the `tipo` parameter (default 1) and `extendido` flag. It checks weather availability, processes location, temperature, and conditions for today/tomorrow, constructs formatted text strings, and returns a tuple with location, temperatures, weather des...
def cargaDatos(tipo = 1, extendido = False): ret = False if not haywheather(): return ('', '', '', '', '', '', '', False) crear = False if hayinfowheather(): crear = sinovalido(tipo) chequeanuevo(tipo) lugar, ...
def pondebug(loque, etipo = 0): pass def haywheather(): rethay = False try: if config.misc.spazeinfobarmeteo.value: rethay = True else: rethay = False return rethay except: rethay = True try: if devtipo() == 0: numero =...
The main task of the code is to retrieve and format specific weather-related data (e.g., location, temperature, icons) based on the `self.type` parameter. It checks service availability, processes data via `cargaDatos`, handles icon paths conditionally, and returns formatted text or image paths. The function also adjus...
def getText(self): global modificando info = None pondebug('getext - tipo [' + str(self.type) + ']' + str(modificando), self.type) try: service = self.source.service info = service and service.info() pondebug('service - tipo [' + str(self.type) + ']', ...
def checkAdminData(id): with open('.\Admin_database.txt','r') as file: for line in file: if line.split('||')[0]==id : if not line.split('||')[-1][:-1]=='t': return 'locked' data=line[:-1] return list(data.split('||')) return...
This function checks if an admin ID exists by retrieving it from an entry widget, validating it against stored data, and either displaying an error for non-existent IDs or proceeding to a verification window after clearing the entry and hiding the current page.
def checkAdminId(): global adminData global idEntry id=idEntry.get() res=checkAdminData(id) if res=='not-found': _error("Account Error","This Admin Account Id wasn't Found !") else : idEntry.delete(0,END) mainPage.withdraw() createAccVerifyWindow(id)
def checkUserData(id): with open('.\database.txt','r') as file: for line in file: if line.split('||')[0]==id : if not line.split('||')[-1][:-1]=='t': return 'locked' data=line[:-1] return list(data.split('||')) return 'not-f...
This function validates a user ID by checking its existence and lock status. If the ID is not found or locked, it displays an error. Otherwise, it clears the input, hides the main page, and opens a verification window for the valid ID.
def checkUserId(): global userData global idEntry id=idEntry.get() res=checkUserData(id) if res=='not-found': _error("Account Error","This Account Id wasn't Found !") elif res=='locked': _error("Account Error","This Account Was Locked !") else : idEntry.delete(0,END) ...
def blocks_are_matching(block_1, block_2): return block_1.start_time == block_2.start_time and block_1.vehicle_task_id == block_2.vehicle_task_id def make_match_not_found_message(block, file_with_block, file_without_block): return f'File {file_with_block} contains a block with vehicle task id {block.vehicle_tas...
The function compares blocks from two files by checking each block in `blocks_1` against `blocks_2` for matches. If a block in `blocks_1` has no match in `blocks_2`, it logs an error. For matched blocks, it further checks for discrepancies using `compare_two_blocks`. It then repeats the process for `blocks_2` against `...
def compare_blocks(blocks_1, blocks_2, file_1, file_2): errors = [] for block_1 in blocks_1: matching_block = None for block_2 in blocks_2: if blocks_are_matching(block_1, block_2): matching_block = block_2 break if matching_block is None: ...
def make_stop_point_in_journey_pattern_to_scheduled_stop_point_map(xml_publication_deliveries): journey_patterns = {} for xml_publication_delivery in xml_publication_deliveries: journey_patterns = journey_patterns | extract_stop_point_in_journeys_patterns_from_publication_delivery( xml_publi...
The main task of the code is to process `publication_delivery_elements` by creating mappings between journey patterns, stop points, and quays, extracting journey and day type information, and compiling structured data blocks. These blocks likely represent organized transportation schedules or route data for further ana...
def extract_data(publication_delivery_elements): stop_point_in_journey_pattern_to_scheduled_stop_point_map = make_stop_point_in_journey_pattern_to_scheduled_stop_point_map( publication_delivery_elements) stop_point_in_journey_pattern_to_quay_map = make_stop_point_in_journey_pattern_to_quay_map( ...
def _get_messages(self) -> list[Message]: messages = self.message_repository.get_messages_to_send() return messages def _send_messages(self, messages) -> list: messages_sent = [] for message in messages: try: message_str = self._create_message_str(message) ...
The code's main task is to read messages from a source, send them (if not in test mode), and update their status, logging progress and errors. It retrieves messages, logs their count, sends them via _send_messages, confirms successful delivery, and updates statuses, handling exceptions by logging errors.
def run(self): try: logging.info("Reading messages from source...") messages = self._get_messages() logging.info(f"Sending {len(messages)} messages...") messages_sent = self._send_messages(messages) if not self.configuration.test_mode_enabled else messages ...
def _init_k_random_centers(self): k_random_indices = np.random.choice(self.n_rows, self.k, replace=False) self.k_centers = [] for random_index in k_random_indices: self.k_centers.append(self.X[random_index]) def _update_k_clusters(self): new_k_clusters = [] for i in range(self.k): new_k_...
The code performs K-means clustering by initializing k random centers, iteratively updating cluster assignments and centroids for a fixed number of iterations (self.r), then returning the final predicted labels of data points based on their cluster membership.
def run(self): self._init_k_random_centers() for _ in range(self.r): self._update_k_clusters() self._update_k_centers() predicted_labels = self._get_predicted_labels() return predicted_labels
def rank_population(self, population): ranking = {} for i in range(0, len(population)): ranking[i] = self.calculate_route_dist(population[i]) return sorted (ranking.items(), key = operator.itemgetter(1)) def calculate_route_dist(self, route): start = None total_dist ...
The main task of the code is to generate the next generation of a population in a genetic algorithm. It ranks the current population, selects the best individuals, creates a mating pool, applies crossover and mutation, removes duplicates, and ensures the next generation meets the required size. Debug information tracks...
def get_next_gen(self, population, size_for_best, mutation_rate, print_debug): ranked_population = self.rank_population(population) if (print_debug): cur_cost = self.calculate_route_dist(population[ranked_population[0][0]]) print("Cost: ", cur_cost) self.generations_c...
def init_population(self, population_size): population = [] for i in range(0, population_size): population.append(self.create_route()) return population def get_next_gen(self, population, size_for_best, mutation_rate, print_debug): ranked_population = self.rank_popu...
This code implements a genetic algorithm to evolve a population of solutions over multiple generations. It initializes a population, iterates through generations to select, mutate, and generate new populations, and returns the best solution found. The algorithm tracks the best cost every 1000 generations and applies el...
def evolve(self, initial_size, size_for_best, mutation_rate, n_generations): population = self.init_population(initial_size) # print("Gen first:") # for ind in population: # print(self.calculate_route_dist(ind), ind) # print('----------------------') for i in range...
def find_local_paths_ucs(self, start): if (self.map.is_movable(start) == False): return traces = {start : None} cost = {} frontier = PriorityQueue() explored = [] frontier.put((0, start)) while not frontier.empty(): dist, node = frontier...
The code solves a pathfinding problem by combining Uniform Cost Search (UCS) for local paths and a genetic algorithm (TSP evolution) to optimize a route through required points. It generates candidate paths, evaluates their efficiency, and reconstructs the full path if valid. The function returns whether a feasible pat...
def find_paths(self): self.find_local_paths_ucs(self.map.start_pos) for cell in self.map.must_pass_points: self.find_local_paths_ucs(cell) pass n_tsp_points = len(self.map.must_pass_points) tsp_path = self.evolve(initial_size= 20 , size_for_best=10, ...
def get_all_adjacent_coords(r, c, seat_matrix): adjacent_coords_template = [ (r - 1, c - 1), (r - 1, c), (r - 1, c + 1), (r, c - 1), (r, c + 1), (r + 1, c - 1), (r + 1, c), (r + 1, c + 1), ] valid_adjacent_coords = [] for idx, adjacent_coord in enumerate(adjacent_coords_template)...
This function determines if a seat's state should change based on adjacent or line-of-sight occupied seats. It returns 'occupied' if an empty seat has no neighbors, 'empty' if an occupied seat exceeds tolerance (4 for "adjacent", 5 for "first_seat"), or the original state otherwise.
def check_seat_state_change(row, col, seat_matrix, method): # Part one if method == "adjacent": coords_list = get_all_adjacent_coords(row, col, seat_matrix) num_occupied_seats = get_num_occupied_adjacent_seats(coords_list, seat_matrix) # Part two elif method == "first_seat": num_...
def depickle_training(): with open(pkl_file, 'rb') as handle: b = pickle.load(handle) #print('pickle len: {}'.format(len(b))) return b def set_training(self, path, import_training=None, n=None): if import_training: self.training = import_training else: for i,filename in enumer...
This code initializes a class by loading pre-trained data from a pickle file if available, otherwise training new data, saving it as a pickle, and loading test keys from a YAML file. It uses `set_training` to manage training data, handles both loading and training processes, and ensures the number of training cards is ...
def __init__(self, train_dir='./train_deck/', n=None): if train_dir == './train_deck/' and os.path.isfile(pkl_file): print('Loading pickled training file...') import_training = depickle_training() self.set_training(train_dir, import_training=import_training) else: print('Training...') ...
def same_rank(self, a, b): return a.rank == b.rank def is_trump_card(self,card): #print('{} vs. {}'.format(card[1][0], self.trump)) return card.suit == self.trump def same_suit(self, a, b): return a.suit == b.suit def sort(self, cds, desc=False): # 1st: sort on rank_val c...
This function determines if the 'you' card beats the 'me' card in a game, checking if they share the same rank (unless 'me' is a trump card), same suit (unless 'me' is a trump card), and then comparing their sorted order to see if 'you' is higher.
def does_beat(self, me, you): # check if same rank (and me is not trump) if self.same_rank(me, you) and not self.is_trump_card(me): return False #change to True for multi-deck same card beat # check if cards are the same suit (and me is not trump) if not self.same_suit(me, y...
def gpd_ad(X, code, u): thresh, Y_ex = get_excesses_ad(X, u) ga, b = get_parameters(code, Y_ex) Z = st.genpareto.cdf(Y_ex, ga, 0, b) n = len(Z) i = np.linspace(1, n, n) stat = -n - (1/n) * np.sum((2 * i - 1) * (np.log(Z) + np.log1p(-Z[::-1]))) return thresh, stat, ga, b def ad_pvalue(stat,...
This function determines an extreme value threshold for a dataset X using either a naive percentile method (code1=0) or Bader's statistical selection method (code1=1). For code1=1, it tests multiple upper-tail thresholds (u_vals) via AD tests, filters valid results, and selects the optimal threshold using forward_stop....
def get_threshold(X, code1, code2, n): Y = np.sort(X) if code1 == 0: #naive, takes 90th percentile (will work so long as n >= 11) thresh = Y[np.ceil((1 - 0.10)*n).astype(int) - 1] u = 0.10 elif code1 == 1: #implement Bader's selection method here u_start=0.79 ...
def get_threshold(X, code1, code2, n): Y = np.sort(X) if code1 == 0: #naive, takes 90th percentile (will work so long as n >= 11) thresh = Y[np.ceil((1 - 0.10)*n).astype(int) - 1] u = 0.10 elif code1 == 1: #implement Bader's selection method here u_start=0.79 ...
This function computes a risk measure by combining three components: the average of non-exceeding values (t1), the average of filtered excesses below a calculated VaR (t2), and a CVaR adjustment term (t3). It applies a utility function to input data Y, determines a threshold, estimates parameters from excesses, and syn...
def exp_ult_evt(Y, utility, param, code1, code2): Y_exp = utility(Y, param) thresh = get_threshold(Y_exp, code1, code2, Y.size)[0] Y_ex = get_excesses(Y_exp, thresh) ga, b = get_parameters(code2, Y_ex) Y_K = Y_exp[:(Y.size - Y_ex.size)] t1 = Y_K.sum() / Y.size #new method goes here al...
def reconstruction_maps(X=None,Ae=None, without_covx=True): W = filterW(Ae,True, without_covx, X) X_fg = np.dot(W,X) X_21 = X - X_fg return {"21cm":X_21,"foregrounds":X_fg} def residual_maps(X=None,Ae=None,without_covx=True): X = reconstruction_maps(X,Ae,without_covx) W_fg = filterW(Ae,Tru...
This function performs component analysis on wavelet-transformed data using GMCA or ICA methods to separate signals. It reconstructs 21cm and foreground maps from the mixing matrix, computes residuals, and aggregates results across divisions if specified. The output includes reconstructed maps, residuals, and the mixin...
def w2CSmaps(X_wt, X, params_WT, params_CS): print("Component Analysis: Starting {} method ...".format(params_CS.method.upper())) time0 = time.time() if int(params_CS.division)==1: if params_CS.method.upper()=="GMCA": import gmca4im_lib2 as g4i A,S = g4i.run_GMCA(X_wt, params_CS.A_ini, params_CS.ns, params_C...
def checkwrongfile(pathout, file=".ipynb_checkpoints"): for dir_ in os.listdir(pathout): idir = os.path.join(pathout,dir_) for ifile in os.listdir(idir): if file==ifile: path = os.path.join(idir,file) os.system("rm -rf {}".format(path)) def extracting_seed...
The code selects filenames from a directory based on parameters like `listdir`, `params_CS`, and existing files. If `listdir` is "21cm", "foregrounds", or "mixmatrix", it randomly chooses files for new realizations or identifies unprocessed ones. For other directories (e.g., "prior"), it filters out already processed f...
def nsamples(params_CS=None,params_path=None, path=None, listdir="21cm", nseed_used=False): try: checkwrongfile(pathout=params_path.pathout, file=".ipynb_checkpoints") except: pass names = np.asarray(os.listdir(path)) if listdir in ["21cm","foregrounds","mixmatrix"]: if params_C...
def building_dictmaps(w,c,params_WT, dic=None): #dic = dictionary if (params_WT.use_c)*(dic!="identity"): J = int(w.shape[1]/params_WT.npix) + 1 w = include_scalar_coeffs(w,c,J-1) elif dic=="identity": J = 1 w = w else: J = int(w.shape[1]/params_WT.npix) + 1 ...
The code applies specified wavelet transforms (Starlet, Axisymmetric, PyWavelets, Needlets, Identity) to input data `X` based on `params_WT`, constructs corresponding dictionaries, and generates compressed sensing (CS) maps using `params_CS`. It handles transform-specific implementations, raises errors for unimplemente...
def maps2CSmaps(X, params_WT, params_CS): params_WT["nbins"],params_WT["npix"] = X.shape ########## # Starck --> Starlet (Isotropic Undecimated Wavelet Transform) if "starlet" in params_WT.wtransform: import gmca4im_lib2 as g4i w, c = g4i.wavelet_transform(X,params_WT.J) building_dictmaps(w,c,params_WT,"starl...
def solveUpperCross(self): """ Solve cross for UP color """ for indexDesired in [EDGEDOWN, EDGELEFT, EDGERIGHT, EDGETOP]: correctEdges = self.correctEdges(UP) if correctEdges == 4: break color2 = self.getAdjFaceColor(UP, indexDesired) #Other c...
The code solves a Rubik's cube using the beginner's method by executing a sequence of steps: upper cross, upper corners, second layer, lower cross orientation, lower cross, and lower corner positioning/orientation. It returns True if solved successfully, False otherwise.
def solve(self): """ Solve cube using beginners method, returns True if cube is solved succeesfully and False if it can't be solved """ self.changePerspective() try: self.solveUpperCross() self.solveUpperCorners() self.solveSec...
def open_the_intranet_website(): """Navigates to the given URL""" browser.goto("https://robotsparebinindustries.com/#/robot-order") page = browser.page() def get_file(): """Gets the cvs file""" http = HTTP() http.download(url="https://robotsparebinindustries.com/orders.csv", overwrite=True) def ...
The main task of the code is to automate the process of inserting weekly sales data into a system via a browser, generate a PDF report, and archive the receipts. It configures a browser, navigates to an intranet site, retrieves a file, inputs data from a CSV file into a form, and archives the results.
def robot_spare_bin_python(): """Insert the sales data for the week and export it as a PDF""" browser.configure( slowmo=100, ) open_the_intranet_website() get_file() fill_form_with_csv_data() archive_receipts()
def usertokernel(address): kerneladdress = address - 0x80000000 - 0x00200000 kerneladdress = (kerneladdress + 2 ** 64) + 0x80000000 return kerneladdress def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): lo...
The function `loadimmkernel` generates a random user memory address, converts it to a kernel address, assigns it to a high-priority register, constructs an assembly instruction line ("li" with the register and kernel address), logs the line, saves a snapshot, and returns the register and kernel address pair for further...
def loadimmkernel(): what_address = user_address_pool[random.randrange(len(user_address_pool))] what_address = what_address + (random.randrange(1024) * 4) kerneladdress = usertokernel(what_address) distreg = choosereg("High-Priority", "kerneladdress") dict_kernel_address[distreg] = kerneladdress ...
def find_pages_on_permission(on_permissions): output_list = [] itcontains = True list_permission = list(on_permissions) for key, value in dict_all_mapped_pages.items(): for i in list_permission: if value.find(i) == -1: itcontains = False break ...
The function `loadimmuser` selects a memory address from either a list of unmapped pages or a combination of unmapped and writable pages, adds a random offset, assigns it to a register, logs the address with metadata, and returns the register name and address. The choice depends on the `from_not_mapped_pages` flag, ens...
def loadimmuser(from_not_mapped_pages): what_address = 0 if from_not_mapped_pages: what_address = list_notmapped_pages[random.randrange(len(list_notmapped_pages))] else: writable_pages = find_pages_on_permission("daguxwrv") reasonable_pages = list_notmapped_pages + writable_pages ...
def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): logical_register_file[key] = [priority, usage, True] return key for key in logical_register_file: val = logical_register_file[key] if (...
The function generates a random value, assigns it to a selected register, updates a dictionary, constructs a data line, logs it, and returns the register.
def loadimmdata(): what_data = random.randrange(0xffffff) distreg = choosereg("High-Priority", "immdata") dict_divw_mul_data[distreg] = what_data line = line_constructor("li", distreg, 0, 0, hex(what_data), 0) print(line) now.append(line) take_snapshot(line) return distreg
def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): logical_register_file[key] = [priority, usage, True] return key for key in logical_register_file: val = logical_register_file[key] if (...
The code generates a hexadecimal string using random letters and digits, converts it to an integer, and stores it in dictionaries associated with a given page and a selected register. It constructs a data structure with the register and integer value, appends it to a list, and returns the register-data pair for potenti...
def nonsecretdata(page): regdata = ["", 0x0] output_str = "" list_letters = ['a', 'b', 'c', 'd', 'e', 'f'] list_digits = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] random_letter = random.choice(list_letters) random_digit = random.choice(list_digits) rate_repeat = random.randrange(1, 5) ...
def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): logical_register_file[key] = [priority, usage, True] return key for key in logical_register_file: val = logical_register_file[key] if (...
The function `startdummybranch` generates a dummy branch instruction ("bne") by selecting source registers and a target label. It checks used registers in `logical_register_file`, randomly picks registers (based on usage count) and a branch label, constructs the instruction line, logs it, and returns the label for trac...
def startdummybranch(): src1 = "" src2 = "" list_all_used_registers = [] count = 0 for key in logical_register_file: if logical_register_file[key][2]: list_all_used_registers.append(key) count = count + 1 if count == 0: src1 = choosereg("Low-Priority", "du...
def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): logical_register_file[key] = [priority, usage, True] return key for key in logical_register_file: val = logical_register_file[key] if (...
This function simulates a cache line construction process by selecting a low-priority register, randomly choosing a load type, and generating a memory access line with the given address. It appends the address's higher bits to a cache tracking list, constructs a machine instruction line, logs it, and captures a snapsho...
def bringtodcache(inputreg, address): distreg = choosereg("Low-Priority", "loadval") which_load = random.randrange(len(different_loads)) what_offset = 0 list_dcached_address.append((address >> 6)) load_address.append(address) line = line_constructor(different_loads[which_load], distreg, inputreg...
def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): logical_register_file[key] = [priority, usage, True] return key for key in logical_register_file: val = logical_register_file[key] if (...
This code generates dummy exception data by randomly selecting memory pages and loads, constructing log entries with specific parameters, appending them to lists, taking snapshots, and returning the selected page for simulation or testing purposes.
def dummyexception(): page = random.choice(list_dummy_exception_pages) list_dummy_exception_pages.remove(page) distreg = choosereg("Low-Priority", "dummy-excp-address") line = line_constructor("li", distreg, 0, 0, hex(page), 0) print(line) now.append(line) take_snapshot(line) which_load ...
def line_constructor(operand, dist, src1, src2, imm, offset): if operand == "fence": line = operand + " " + src1 + ", " + src2 + "; \\" + "\n" elif operand == "li" or operand == "jal": line = operand + " " + str(dist) + ", " + str(imm) + "; \\" + "\n" elif operand == "ld" or operand == "lw" ...
This code generates assembly instructions to modify a page table entry (PTE) in supervisor mode. It converts permission flags into bitmasks, loads PTE address and permissions into registers, manipulates bits to update the PTE, and appends the generated instructions to a list. The process includes setting up dummy pages...
def smode_change_pte(input_page, dummy_page, permissions): list_chars = list(permissions) permission_bits = 0 for i in range(len(list_chars)): if list_chars[i] != '-': j = ((-1) * i) + 7 permission_bits = permission_bits + (2**j) line = line_constructor("li", "x4", 0, 0, ...
def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): logical_register_file[key] = [priority, usage, True] return key for key in logical_register_file: val = logical_register_file[key] if (...
The function `fill_up_user_pages` selects a random page from a list, maps it if unmapped, and generates assembly-like instructions to store predefined data patterns into memory. It uses register allocation, constructs memory-store operations with offsets, and manages page tracking via lists and dictionaries. The core t...
def fill_up_user_pages(): random_page = random.choice(list_should_be_filled_user_pages) if random_page in list_notmapped_pages: #print("kalle dooghi" + hex(random_page)) list_notmapped_pages.remove(random_page) dict_all_mapped_pages[random_page] = "daguxwrv" list_should_be_filled...
def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): logical_register_file[key] = [priority, usage, True] return key for key in logical_register_file: val = logical_register_file[key] if (...
The function `randominst()` generates a random instruction line by selecting a random operation from a list, determining used registers, and choosing source and destination registers either randomly or from used ones. It constructs a machine instruction line, appends it to a list, and captures a snapshot for tracking. ...
def randominst(): inst = different_instructions[random.randrange(len(different_instructions))] list_all_used_registers = [] count = 0 for key in logical_register_file: if logical_register_file[key][2]: list_all_used_registers.append(key) count = count + 1 if count == ...
def loadimmdata(): what_data = random.randrange(0xffffff) distreg = choosereg("High-Priority", "immdata") dict_divw_mul_data[distreg] = what_data line = line_constructor("li", distreg, 0, 0, hex(what_data), 0) print(line) now.append(line) take_snapshot(line) return distreg def choosereg(...
The code generates and executes a series of 'divw' instructions with varying intensity levels, manages register allocation by selecting source/destination registers based on usage, and creates a branch instruction ("bne") using a randomly chosen label. It appends generated instructions to a list, snapshots them, and re...
def specwindowopen(intensity): list_all_used_registers = [] count = 0 for key in logical_register_file: if logical_register_file[key][2]: list_all_used_registers.append(key) count = count + 1 if count == 0: src1 = loadimmdata() src2 = loadimmdata() eli...
def find_reg_secret_pair(secret): if secret in dict_reg_secret_pairs.values(): key = get_key(secret, dict_reg_secret_pairs) return key return "NotFound" def choosereg(priority, usage): for key in logical_register_file: val = logical_register_file[key] if (val[2] == False): ...
This function associates a memory page with a secret value and a register. It checks if the page already has a secret; if not, it generates a secret based on the page's higher bits, assigns it to a register, updates dictionaries, logs the action, and returns the register-secret pair. If the secret exists but no registe...
def find_page_secret_pair(address): page = address >> 12 page = page << 12 regdata = ["", 0] if page in dict_page_secret_pairs.keys(): secret = dict_page_secret_pairs[page] reg = find_reg_secret_pair(secret) if reg == "NotFound": regdata = [] distreg = cho...
def loadimmdata(): what_data = random.randrange(0xffffff) distreg = choosereg("High-Priority", "immdata") dict_divw_mul_data[distreg] = what_data line = line_constructor("li", distreg, 0, 0, hex(what_data), 0) print(line) now.append(line) take_snapshot(line) return distreg def choosereg(...
The function generates a sequence of delay instructions with random operands and branching logic. It constructs a delay slot instruction using either data from dictionaries or immediate values, appends it to a list, and takes a snapshot. It then creates a branch instruction to a randomly chosen label, ensuring it doesn...
def shortdelay(label): keys_list = list(dict_divw_mul_data.keys()) if len(keys_list) >= 2: if random.randrange(2) > 0: src1 = random.choice(keys_list) src2 = random.choice(keys_list) else: src1 = loadimmdata() src2 = loadimmdata() else: ...
def specwindowopen(intensity): list_all_used_registers = [] count = 0 for key in logical_register_file: if logical_register_file[key][2]: list_all_used_registers.append(key) count = count + 1 if count == 0: src1 = loadimmdata() src2 = loadimmdata() eli...
The code simulates/logging an instruction to access an instruction cache. It appends the address to a list, constructs a "jalr" (jump-and-link-register) machine instruction using the input register, prints/log the instruction, stores it in a timeline, and captures a system state snapshot. The branch label management su...
def bringtoicache(inputreg, address): branchlabel = specwindowopen(4) list_icached_address.append(address) line = line_constructor("jalr", "x1", inputreg, 0, 0, 0) print(line) now.append(line) take_snapshot(line) specwindowclose(branchlabel)
def find_pages(off_permissions): output_list = [] for item in dict_all_mapped_pages.values(): if (does_it_contain(item, off_permissions)) == False: output_list.append(get_key(item, dict_all_mapped_pages)) return output_list def specwindowopen(intensity): list_all_used_registers = [] ...
The code's main task is to locate a unique memory address in a randomly selected page, ensuring it's not in a cache list, then generate and record specific assembly instructions for a low-level performance or security test, involving register allocation, memory access, and snapshot capturing.
def prime_lfb(): list_secret_mapped_pages = find_pages("v") + find_pages("r") + find_pages("a") if not list_secret_mapped_pages: return random_page = random.choice(list_secret_mapped_pages) random_address = random_page + (random.randrange(1024) * 4) found = False while found == False: ...
def loadimmkernel(): what_address = user_address_pool[random.randrange(len(user_address_pool))] what_address = what_address + (random.randrange(1024) * 4) kerneladdress = usertokernel(what_address) distreg = choosereg("High-Priority", "kerneladdress") dict_kernel_address[distreg] = kerneladdress ...
This code simulates a Meltdown-style exploit by randomly selecting kernel addresses, checking their mapping status, and attempting to access them via user-space memory. It constructs and executes speculative execution instructions to bypass memory isolation, then records the results. The function handles both mapped an...
def meltdown_us(): regdata = ["", 0] found = False if len(dict_kernel_address) != 0: if random.randrange(2) > 0: keys_list = list(dict_kernel_address.keys()) regdata[0] = random.choice(keys_list) regdata[1] = dict_kernel_address[regdata[0]] else: ...
def find_pages(off_permissions): output_list = [] for item in dict_all_mapped_pages.values(): if (does_it_contain(item, off_permissions)) == False: output_list.append(get_key(item, dict_all_mapped_pages)) return output_list def choosereg(priority, usage): for key in logical_register_...
The function simulates manipulating memory page permissions by randomly selecting a permission scenario, locating or creating pages with specific access rights, and executing operations like loading data and taking snapshots. It handles both existing mapped pages and new page mappings, adjusting permissions using super...
def play_with_permission_bits(): list_pages = [] notpermission = [] list_permission_gadgets = ["read_invalid_page", "read_exe_only_page", "read_no_permis_page", "read_acc_off_page", "read_dirt_off_page","read_acc_dirt_off_page", "read_user_off_page", ...
def find_pages_on_permission(on_permissions): output_list = [] itcontains = True list_permission = list(on_permissions) for key, value in dict_all_mapped_pages.items(): for i in list_permission: if value.find(i) == -1: itcontains = False break ...
The main task of the code is to handle memory forwarding by randomly selecting valid memory addresses from a dictionary, checking their mapping status, and generating corresponding assembly-like instructions (store/load operations) based on whether the address is mapped or requires page mapping. It constructs instructi...
def st_ld_forwarding(): regdata = ["", 0x0] found = False dict_reasonable_adresses = {} writable_pages = find_pages_on_permission("daguxwrv") for key, value in dict_stored_address.items(): if ((value >> 12) << 12) in writable_pages: dict_reasonable_adresses[key] = value if le...
def _get_user(request): authz = request.authorization if not authz or not authz.username: raise Unauthorized("Need a username\n") user = authz.username if "/" in user: raise Forbidden(f"Disallowed user {user}\n") return user def sign(self, caller, request): body = json.loa...
This method handles HTTP requests by routing based on the URL path. It identifies the user, executes `self.sign` for the root path (`/`), or `self.list` for paths starting with `/list/`. It captures exceptions, returning HTTP errors or internal server errors with tracebacks for unhandled exceptions.
def __call__(self, request): try: caller = _get_user(request) if request.path == "/": return self.sign(caller, request) if list_bucket := trim_start(request.path, "/list/"): return self.list(caller, request, list_bucket) except HTTPEx...
def get_user(sender_id): user = Api.get_user(sender_id) if not user: return False facebook_data = Facebook.get_user(sender_id) if not facebook_data: return False if user_states.get(sender_id) is None: user_states[sender_id] = { "state": "idle", "user...
The code processes incoming messages by checking the user's state (registered or not) and routing them to specific handlers based on their state: idle, given_task_options, or given_task. If unregistered, it attempts to retrieve user info; if unsuccessful, it notifies the user. Unknown states trigger an error message, e...
def handle_message(message): sender_id = message["sender_id"] # If we haven't seen the user before, check if the user is registered if user_states.get(sender_id) is None: success = get_user(sender_id) if not success: Facebook.send_message(sender_id, "This is embarrassing, I'm ha...
def employedBeePhase(self): for i in range(0, self.foodCount): self.updateFood(i) def onlookerBeePhase(self): foodScore = [d.score for d in self.foodList] maxScore = np.max(foodScore) accuFitness = [(0.9*d/maxScore+0.1, k) for k,d in enumerate(foodScor...
The code implements an optimization algorithm (likely Artificial Bee Colony) by iteratively running three phases—employed, onlooker, and scout bees—to improve the best solution. It tracks the best fitness score at each iteration in a `trace` list and optionally prints progress. The main task is to perform iterative opt...
def solve(self): trace = [] trace.append(self.bestFood.score) for k in range(self.maxIterCount): self.employedBeePhase() self.onlookerBeePhase() self.scoutBeePhase() trace.append(self.bestFood.score) if(color and pp): pr...
def employedBeePhase(self): for i in range(0, self.foodCount): self.updateFood(i) def onlookerBeePhase(self,Iter): a = 2 * (1 - Iter / self.maxIterCount) a2=-1+Iter*((-1)/self.maxIterCount) maxScore = np.max(self.foodScore) accuFitness =...
The code implements the Artificial Bee Colony (ABC) optimization algorithm. It iteratively performs three phases—employed bee, onlooker bee, and scout bee—to optimize a solution. The algorithm tracks the best fitness value at each iteration, normalizes it, and stores progress in `trace`. Finally, it returns the optimiz...
def solve(self): trace1 = [] trace=[] trace1.append((self.bestFood.score, np.mean(self.foodScore))) for k in range(self.maxIterCount): self.employedBeePhase() self.onlookerBeePhase(k) self.scoutBeePhase() tt=self.bestFood....
def safe_loads(s): try: return json.loads(s.replace("'", '"')) except json.JSONDecodeError: return s def _initialize_teams(self, seed_data: pd.Series, nicknames: dict) -> List[Team]: if isinstance(seed_data["team_name"], list): teams = [ Team( ...
This method initializes team seeds by loading CSV data from a URL, processes team names, maps them using provided nicknames, and assigns teams to each seed index. It then sets up matchups based on the initialized seeds.
def initialize_seeds_with_data(self, nicknames: dict): url = f"{GH_URL}data/{YEAR}/{self.region_name}_{self.rnd}.csv" data = pd.read_csv(open_url(url)) data["team_name"] = data["team_name"].map(lambda x: safe_loads(x)) data = data.set_index("effective_seed") for seed_idx in dat...
def joined_attributes(self) -> Dict[str, str]: """ Returns a dict of attributes created dynamically by self._config().joined_attributes """ return { attr: self.__getattribute__(attr) for attr in self._config().__joined_attributes__ } def index_attributes(s...
The main task of the code is to generate a dictionary representation of an object as it would be stored in the database, combining model data, joined attributes, and index attributes, while optionally omitting aliases if configured to do so.
def _db_item(self) -> Dict[str, Any]: """ Returns the item exactly as it is in the database. If self._config().store_aliases is False then those aliases will be omitted. """ item = { **self.model_dump(), **self.joined_attributes(), **self.index...
def get_cross_section_zammit(): ''' Get the H2p (rotovibrational level resolved) cross sections from Zammit et al. (2017), together with the kinetic energy released in the gas. Reference: https://ui.adsabs.harvard.edu/abs/2017ApJ...851...64Z/abstract Output: ground_states_data: dictionary w...
The code calculates the photodissociation rate of H2p and its associated heating rate by interpolating between the low-density (ground state) and LTE limits, using input parameters like wavelength, spectra, gas density, temperature, and cross-section references. It integrates monochromatic luminosity with interpolated ...
def calculate_kH2p( wavelength_array, spectra_wl, distance, gas_density, gas_temperature, cross_section_reference='Z_17' ): ''' Calculate the photodissociation rate of H2p and the corresponding heating rate. The rate is interpolated between the low density limit (where only the roto...
def encrypt_server_message(message): if isinstance(message, bytes): return PKCS1_OAEP.new(server_pubKey).encrypt(message) else: return PKCS1_OAEP.new(server_pubKey).encrypt(message.encode()) def decrypt_my_message(message): dcr_message = PKCS1_OAEP.new(my_key_pair).decrypt(message) retur...
The function `join_chat()` prompts the user for a chatroom ID, sends an encrypted join request to the server, decrypts the server's response, and either reports failure or retrieves the destination user's public key to initiate chat mode. It handles secure communication setup for joining a specified chatroom.
def join_chat(): # Send a message to the server requesting to join a chat room CHAT_NUM=input("Enter the ID of the Chatroom you wish to join\n") current_chat_room = CHAT_NUM message = "--joinchat" + str(CHAT_NUM) enc_message = encrypt_server_message(message.encode()) client_socket.send(enc_messa...
def find(): message = b"--find" enc_message = encrypt_server_message(message) client_socket.send(enc_message) server_message = client_socket.recv(4096) dcr_server_message = decrypt_my_message(server_message).decode() if dcr_server_message == "--none": print("There are no users to messag...
The code defines a console menu system for a chat application, allowing users to find users, create new chats, view existing chats, join chatrooms, delete their account, or return to the sign-in screen. It processes user input by calling corresponding functions and provides help information for available commands.
def mode_console(): userin=input("[F]ind, [N]ew, [V]iew, [J]oin, [D]elete Account, [R]eturn\n") if userin== 'F': find() elif userin== 'N': new_chat() elif userin== 'V': view_chat() elif userin== 'J': join_chat() elif userin=='R': print("Signing out") ##aka...