dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def pairwise_distance(point_cloud): """Compute pairwise distance of a point cloud. Args: point_cloud: tensor (batch_size, num_points, num_dims) Returns: pairwise distance: (batch_size, num_points, num_points) """ og_batch_size = point_cloud.get_shape().as_list()[0] point_cloud = tf...
This code performs feature extraction using a dynamic graph convolutional neural network (DGCNN) with attention mechanisms. It computes k-nearest neighbor graphs, extracts edge features, applies convolutional layers, and uses attention units to refine features. The process repeats thrice, aggregating outputs through co...
def feature_extraction2(inputs, scope='feature_extraction2', is_training=True, bn_decay=None): with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): k = 10 adj_matrix = pairwise_distance(inputs) neg_adj = -adj_matrix _, nn_idx = tf.nn.top_k(neg_adj, k=k) edge_feature = get_edge...
def conv2d(inputs, num_output_channels, kernel_size, scope=None, stride=[1, 1], padding='SAME', use_xavier=True, stddev=1e-3, weight_decay=0.00001, activation_fn=tf.nn.relu, bn=False, ibn = False, ...
This code extracts hierarchical features from 3D point cloud inputs using a dense convolutional network. It processes inputs through multiple dense blocks with growth rates, concatenating features across layers to build a multi-scale representation. The network includes convolutional layers, feature aggregation, and di...
def feature_extraction(inputs, scope='feature_extraction2', is_training=True, bn_decay=None): with tf.variable_scope(scope,reuse=tf.AUTO_REUSE): use_bn = False use_ibn = False growth_rate = 24 dense_n = 3 knn = 16 comp = growth_rate*2 l0_features = tf.expan...
def check_params(self): LOGGER.info("Setting configuration") LOGGER.debug("polyConfig: {}".format(self.polyConfig)) #self.addCustomParam({ # 'Latitude': self.latitude, # 'Longitude': self.longitude, # 'Timezone': self.localtz, #}) LOGGER.info("C...
The main task of the code is to initialize a Polyglot v2 NodeServer integration by loading configuration data, updating system profiles, installing nodes, setting location/timezone parameters, and retrieving/displaying sunrise/sunset data for the current and next day. It handles server version checks, environment setup...
def start(self): """ Optional. Polyglot v2 Interface startup done. Here is where you start your integration. This will run, once the NodeServer connects to Polyglot and gets it's config. In this example I am calling a discovery method. While this is optional, this is wher...
def create_critics_data(begin_data, end_date): critics_data = pd.read_csv('data/rotten_tomatoes_critic_reviews.csv') critics_data = critics_data.dropna() critics_data['review_date'] = pd.to_datetime(critics_data['review_date'], infer_datetime_format=True) critics_data = critics_data[ (critics_da...
The main task of the code is to process and merge movie and critic data (2010-2016), filter reviews post-release, aggregate average scores, enrich with director/actor data, select key features, and save the cleaned dataset as "processed_data.csv" for analysis.
def main(): start_date = datetime(2010, 1, 1) end_date = datetime(2016, 12, 31) critics_data = create_critics_data(start_date, end_date) movies_data = create_movies_data(start_date, end_date) critics_data = movies_data.merge(critics_data, on='title') critics_data = critics_data[critics_data['rel...
def preprocess(path, num_of_bins, get_dummies=True): """ :param path: Data path :param num_of_bins: Number of bins :param get_dummies: If do convert categorical data to dummies :return: Processed dataframe """ data = pd.read_csv(path) data['release_date'] = pd.to_datetime(data['release_d...
(The code performs bootstrapping to estimate Average Treatment Effects (ATE) using multiple causal inference methods (S-learner, T-learner, IPW, matching) on movie data. It preprocesses features, iterates over resampled data, calculates ATE for specified label combinations, and reports confidence intervals and p-values...
def main(args): continuous_features = ['budget', 'runtime'] categorical_features = ['is_top_production_company', 'known_actors', 'known_directors'] bins = args.bins original_data, genres, months = preprocess('processed_data.csv', bins, get_dummies=args.get_dummies) labels_combinations = args.label_c...
def get_offset(self): if not self._state["offset_enabled"]: return 0 try: return float( self._interp([self._state["control_position"][ax] for ax in self._data.axis_names]) ) except KeyError: self.logger.error("Not all control positi...
This method sets a zero reference position, adjusts offset data by subtracting the current offset, creates an interpolator for the data, updates the system's current and destination positions based on the new zero point, and applies limits. It calibrates the system's positional tracking and data alignment for subsequen...
def set_zero_position(self, position: float): self._state["zero_position"] = position # Zero curves offset = self._data[self._offset_channel] offset -= self.get_offset() self._data.flush() self._interp = RegularGridInterpolator( [ax[:].flatten() for ax in se...
def createFiles(filepath, foldernames): '''@foldernames is the name of the folder where maps will be saved and should be sorted as [amaps, bmaps, ddc-maps, diffmaps, perfmaps, fmaps]''' '''Directors are in current directory, model_results and ROI, finds corresponding slices and then creates a file...
The code processes MRI data by generating masked files from original slices and specific masks, pads them to 64x64 resolution, and saves the results. It uses functions to create, pad, and store masked datasets for further analysis, ensuring standardized file formats for subsequent tasks like normalization or modeling.
def runProcess(): #-----Create Files from Masks and Original MRI slices filepath = ['RelDiffMaps_T1_T0', 'ROIs'] filenames = ['mmasks/mask_alpha_','mmasks/mask_beta_','mmasks/mask_ddc_','mmasks/mask_diff_','mmasks/mask_perf_','mmasks/mask_f_'] adict, bdict, ddict, diff_dict, perf_dict, f_dict = createF...
def readImage (thigh, img): imgOr = cv2.imread(img, 0) imgTh = cv2.imread(img, 0) opening = ndimage.grey_opening(imgTh, size=(3, 4)) gauss = cv2.GaussianBlur(opening, (11, 11), 0) imgTh[gauss < thigh] = 0 imgTh[gauss >= thigh] = 1 kernel = np.ones((1, 5)) erode = cv2.erode(imgTh, ke...
The code processes an image through connected component analysis, image combination, border reduction, thresholding, and pixel counting. It visualizes intermediate results and calculates statistical distances for regions, displaying metrics like original, blur, standard deviation, and union values to analyze image feat...
def execute(imagen): imgOr, imgDl = readImage(80, imagen) imgCc, _ = cConexas(imgDl) imgCc, regiones = cConexas2(imgCc) imgCombine = combine(imgOr, imgCc) rmb = reduceMiddleBorder(imgCombine,regiones) thHigh = rmb.copy() thHigh[rmb > 120] = 255 thHigh[rmb <= 120] = 0 imgReduc = red...
def import_file1(self, file1): """ This function will import the csv file :param file1: file name to be imported :return: api endpoints present at the csv file """ with open(file1) as csvDataFile: csvReader = csv.DictReader(csvDataFile) for line in...
The main task of the code is to read two CSV files, map each line to a dictionary with line numbers as keys, and compare their endpoints using the `get_end_points` method, returning `True` or `False` based on the comparison result.
def make_end_points_dict(self, file1, file2): """ :param file1:Name of the csv file to be imported :param file2:Name of the csv file to be imported :return: True or false depending on the response is equal or not. """ file_one_end_point_dict = {} file_two_end_poin...
def preprocessing(self): #Preprocessing self.content = re.sub(r'[^\x00-\x7f]',r'',self.content) self.content = ' '.join(self.content.strip().split('\n')) #Tokenizing the Content self.words, self.sentences = self.fuzzy_tokenizer(self.content) #Tokeni...
The code generates a summary by selecting high-scoring sentences using fuzzy logic, combining features like term frequency, sentence position, proper nouns, numerical data, similarity, and thematic relevance. It preprocesses text, calculates sentence-level and word-level features, assigns fuzzy scores, ranks sentences,...
def execute(self): #Preprocessing Step self.preprocessing() #Functions that require sentences at sentence level self.sentence_position() self.proper_nounsAndNumeric_feature() #Total_freq has a term frequency of a content total_freq =self.term_frequency(self.conten...
def print_intro(intro): #print the intro print(intro["story"]) def print_chemicals(chemicals): #funtion to print the chemicals option chemicals_order = collections.OrderedDict(chemicals) #put the chemicals in order print("Use these chemicals to make hydrofluoric acid!!!") for element in chemicals_o...
The main task of the code is to display an introduction and chemical information, then enter an infinite loop to repeatedly execute a menu function (`menu2`) with predefined options (`possible_answer`), likely handling user interactions or processing inputs until manually terminated.
def main(): print_intro(intro) print_chemicals(chemicals) while True: menu2(possible_answer)
def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDalpha(Tk)) def a_voigt(Tk): return Aalpha/(4.*np.pi*DeltanuDalpha(Tk)) def gammaGP(z): return 1./taugp(z)
The function computes a physical quantity involving Lyman-alpha radiation, using the Airy function and parameters related to temperature (Tk) and redshift (z). It combines constants, temperature-dependent terms (a_voigt, eta_lya), and gammaGP(z) to derive a result based on the squared Airy function components.
def Ic_lyalpha(z,Tk): beta = eta_lya(Tk)*(4.*a_voigt(Tk)/np.pi/gammaGP(z))**(1./3.) return (4./np.pi)**(-1./6.)*np.pi**(3./2.)*(a_voigt(Tk)/gammaGP(z))**(1./3.)*beta*( special.airy(-beta)[0]**2. + special.airy(-beta)[2]**2. )
def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDalpha(Tk)) def a_voigt(Tk): return Aalpha/(4.*np.pi*DeltanuDalpha(Tk)) def gammaGP(z): return 1./taugp(z)
The function computes a Lyman-alpha emission coefficient using a polynomial approximation of beta, derived from input parameters z and Tk. It combines the Voigt profile parameter a_voigt, gammaGP, and coefficients A0-A2 to return a scaled polynomial expression involving beta, representing a fitted physical model for sp...
def Ii_lyalpha(z,Tk): beta = eta_lya(Tk)*(4.*a_voigt(Tk)/np.pi/gammaGP(z))**(1./3.) A0, A1, A2 = -0.6979, 2.5424, -2.5645 #y = np.linspace(1.e-5,1.e3) #integ = integrate.simps(1./np.sqrt(y)*np.exp( -np.pi*gammaGP/6./a_voigt(Tk)*y**3. - 2.*eta_lya(Tk)*y )*special.erfc(np.sqrt(np.pi*gammaGP/2./a_voigt(Tk)...
def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDalpha(Tk)) def a_voigt(Tk): return Aalpha/(4.*np.pi*DeltanuDalpha(Tk)) def gammaGP(z): return 1./taugp(z)
The function `S_alpha_wing` computes a parameter involving special functions (Airy and hypergeometric) to model a physical process, likely in plasma or atomic physics. It calculates `alf` using inputs `z` and `Tk`, then evaluates a complex expression for `OneMinusSalpha`, returning `1 - OneMinusSalpha` as the result.
def S_alpha_wing(z,Tk): alf = eta_lya(Tk)*(3.*a_voigt(Tk)/2./np.pi/gammaGP(z))**(1./3.) OneMinusSalpha = 4.*alf/9.*( 3.**(2./3.)*np.pi*special.airy(-2.*alf/3.**(1./3.))[2] + (3.*alf**2.)*special.hyp1f2(1.,4./3.,5./3.,-8.*alf**3./27.)[0] ) return 1.-OneMinusSalpha
def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDalpha(Tk)) def a_voigt(Tk): return Aalpha/(4.*np.pi*DeltanuDalpha(Tk)) def gammaGP(z): return 1./taugp(z)
This function calculates the parameter S_alpha for a spectral line profile, returning 1 minus a term derived from the Voigt line shape (a_voigt), gamma function (special.gamma), and other temperature-dependent factors (eta_lya, gammaGP). It uses Tk (temperature) and z (redshift) to compute a line profile parameter rele...
def S_alpha_wing_1st(z,Tk): alf = eta_lya(Tk)*(3.*a_voigt(Tk)/2./np.pi/gammaGP(z))**(1./3.) OneMinusSalpha = 4.*np.pi/(3.*np.sqrt(3.)*special.gamma(2./3.))*alf return 1.-OneMinusSalpha
def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDalpha(Tk)) def a_voigt(Tk): return Aalpha/(4.*np.pi*DeltanuDalpha(Tk)) def gammaGP(z): return 1./taugp(z)
This function calculates the parameter S_alpha for a second-order approximation in a physical model, using inputs z and Tk. It computes a term 'alf' involving eta_lya, a_voigt, and gammaGP functions, then derives OneMinusSalpha via a combination of gamma functions and power terms. The result is 1 minus OneMinusSalpha, ...
def S_alpha_wing_2nd(z,Tk): alf = eta_lya(Tk)*(3.*a_voigt(Tk)/2./np.pi/gammaGP(z))**(1./3.) OneMinusSalpha = 4.*np.pi/(3.*np.sqrt(3.)*special.gamma(2./3.))*alf - 8.*np.pi/(3.*np.sqrt(3.)*special.gamma(1./3.))*alf**2. return 1.-OneMinusSalpha
def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDalpha(Tk)) def a_voigt(Tk): return Aalpha/(4.*np.pi*DeltanuDalpha(Tk)) def gammaGP(z): return 1./taugp(z)
The function calculates the alpha wing correction factor using a combination of gamma functions and input parameters, returning 1 minus the computed value. It involves terms with eta_lya, a_voigt, and gammaGP functions, applying a cubic polynomial to alf to determine the final result.
def S_alpha_wing_3rd(z,Tk): alf = eta_lya(Tk)*(3.*a_voigt(Tk)/2./np.pi/gammaGP(z))**(1./3.) OneMinusSalpha = 4.*np.pi/(3.*np.sqrt(3.)*special.gamma(2./3.))*alf - 8.*np.pi/(3.*np.sqrt(3.)*special.gamma(1./3.))*alf**2. + 4./3.*alf**3. return 1.-OneMinusSalpha
def frac_heat(x): # From Furlanetto 2006, Shull & Steenberg 1985, check x_e or x_HII C, a, b = 0.9971, 0.2663, 1.3163 if x>=1.: return C elif x > 1.e-4: return C*(1.-(1.-x**(a))**(b)) else: return 0.15 def dFcolldz(Tvir,z): dz = 0.01 return (Fcoll(Tvir,z+dz)-Fcoll(Tvir,...
This function calculates the X-ray heating rate from star formation in high-redshift cosmology, using parameters z (redshift) and xe (ionization fraction). It combines astrophysical constants, Hubble parameter, collapsed mass fraction derivatives, and stellar fraction to compute energy deposition via X-ray photons, ess...
def xray_heat_ots( z, xe ): # On the spot aprox. xi_heat is f_X of Furlanetto '06 return LSFR/kelvintoerg*year_sec*mu*m_p/Msun*fstar*frac_heat(xe)*dFcolldz(Tvir,z)/dtdz(z)/Hz(z)
def Hz(z): return H0*np.sqrt(Omega_m*(1.+z)**3. + Omega_l) def dFcolldz(Tvir,z): dz = 0.01 return (Fcoll(Tvir,z+dz)-Fcoll(Tvir,z-dz))/2./dz def dtdz(z): return -1./Hz(z)/(1.+z)
This function calculates the ionizing photon production rate (Jα) from star formation during cosmic reionization, using Mirocha 2015's approximation. It combines parameters like total star formation rate (Ntot2), stellar fraction (fstar), redshift (z), and cosmological factors (Hz, nualpha) with derivatives of collapse...
def Jalpha_M15(Tvir,z): # Mirocha '15 aprox Ja = Ntot2*fstar*c*(1.+z)**2./(4.*np.pi*nualpha/3.*Hz(z))*n0_b*dFcolldz(Tvir,z)/dtdz(z) return Ja
def Fcoll(Tvir,z): logM = np.linspace(np.log(Mmin(Tvir,z)),np.log(cutoff_mass)) integral = integrate.simps(np.exp(logM)*dndlnM(np.exp(logM),z), logM ) return integral/Omega_m/rhoc def dFcolldz(Tvir,z): dz = 0.01 return (Fcoll(Tvir,z+dz)-Fcoll(Tvir,z-dz))/2./dz def EmiLy(nu_norm): # nu_norm=nu/nualph...
This function computes the ionizing photon background (J_alpha) contribution from the continuous component of the intergalactic medium. It uses either an analytical formula (if Ja_anal is True) or numerical integration over redshift to calculate the integral involving collisional ionization rates and emissivity. The re...
def Jalpha_cont(Tvir,z): # J_alpha only from continuous bakcground inn, n = 0, 2 zmaxn = (1.+z)*(1.-(n+1.)**(-2.))/(1.-(n)**(-2.)) - 1. if Ja_anal: sum = frec_n[inn]/nu_n[inn]*( Fcoll(Tvir,z) - Fcoll(Tvir,zmaxn) ) Ja = c*(1.+z)**3./(4.*np.pi)*n0_b*fstar*Ntot2/np.log(4./3.)/nualpha*sum ...
def sigmaefftot(xe,numin,nu0,alpha): sigHI = f_H*(1.-xe)*sigmaeff(alist[0],blist[0],nuTlist[0],slist[0],numin,nu0,alpha) sigHeI = f_He*(1.-xe)*sigmaeff(alist[1],blist[1],nuTlist[1],slist[1],numin,nu0,alpha) sigHeII = f_He*xe*sigmaeff(alist[2],blist[2],nuTlist[2],slist[2],numin,nu0,alpha) return sigHI + ...
The code computes the X-ray heating rate contribution from cosmic reionization by integrating a product of efficiency factors, cosmological parameters, and redshift-dependent functions over a range of redshifts, returning the scaled result involving energy conversion factors and cosmological terms.
def xray_heat_full( z, xe ): # UPDATE zprime = np.linspace( z, z_init+1. , num=100) int = integrate.simps( sigmaefftot(xe,hnumin(z,zprime),hnu_thresh,a_spec)*(-1.)*dFcolldz(Tvir,zprime)*((1.+zprime)/(1.+z))**(-a_spec), zprime ) return hnu_thresh/kelvintoeV*xi_heat/(a_spec/(a_spec-1.))*frac_heat(xe)*c*(1.+z)...
def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDalpha(Tk)) def gammaGP(z): return 1./taugp(z) def sigmavoigt(x,Tk): y = np.linspace(0,x) return integrate.simps(1./voigt(y,Tk), y)
This function computes a correction term deltaJ via numerical integration involving parameters x, z, Tk, and auxiliary functions (eta_lya, gammaGP, sigmavoigt). It evaluates an exponential integral over a logarithmic grid (logyy) and returns 1 - deltaJ, representing a modified optical depth or transmission factor in a ...
def J2(x,z,Tk): # over Jinf; continuous back. and injected with x<0 logyy = np.linspace(-5.,np.log(xlim)) yy = np.exp(logyy) deltaJ = 2.*eta_lya(Tk)*integrate.simps( np.exp( -2.*eta_lya(Tk)*yy -2.*gammaGP(z)*( sigmavoigt(x,Tk) - sigmavoigt(x-yy,Tk) ) )*yy , logyy ) return 1.-deltaJ
def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDalpha(Tk)) def gammaGP(z): return 1./taugp(z) def sigmavoigt(x,Tk): y = np.linspace(0,x) return integrate.simps(1./voigt(y,Tk), y)
This function computes a dimensionless correction factor (1 - deltaJat0) by numerically integrating a complex exponential expression involving the Voigt function, temperature-dependent parameters (eta_lya, gammaGP), and logarithmic spacing. The integration evaluates the impact of spectral line broadening and absorption...
def Jat0(z,Tk): # over Jinf logyy = np.linspace(-5.,np.log(xlim)) yy = np.exp(logyy) deltaJat0 = 2.*eta_lya(Tk)*integrate.simps( np.exp( -2.*eta_lya(Tk)*yy -2.*gammaGP(z)*( sigmavoigt(yy,Tk) ) )*yy , logyy ) return 1.-deltaJat0
def xray_heat_ots( z, xe ): # On the spot aprox. xi_heat is f_X of Furlanetto '06 return LSFR/kelvintoerg*year_sec*mu*m_p/Msun*fstar*frac_heat(xe)*dFcolldz(Tvir,z)/dtdz(z)/Hz(z) def frac_heat(x): # From Furlanetto 2006, Shull & Steenberg 1985, check x_e or x_HII C, a, b = 0.9971, 0.2663, 1.3163 if x>=1...
The function computes the complete X-ray heating rate by subtracting a correction term from the base X-ray heating rate. The correction accounts for thermal contributions (nuTlist), temperature unit conversion (kelvintoeV), heating efficiency (xi_heat), spectral parameters (a_spec), fractional heating (frac_heat), cool...
def xray_heat_ots_complete( z, xe ): # On the spot aprox. with 2nd term with \nu_th return xray_heat_ots(z, xe) - (nuTlist[0]+nuTlist[1]+nuTlist[2])/kelvintoeV*xi_heat/(a_spec/(a_spec-1.))*frac_heat(xe)*dFcolldz(Tvir,z)/dtdz(z)/Hz(z)
def Jat0(z,Tk): # over Jinf logyy = np.linspace(-5.,np.log(xlim)) yy = np.exp(logyy) deltaJat0 = 2.*eta_lya(Tk)*integrate.simps( np.exp( -2.*eta_lya(Tk)*yy -2.*gammaGP(z)*( sigmavoigt(yy,Tk) ) )*yy , logyy ) return 1.-deltaJat0 def eta_lya(Tk): return hplanck*nualpha/m_pc2/eVtoerg*(nualpha/DeltanuDa...
The function `J1` computes a modified value based on input parameters `x`, `z`, and `Tk`, using an exponential decay term involving `eta_lya`, `gammaGP`, and `sigmavoigt` functions. It scales the base value `Jat0(z, Tk)` by the exponential factor to model attenuation or decay processes, likely in a physical or engineer...
def J1(x,z,Tk): # over Jinf; injected with x>0 return Jat0(z,Tk)*np.exp( -2.*eta_lya(Tk)*x -2.*gammaGP(z)*sigmavoigt(x,Tk) )
def Ts(z,yc,yly,Tk): # Spin temperature [K] return (Tcmb0*(1.+z) + (yc + yly)*Tk)/(1. + yc + yly) def y_coll(z,xH,T,Delta): # Collisional coupling coefficient y_coll return Tstar/T/A10*n_H(z)*Delta*( kappa_HH(T)*xH + kappa_eH(T)*(1.-xH) + kappa_pH(T)*(1.-xH) ) def y_lya(z,Jalph,T): # Ly-alpha coupling co...
The function calculates the 21cm radiation heating rate (heat21) in a cosmological context. It determines Tspin based on strong coupling conditions, then computes heat21 using parameters like Tstar, A10, hydrogen densities, redshift (z), and the CMB temperature. The formula incorporates factors for spin temperature, co...
def heat_21( z, xH, Tk, Delta ): if strongcoupling: Tspin=Tk else: Tspin = Ts(z,y_coll(z,xH,Tk,Delta),y_lya(z,Jalpha(Tvir,z),Tk),Tk) heat21 = 3./4.*Tstar*A10*xH*n0_h/n0_b/Hz(z)*(Tcmb0*(1.+z)/Tspin - 1.) return heat21
def set_image_dpi(self, file_path): im = Image.open(file_path) # size = self.get_size_of_scaled_image(im) # im_resized = im.resize(size, Image.ANTIALIAS) im.save(file_path, dpi=(300, 300)) def deter_angle(self,image, prop): # Convert color image to grayscale img = cv2.cvt...
The code preprocesses an image by detecting horizontal and vertical line angles to correct orientation. It rotates the image using the median angle of frequently occurring horizontal lines, then applies an affine transformation to adjust vertical skew. The image is saved, reloaded, and lines are removed before returnin...
def preprocess_image(self): ''' 1. Gets all angles of horizontral lines from function lines_extraction() 2. All angles are in range of 80deg~100deg or -10deg~10deg. All angles are split into two sets. 3. Select one set with more frequently angles. 4. Find out median value of sel...
def check_scan_or_digit(self): ''' Check if pdf is digital or scanned. ''' d = self.digit_page.get_text_words() digit = False if len(d) > 10:# and digit_flag: digit = self.get_digit(d) return digit def preprocess_image(self): ''' 1. Ge...
The main task of the code is to process a page by detecting text and boxes. It uses `text_detection` for non-headpages or `getting_table`/`reconstruction` for headpages, returning detected boxes and text. Preprocessing and conditional logic determine the workflow based on `headpage_checking` and scan/digit type.
def parse_page(self): ''' main process. ''' box, text = [], [] digit = self.check_scan_or_digit() self.preprocess_image() ############################# if not self.headpage_checking: global page_digit page_digit = self.text_detectio...
def print_room_summary(): print(summarize_room('')[:-1]) def close(): print("DeRegistering from Discovery") message = f"DEREGISTER {name}" room_socket.sendto(message.encode(), disco_server) print("closing room") sys.exit(0) def process_message(message, addr, room_socket): global connections ...
The main task of the code is to create a room server for a multiplayer game. It parses command-line arguments to set the room's name, description, items, and connections. It initializes a socket, registers the room with a discovery server, and listens for client messages. The server processes incoming client packets, h...
def main(): global room_server global name global description global items global connections global room_socket # Register our signal handler for shutting down. signal.signal(signal.SIGINT, signal_handler) # Check command line arguments for room settings. parser = argparse.A...
def get_voices(voice): voices = engine.getProperty('voices') # print(voices[0].id) if voice == 1: engine.setProperty('voice', voices[0].id) speak("Hello this is Ultron") if voice == 2: engine.setProperty('voice', voices[1].id) speak("Hello this is friday") def wishme(): ...
The main task of the code is to execute voice-controlled commands for various functions like checking time/date, sending emails/WhatsApp messages, searching Wikipedia, opening websites, and system control (shutdown, restart, sleep). It listens for user queries, processes them, and triggers corresponding actions using l...
def TaskExecution(self): # pyautogui.press('esc') # speak("verification successful") # speak("Welcome back sandeep") get_voices(1) wishme() while True: self.query = self.takeCommandMic().lower() if 'time' in self.query: Time() ...
def find_best_split(self, rows): """Find the best question to ask by iterating over every feature / value and calculating the information gain.""" best_gain = 0 # keep track of the best information gain best_question = None # keep train of the feature / value that produced it b...
The main task of the code is to recursively build a decision tree by partitioning data based on the attribute-value with the highest information gain. If no further gain is possible, it returns a leaf node. Otherwise, it splits the data, recursively constructs true/false branches, and combines them into a decision node...
def build_tree(self, rows): """Builds the tree.""" # Try partitioning the dataset on each of the unique attribute, # calculate the information gain, # and return the question that produces the highest gain. gain, question = self.find_best_split(rows) # Base case: no fur...
def comparepairs(pairone, pairtwo): j = 0 while True: try: # both ints if type(pairone[j]) == int and type(pairtwo[j]) == int: # check if left sjde js larger if pairone[j] > pairtwo[j]: return False elif ...
This code implements the merge sort algorithm to recursively sort an array by dividing it into halves, sorting each half, and merging them back together. It handles base cases for arrays of length 1 or 2, using a comparison function to ensure correct ordering. The `merge` function is assumed to combine two sorted subar...
def mergesort(_array): # for lists of length 2 or less return it # in sorted form if len(_array) == 1: return _array elif len(_array) == 2: if comparepairs(_array[0], _array[1]): # if in right order return _array return [_array[1], _array[0]] else: # recur...
def before_train(self): logger.info("config: \n{}".format(str(self.config))) def train_in_epoch(self): for self.epoch in range(self.start_epoch, self.max_epoch): self.before_epoch() self.train_in_iter() self.after_epoch() def after_train(self): pass
The main task of the code is to structure a training process by executing setup operations (`before_train`), performing training within an epoch (`train_in_epoch`), and ensuring cleanup/post-processing (`after_train`) occurs regardless of exceptions. The `try-except-finally` block handles potential errors during traini...
def train(self): self.before_train() try: self.train_in_epoch() except Exception: raise finally: self.after_train()
def get_groups_categories_subcategories(termcodes): groups = set() categories = set() subcategories_three_digit = set() subcategories_four_digit = set() for termcode in termcodes: if re.match("[A-Z][0-9][0-9]-[A-Z][0-9][0-9]$", termcode.code): groups.add(TerminologyEntry([termco...
The main task of the code is to organize medical terminology codes (termcodes) into a structured hierarchical tree format by grouping subcategories, categories, and groups. It processes four-digit and three-digit subcategories, nests them under appropriate categories and groups, constructs a tree structure for groups, ...
def to_icd_tree(termcodes): groups, categories, subcategories_three_digit, subcategories_four_digit = \ get_groups_categories_subcategories(termcodes) result = [] add_subcategories_four_digit_to_subcategories_three_digit_or_result(subcategories_four_digit, ...
def prepareret_ports(db, cid): cursor = db.cursor() ports = cursor.execute(f"SELECT * FROM ports WHERE id_r={cid}").fetchall() pts = '' for port in ports: pts += '{"portid": "' + str(port[1]) + '", "ip": "' + str(port[3]) + '", "mac": "' + str( port[2]) + '", "name": "' + str(port[4]...
This function processes HTTP requests by checking form data or query parameters. It executes specific functions based on the 'cmd' value (e.g., loading ports, switches, or stack masters) or 'get_port' query parameter, returning results from operations like data retrieval, storage, or configuration updates. It dynamical...
def get_cmd(): ret = '' if 'cmd' in request.form: cmd = request.form['cmd'] if cmd == 'loadports': if 'id' in request.form: ret = prepareret_ports(request.form['id']) elif cmd == 'getstackmasters': ret = getstackmasters() elif cmd == 'loads...
def getRigidBodyBones(scene, rigidBody): bone, armature = findBoneWithArmatureObject(scene, rigidBody.boneName) if armature == None or bone == None: print("Warning: Could not find bone name specified in rigid body: %s" % rigidBody.name) return None, None poseBone = armature.pose.bones[r...
This function updates the bone shape of a rigid body in a 3D scene by combining mesh data from all associated physics shapes. It retrieves the bone and pose bone, checks for valid physics shapes, aggregates vertices and faces from each shape, adjusts face indices to align with combined vertices, and applies the resulti...
def updateBoneShapeOfRigidBody(scene, rigidBody): bone, poseBone = getRigidBodyBones(scene, rigidBody) if bone == None or poseBone == None: return if len(rigidBody.physicsShapes) == 0: removeRigidBodyBoneShape(scene, rigidBody) return combinedVertices, combinedFaces = [...
def route_filter(update): #localprefs # should probably make this a JSON input at some point vals = update.split(" ") action = vals[0] #either update or withdraw prefix = vals[1] neighbor = vals[2] local_pref = local_prefs[neighbor] as_path = vals[3].split(",") if ASN in as_path: ...
The code processes BGP updates/withdrawals by filtering routes, updating the RIB table with new entries or removing withdrawn ones, and triggering route selection. It handles updates by adding entries to the RIB and withdrawals by deleting routes via system commands, ensuring consistency in the routing table.
def process_updates(sockets, updates): global RIBTable # update looks like: # <update/withdraw> prefix neighbor as1,as2,as3 for update in updates: rib_entry, action = route_filter(update) if not rib_entry: # ASN was in the asn_path continue #prefix and next hop shou...
def initiate_connections(neighbors): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', BGP_PORT)) server_socket.listen() read_list = [server_socket] print(f"ASN {ASN} created server Socket...
This code implements a BGP router that establishes connections with neighbors, advertises IP prefixes, and handles link failures by withdrawing affected routes from the RIBTable and kernel routing table. It uses select() for socket monitoring, processes updates, and triggers route reselection when neighbors disconnect,...
def main(): # TODO: local pref has to be passed in as an argument global ASN global local_prefs global SOURCE global RIBTable parser = argparse.ArgumentParser() parser.add_argument('--ip', type=str, required=True) parser.add_argument('--neighbor', nargs=3, action='append', type=str, re...
def print_valid_sections(): """ Print a list of all valid sections in a Yahtzee scorecard. This allows the user to visualize all the possible places to score. Recognition is better than recall. :postcondition: Always prints the same list of valid Yahtzee score sections, regardless of player's scorecar...
The main task of the code is to prompt a player to commit their Yahtzee hand to their scorecard by selecting a valid section. It checks if the chosen section is unassigned (value -1), calculates the score using a point calculator, and updates the scorecard. If the section is already filled, it validates for Yahtzee bon...
def commit_score(current_hand: list, scorecard: dict): """ Prompt player to commit their current hand as a value on their Yahtzee scorecard. Prompt player to input the type of hand they would like to score. E.g. 'aces' If the inputted hand already has points assigned in the scorecard, display an error ...
def roll_dice(current_hand: list): """ Roll dice to create a 5-dice hand. Modify the list such that it contains 5 random integers between 1 and 6 inclusively. :param current_hand: a potentially empty list representing face values of rolled dice. :precondition: current_hand length should be between...
The function simulates a player's turn in a dice game, allowing up to three rolls. It initializes an empty hand, repeatedly rolls dice, lets the player re-roll selected dice, and commits the final hand to the scorecard if it contains 5 dice. If not, it proceeds to the final roll and commits the score afterward. The cor...
def game(scorecard: dict): """ Drives the entire turn for the current player """ rolls_left = 3 hand = [] while rolls_left > 1: input('\nPress enter to roll dice...') roll_dice(hand) rolls_left -= 1 print(f'\nYour current hand is {hand}\n') hand = re_roll(...
def create_scorecard(): """ Create a dictionary data structure to track a player's score. Each hand in Yahtzee will be a key in the dictionary, and the default value for each key will be None. Logic: As long as there is a None value in either player's scorecard dictionary, the game will continue. ...
The main task of the code is to run a two-player Yahtzee game by alternating turns, tracking scores via scorecards, and determining the winner once all categories are filled. It initializes scorecards, manages player turns, updates scores after each round, and calculates final scores to announce the winner.
def main(): """ Drives the program. """ print('Welcome to two player Yahtzee!\n------------------------------') p1_scorecard = create_scorecard() p2_scorecard = create_scorecard() turn_counter = 1 while -1 in p1_scorecard.values() or -1 in p2_scorecard.values(): # these conditio...
def _configure_cni_relation(self): self.unit.status = MaintenanceStatus("Configuring CNI relation") cidr = self.model.config["cluster-pool-ipv4-cidr"] for r in self.model.relations["cni"]: r.data[self.unit]["cidr"] = cidr r.data[self.unit]["cni-conf-file"] = "05-cilium.co...
The method `_on_config_changed` handles configuration updates by triggering setup tasks: configuring CNI relations, Cilium networking, installing CLI resources, enabling Hubble port forwarding, and updating operational status. It ensures the system adapts to new configurations by orchestrating these dependent operation...
def _on_config_changed(self, event): self._configure_cni_relation() self._configure_cilium(event) self._install_cli_resources() self._on_port_forward_hubble() self._set_active_status()
def initialBoardGraph(): '''creat an enmpty board graph''' turtle.setworldcoordinates(-100,800,800,-100) turtle.color("lightgreen") turtle.shape("square") turtle.shapesize(4,4,1) turtle.penup() turtle.hideturtle() for i in range(8): if i % 2 == 0: for j in range(0,8,2...
This code implements an Othello game loop, handling player moves, validating positions, updating the board, switching turns, checking termination conditions, and determining the winner. It uses turtle for input, processes valid moves for "black", manages game state transitions, and terminates when no moves remain or th...
def main(): initialBoardGraph() board = initialBoardList() boardmove(board) while True: location = turtle.textinput("othello","input row and col, do not split(e.g. 23)") choPairList = getValidMove(board,"black") if location == "": return "game terminated" row ...
def play(target, shortest, longest, playmode): print("Enter a guess:") print() guess = '' ruled_out = set() #letters that have been ruled out confirmed_in = set() #letters confirmed as in fixed_counts = set() #subset of confirmed_in letters with a known exact count (positions may or may no...
The code plays a word game through multiple levels, filtering words by length, frequency, and difficulty. It tracks user progress, enforces time limits, and advances to the next level upon solving required words. The game displays stats, allows quitting, and saves progress.
def play_levels(start_level): for lvl in range((start_level-1),len(LEVELS)): level = LEVELS[lvl] #grab the level tuple shortest = level[0] longest = level[1] min_frequency = WORD_DIFFICULTY[level[2]][0] max_frequency = WORD_DIFFICULTY[level[2]][1] word_desc = WORD_...
def updateScreen(): py.display.update() py.time.Clock().tick(30) return def onRect(pos, button): if button.x <= pos[0] <= button.x + button.w: if button.y <= pos[1] <= button.y + button.h: return True return False def menu(): background = Picture("map/island.png") (levels_buttons, levels) = getLevels() hom...
The main task of the code is to create a main menu interface with a background image and two buttons (Start and Quit). It continuously displays the menu, handles mouse click events to detect button presses, and transitions to the "menu" function when the Start button is clicked, or exits the application when the Quit b...
def main(): background = Picture("png/background1.png") start_button = Button(350, 214, 325, 125, "start-button.png") quit_button = Button(410, 350, 200, 75, "quit-button.png") while True: background.show() start_button.show() quit_button.show() updateScreen() go = "" for event in py.event.get(): i...
def get_smtp(url,text): try: if "MAIL_HOST" in text: if "MAIL_HOST=" in text: mailhost = reg("\nMAIL_HOST=(.*?)\n", text)[0] try: mailport = reg("\nMAIL_PORT=(.*?)\n", text)[0] except: mailport = 587 mailuser = reg("\nMAIL_USERNAME=(.*?)\n", text)[0] ...
This code checks if a URL is vulnerable to a Laravel .env file exposure or a potential exploit via the PHPUnit framework. It attempts to access the .env file, searches for the "APP_KEY" value, and if found, triggers a vulnerability check. If not, it tries a POST request and switches to HTTPS if needed. If the PHP unit ...
def di_chckngntd(url): try: text = '\033[32;1m#\033[0m'+url headers = {'User-agent':'Mozilla/5.0 (Linux; U; Android 4.4.2; en-US; HM NOTE 1W Build/KOT49H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/11.0.5.850 U3/0.8.0 Mobile Safari/534.30'} get_source = requests.get(url+"/.env", headers=...
def get_smtp(url,text): try: if "MAIL_HOST" in text: if "MAIL_HOST=" in text: mailhost = reg("\nMAIL_HOST=(.*?)\n", text)[0] try: mailport = reg("\nMAIL_PORT=(.*?)\n", text)[0] except: mailport = 587 mailuser = reg("\nMAIL_USERNAME=(.*?)\n", text)[0] ...
This code scans a URL for potential vulnerabilities related to the "APP_KEY" in a web application. It checks for the presence of "APP_KEY" in files like .env, .env.save, or HTML responses by making GET/POST requests with specific headers. If detected, it triggers further actions (e.g., `get_smtp`, `exploit`). If no vul...
def di_chckngntdsave(url): try: text = '\033[32;1m#\033[0m'+url headers = {'User-agent':'Mozilla/5.0 (Linux; U; Android 4.4.2; en-US; HM NOTE 1W Build/KOT49H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/11.0.5.850 U3/0.8.0 Mobile Safari/534.30'} get_source = requests.get(url+"/.env", head...
def load_student_dict(csvfile): ''' load a mapping from id to name ''' filed = open(csvfile) csv_reader = csv.reader(filed) for row in csv_reader: classdict[row[0]] = row[1] def init_table(tablefile): ''' A: labnum B: stuId1 C: percentage1 D: stuId2 E: percentage2...
The code processes multiple HTML files (lab1 to lab9), extracts data from each, and consolidates them into an Excel spreadsheet (result.xlsx). It first loads student data from a CSV file, initializes an Excel table, then iteratively reads HTML content, appending each lab's data to the consolidated Excel file for aggreg...
def main(): load_student_dict("./data/classDict.csv") init_table("./judge/report/result.xlsx") for idx in range(1, 10): tabledata = read_from_html("./judge/report/lab%d/index.html" % idx) append_table("./judge/report/result.xlsx", tabledata, idx)
def Practice(self): config.progStatus['name'] = 'Practice' messages = (('During the stimulation a fixation cross will appear on ' 'the screen.\nPlease relax, and focus on the cross when ' 'it is on the screen.\nAn example of the cross is on the ' ...
The code's main task is to continuously check the state of predefined buttons in a configuration and execute corresponding methods (e.g., Practice(), Training(), Calibration()) based on which button is active. The loop runs until `self.stopped()` is true, with a 0.1-second delay when no buttons are pressed to prevent e...
def run(self): while not self.stopped(): if config.buttonState['PracticeRun']: self.Practice() elif config.buttonState['TrainingRun']: self.Training() elif config.buttonState['CalibrationRun']: self.Calibration() eli...
def create_cells(self): for i in range(len(self.models)): os.chdir(self.models[i]) self.cells.append(eval(self.models[i].lower()).create_cell(add_synapses=False)) os.chdir(root_path) def build_gate(self): establishSynapses(self.cells[0], self.cells[2], self.thres, self.weight) establishSynapses(self.cell...
The code initializes an object by creating cells, building gates, and retrieving terminals, likely setting up a structured system or circuit with interconnected components for further operations.
def __init__(self): self.create_cells() self.build_gate() self.get_terminals()
def create_cells(self): for i in range(len(self.models)): os.chdir(self.models[i]) self.cells.append(eval(self.models[i].lower()).create_cell(add_synapses=False)) os.chdir(root_path) def build_gate(self): establishSynapses(self.cells[0], self.cells[2], self.thres) establishSynapses(self.cells[1], self.ce...
The code initializes an object by creating cells, constructing a gate, and retrieving terminals, likely setting up a structured system or model with components and connections.
def __init__(self): self.create_cells() self.build_gate() self.get_terminals()
def insert_char(self, char: str) -> None: #Insert the given char at the current cursor position. Since python strings are immutable we create a new string #consisting of the previous string split where the cursor is plus the added character. text_before = self.text[self.cursor_pos_y].line_text[:...
The code handles keyboard input in a text editor, performing actions like character insertion, deletion, line splitting, cursor navigation, and control functions. It processes keys such as backspace, delete, Enter, TAB, arrow keys, and control keys (e.g., Ctrl+S for save, Ctrl+Q for exit). It updates the text buffer, a...
def detect_key(self) -> None: #Text characters, this range covers all of extended ASCII. if self.key >= 32 and self.key <= 253: self.insert_char(chr(self.key)) #Disables find function and increments buffer modification counter. self.modification_handler() #B...
def detect_key(self) -> None: #Text characters, this range covers all of extended ASCII. if self.key >= 32 and self.key <= 253: self.insert_char(chr(self.key)) #Disables find function and increments buffer modification counter. self.modification_handler() #B...
The code defines an editor method that runs an infinite loop to handle screen updates, key detection, scrolling, FPS metering, and prompt processing in a text editor interface, refreshing the display continuously based on user input and internal state changes.
def editor(self) -> None: while True: self.stdscr.clear() self.get_size() self.detect_key() self.scroll_handler() self.fps_meter.fps_handler() self.print_screen() self.prompt.prompt_handler() self.stdscr.refresh(...
def check_balance(self, card): query = """SELECT balance FROM card WHERE number = ?""" data_tuple = (card,) self.cur.execute(query, data_tuple) rows = self.cur.fetchone() return rows[0] def add_income(self, card, income): query = """UPDATE card SET balance = balance + ? W...
This function displays an account management menu, allowing users to check balance, add income, transfer funds, close accounts, log out, or exit. It processes user choices by calling corresponding methods, maintaining the loop until logout or exit.
def account_menu(self, card): while self.logged_in: print('1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit') choice = input() if choice == '1': print('\nBalance: ', self.check_balance(card)) elif choice == '2': ...
def ShowPopUpMessage(self, popUpMessage): messageBoxElement = QMessageBox() messageBoxElement.setWindowTitle("ERROR!") messageBoxElement.setText(popUpMessage) execute = messageBoxElement.exec_() def ReadAndPlotMainSignal(self, timeReadings, amplitudeReadings): self.readSignalTime...
This method handles a confirmation button action by checking if there's a signal to process. If not, it alerts the user; otherwise, it plots the signal, resets UI elements, and updates the frequency label to '0 Fmax'.
def ComposerConfirmButtonAction(self): if isSummedSinusoidalsPlotNotEmpty == False: self.ShowPopUpMessage("No Signal to Sample! ") else: self.ReadAndPlotMainSignal(self.applicationTimeAxis, self.summedComposerSinusoidals) self.ResetSliderAndMainGraph() self.ui.ma...
def response400(conn): conn.send('HTTP/1.1 400 BAD REQUEST\n') conn.send('Connection: close\n\n') conn.close() def getContentType(path): try: extension = path.split('.')[1] return contentTypes[extension] except: return contentTypes['html'] def response200(conn, text, contentT...
The code handles HTTP requests by parsing method and path, routing GET requests to predefined routes, processing POST requests for specific endpoints like /save, /reboot, and /identify, and returning appropriate HTTP responses (200/400/404) based on validity and action outcomes.
def handleRequest(conn): request = conn.recv(1024) requestSegments = request.split() if len(requestSegments) <= 2: response400(conn) method = requestSegments[0].decode('utf-8') path = requestSegments[1].decode('utf-8') contentType = getContentType(path) if path in routes and metho...
def setupAP(): ap = network.WLAN(network.AP_IF) ap.active(True) ap.config(essid=AP_SSID, password=AP_PASSWOD, security=3) while ap.active() == False: pass print('Connection successful') print(ap.ifconfig()) def saveDeviceInfo(): setStorage({ 'mac': hexlify(network.WLAN().co...
The function `serveSetupServer` initializes a server setup by configuring a wireless access point, saving device information, establishing a server instance, importing routing configurations, and handling incoming server requests.
def serveSetupServer(): setupAP() saveDeviceInfo() s = setupServer() importRoutes() serverRequests(s)
def _requests_parameters(self, entries_required, limit): """Prepare query parameters for requests sent to the API.""" if entries_required < limit: return {'start': to_string(self.__start_date), 'end': to_string(self.__end_date)}, date_range = self._date_range(ent...
The function `_get_missing_data` identifies and retrieves missing historical data from an API by comparing database entries against required data. It constructs API parameters, filters out existing data using `reject_values`, and uses an `ApiWorker` to fetch new data. The result, along with any errors, is returned.
def _get_missing_data(self, c, db_data, entries_required): """Download missing historical data from the api.""" parameters = self._requests_parameters(entries_required, settings.ROWS_LIMIT) reject_values = [to_string(day) for day in ...
def _get_cryptocurrency(self): """Get cryptocurrency from the database or the API.""" error = None with self.__db: c = Cryptocurrency.get_or_none(currency_name=self.__currency) if c is not None: return c, error url = settings.CRYPTOCURRENCY_URL.safe_subst...
The main task of the code is to retrieve cryptocurrency data from a database or API, ensuring the required number of historical entries is met. It checks existing database data, fetches missing entries if needed, and returns complete data or error messages.
def get_data(self): """Gather the requested data from the db or the API.""" c, error = self._get_cryptocurrency() if c is None: return None, error with self.__db: db_data = self._get_historical_values(c) entries_required = self._count_days() if le...
def create_ax(self,fig): ax = Axes3D(fig) self.config_ax(ax) return ax def config_ax(self, ax): ax.set_xlim3d(-1000,1000) ax.set_ylim3d(-1000,1000) ax.set_zlim3d(-1000,1000) ax.set_aspect('equal', 'box') def plot_conf(self, ax, angular_positions): conf=sel...
This function animates the interpolation of an angle from `angle_init` to `angle_end` over 100 frames, updating a plot each frame. It optionally plots a predicted position if provided, clears and reconfigures the axes for each frame, and prints final results. The animation visualizes the motion and compares the predict...
def animate(self, angle_init,angle_end, ax = None, predicted_pos=None): T=100; if (ax==None): fig = plt.figure() ax = self.create_ax(fig) for t in range(T): ax.clear() self.config_ax(ax) self.plot_conf(ax,angle_init + t/T * (a...
def init_configure(self): self.servers_configure = [configure for configure in self.load_json.get_network_configure().values()] self.thread_pool = ThreadPool(len(self.servers_configure)) def init_sessions(self): print("* Conneting to servers...") sessions = self.init_ssh_and_sftp_session...
The main task of the code is to run an interactive IDE by initializing configurations, managing sessions in a context, and processing user commands in a loop. It repeatedly retrieves commands via `input_command()`, executes them with `exec_one_command()`, and maintains session context. However, the final recursive call...
def run_ide(self): self.init_configure() with self.init_sessions() as sessions: while command:=self.input_command(): self.exec_one_command(sessions, command) self.run_ide()
def is_alive(self): """Check whether the hero is alive and return true or false.""" return self.current_health > 0 def attack(self): """ Calculate the total damage from all ability attacks. return: total:Int """ dmg = 0 for abl in self.abilities: ...
This code simulates a battle between two entities (self and opponent) by alternating attacks until one dies or 200 rounds pass. It tracks health, determines the winner, and updates kill/death statistics. The fight prints status updates after each round and declares the outcome.
def fight(self, opponent): """Fight between hero and opponent.""" print('A fight is beginning between ' + self.name + ' and ' + opponent.name + '!') # choose first attacker fighter = random.randint(0, 1) rounds = 0 while self.is_alive() and opponent.is_alive...
def get_WRF_variables(common_object, scenario_type, date_time): #, lon_index_west, lat_index_south, lon_index_east, lat_index_north): # location of WRF file file_location = '/global/cscratch1/sd/ebercosh/WRF_TCM/' + scenario_type + '/' + date_time.strftime('%Y') + '/wrfout_d01_crop_' # open file data = Dataset(file...
This function retrieves atmospheric variables (u-wind, v-wind, relative vorticity, and curve vorticity) from different meteorological models. It selects the appropriate model-specific method based on the 'model' attribute of the input object, then returns the four variables as tuples. The function acts as a dispatcher,...
def get_variables(common_object, scenario_type, date_time): if common_object.model == 'WRF': u_levels, v_levels, rel_vort_levels, curve_vort_levels = get_WRF_variables(common_object,scenario_type,date_time) elif common_object.model == 'MERRA2': u_levels, v_levels, rel_vort_levels, curve_vort_levels = get_MERRA2_v...
def get_data(self): table = {39: None, 91: None, 93: None} self.data_list = ['date', 'location', 'current_pressure', 'current_temp', 'today_precip', 'current_humidity', 'wind_speed', 'wind_direction', 'wind_gust', 'wind_chill', 'dew_point'] #sql = f"SELECT {str(self.data_list).translate(table)} ...
This code initializes a class with a database connection and location, sets up a cursor, and fetches weather-related data including precipitation, temperature lists, and historical dates.
def __init__(self, connection, location): self.location = location self.connection = connection self.cursor = self.connection.cursor() self.get_data() self.get_current_data() self.get_last_dates() self.get_weekly_precip() self.get_temp_list()
def redraw(): c.resetIndex() drawLines(controlPointsCoordinates, t) p = deCasteljau(t, controlPointsCoordinates)[0][0] pts_bernstein = bernstein_Polynomi(t, controlPointsCoordinates) circle.set_center(p) circle.figure.canvas.draw() for i in range(len(circle_b)): circle_b[i].remove() ...
The main task of the code is to redraw a plot containing a curve and Bernstein polynomials using control points. It clears the plot, accesses global control point coordinates, draws the curve, overlays Bernstein polynomials, and updates the visualization with `plt.draw()` to reflect changes in real-time.
def redrawAll(): redraw() global controlPointsCoordinates draw_curve(controlPointsCoordinates) drawBersteinpolinoms(controlPointsCoordinates) plt.draw()
def draw_control_polygon(points): controlPolygonContainer.clearLines() controlPolygonContainer.addLine(points, 'green') controlPolygonContainer.redraw() def updateTextAndCheckConfiguration(): global variableLabel, eqLabel, infoLabel, degreeLabel if variableLabel is not None: variableLabel.remove() ...
The main task of the code is to redraw a B-Spline curve and its associated elements (control polygon, tangent arrows, construction lines) based on the current configuration. If the configuration is invalid, it clears previous elements and redraws the canvas; otherwise, it draws the B-Spline curve, functions, points, ta...
def redrawAll(): global controlPointsCoordinates, tangentArrow, circle c.resetIndex() draw_control_polygon(controlPointsCoordinates) valid = updateTextAndCheckConfiguration() if not valid: curveContainer.clearLines() curveContainer.redraw() if tangentArrow is not None: ...
def generate_children(parent_node, state): if(parent_node.value == None): possible_moves = first_move(state.num_tokens) nodes = create_nodes(parent_node, possible_moves, state) else: tokens_remaining = get_remaining_tokens(state.num_tokens, state.taken_tokens) possible_moves = get_possible_tokens(state.taken_...
This function implements the alpha-beta pruning algorithm for game tree search, recursively evaluating node scores while optimizing performance by pruning non-optimal branches. It alternates between maximizing and minimizing values based on the player's turn, updating alpha/beta bounds to avoid unnecessary computations...
def run_ab_algo(node, state, depth, players_turn, alpha, beta): if depth == 0: max_depth = math.inf else: max_depth = depth global evaluated_counter global depth_counter children = generate_children(node, node.state) if node.depth == max_depth or len(children) == 0: evaluated_counter += 1 if node.dep...
def parse_input(inputStr): # parses string input and returns array of integers parsed_input = list(map(int, inputStr.split(" "))) num_tokens = parsed_input[0] num_taken_tokens = parsed_input[1] # Handles wether there have been any tokens that were taken if num_taken_tokens != 0: list_taken_tokens = list(parse...
The code implements a game-playing algorithm using alpha-beta pruning. It parses input values, initializes game states, and executes the algorithm to determine optimal moves. The process tracks visited nodes and outputs results, simulating strategic decision-making in a turn-based game with token-taking mechanics.
def main(): str_input = "3 1 1 1" num_tokens, num_taken_tokens, list_taken_tokens, depth, start_token = parse_input(str_input) start_state = State(list_taken_tokens, num_tokens) start_node = Node(start_token, None, 0, None, -math.inf, math.inf, [], start_state) players_turn = get_players_turn(list_taken_tokens) ...
def getCtAugmentedCandidate( augmentation_dict, series_uid, center_xyz, width_irc, use_cache=True ): if use_cache: ct_chunk, center_irc = getCtRawCandidate(series_uid, center_xyz, width_irc) else: ct = getCt(series_uid) ct_chunk, center_irc = ct.getRawCandidate(center_xyz, wi...
This code retrieves a data sample from a medical imaging dataset, selecting either positive (nodule) or negative samples based on a specified ratio. It applies data augmentation or loads raw data, converts it to tensors, and returns the image tensor, label (nodule status), series UID, and spatial coordinates for model ...
def __getitem__(self, index): # ration positive:negative if self.ratio_int: pos_index = index // (self.ratio_int + 1) if index % (self.ratio_int + 1): neg_index = index - 1 - pos_index neg_index %= len(self.negative_list) candidate...
def set_up_parser() -> optparse.OptionParser: usage = "usage: %prog [options]" desc = """Run all benchmarks for all tools """ parser = optparse.OptionParser(usage=usage, description=desc) parser.add_option("--verbose", "-v", action="store_true", default=False, dest="verbose", ...
The main task of the code is to execute benchmark tests using specified tools on curated test cases, manage command-line arguments, randomize test order, and store results in CSV/JSON files and an SQLite database. It validates inputs, ensures tool/case availability, and handles result persistence with timestamped filen...
def main() -> None: parser = set_up_parser() global opts (opts, args) = parser.parse_args() if len(args) > 0: print("Benchmarking does not accept arguments") exit(-1) random.seed(opts.seed) opts.timestamp = strftime("%Y-%m-%d-%H:%M", gmtime()) tools_used = get_tools_used() ...
def set_up_parser() -> optparse.OptionParser: usage = "usage: %prog [options]" desc = """Generate all graphs """ parser = optparse.OptionParser(usage=usage, description=desc) parser.add_option("--verbose", "-v", action="store_true", default=False, dest="verbose", help="More ve...
The main task of the code is to generate specific types of graphs (CDF, box plots, comparative) based on command-line arguments. It creates a "graphs" directory if it doesn't exist, parses input options, checks data consistency, and conditionally executes graph generation functions depending on flags like --cdf_only, -...
def main() -> None: try: os.mkdir("graphs") except FileExistsError: pass parser = set_up_parser() global opts (opts, _) = parser.parse_args() only_some : bool = opts.cdf_only or opts.box_only or opts.comp_only check_all_same_tout() if not only_some or opts.cdf_only: ...
def new_run(self, start): xkey, ykeys, mcakeys, normkey = self.get_data_keys(start) plot_hints = start.get('plot_hints', {}) style_hints = plot_hints.get('style', {}) if 'repeat' in start: repeat_md = start['repeat'] max_runs = repeat_md['len'] cols = ...
This method processes incoming documents by triggering specific actions based on the document name. If the name is 'start', it initiates a new run; if 'stop', it generates an average plot. Finally, it streams the document into runs for further processing.
def new_document(self, name, doc): if name == 'start': print("received start doc!") self.new_run(doc) if name == 'stop': print("received stop doc!") self.plot_average(doc) self.stream_documents_into_runs(name, doc)
def get_session_code(): conn = http.client.HTTPConnection("172.24.183.26:9763") payload = "<xsd:registerClient xmlns:xsd=\"http://interaction.api.ws.diva.fpdigital.com/xsd\">\r\n " \ "<xsd:appName>Tape Test Application</xsd:appName>\r\n " \ "<xsd:locName>1</xsd:locName>\r\n ...
The code handles POST requests to check the status of a request using either a barcode or a 4-digit request ID. It validates inputs, retrieves data via session code, and returns status results or error messages. For GET requests, it renders the status template.
def status(): # check if POST; parse input for request number or barcode; call status function and return; reload page if GET if request.method == "POST": sescode = get_session_code() if re.match(r'D\d{5,7}', request.form['reqnumber'], re.I): bcode = 'D' + request.form['reqnumber'][1...
def _pause_game(self) -> None: """PRIVATE: Handles pause game logic. """ self.stats.game_paused = True def _start_game(self) -> None: """Contains the logic to actually start the game. Callable fron both clicking the button and pressing the Enter key. """ # Reset g...
This function handles key press events in a Pygame game, controlling ship movement (left/right), exiting the game (Escape/Q), pausing (P), starting/resuming gameplay (Enter/Return), and firing bullets (Spacebar). It updates game state variables based on the pressed key, enabling player interaction and game control feat...
def _check_keydown_events(self, event: pygame.event.Event) -> None: """PRIVATE: Respond to key presses. Args: event (pygame.event.Event): the key release PyGame event """ if event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame...
def key_to_action(self, event: pygame.event.Event) -> PlayerAction: if event.key in [pygame.K_ESCAPE, pygame.K_q]: self.logger.info(f"Session: {self.session_id}; Event: Game End; Method: Key Press {pygame.key.name(event.key)}") sys.exit() if event.key == pygame.K_h and self.engin...
The main task of the code is to run a game loop that processes user inputs (keyboard/mouse events), maps them to game actions, updates the game state via `engine.play()`, and renders the game on the screen. It continuously checks for quit events, logs input actions, and maintains the game window with `pygame.display.fl...
def run_game(self) -> None: while True: action = None for event in pygame.event.get(): if event.type == pygame.QUIT: self.logger.info(f"Session: {self.session_id}; Event: Game End; Method: Click Exit") sys.exit() if ...
def _check_keydown_events(self, event: pygame.event.Event) -> None: """PRIVATE: Respond to key presses. Args: event (pygame.event.Event): the key release PyGame event """ if event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame...
This function processes Pygame events to handle user inputs: exits the game on quit, triggers keydown/up actions, and checks mouse clicks on play/resume buttons by capturing mouse positions and calling corresponding methods.
def _check_events(self) -> None: """PRIVATE: Respond to keypresses and mouse events. """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) ...
def _check_fleet_edges(self) -> None: """Respond appropriately if any aliens have reached an edge. """ for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self) -> None: """Respond to t...
This method updates alien positions by checking fleet edges and moving aliens. It detects collisions between the ship and aliens, triggering a response if hit, and checks if any aliens reach the screen bottom for further handling.
def _update_aliens(self): """Check if the fleet is at an edge, then update the positions of all aliens in the fleet. """ self._check_fleet_edges() self.aliens.update() # Look for alien-ship collisions. if pygame.sprite.spritecollideany(self.ship, self.aliens): ...
def _check_events(self) -> None: """PRIVATE: Respond to keypresses and mouse events. """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) ...
The main task of the code is to execute the game's main loop by continuously checking events, updating game elements like the player's ship, bullets, and aliens when the game is active and not paused, and rendering the updated screen to create an interactive gameplay experience.
def run_game(self) -> None: """Starts the main loop for the game. """ while True: self._check_events() if self.stats.game_active and not self.stats.game_paused and not self.stats.level_break: self.ship.update() self._update_bullets() ...
def Fetch_Filings_Annual(Api_Key): api_query = QueryApi(api_key = Api_Key) # Now run query to get all the 10-K filings for Southwestern Airlines using ticker LUV query = { "query": { "query_string": { "query": "(formType:\"10-K\") AND ticker:LUV" } ...
The main task of the code is to perform horizontal financial analysis by fetching annual filings using an API key, converting the retrieved data into a structured dataframe, and generating visualizations to analyze trends and comparisons across different financial metrics.
def Horizontal_Analysis(Api_Key): accession_numbers = Fetch_Filings_Annual(Api_Key) result= Main_Dataframe(accession_numbers) plotting_variables(result)
def get_volume(self, first=None): """ reads sample data and calculates volume """ self.test_and_restart_stream() volumes = [] iterations = int(self.device['defaultSampleRate'] / self.chunk * self.recording_sample) for _ in xrange(0, iterations): data...
The function continuously monitors audio volume, checking if it falls below a predefined threshold within a specified time frame (defaulting to 1 hour). If the volume is below the threshold, it triggers an alert message. It uses a loop to repeatedly check the volume until the end time is reached, ensuring real-time mon...
def volume_threshold_detection(self, end_time=None): """ Prints an alert when above the volume threshold """ if end_time is None: end_time = time.time() + 3600 while end_time > time.time(): sys.stdout.flush() average = self.get_volume() is_...
def get_volume(self, first=None): """ reads sample data and calculates volume """ self.test_and_restart_stream() volumes = [] iterations = int(self.device['defaultSampleRate'] / self.chunk * self.recording_sample) for _ in xrange(0, iterations): data...
The code continuously monitors volume levels by calculating an average, comparing it against a threshold, and outputting '0' if below the threshold or '1' otherwise in an infinite loop.
def simple_detector(self, first=None): """ """ while True: average = self.get_volume() is_below_threshold = self.detect_volume_threshold(average) if is_below_threshold: self.stdout('0') else: self.stdout('1')
def get_volume(self, first=None): """ reads sample data and calculates volume """ self.test_and_restart_stream() volumes = [] iterations = int(self.device['defaultSampleRate'] / self.chunk * self.recording_sample) for _ in xrange(0, iterations): data...
This function continuously monitors volume levels, detecting transitions across a threshold. It triggers events (stdout 0/1) only when the volume crosses into or out of the threshold state, using a loop to maintain persistent monitoring and track previous threshold status via the 'was_at_threshold' flag.
def change_detector(self, first=None): """ Only fires an event when a transition occurs """ while True: average = self.get_volume() is_below_threshold = self.detect_volume_threshold(average) if is_below_threshold and not self.was_at_threshold: ...
def get_volume(self, first=None): """ reads sample data and calculates volume """ self.test_and_restart_stream() volumes = [] iterations = int(self.device['defaultSampleRate'] / self.chunk * self.recording_sample) for _ in xrange(0, iterations): data...
This function monitors volume and time thresholds, alerting when both are exceeded. It continuously checks volume levels, detects if they fall below a threshold, and tracks time since the threshold was met. When both conditions are satisfied, it triggers an alert, then resets states to prepare for future detections.
def timed_volume_detector(self, first=None): """ alerts once time and volume thresholds are exceeded """ # if end_time is None: # end_time = time.time() + 3600 # while end_time > time.time(): while True: average = self.get_volume() is_below_thr...
def checkSolarEff(self): return abs(math.sin(math.radians(self.lastDriveAngle))) def distFrom(self,waypoint): return math.sqrt((waypoint.x - self.x)**2 + (waypoint.y - self.y)**2) def faultCheckPass(self): #battery has enough power return self.batteryCharge >= self.minPowerBeforeCharge def dist(self,x1,...
The code navigates a rover toward a target waypoint by evaluating neighboring cells for obstacles, selecting the closest valid position, and updating the rover's position, battery, and telemetry data. It avoids obstacles, manages power consumption, logs system status, and ensures communication with a lander. The loop c...
def drive(self, waypoint): #while we are not near enough to our target #nss collect data self.nSystem.log(self.time,self.x,self.y,self.map) #collect telemetry data self.telemetryLog.append(Telemetry(self.time,self.x,self.y,self.batteryCharge,self.checkSolarEff(),self.landerConnectionStrength,self.nS...
def _debug(self, *args, **kwargs): print((self._indent + kwargs.get('incr', 0)) * ' ' + ' '.join(['{}'] * len(args)).format(*args)) def _tn(self): """Return a temporary variable name.""" self._ti += 1 return '__temp__' + str(self._ti) def ast_name(id, ctx=Load()): n...
This method processes comparison operations in an AST node by breaking down chained comparisons (e.g., a > b > c) into individual comparisons. It evaluates each comparison operation sequentially, stores intermediate results, and combines them using a logical AND operation through BoolOp. If multiple operators exist, it...
def visit_Compare(self, node): self._debug('Compare', node.ops, incr=1) if len(node.ops) > 1: values = [] left = self[node.left] for op, right in zip(node.ops, node.comparators): right = self[right] tn = self._tn() valu...
def possibleMove(self, row, col, num): # check row for i in range(9): if self.board[row][i] == num and col != i: return False # check column for i in range(9): if self.board[i][col] == num and row != i: return False # chec...
This function solves a Sudoku puzzle using backtracking with GUI visualization. It iterates through the board to find empty cells, attempts valid numbers (1-9), and recursively proceeds. If a number is invalid, it backtracks, updating the GUI with delays to show progress. The process continues until the board is solved...
def solveGUI(self, startTime): # find an empty cell for row in range(9): for col in range(9): if self.board[row][col] == 0: # outline the empty cell when it is visited self.cells[row][col].outlined = True # try all ...
def checkResetClick(mouseX, mouseY): # check if the reset button was clicked if mouseX > RESET_BTN_X and mouseX < RESET_BTN_X + BTN_WIDTH and mouseY > BTN_Y and mouseY < BTN_Y + BTN_HEIGHT: return True else: return False def checkSolveClick(mouseX, mouseY): # check if the solve button wa...
This code implements a Sudoku solver game using Pygame, handling user interactions for inputting numbers, resetting the board, and solving puzzles. It maintains a game loop to process events like mouse clicks (for cell selection, reset/solve buttons) and keyboard inputs (number placement/deletion). The board's state is...
def main(): # main function with the game loop pygame.display.set_caption("Sudoku Solver") board = Grid(9, 9, 540) startTime = time.time() key = None running = True while running: # look for any event for event in pygame.event.get(): # close button if...
def getPullRequestMetadata(data): """Fetch pull request metadata.""" pullRequestData = {} payloadParser = GithubWebhookPayloadParser(data) pullRequestData['url'] = payloadParser.getPullRequestUrl() pullRequestData['title'] = payloadParser.getPullRequestTitle( ) or 'Unknown Title' pullReques...
The function `createSlackMessagePayload` generates a Slack notification payload from input data. It extracts pull request metadata, constructs a message text using this metadata and the input data, and assembles the final payload structure. The payload is then returned for sending a Slack notification.
def createSlackMessagePayload(data): """Create payload for slack notification.""" pr_metadata = getPullRequestMetadata(data) msg_text = getMessage(pr_metadata, data) message = buildPayload(msg_text, pr_metadata) return message
def Remove_Numeric_Values(data, column_names): for column in column_names: if data.dtypes[column] == np.int64: median_value = np.median(data[column].values) i = 0 while i < len(data[column].values): if int(data[column].iloc[i]) < median_value: ...
The code constructs a decision tree classifier using the ID3 algorithm. It reads and preprocesses training/test data, removes numeric attributes, calculates initial error, builds the tree recursively based on user-specified depth and attribute selection criteria (entropy/Gini/majority), then evaluates training/test acc...
def main(): print('Please Input the Tree Depth') tree_depth = int(input()) print('Please Input how you want to select the attribute. 1=Entropy, 2=Gini, 3=Majority') decider = int(input()) #Goal is to use Pandas to generate the table. bank_cols = ['age','job','marital','education','default','bal...
def Remove_Numeric_Values(data, column_names): for column in column_names: if data.dtypes[column] == np.int64: median_value = np.median(data[column].values) i = 0 while i < len(data[column].values): if int(data[column].iloc[i]) < median_value: ...
The main task of the code is to implement an ensemble learning approach using decision stumps on the bank dataset. It iteratively trains stumps, calculates training/test errors, adjusts weights, and computes final hypotheses. The code processes data with Pandas, removes numeric values, and visualizes error trends over ...
def main(): print('Please Input The Number of Stumps') iterations = int(input()) #Goal is to use Pandas to generate the table. bank_cols = ['age','job','marital','education','default','balance','housing', 'loan', 'contact', 'day', 'month', 'duration', 'campaign', 'pdays', 'previous', 'poutcome'...
def Adjust_Labels(data): for example in data: if example[len(example)-1] == 0: example[len(example)-1] = -1 return data def NN_Initialization(input_length, width): # Get the length of one input example # input_length = len(inputs) neural_net = list() #Create the first Hidden ...
The main task of the code is to train a neural network using backpropagation on a dataset loaded from CSV files. It adjusts labels, initializes a network with user-specified layer widths, trains it over 24 epochs with a decaying learning rate, and evaluates training/test errors. The code handles data loading, forward/b...
def main(): here = os.path.dirname(os.path.abspath(__file__)) train_file = os.path.join(here,'train.csv') test_file = os.path.join(here,'test.csv') data = np.genfromtxt(train_file,delimiter=',',dtype=np.float32) test_data = np.genfromtxt(test_file,delimiter=',',dtype=np.float32) data = Adjust_La...
def Analytical_Best(train_data): x_rows = [] y_rows = [] for row in train_data: i = 0 current_row = [] while i < len(row)-1: current_row.append(row[i]) i+=1 y_rows.append(row[len(row)-1]) x_rows.append(current_row) x_matrix = np.matrix(x_ro...
The main task of the code is to read training and test data from CSV files, convert their contents to floating-point numbers, compute an analytical weight vector using the `Analytical_Best` function, and then perform either Batch or Stochastic Gradient Descent regression based on user input, using the provided datasets...
def main(): training_file = r"./train.csv" test_file = r"./test.csv" with open(training_file, newline='')as f: reader = csv.reader(f) train_data = list(reader) with open(test_file, newline='')as f: reader = csv.reader(f) test_data = list(reader) i = 0 j = 0 ...
def remove_special_characters(text): regex = r'[^a-zA-Z0-9\s]' text = re.sub(regex,'',text) return text def pos_tagging(text): pos_tag = nltk.pos_tag(text.split()) pos_tagged_noun_verb = [] for word,tag in pos_tag: if tag == "NN" or tag == "NNP" or tag == "NNS" or tag == "VB" or tag == "...
This function calculates a sentence's importance score by summing TF-IDF values of its processed words. It cleans the input sentence (removing special characters, numbers), performs POS tagging, lemmatizes non-stopwords (>1 character), and accumulates their TF-IDF scores using the provided frequency dictionary and cont...
def sentence_importance(sentence,dict_freq,sentences): sentence_score = 0 sentence = remove_special_characters(str(sentence)) sentence = re.sub(r'\d+', '', sentence) pos_tagged_sentence = [] no_of_sentences = len(sentences) pos_tagged_sentence = pos_tagging(sentence) for word in pos_t...
def remove_special_characters(text): regex = r'[^a-zA-Z0-9\s]' text = re.sub(regex,'',text) return text def lemmatize_words(words): lemmatized_words = [] for word in words: lemmatized_words.append(wordlemmatizer.lemmatize(word)) return lemmatized_words def freq(words): words = [word.l...
This code generates a summary by selecting the most important sentences from a document based on word frequency. It processes the input text by removing special characters, numbers, and stopwords, then lemmatizes words. Sentence importance is calculated using word frequencies, and the top sentences (determined by the s...
def generate_summary(document, percentage=30): tokenized_sentence = document text = " ".join(tokenized_sentence) text = remove_special_characters(str(text)) text = re.sub(r'\d+', '', text) tokenized_words_with_stopwords = word_tokenize(text) tokenized_words = [word for word in tokenized_words_w...
def generate_first_move(game_board, die, moves, player_figure): if game_board.bar.count(player_figure) > 0: generate_bar_move(game_board, die, moves, player_figure) else: n, m, step = set_for_loop(player_figure) for i in range(n, m, step): if len(game_board.triangles[i]) == 0...
This function generates valid moves for a player in backgammon when rolling equal dice. It processes existing moves by simulating each, checking for valid positions on the board, handling checkers on the bar, and determining possible moves in triangles. It considers bearing off, opponent checkers, and ensures moves com...
def generate_equal_dice_move(self, game_board, die, player_figure): if len(self.moves) == 0: generate_first_move(game_board, die, self.moves, player_figure) else: old_moves = deepcopy(self.moves) new_moves = list() for moves in list(self.moves): ...
def generate_equal_dice_moves(self, game_board, dice, player_figure): size = len(self.moves) for i in range(0, 4): self.generate_equal_dice_move(game_board, dice.die1, player_figure) if len(self.moves) == 0: break else: if len(self.move...
The main task of the code is to generate valid player moves based on dice rolls. It handles equal dice separately, then processes each die individually to build possible moves. It combines results, filters invalid moves, and ensures moves align with dice values. The code tracks validity of each die and combines moves w...
def generate_moves(self, game_board: Board, dice: Dice, player_figure): if dice.die1 == dice.die2: self.generate_equal_dice_moves(game_board, dice, player_figure) return size = 0 generate_first_move(game_board, dice.die1, self.one_die_moves, player_figure) if len(...
def calc_pareto(self): self.MRS1=MRS(self.u1) # marginal rate of substitution of the 1st participant self.MRS2=MRS(self.u2) # marginal rate of substitution of the 2nd participant # these can be used as offer/deamnd functions # MRS solved for p (i.e. not a function x and y, but x and p): ...
The main task of the code is to compute all solution sets related to a "box" by sequentially calculating Pareto optimal solutions, core solutions, equilibrium solutions, and budget constraints. This method orchestrates these four calculations to comprehensively determine the box's solution space in optimization or game...
def calc(self): """ calculate all solutions of the box """ self.calc_pareto() self.calc_core() self.calc_eq() self.calc_budget()
def ttopt_init(n, rmax, Y0=None, with_rank=False): """Build initial approximation for the main algorithm.""" d = len(n) r = [1] for i in range(1, d): r.append(min(rmax, n[i-1] * r[i-1])) r.append(1) if Y0 is None: Y0 = [np.random.randn(r[i], n[i], r[i + 1]) for i in range(d)] ...
The function `ttopt` efficiently finds the minimum value of a high-dimensional, implicitly defined tensor using adaptive sampling and tensor train (TT) decomposition. It avoids explicitly constructing the tensor by evaluating it through a provided function `f` at sampled indices. The method employs the cross-maximum-vo...
def ttopt(f, n, rmax=5, evals=None, Y0=None, fs_opt=1., add_opt_inner=True, add_opt_outer=False, add_opt_rect=False, add_rnd_inner=False, add_rnd_outer=False, J0=None, is_max=False): """Find the minimum element of the implicitly given multidimensional array. This function computes the minimum of the implicitly...
def del_connection(self): '''delete the connected jewels''' for i in range(self._column): for j in range(self._row): if self._board[i][j][0] == '*': self._board[i][j] = ' ' _fill(self._board) self._has_connection = False def drop_fa...
The main task of the code is to manage time passage by checking and handling two states: if a connection exists, it deletes it; if a faller exists, it drops it. Finally, it checks for a new connection. This function likely operates in a game or simulation context, managing object interactions or transitions over time.
def pass_time(self): '''pass the time''' if self._has_connection: self.del_connection() elif self._has_faller: self.drop_faller() self.check_connection()
def _create_display(self, size: tuple[int, int]) -> None: pygame.display.set_mode(size, pygame.RESIZABLE) def _update_world(self) -> None: for event in pygame.event.get(): self._handle_event(event) if not self._state._has_faller and not self._state._has_connection: ...
The code initializes a Pygame application, creates a display window, and runs a game loop that updates the game state and redraws the screen at a fixed frame rate. The loop continues until `self._running` is False, ensuring proper cleanup with `pygame.quit()` in the `finally` block.
def run(self) -> None: pygame.init() try: clock = pygame.time.Clock() self._create_display((_INITIAL_WIDTH, _INITIAL_HEIGHT)) while self._running: clock.tick(_FRAME_RATE) self._update_world() self._redraw() ...