content
stringlengths
22
815k
id
int64
0
4.91M
def test_abstract_guessing(): """Test abstract guessing property.""" class _CustomPsychometric(DiscriminationMethod): def psychometric_function(self, d): return 0.5 with pytest.raises(TypeError, match="abstract method"): _CustomPsychometric()
5,345,500
def remove_repeats(msg): """ This function removes repeated characters from text. :param/return msg: String """ # twitter specific repeats msg = re.sub(r"(.)\1{2,}", r"\1\1\1", msg) # characters repeated 3 or more times # laughs msg = re.sub(r"(ja|Ja)(ja|Ja)+(j)?", r"jaja", msg) # spanish msg = re.sub(r"(rs|Rs)(Rs|rs)+(r)?", r"rsrs", msg) # portugese msg = re.sub(r"(ha|Ha)(Ha|ha)+(h)?", r"haha", msg) # english return msg
5,345,501
def _legend_main_get(project, row): """ forma la leyenda de la serie principal del gráfico input project: es el tag project del proyecto seleccionado en fichero XYplus_parameters.f_xml -en XYplus_main.py- row: es fila activa devuelta por select_master) de donde se extrae el título del gráfico return un str con la leyenda del punto principal del gráfico """ legend_master = project.find('graph/legend_master').text.strip() columns_master = project.findall('graph/legend_master/column') if len(columns_master) == 0: return legend_master subs = [row[int(col1.text)-1] for col1 in columns_master] return legend_master.format(*subs)
5,345,502
def prop_elliptical_obscuration(wf, xradius, yradius, xc = 0.0, yc = 0.0, **kwargs): """Multiply the wavefront by an elliptical obscuration. Parameters ---------- wf : obj WaveFront class object xradius : float X ellipse radius in meters, unless norm is specified yradius : float Y ellipse radius in meters, unless norm is specified xc : float X-center of aperture relative to center of wavefront. Default is 0.0 yc : float Y-center of aperture relative to center of wavefront. Default is 0.0 Returns ------- None Multiplies current wavefront in wf object by an elliptical obscuration. Other Parameters ---------------- NORM : bool If set to True, the specified radii and aperure center are assumed to be normalized to the current beam radius. Default is False. """ if ("NORM" in kwargs and kwargs["NORM"]): norm = True else: norm = False wf.wfarr *= wf.wfarr * proper.prop_shift_center(proper.prop_ellipse(wf, xradius, yradius, xc, yc, NORM = norm, DARK = True)) return
5,345,503
def gen_queen_moves_quiet(queen_bitboard, opponents_pieces, blockers): """ generate capturing queen moves Args: queen_bitboard (int): Bitboard of positions of queens all_pieces (int): Bitboard of all other pieces on the board Returns: generator for all capturing queen moves gives 3-tuples (from, to, promote) """ while queen_bitboard: queen_square = forward_bit_scan(queen_bitboard) attack_bitboard = queen_sliding_quiet(queen_square, blockers) queen_bitboard = unset_bit(queen_bitboard, queen_square) attack_bitboard &= opponents_pieces yield from yield_moveset(queen_square, attack_bitboard)
5,345,504
def contrast_jwst_num(coro_floor, norm, matrix_dir, rms=50*u.nm): """ Compute the contrast for a random segmented OTE misalignment on the JWST simulator. :param coro_floor: float, coronagraph contrast floor :param norm: float, normalization factor for PSFs: peak of unaberrated direct PSF :param matrix_dir: str, directory of saved matrix :param rms: astropy quantity (e.g. m or nm), WFE rms (OPD) to be put randomly over the entire segmented mirror :return: 2x float, E2E and matrix contrast """ # Keep track of time start_time = time.time() # Parameters nb_seg = CONFIG_PASTIS.getint('JWST', 'nb_subapertures') iwa = CONFIG_PASTIS.getfloat('JWST', 'IWA') owa = CONFIG_PASTIS.getfloat('JWST', 'OWA') sampling = CONFIG_PASTIS.getfloat('JWST', 'sampling') # Import numerical PASTIS matrix filename = 'pastis_matrix' matrix_pastis = fits.getdata(os.path.join(matrix_dir, filename + '.fits')) # Create random aberration coefficients on segments, scaled to total rms aber = util.create_random_rms_values(nb_seg, rms) ### E2E JWST sim start_e2e = time.time() jwst_sim = webbpsf_imaging.set_up_nircam() jwst_sim[0].image_mask = CONFIG_PASTIS.get('JWST', 'focal_plane_mask') log.info('Calculating E2E contrast...') # Put aberration on OTE jwst_sim[1].zero() for nseg in range(nb_seg): # TODO: there is probably a single function that puts the aberration on the OTE at once seg_num = webbpsf_imaging.WSS_SEGS[nseg].split('-')[0] jwst_sim[1].move_seg_local(seg_num, piston=aber[nseg].value, trans_unit='nm') image = jwst_sim[0].calc_psf(nlambda=1) psf_jwst = image[0].data / norm # Create DH dh_mask = util.create_dark_hole(psf_jwst, iwa=iwa, owa=owa, samp=sampling) # Get the mean contrast contrast_jwst = util.dh_mean(psf_jwst, dh_mask) end_e2e = time.time() ## MATRIX PASTIS log.info('Generating contrast from matrix-PASTIS') start_matrixpastis = time.time() # Get mean contrast from matrix PASTIS contrast_matrix = util.pastis_contrast(aber, matrix_pastis) + coro_floor # calculating contrast with PASTIS matrix model end_matrixpastis = time.time() ## Outputs log.info('\n--- CONTRASTS: ---') log.info(f'Mean contrast from E2E: {contrast_jwst}') log.info(f'Contrast from matrix PASTIS: {contrast_matrix}') log.info('\n--- RUNTIMES: ---') log.info(f'E2E: {end_e2e-start_e2e}sec = {(end_e2e-start_e2e)/60}min') log.info(f'Matrix PASTIS: {end_matrixpastis-start_matrixpastis}sec = {(end_matrixpastis-start_matrixpastis)/60}min') end_time = time.time() runtime = end_time - start_time log.info(f'Runtime for contrast_calculation_simple.py: {runtime} sec = {runtime/60} min') return contrast_jwst, contrast_matrix
5,345,505
def ordinal_mapper(fh, coords, idmap, fmt=None, n=1000000, th=0.8, prefix=False): """Read an alignment file and match reads and genes in an ordinal system. Parameters ---------- fh : file handle Alignment file to parse. coords : dict of list Gene coordinates table. idmap : dict of list Gene identifiers. fmt : str, optional Alignment file format. n : int, optional Number of lines per chunk. th : float Minimum threshold of overlap length : alignment length for a match. prefix : bool Prefix gene IDs with nucleotide IDs. See Also -------- align.plain_mapper Yields ------ tuple of str Query queue. dict of set of str Subject(s) queue. """ # determine file format fmt, head = (fmt, []) if fmt else infer_align_format(fh) # assign parser for given format parser = assign_parser(fmt, ext=True) # cached list of query Ids for reverse look-up # gene Ids are unique, but read Ids can have duplicates (i.e., one read is # mapped to multiple loci on a genome), therefore an incremental integer # here replaces the original read Id as its identifer rids = [] rid_append = rids.append # cached map of read to coordinates locmap = defaultdict(list) def flush(): """Match reads in current chunk with genes from all nucleotides. Returns ------- tuple of str Query queue. dict of set of str Subject(s) queue. """ # master read-to-gene(s) map res = defaultdict(set) # iterate over nucleotides for nucl, locs in locmap.items(): # it's possible that no gene was annotated on the nucleotide try: glocs = coords[nucl] except KeyError: continue # get reference to gene identifiers gids = idmap[nucl] # append prefix if needed pfx = nucl + '_' if prefix else '' # execute ordinal algorithm when reads are many # 8 (5+ reads) is an empirically determined cutoff if len(locs) > 8: # merge and sort coordinates # question is to add unsorted read coordinates into pre-sorted # gene coordinates # Python's Timsort algorithm is efficient for this task queue = sorted(chain(glocs, locs)) # map reads to genes using the core algorithm for read, gene in match_read_gene(queue): # add read-gene pairs to the master map res[rids[read]].add(pfx + gids[gene]) # execute naive algorithm when reads are few else: for read, gene in match_read_gene_quart(glocs, locs): res[rids[read]].add(pfx + gids[gene]) # return matching read Ids and gene Ids return res.keys(), res.values() this = None # current query Id target = n # target line number at end of current chunk # parse alignment file for i, row in enumerate(parser(chain(iter(head), fh))): query, subject, _, length, beg, end = row[:6] # skip if length is not available or zero if not length: continue # when query Id changes and chunk limits has been reached if query != this and i >= target: # flush: match currently cached reads with genes and yield yield flush() # re-initiate read Ids, length map and location map rids = [] rid_append = rids.append locmap = defaultdict(list) # next target line number target = i + n # append read Id, alignment length and location idx = len(rids) rid_append(query) # effective length = length * th # -int(-x // 1) is equivalent to math.ceil(x) but faster # this value must be >= 1 locmap[subject].extend(( (beg << 48) + (-int(-length * th // 1) << 31) + idx, (end << 48) + idx)) this = query # final flush yield flush()
5,345,506
def modify_tilt(path, bin_factor, exclude_angles=[]): """ Modifies the bin-factor and exclude-angles of a given tilt.com file. Note: This will overwrite the file! Parameters ---------- path : str Path to the tilt.com file. bin_factor : int The new bin-factor. exclude_angles : List<int> List of the tilt-angles to exclude during reconstruction. Default: ``[]`` """ f = open(path, 'r') content = [l.strip() for l in f] f.close() if not ('UseGPU 0' in content): content.insert(len(content) - 1, 'UseGPU 0') binned_idx = [i for i, s in enumerate(content) if 'IMAGEBINNED' in s][0] content[binned_idx] = 'IMAGEBINNED ' + str(bin_factor) if len(exclude_angles) > 0: exclude_idx = [i for i, s in enumerate(content) if 'EXCLUDELIST2 ' in s] if len(exclude_idx) == 0: exclude_idx = len(content) - 1 else: exclude_idx = exclude_idx[0] content[exclude_idx] = "EXCLUDELIST2 " + str(exclude_angles)[1:-1] f = open(path, 'w') for l in content: f.writelines("%s\n" % l) print(l) f.close()
5,345,507
def file_lines(filename): """ >>> file_lines('test/foo.txt') ['foo', 'bar'] """ return text_file(filename).split()
5,345,508
def repr_should_be_defined(obj): """Checks the obj.__repr__() method is properly defined""" obj_repr = repr(obj) assert isinstance(obj_repr, str) assert obj_repr == obj.__repr__() assert obj_repr.startswith("<") assert obj_repr.endswith(">") return obj_repr
5,345,509
def read_tiff(tiff_path): """ Args: tiff_path: a tiff file path Returns: tiff image object """ if not os.path.isfile(tiff_path) or not is_tiff_file(tiff_path): raise InvalidTiffFileError(tiff_path) return imread(tiff_path)
5,345,510
def changePassword(): """ Change to a new password and email user. URL Path: URL Args (required): - JSON structure of change password data Returns: 200 OK if invocation OK. 500 if server not configured. """ @testcase def changePasswordWorker(): try: util.debugPrint("changePassword") if not Config.isConfigured(): util.debugPrint("Please configure system") abort(500) urlPrefix = Config.getDefaultPath() requestStr = request.data accountData = json.loads(requestStr) return jsonify(AccountsChangePassword.changePasswordEmailUser( accountData, urlPrefix)) except: print "Unexpected error:", sys.exc_info()[0] print sys.exc_info() traceback.print_exc() util.logStackTrace("Unexpected error:" + str(sys.exc_info()[0])) raise return changePasswordWorker()
5,345,511
def parallel_for( loop_callback: Callable[[Any], Any], parameters: List[Tuple[Any, ...]], nb_threads: int = os.cpu_count()+4 ) -> List[Any]: """Execute a for loop body in parallel .. note:: Race-Conditions Code executation in parallel can cause into an "race-condition" error. Arguments: loop_callback(Callable): function callback running in the loop body parameters(List[Tuple]): element to execute in parallel Returns: (List[Any]): list of values Examples: .. example-code:: >>> x = lambda x: x ** 2 >>> parallel_for(x, [y for y in range(10)]) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] """ with closing(multiprocessing.pool.ThreadPool(nb_threads)) as pool: return pool.map(loop_callback, parameters)
5,345,512
def indexName(): """Index start page.""" return render_template('index.html')
5,345,513
def on_vlc_closed(to_watch_folder, watched_folder, ml_xspf, trigger): """ Checks if modified event trigger was ml.xspf. If yes then finds movie in to_watch_folder that returns true from is_movie_watched(), and calls ask_and_move with the movie folder as source and the watched folder as destination. """ if os.path.exists(trigger) and os.path.samefile(trigger, ml_xspf): logging.info('in on_vlc_closed() -> ') for content in os.listdir(to_watch_folder): folder_moved = False movie_folder = os.path.join(to_watch_folder, content) if not os.path.isdir(movie_folder): continue for file_ in os.listdir(movie_folder): movie = os.path.join(movie_folder, file_) if not os.path.isfile(movie): continue logging.info(f"Movie: {movie}; IsWatched: {is_movie_watched(movie)}") if is_movie_watched(movie): logging.info(f"Moving {movie_folder} to {watched_folder}") ask_and_move(movie_folder, watched_folder, message=f"Move {movie_folder} to {watched_folder}?", success_message=f"Successfully moved {movie_folder} to {watched_folder}.", retry_message="Unable to move folder. Retry?") folder_moved = True break if folder_moved: continue logging.info("leaving on_vlc_close() ->")
5,345,514
def translate_http_code(): """Print given code :return: """ return make_http_code_translation(app)
5,345,515
def _def_tconst(pattern, _): """Temporal constraints for the energy interval abstraction pattern""" deflection = pattern.hypothesis pattern.last_tnet.add_constraint(deflection.start, deflection.end, DEF_DUR)
5,345,516
def delete_directory(a_dir): """ Delete a directory tree recursively """ shutil.rmtree(a_dir, onerror=on_remove_error)
5,345,517
def test_colossus_vmax_consistency_z1(): """ """ try: from colossus.cosmology import cosmology from colossus.halo.profile_nfw import NFWProfile as ColossusNFW except ImportError: return _cosmo = cosmology.setCosmology('planck15') masses_to_check = 10**np.array((11., 12, 13, 14, 15)) conc_to_check = [5., 10., 15.] z = 1. nfw = NFWProfile(cosmology=Planck15, redshift=z) for M, c in product(masses_to_check, conc_to_check): colossus_nfw = ColossusNFW(M=M, c=c, mdef='vir', z=z) colossus_vmax, colossus_rmax = colossus_nfw.Vmax() halotools_vmax = nfw.vmax(M, c)[0] msg = ("\nM = {0:.2e}, c = {1:.1f}, z = {2:.1f}\n" "Colossus Vmax = {3:.2f}\nHalotools Vmax = {4:.2f}\n".format( M, c, z, colossus_vmax, halotools_vmax)) assert np.allclose(colossus_vmax, halotools_vmax, rtol=0.05), msg
5,345,518
def interactive(python): """ Main entrypoint into dbmp interactive mode """ args = '' if not os.path.exists(HISTORY): io.open(HISTORY, 'w+').close() try: while True: pt.shortcuts.clear() pt.shortcuts.set_title("Datera Bare-Metal Provisioner") print("Welcome to the DBMP Interactive Session") print( pt.HTML("Would you like to <green>provison</green>, " "or <red>clean</red> up or <blue>list</blue>?")) out = session.prompt(pt.HTML( "choices: [(<green>p</green>)rovision, " "(<red>c</red>)lean, " "(<blue>l</blue>)ist]> "), default="p", lexer=pt.lexers.PygmentsLexer(WelcomeLexer), style=dbmp_style, multiline=False, key_bindings=bindings, completer=dbmp_interactive_completer) out = out.strip().lower() print() if out in {"p", "provision"}: args = provision() if out in {"c", "clean"}: args = clean() if out in {"l", "list"}: args = dlist() if out in QUIT: if args: print(args) app_exit(0) if not pt.shortcuts.confirm("Are you using multipath?"): args.append("--no-multipath") dbmp_exe(python, args) except KeyboardInterrupt: app_exit(1)
5,345,519
def dose_rate(sum_shielding, isotope, disable_buildup = False): """ Calculate the dose rate for a specified isotope behind shielding behind shielding barriers. The dose_rate is calculated for 1MBq Args: sum_shielding: dict with shielding elements isotope: isotope name (string) """ t = transmission_sum(sum_shielding, isotope, disable_buildup) energies = ps.config.get_setting(ps.ISOTOPES)[isotope][ps.ENERGY_keV] abundance = ps.config.get_setting(ps.ISOTOPES)[isotope][ps.ABUNDANCE] if DEBUG: ps.logger.debug(isotope) ps.logger.debug('t: %s', t) ps.logger.debug('energies: %s', energies) ps.logger.debug('abundance: %s', abundance) rate = H10(energy_keV=energies, abundance=t * np.array(abundance)) return rate
5,345,520
def parmap(f, X, nprocs=1): """ parmap_fun() and parmap() are adapted from klaus se's post on stackoverflow. https://stackoverflow.com/a/16071616/4638182 parmap allows map on lambda and class static functions. Fall back to serial map when nprocs=1. """ if nprocs < 1: raise ValueError("nprocs should be >= 1. nprocs: {}".format(nprocs)) nprocs = min(int(nprocs), mp.cpu_count()) # exception handling f # simply ignore all exceptions. If exception occurs in parallel queue, the # process with exception will get stuck and not be able to process # following requests. def ehf(x): try: res = f(x) except Exception as e: res = e return res # fall back on serial if nprocs == 1: return list(map(ehf, X)) q_in = mp.Queue(1) q_out = mp.Queue() proc = [mp.Process(target=_parmap_fun, args=(ehf, q_in, q_out)) for _ in range(nprocs)] for p in proc: p.daemon = True p.start() sent = [q_in.put((i, x)) for i, x in enumerate(X)] [q_in.put((None, None)) for _ in range(nprocs)] res = [q_out.get() for _ in range(len(sent))] [p.join() for p in proc] # maintain the order of X ordered_res = [x for i, x in sorted(res)] for i, x in enumerate(ordered_res): if isinstance(x, Exception): warnings.warn("{} encountered in parmap {}th arg {}".format( x, i, X[i])) return ordered_res
5,345,521
def is_char_token(c: str) -> bool: """Return true for single character tokens.""" return c in ["+", "-", "*", "/", "(", ")"]
5,345,522
def pre_commit(session_: Session) -> None: """Lint using pre-commit.""" args = session_.posargs or ["run", "--all-files", "--show-diff-on-failure"] _export_requirements(session_) poetry_install(session_) session_.install("pre-commit") session_.run("pre-commit", *args) if args and args[0] == "install": activate_virtualenv_in_precommit_hooks(session_) _cleanup_requirements()
5,345,523
def _float_arr_to_int_arr(float_arr): """Try to cast array to int64. Return original array if data is not representable.""" int_arr = float_arr.astype(numpy.int64) if numpy.any(int_arr != float_arr): # we either have a float that is too large or NaN return float_arr else: return int_arr
5,345,524
def test_bernese_koordinat_kovarians(): """Test at den samlede løsnings kovariansmatrix læses korrekt.""" BUDP = BerneseSolution(ADDNEQ2096, CRD2096, COV2096)["BUDP"] skalering = 0.001 ** 2 assert BUDP.kovarians.xx == 0.9145031116e-01 * skalering assert BUDP.kovarians.yx == 0.1754111808e-01 * skalering assert BUDP.kovarians.zx == 0.9706757931e-01 * skalering assert BUDP.kovarians.yy == 0.1860172410e-01 * skalering assert BUDP.kovarians.zy == 0.2230707662e-01 * skalering assert BUDP.kovarians.zz == 0.1740501496e00 * skalering # Kontroller at spredning bestemt fra kovariansmatrix er ens med spredning # aflæst i ADDNEQ-filen. Vi har kun 5 decimaler til rådighed ved læsning af # koordinatspredningerne derfor sættes abs_tol=1e-5 assert math.isclose(math.sqrt(BUDP.kovarians.xx), BUDP.koordinat.sx, abs_tol=1e-5) assert math.isclose(math.sqrt(BUDP.kovarians.yy), BUDP.koordinat.sy, abs_tol=1e-5) assert math.isclose(math.sqrt(BUDP.kovarians.zz), BUDP.koordinat.sz, abs_tol=1e-5)
5,345,525
def latest(scores: Scores) -> int: """The last added score.""" return scores[-1]
5,345,526
def get_dp_2m(wrfin, timeidx=0, method="cat", squeeze=True, cache=None, meta=True, _key=None, units="degC"): """Return the 2m dewpoint temperature. This functions extracts the necessary variables from the NetCDF file object in order to perform the calculation. Args: wrfin (:class:`netCDF4.Dataset`, :class:`Nio.NioFile`, or an \ iterable): WRF-ARW NetCDF data as a :class:`netCDF4.Dataset`, :class:`Nio.NioFile` or an iterable sequence of the aforementioned types. timeidx (:obj:`int` or :data:`wrf.ALL_TIMES`, optional): The desired time index. This value can be a positive integer, negative integer, or :data:`wrf.ALL_TIMES` (an alias for None) to return all times in the file or sequence. The default is 0. method (:obj:`str`, optional): The aggregation method to use for sequences. Must be either 'cat' or 'join'. 'cat' combines the data along the Time dimension. 'join' creates a new dimension for the file index. The default is 'cat'. squeeze (:obj:`bool`, optional): Set to False to prevent dimensions with a size of 1 from being automatically removed from the shape of the output. Default is True. cache (:obj:`dict`, optional): A dictionary of (varname, ndarray) that can be used to supply pre-extracted NetCDF variables to the computational routines. It is primarily used for internal purposes, but can also be used to improve performance by eliminating the need to repeatedly extract the same variables used in multiple diagnostics calculations, particularly when using large sequences of files. Default is None. meta (:obj:`bool`, optional): Set to False to disable metadata and return :class:`numpy.ndarray` instead of :class:`xarray.DataArray`. Default is True. _key (:obj:`int`, optional): A caching key. This is used for internal purposes only. Default is None. units (:obj:`str`): The desired units. Refer to the :meth:`getvar` product table for a list of available units for 'td2'. Default is 'degC'. Returns: :class:`xarray.DataArray` or :class:`numpy.ndarray`: The 2m dewpoint temperature. If xarray is enabled and the *meta* parameter is True, then the result will be a :class:`xarray.DataArray` object. Otherwise, the result will be a :class:`numpy.ndarray` object with no metadata. """ varnames=("PSFC", "Q2") ncvars = extract_vars(wrfin, timeidx, varnames, method, squeeze, cache, meta=False, _key=_key) # Algorithm requires hPa psfc = .01*(ncvars["PSFC"]) # Copy needed for the mmap nonsense of scipy.io.netcdf, which seems to # break with every release q2 = ncvars["Q2"].copy() q2[q2 < 0] = 0 td = _td(psfc, q2) return td
5,345,527
def fit_uncertainty(points, lower_wave, upper_wave, log_center_wave, filter_size): """Performs fitting many times to get an estimate of the uncertainty """ mock_points = [] for i in range(1, 100): # First, fit the points coeff = np.polyfit(np.log10(points['rest_wavelength']), np.random.normal(points['f_lambda'], points['err_f_lambda']), deg=2) # , w=(1/points['err_f_lambda']) # Get the polynomial fit_func = np.poly1d(coeff) # x-range over which we fit fit_wavelengths = np.arange( np.log10(lower_wave), np.log10(upper_wave), 0.001) # Values of the points we fit fit_points = fit_func(fit_wavelengths) # Indexes of the values that lie in the mock filter fit_idx = np.logical_and(fit_wavelengths > (log_center_wave - filter_size), fit_wavelengths < (log_center_wave + filter_size)) # Average the values in the mock filter to get the mock point mock_sed_point = np.mean(fit_points[fit_idx]) mock_points.append(mock_sed_point) # PERCENTILE ERROR HERE? mock_sed_point, l_err, u_err = np.percentile(mock_points, [50, 15.7, 84.3]) return mock_sed_point, u_err - mock_sed_point, mock_sed_point - l_err
5,345,528
def from_dateutil_rruleset(rruleset): """ Convert a `dateutil.rrule.rruleset` instance to a `Recurrence` instance. :Returns: A `Recurrence` instance. """ rrules = [from_dateutil_rrule(rrule) for rrule in rruleset._rrule] exrules = [from_dateutil_rrule(exrule) for exrule in rruleset._exrule] rdates = rruleset._rdate exdates = rruleset._exdate dts = [r._dtstart for r in rruleset._rrule] + rruleset._rdate if len(dts) > 0: dts.sort() dtstart = dts[0] else: dtstart = None return Recurrence(dtstart, rrules, exrules, rdates, exdates)
5,345,529
def error_038_italic_tag(text): """Fix the error and return (new_text, replacements_count) tuple.""" backup = text (text, count) = re.subn(r"<(i|em)>([^\n<>]+)</\1>", "''\\2''", text, flags=re.I) if re.search(r"</?(?:i|em)>", text, flags=re.I): return (backup, 0) else: return (text, count)
5,345,530
def create_user(): """ Method that will create an user . Returns: user.id: The id of the created user Raises: If an error occurs it will be displayed in a error message. """ try: new_user = User(name=login_session['username'], email=login_session[ 'email'], picture=login_session['picture']) db_session.add(new_user) db_session.commit() user = db_session.query(User).filter_by(email=login_session['email']).one() return user.id except Exception as e: flash('An error has occurred: {}'.format(str(e)), 'error') return None
5,345,531
def store_relation( self, relation_name, persist_type, relation_persist_type, validate = False, force_persist = False, raise_exception = False, store_relations = True, entity_manager = None ): """ Stores a relation with the given name in the entity using the permissions granted by the persist type. In case the raise exception flag is set an exception is raise upon validation of model failure. The storage of the relation implies previous validation of associative permissions and so this method may change the current entity relation in case of malicious manipulation. :type relation_name: String :param relation_name: The name of the relation to be saved. This value may refer a lazy loaded relation. :type persist_type: int :param persist_type: The persist type mask that controls the persistence access. :type relation_persist_type: int :param relation_persist_type: The pre-defined (base) persist type mask that controls the relation persist type. :type validate: bool :param validate: Flag controlling if a validation should be run in the relation model before persisting it. :type force_persist: bool :param force_persist: Flag controlling if the persistence should be forced in which case the persist type mask is completely ignored by the persistence engine. :type raise_exception: bool :param raise_exception: If an exception must be raised in case a validation fails in one of the relation values. :type store_relations: bool :param store_relations: If the complete set of relations of the current entity should also be persisted (chained storage). :type entity_manager: EntityManager :param entity_manager: The optional entity manager reference to be used. """ # in case the relation is lazy loaded in the # current entity no need to store it and so the # control flow should be returned immediately if self.is_lazy_loaded(relation_name): return # starts the flag that controls in case # an error is set error_set = False # retrieves the relation value from the entity and then # converts it to an enumerable type for compatibility # (if required by the relation type) relation_value = self.get_value(relation_name) relation_is_to_many = self.is_to_many(relation_name) relation_value = not relation_is_to_many and [relation_value] or relation_value # creates the list to store the relation values # that are not "associable" and that so must be # removed from the entity, to avoid malicious # association in the data source remove_relations = [] # iterates over all the relation values for storage # in case a validation fails it accumulates the various # errors around the storing procedure "soft fail" for _relation_value in relation_value: try: # retrieves the id attribute value from the relation value # to use under the relation validation check (check if they were # previously associated) id_attribute_value = _relation_value.get_id_attribute_value() # sets the relation valid flag as unset by default, no relation # validation is done by default relation_valid = False # in case the current persist type includes the update permission # the relation validation must be run in order to provide extra # relation validation permissions if persist_type & (PERSIST_UPDATE | PERSIST_SAVE): # in case the relation value is set and it's valid # (not empty) it's ready for validation of relations if _relation_value: # validate the given entity for relation with the relation # value in the attribute of name relation name relation_valid = self.validate_relation(id_attribute_value, relation_name) # otherwise the validation is not required # the value is not valid, not set else: # sets the relation as (automatically) valid, it's impossible # to check if an invalid relation is valid relation_valid = True # in case the relation is not valid (must remove update from # the persist type, not safe) if not relation_valid: # "calculates" the new persist type based on the base persist type # removes the update type from the persist type (it's not safe) persist_type &= PERSIST_ALL ^ PERSIST_UPDATE # checks if the relations is "storable" a relation is considered to be # "storable" if the persist type of it contains either the update or the # save permission (otherwise it's impossible to store it) is_storable = persist_type & (PERSIST_UPDATE | PERSIST_SAVE) # checks if the relation value is "associable", the relation value # is "associable" in case it's going to be created (no id attribute set), # in case the relation has just been saved (in current context), in # case the associate "permission" is set in the persist type or in # case the relation was previously (other transaction) set in the # entity (relation validation) is_associable = relation_valid or id_attribute_value == None or\ _relation_value.is_saved() or relation_persist_type & PERSIST_ASSOCIATE # stores the relation value in the data source # using the "propagated" persist type (only in # case the relation is "storable") is_storable and _relation_value.store( persist_type, validate, force_persist = force_persist, store_relations = store_relations, entity_manager = entity_manager ) # in case the relation is not valid it must be removed # from the entity to avoid "malicious" association to be set # on the data source (corrupting data from a security point) not is_associable and remove_relations.append(_relation_value) except exceptions.ModelValidationError: # in case the raise exception flag is set # the exception must be "raised again" if raise_exception: raise # sets the error set flag, to trigger # the add error action at the end of # the relation store error_set = True # in case there is at least one item in the relation # that is considered not valid (to be removed) the relation # is considered invalid and is removed from the entity # model (provides the main data model security measure) remove_relations and self.delete_value(relation_name) # adds an error to the entity on the relation # for latter usage and presentation to user if error_set: self.add_error(relation_name, "relation validation failed")
5,345,532
def buildStartAndEndWigData(thisbam, LOG_EVERY_N=1000, logger=None): """parses a bam file for 3' and 5' ends and builds these into wig-track data Returns a dictionary of various gathered statistics.""" def formatToWig(wigdata): """ take in the read position data and output in wigTrack format""" this_wigTracks = {} for key in wigdata.keys(): track = wigTrack() track.wigtype = "fixedStep" track.chr = key track.start = 1 track.step = 1 track.position = numpy.arange(len(wigdata[key]))+track.start this_wigTracks[key] = track this_wigTracks[key].data = wigdata[key] this_wigData = wigData() this_wigData.tracks = this_wigTracks return(this_wigData) if type(thisbam) is str: thisbam = pysam.AlignmentFile(thisbam, "rb") all_wigdata={ "fwd":{ "five_prime":{}, "three_prime":{} }, "rev":{ "five_prime":{}, "three_prime":{} } } chromSizes = dict(zip(thisbam.references, thisbam.lengths)) for key in chromSizes.keys(): for strand in all_wigdata.keys(): for end in all_wigdata[strand].keys(): all_wigdata[strand][end][key] = numpy.zeros(chromSizes[key]) counter=0 nlogs=0 for read in thisbam.fetch(): if read.is_reverse: all_wigdata["rev"]["five_prime"][read.reference_name][read.reference_end-1]+=1 all_wigdata["rev"]["three_prime"][read.reference_name][read.reference_start]+=1 else: all_wigdata["fwd"]["five_prime"][read.reference_name][read.reference_start]+=1 all_wigdata["fwd"]["three_prime"][read.reference_name][read.reference_end-1]+=1 counter+=1 if (counter % LOG_EVERY_N)==0: msg = "processed {these} reads...".format(these=(nlogs*LOG_EVERY_N)) if logger is not None: logger.info(msg) else: print(msg) nlogs+=1 msg = "Processed {counted} reads...".format(counted=counter) if logger is not None: logger.info(msg) else: print(msg) msg = "Formatting wig tracks..." if logger is not None: logger.info(msg) else: print(msg) for strand in all_wigdata.keys(): for end in all_wigdata[strand].keys(): all_wigdata[strand][end] = formatToWig(all_wigdata[strand][end]) return(all_wigdata, chromSizes)
5,345,533
def time_series_h5(timefile: Path, colnames: List[str]) -> Optional[DataFrame]: """Read temporal series HDF5 file. If :data:`colnames` is too long, it will be truncated. If it is too short, additional column names will be deduced from the content of the file. Args: timefile: path of the TimeSeries.h5 file. colnames: names of the variables expected in :data:`timefile` (may be modified). Returns: A :class:`pandas.DataFrame` containing the time series, organized by variables in columns and the time steps in rows. """ if not timefile.is_file(): return None with h5py.File(timefile, 'r') as h5f: dset = h5f['tseries'] _, ncols = dset.shape ncols -= 1 # first is istep h5names = h5f['names'].asstr()[len(colnames) + 1:] _tidy_names(colnames, ncols, h5names) data = dset[()] pdf = pd.DataFrame(data[:, 1:], index=np.int_(data[:, 0]), columns=colnames) # remove duplicated lines in case of restart return pdf.loc[~pdf.index.duplicated(keep='last')]
5,345,534
def decode_jwt(token): """decodes a token and returns ID associated (subject) if valid""" try: payload = jwt.decode(token.encode(), current_app.config['SECRET_KEY'], algorithms=['HS256']) return {"isError": False, "payload": payload["sub"]} except jwt.ExpiredSignatureError as e: current_app.logger.error("Token expired.") raise ExpiredTokenError() except jwt.InvalidTokenError as e: current_app.logger.error("Invalid token.") raise InvalidTokenError()
5,345,535
def _validate_image_info(ext, image_info=None, **kwargs): """Validates the image_info dictionary has all required information. :param ext: Object 'self'. Unused by this function directly, but left for compatibility with async_command validation. :param image_info: Image information dictionary. :param kwargs: Additional keyword arguments. Unused, but here for compatibility with async_command validation. :raises: InvalidCommandParamsError if the data contained in image_info does not match type and key:value pair requirements and expectations. """ image_info = image_info or {} md5sum_avail = False os_hash_checksum_avail = False for field in ['id', 'urls']: if field not in image_info: msg = 'Image is missing \'{}\' field.'.format(field) raise errors.InvalidCommandParamsError(msg) if type(image_info['urls']) != list or not image_info['urls']: raise errors.InvalidCommandParamsError( 'Image \'urls\' must be a list with at least one element.') checksum = image_info.get('checksum') if checksum is not None: if (not isinstance(image_info['checksum'], str) or not image_info['checksum']): raise errors.InvalidCommandParamsError( 'Image \'checksum\' must be a non-empty string.') md5sum_avail = True os_hash_algo = image_info.get('os_hash_algo') os_hash_value = image_info.get('os_hash_value') if os_hash_algo or os_hash_value: if (not isinstance(os_hash_algo, str) or not os_hash_algo): raise errors.InvalidCommandParamsError( 'Image \'os_hash_algo\' must be a non-empty string.') if (not isinstance(os_hash_value, str) or not os_hash_value): raise errors.InvalidCommandParamsError( 'Image \'os_hash_value\' must be a non-empty string.') os_hash_checksum_avail = True if not (md5sum_avail or os_hash_checksum_avail): raise errors.InvalidCommandParamsError( 'Image checksum is not available, either the \'checksum\' field ' 'or the \'os_hash_algo\' and \'os_hash_value\' fields pair must ' 'be set for image verification.')
5,345,536
def show(nodes, print_groups): """Show generic information on node(s).""" from aiida.cmdline.utils.common import get_node_info for node in nodes: # pylint: disable=fixme #TODO: Add a check here on the node type, otherwise it might try to access # attributes such as code which are not necessarily there echo.echo(get_node_info(node)) if print_groups: from aiida.orm.querybuilder import QueryBuilder from aiida.orm.group import Group from aiida.orm.node import Node # pylint: disable=redefined-outer-name # pylint: disable=invalid-name qb = QueryBuilder() qb.append(Node, tag='node', filters={'id': {'==': node.pk}}) qb.append(Group, tag='groups', group_of='node', project=['id', 'name']) echo.echo("#### GROUPS:") if qb.count() == 0: echo.echo("No groups found containing node {}".format(node.pk)) else: res = qb.iterdict() for gr in res: gr_specs = "{} {}".format(gr['groups']['name'], gr['groups']['id']) echo.echo(gr_specs)
5,345,537
def format_point(point: Point) -> str: """Return a str representing a Point object. Args: point: Point obj to represent. Returns: A string representing the Point with ° for grades, ' for minutes and " for seconds. Latitude is written before Longitude. Example Output: 30°21'12", 10°21'22" """ lat = to_sexagesimal(point.latitude) long = to_sexagesimal(point.longitude) return f'[{lat.deg}°{lat.min}\'{lat.sec}\", {long.deg}°{long.min}\'{long.sec}\"]'
5,345,538
def handle_get_authentication_groups_db(self, handle, connection, match, data, hdr): """ GET /authentication/groups_db Get user database on this runtime Response status code: OK or INTERNAL_ERROR Response: { "policies": { <policy-id>: policy in JSON format, ... } } """ # TODO:to be implemented pass
5,345,539
def families_horizontal_correctors(): """.""" return ['CH']
5,345,540
def test_viewmodel(): """Get a data manager instance for each test function.""" # Create the device under test (dut) and connect to the database. dut = RAMSTKHardwareBoMView() yield dut # Unsubscribe from pypubsub topics. pub.unsubscribe(dut.on_insert, "succeed_insert_hardware") pub.unsubscribe(dut.on_insert, "succeed_insert_design_electric") pub.unsubscribe(dut.on_insert, "succeed_insert_design_mechanic") pub.unsubscribe(dut.on_insert, "succeed_insert_milhdbk217f") pub.unsubscribe(dut.on_insert, "succeed_insert_nswc") pub.unsubscribe(dut.on_insert, "succeed_insert_reliability") pub.unsubscribe(dut.do_set_tree, "succeed_retrieve_hardwares") pub.unsubscribe(dut.do_set_tree, "succeed_retrieve_design_electrics") pub.unsubscribe(dut.do_set_tree, "succeed_retrieve_design_mechanics") pub.unsubscribe(dut.do_set_tree, "succeed_retrieve_milhdbk217fs") pub.unsubscribe(dut.do_set_tree, "succeed_retrieve_nswcs") pub.unsubscribe(dut.do_set_tree, "succeed_retrieve_reliabilitys") pub.unsubscribe(dut.do_set_tree, "succeed_delete_hardware") pub.unsubscribe(dut.do_set_tree, "succeed_delete_design_electric") pub.unsubscribe(dut.do_set_tree, "succeed_delete_design_mechanic") pub.unsubscribe(dut.do_set_tree, "succeed_delete_milhdbk217f") pub.unsubscribe(dut.do_set_tree, "succeed_delete_nswc") pub.unsubscribe(dut.do_set_tree, "succeed_delete_reliability") pub.unsubscribe(dut.do_calculate_hardware, "request_calculate_hardware") pub.unsubscribe( dut.do_calculate_power_dissipation, "request_calculate_power_dissipation" ) pub.unsubscribe( dut.do_predict_active_hazard_rate, "request_predict_active_hazard_rate" ) # Delete the device under test. del dut
5,345,541
def variable_select_source_data_proxy(request): """ @summary: 获取下拉框源数据的通用接口 @param request: @return: """ url = request.GET.get('url') try: response = requests.get( url=url, verify=False ) except Exception as e: logger.exception('variable select get data from url[url={url}] raise error: {error}'.format(url=url, error=e)) text = _('请求数据异常: {error}').format(error=e) data = [{'text': text, 'value': ''}] return JsonResponse(data, safe=False) try: data = response.json() except Exception: try: content = response.content.decode(response.encoding) logger.exception('variable select get data from url[url={url}] is not a valid JSON: {data}'.format( url=url, data=content[:500]) ) except Exception: logger.exception('variable select get data from url[url={url}] data is not a valid JSON'.format(url=url)) text = _('返回数据格式错误,不是合法 JSON 格式') data = [{'text': text, 'value': ''}] return JsonResponse(data, safe=False)
5,345,542
def test_directed_valid_paths(): """ antco.ntools.getValidPaths() (directed) testing unit """ # Initial position (0) -> Valid paths: (1) adj_matrix = np.array([ [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0], [1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0]], dtype=np.int8) current_path = np.array([0], dtype=np.int64) choices = getValidPaths(0, current_path, adj_matrix) assert choices == [1], 'FAILED TEST: antco.ntools.getValidPaths() (directed)' current_path = np.array([0], dtype=np.int64) choices = getValidPaths(1, current_path, adj_matrix) assert choices == [2, 5], 'FAILED TEST: antco.ntools.getValidPaths() (directed)' current_path = np.array([5], dtype=np.int64) choices = getValidPaths(1, current_path, adj_matrix) assert choices == [2], 'FAILED TEST: antco.ntools.getValidPaths() (directed)' current_path = np.array([5, 2], dtype=np.int64) choices = getValidPaths(1, current_path, adj_matrix) assert choices == [], 'FAILED TEST: antco.ntools.getValidPaths() (directed)' print('SUCCESSFUL TEST: antco.ntools.test_valid_paths() (directed)')
5,345,543
async def select_guild_lfg_events(guild_id: int) -> list[asyncpg.Record]: """Gets the lfg messages for a specific guild ordered by the youngest creation date""" select_sql = f""" SELECT id, message_id, creation_time, voice_channel_id FROM lfgmessages WHERE guild_id = $1 ORDER BY creation_time ASC;""" async with (await get_connection_pool()).acquire(timeout=timeout) as connection: return await connection.fetch(select_sql, guild_id)
5,345,544
def ValueToString(descriptor, field_desc, value): """Renders a field value as a PHP literal. Args: descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. field_desc: The type descriptor for the field value to be rendered. value: The value of the field to be rendered. Returns: A PHP literal for the provided value. """ if field_desc.label == descriptor.FieldDescriptor.LABEL_REPEATED: if value: return '[%s]' % ', '.join([NonRepeatedValueToString(descriptor, field_desc, s) for s in value]) return '[]' return NonRepeatedValueToString(descriptor, field_desc, value)
5,345,545
def get_checkpoints(run_dir, from_global_step=None, last_only=False): """Return all available checkpoints. Args: run_dir: Directory where the checkpoints are located. from_global_step (int): Only return checkpoints after this global step. The comparison is *strict*. If ``None``, returns all available checkpoints. Returns: List of dicts (with keys ``global_step``, ``file``) with all the checkpoints found. Raises: ValueError: If there are no checkpoints in ``run_dir``. """ # The latest checkpoint file should be the last item of # `all_model_checkpoint_paths`, according to the CheckpointState protobuf # definition. # TODO: Must check if the checkpoints are complete somehow. ckpt = tf.train.get_checkpoint_state(run_dir) if not ckpt or not ckpt.all_model_checkpoint_paths: raise ValueError('Could not find checkpoint in {}.'.format(run_dir)) # TODO: Any other way to get the global_step? (Same as in `checkpoints`.) checkpoints = sorted([ {'global_step': int(path.split('-')[-1]), 'file': path} for path in ckpt.all_model_checkpoint_paths ], key=lambda c: c['global_step']) if last_only: checkpoints = checkpoints[-1:] tf.logging.info( 'Using last checkpoint in run_dir, global_step = {}'.format( checkpoints[0]['global_step'] ) ) elif from_global_step is not None: checkpoints = [ c for c in checkpoints if c['global_step'] > from_global_step ] tf.logging.info( 'Found %s checkpoints in run_dir with global_step > %s', len(checkpoints), from_global_step, ) else: tf.logging.info( 'Found {} checkpoints in run_dir'.format(len(checkpoints)) ) return checkpoints
5,345,546
def ssget_p() -> selection_result: """ 选择上一个选择集 """
5,345,547
def write_env_file(env_dict): """ Write the env_file information to a temporary file If there is any error, return None; otherwise return the temp file """ try: temp_file = tempfile.NamedTemporaryFile(mode='w') for key in env_dict.keys(): val = env_dict[key] if val is None or val=='': continue temp_file.write('%s=%s\n' % (key, env_dict[key])) temp_file.flush() return temp_file except KeyboardInterrupt: # If Control-C etc, allow calling function to cleanup before halting the script close_ignore_exception(temp_file) return None except Exception as e: sys.stderr.write("Exception %s\n" % e) close_ignore_exception(temp_file) return None return None
5,345,548
def __load_txt_resource__(path): """ Loads a txt file template :param path: :return: """ txt_file = open(path, "r") return txt_file
5,345,549
def parse_cpu_spec(spec): """Parse a CPU set specification. :param spec: cpu set string eg "1-4,^3,6" Each element in the list is either a single CPU number, a range of CPU numbers, or a caret followed by a CPU number to be excluded from a previous range. :returns: a set of CPU indexes """ cpuset_ids = set() cpuset_reject_ids = set() for rule in spec.split(','): rule = rule.strip() # Handle multi ',' if len(rule) < 1: continue # Note the count limit in the .split() call range_parts = rule.split('-', 1) if len(range_parts) > 1: # So, this was a range; start by converting the parts to ints try: start, end = [int(p.strip()) for p in range_parts] except ValueError: raise exception.Invalid(_("Invalid range expression %r") % rule) # Make sure it's a valid range if start > end: raise exception.Invalid(_("Invalid range expression %r") % rule) # Add available CPU ids to set cpuset_ids |= set(range(start, end + 1)) elif rule[0] == '^': # Not a range, the rule is an exclusion rule; convert to int try: cpuset_reject_ids.add(int(rule[1:].strip())) except ValueError: raise exception.Invalid(_("Invalid exclusion " "expression %r") % rule) else: # OK, a single CPU to include; convert to int try: cpuset_ids.add(int(rule)) except ValueError: raise exception.Invalid(_("Invalid inclusion " "expression %r") % rule) # Use sets to handle the exclusion rules for us cpuset_ids -= cpuset_reject_ids return cpuset_ids
5,345,550
def _IterStringLiterals(path, addresses, obj_sections): """Yields all string literals (including \0) for the given object path. Args: path: Object file path. addresses: List of string offsets encoded as hex strings. obj_sections: List of contents of .rodata.str sections read from the given object file. """ next_offsets = sorted(int(a, 16) for a in addresses) if not obj_sections: # Happens when there is an address for a symbol which is not actually a # string literal, or when string_sections_by_path is missing an entry. logging.warning('Object has %d strings but no string sections: %s', len(addresses), path) return for section_data in obj_sections: cur_offsets = next_offsets # Always assume first element is 0. I'm not entirely sure why this is # necessary, but strings get missed without it. next_offsets = [0] prev_offset = 0 # TODO(agrieve): Switch to using nm --print-size in order to capture the # address+size of each string rather than just the address. for offset in cur_offsets[1:]: if offset >= len(section_data): # Remaining offsets are for next section. next_offsets.append(offset) continue # Figure out which offsets apply to this section via heuristic of them # all ending with a null character. if offset == prev_offset or section_data[offset - 1] != '\0': next_offsets.append(offset) continue yield section_data[prev_offset:offset] prev_offset = offset if prev_offset < len(section_data): yield section_data[prev_offset:]
5,345,551
def distance_fit_from_transits() -> typing.List[float]: """ This uses the observers position from full transits and then the runway positions from all the transit lines fitted to a """ ((x_mean, x_std), (y_mean, y_std)) = observer_position_mean_std_from_full_transits() transits = transit_x_axis_distances(x_mean, y_mean) times = [v.time for v in transits] dists = [v.distance for v in transits] popt, pcov = curve_fit( video_utils.polynomial_3, times, dists, ) return popt
5,345,552
def collate_fn_synthesize(batch): """ Create batch Args : batch(tuple) : List of tuples / (x, c) x : list of (T,) c : list of (T, D) Returns : Tuple of batch / Network inputs x (B, C, T), Network targets (B, T, 1) """ local_conditioning = len(batch[0]) >= 2 if local_conditioning: new_batch = [] for idx in range(len(batch)): x, c = batch[idx] if upsample_conditional_features: assert len(x) % len(c) == 0 and len(x) // len(c) == hop_length new_batch.append((x, c)) batch = new_batch else: pass input_lengths = [len(x[0]) for x in batch] max_input_len = max(input_lengths) # x_batch : [B, T, 1] x_batch = np.array([_pad_2d(x[0].reshape(-1, 1), max_input_len) for x in batch], dtype=np.float32) assert len(x_batch.shape) == 3 y_batch = np.array([_pad(x[0], max_input_len) for x in batch], dtype=np.float32) assert len(y_batch.shape) == 2 if local_conditioning: max_len = max([len(x[1]) for x in batch]) c_batch = np.array([_pad_2d(x[1], max_len) for x in batch], dtype=np.float32) assert len(c_batch.shape) == 3 # (B x C x T') c_batch = torch.tensor(c_batch).transpose(1, 2).contiguous() else: c_batch = None # Convert to channel first i.e., (B, C, T) / C = 1 x_batch = torch.tensor(x_batch).transpose(1, 2).contiguous() # Add extra axis i.e., (B, T, 1) y_batch = torch.tensor(y_batch).unsqueeze(-1).contiguous() input_lengths = torch.tensor(input_lengths) return x_batch, y_batch, c_batch, input_lengths
5,345,553
def max_(context, mapping, args, **kwargs): """Return the max of an iterable""" if len(args) != 1: # i18n: "max" is a keyword raise error.ParseError(_("max expects one argument")) iterable = evalwrapped(context, mapping, args[0]) try: return iterable.getmax(context, mapping) except error.ParseError as err: # i18n: "max" is a keyword hint = _("max first argument should be an iterable") raise error.ParseError(bytes(err), hint=hint)
5,345,554
def dict_to_duration(time_dict: Optional[Dict[str, int]]) -> Duration: """Convert a QoS duration profile from YAML into an rclpy Duration.""" if time_dict: try: return Duration(seconds=time_dict['sec'], nanoseconds=time_dict['nsec']) except KeyError: raise ValueError( 'Time overrides must include both seconds (sec) and nanoseconds (nsec).') else: return Duration()
5,345,555
def gen_ex_tracking_df(subj_dir): """Generate subject tracking error data frames from time series CSVs. This method generates tracking error (Jaccard distance, CSA, T, AR) data frames from raw time series CSV data for a single subject. Args: subj_dir (str): path to subject data directory, including final '/' Returns: pandas.DataFrame mean errors (Jaccard distance, CSA, T, AR) pandas.DataFrame standard deviation errors (Jaccard distance, CSA, T, AR) """ df_iou = gen_jd_vals(subj_dir) df_csa = gen_def_err_vals(subj_dir, 'CSA') df_t = gen_def_err_vals(subj_dir, 'T') df_tr = gen_def_err_vals(subj_dir, 'AR') df_iou_mean = df_iou.mean().to_frame() df_csa_mean = df_csa.mean().to_frame() df_t_mean = df_t.mean().to_frame() df_tr_mean = df_tr.mean().to_frame() df_means = df_iou_mean.copy() df_means.rename(columns={0: 'Jaccard Distance'}, inplace=True) df_means['CSA'] = df_csa_mean[0] df_means['T'] = df_t_mean[0] df_means['AR'] = df_tr_mean[0] df_iou_std = df_iou.std().to_frame() df_csa_std = df_csa.std().to_frame() df_t_std = df_t.std().to_frame() df_tr_std = df_tr.std().to_frame() df_stds = df_iou_std.copy() df_stds.rename(columns={0: 'Jaccard Distance'}, inplace=True) df_stds['CSA'] = df_csa_std[0] df_stds['T'] = df_t_std[0] df_stds['AR'] = df_tr_std[0] return df_means, df_stds
5,345,556
def getCentral4Asics(evt, type, key): """Adds a one-dimensional stack of its 4 centermost asics to ``evt["analysis"]["central4Asics"]``. Args: :evt: The event variable :type(str): The event type (e.g. photonPixelDetectors) :key(str): The event key (e.g. CCD) :Authors: Carl Nettelblad ([email protected]) Benedikt J. Daurer ([email protected]) """ getSubsetAsics(evt, type, key, map(lambda i : (i * 8 + 1) * 2, xrange(4)), "central4Asics")
5,345,557
def mse(y_true: np.ndarray, y_pred: np.ndarray) -> float: """Compute the MSE (Mean Squared Error).""" return sklearn.metrics.mean_squared_error(y_true, y_pred)
5,345,558
def run_single_thread(experiment: Experiment, thread_ids: list, distances: dict, times: dict, matchings: dict, printing: bool) -> None: """ Single thread for computing distances """ for election_id_1, election_id_2 in thread_ids: if printing: print(election_id_1, election_id_2) start_time = time() distance = get_distance(experiment.elections[election_id_1], experiment.elections[election_id_2], distance_id=experiment.distance_id) if type(distance) is tuple: distance, matching = distance matching = np.array(matching) matchings[election_id_1][election_id_2] = matching matchings[election_id_2][election_id_1] = np.argsort(matching) distances[election_id_1][election_id_2] = distance distances[election_id_2][election_id_1] = distances[election_id_1][election_id_2] times[election_id_1][election_id_2] = time() - start_time times[election_id_2][election_id_1] = times[election_id_1][election_id_2]
5,345,559
def test_insert_empty_tree(empty_ktree): """Test insert into empty tree.""" empty_ktree.insert(1, None) assert empty_ktree.root.val == 1
5,345,560
def test_ar_raw(): """Test fitting AR model on raw data.""" raw = io.read_raw_fif(raw_fname).crop(0, 2).load_data() raw.pick_types(meg='grad') # pick MEG gradiometers for order in (2, 5, 10): coeffs = fit_iir_model_raw(raw, order)[1][1:] assert_equal(coeffs.shape, (order,)) assert_allclose(-coeffs[0], 1., atol=0.5) # let's make sure we're doing something reasonable: first, white noise rng = np.random.RandomState(0) raw._data = rng.randn(*raw._data.shape) raw._data *= 1e-15 for order in (2, 5, 10): coeffs = fit_iir_model_raw(raw, order)[1] assert_allclose(coeffs, [1.] + [0.] * order, atol=2e-2) # Now let's try pink noise iir = [1, -1, 0.2] raw._data = lfilter([1.], iir, raw._data) for order in (2, 5, 10): coeffs = fit_iir_model_raw(raw, order)[1] assert_allclose(coeffs, iir + [0.] * (order - 2), atol=5e-2)
5,345,561
def test_known_good() -> None: """Test to see if known good strings pass verification.""" data = [ 'HELLOW' 'TFSI4JR', 'JDLULAG', 'BMQRZPX', 'V6B4ORO', 'BMRJXQ7', 'LZYMFSV', '7JWZVIK', 'UZI5F4A', 'AWCWP3K', 'PQCFBLJ', 'T34OQKF', 'LTEGIQO', 'LMZFORD', 'DWE67XD', 'FUGDOJR', 'O5BAULZ', 'ZP5H5MK', 'G3NZWI3', 'FKXK7GX', 'UETCW4P', 'WRJ26DM', 'VPYO6PP', 'UFUBNW2', ] d32 = Damm32() for word in data: assert d32.verify(word)
5,345,562
def policy_improvement(env, V, gamma): """ Obtain an improved policy based on the values @param env: OpenAI Gym environment @param V: policy values @param gamma: discount factor @return: the policy """ n_state = env.observation_space.n n_action = env.action_space.n policy = torch.zeros(n_state) for state in range(n_state): v_actions = torch.zeros(n_action) for action in range(n_action): for trans_prob, new_state, reward, _ in env.env.P[state][action]: v_actions[action] += trans_prob * (reward + gamma * V[new_state]) policy[state] = torch.argmax(v_actions) return policy
5,345,563
def loudness_zwst_freq(spectrum, freqs, field_type="free"): """Zwicker-loudness calculation for stationary signals Calculates the acoustic loudness according to Zwicker method for stationary signals. Normatice reference: ISO 532:1975 (method B) DIN 45631:1991 ISO 532-1:2017 (method 1) The code is based on BASIC program published in "Program for calculating loudness according to DIN 45631 (ISO 532B)", E.Zwicker and H.Fastl, J.A.S.J (E) 12, 1 (1991). Note that due to normative continuity, as defined in the preceeding standards, the method is in accordance with ISO 226:1987 equal loudness contours (instead of ISO 226:2003) Parameters ---------- spectrum : numpy.array A RMS frequency spectrum, size (Nfreq, Ntime) freqs : list List of the corresponding frequencies, size (Nfreq,) or (Nfreq, Ntime) field_type : str Type of soundfield corresponding to spec_third ("free" by default or "diffuse") Outputs ------- N : float or numpy.array Calculated loudness [sones], size (Ntime,). N_specific : numpy.ndarray Specific loudness [sones/bark], size (Nbark, Ntime). bark_axis : numpy.array Frequency axis in bark, size (Nbark,). """ if len(spectrum) != len(freqs): raise ValueError('Input spectrum and frequency axis must have the same shape') # Compute third octave band spectrum spec_third, _ = noct_synthesis(spectrum, freqs, fmin=24, fmax=12600) # Compute dB values spec_third = amp2db(spec_third, ref=2e-5) # Compute main loudness Nm = _main_loudness(spec_third, field_type) # # Computation of specific loudness pattern and integration of overall # loudness by attaching slopes towards higher frequencies N, N_specific = _calc_slopes(Nm) # Define Bark axis bark_axis = np.linspace(0.1, 24, int(24 / 0.1)) return N, N_specific, bark_axis
5,345,564
def func(back=2): """ Returns the function name """ return "{}".format(sys._getframe(back).f_code.co_name)
5,345,565
def normU(u): """ A function to scale Uranium map. We don't know what this function should be """ return u
5,345,566
def test_save_topic_figures(): """Writes out images for topics. """ model_file = join(get_test_data_path(), 'gclda_model.pkl') temp_dir = join(get_test_data_path(), 'temp') model = Model.load(model_file) model.save_topic_figures(temp_dir, n_top_words=5) figures = glob(join(temp_dir, '*.png')) assert len(figures) == model.n_topics # Perform cleanup rmtree(temp_dir)
5,345,567
def exact_riemann_solution(q_l, q_r, gamma=1.4, phase_plane_curves=False): """Return the exact solution to the Riemann problem with initial states q_l, q_r. The solution is given in terms of a list of states, a list of speeds (each of which may be a pair in case of a rarefaction fan), and a function reval(xi) that gives the solution at a point xi=x/t. The input and output vectors are the conserved quantities. If phase_plane_curves==True, then the appropriate Hugoniot Locus and/or integral curve is returned for the 1- and 3-waves. """ rho_l, u_l, p_l = conservative_to_primitive(*q_l) rho_r, u_r, p_r = conservative_to_primitive(*q_r) # Compute left and right state sound speeds c_l = sound_speed(rho_l, p_l, gamma) c_r = sound_speed(rho_r, p_r, gamma) ws = np.zeros(5) wave_types = ['', 'contact', ''] if rho_l == 0: # 3-rarefaction connecting right state to vacuum p = 0. rho_l_star = 0. rho_r_star = 0. u_vacuum_r = integral_curve_3(0., rho_r, u_r, p_r, gamma) u = u_vacuum_r ws[0] = 0. ws[1] = 0. ws[2] = 0. ws[3] = u_vacuum_r ws[4] = u_r + c_r wave_types = ['contact', 'contact', 'raref'] elif rho_r == 0: # 1-rarefaction connecting left state to vacuum p = 0 rho_l_star = 0. rho_r_star = 0. u_vacuum_l = integral_curve_1(0., rho_l, u_l, p_l, gamma) u = u_vacuum_l ws[0] = u_l - c_l ws[1] = u_vacuum_l ws[2] = 0. ws[3] = 0. ws[4] = 0. wave_types = ['raref', 'contact', 'contact'] elif u_l - u_r + 2*(c_l+c_r)/(gamma-1.) < 0: # Middle states are vacuum p = 0. rho_l_star = 0. rho_r_star = 0. u_vacuum_l = integral_curve_1(0., rho_l, u_l, p_l, gamma) u_vacuum_r = integral_curve_3(0., rho_r, u_r, p_r, gamma) u = 0.5*(u_vacuum_l + u_vacuum_r) ws[0] = u_l - c_l ws[1] = u_vacuum_l ws[2] = u ws[3] = u_vacuum_r ws[4] = u_r + c_r wave_types = ['raref', 'contact', 'raref'] else: # Check whether the 1-wave is a shock or rarefaction def phi_l(p): if p >= p_l: return hugoniot_locus_1(p, rho_l, u_l, p_l, gamma) else: return integral_curve_1(p, rho_l, u_l, p_l, gamma) # Check whether the 1-wave is a shock or rarefaction def phi_r(p): if p >= p_r: return hugoniot_locus_3(p, rho_r, u_r, p_r, gamma) else: return integral_curve_3(p, rho_r, u_r, p_r, gamma) phi = lambda p: phi_l(p)-phi_r(p) exp = (1.-gamma)/(2.*gamma) guess = ((c_l + c_r - (gamma-1.)*(u_r-u_l)/2.)/(c_l*p_l**exp+c_r*p_r**exp))**(-1./exp) # Compute middle state p, u by finding curve intersection p, info, ier, msg = fsolve(phi, guess, full_output=True, xtol=1.e-14) # For strong rarefactions, sometimes fsolve needs help if ier != 1: p, info, ier, msg = fsolve(phi, guess, full_output=True, factor=0.1, xtol=1.e-10) # This should not happen: if ier != 1: print('Warning: fsolve did not converge.') print(msg) u = phi_l(p) ws[2] = u # Find shock and rarefaction speeds if p > p_l: wave_types[0] = 'shock' rho_l_star = rho_l*(1+beta(gamma)*p/p_l)/(p/p_l+beta(gamma)) ws[0] = (rho_l*u_l - rho_l_star*u)/(rho_l - rho_l_star) ws[1] = ws[0] else: wave_types[0] = 'raref' rho_l_star = (p/p_l)**(1./gamma) * rho_l c_l_star = sound_speed(rho_l_star, p, gamma) ws[0] = u_l - c_l ws[1] = u - c_l_star if p > p_r: wave_types[2] = 'shock' rho_r_star = rho_r*(1+beta(gamma)*p/p_r)/(p/p_r+beta(gamma)) ws[4] = (rho_r*u_r - rho_r_star*u)/(rho_r - rho_r_star) ws[3] = ws[4] else: wave_types[2] = 'raref' rho_r_star = (p/p_r)**(1./gamma) * rho_r c_r_star = sound_speed(rho_r_star, p, gamma) ws[3] = u + c_r_star ws[4] = u_r + c_r # Find solution inside rarefaction fans (in primitive variables) def raref1(xi): u1 = ((gamma-1.)*u_l + 2*(c_l + xi))/(gamma+1.) rho1 = (rho_l**gamma*(u1-xi)**2/pospart(gamma*p_l))**(1./(gamma-1.)) p1 = p_l*(rho1/pospart(rho_l))**gamma return rho1, u1, p1 def raref3(xi): u3 = ((gamma-1.)*u_r - 2*(c_r - xi))/(gamma+1.) rho3 = (rho_r**gamma*(xi-u3)**2/pospart(gamma*p_r))**(1./(gamma-1.)) p3 = p_r*(rho3/pospart(rho_r))**gamma return rho3, u3, p3 q_l_star = np.squeeze(np.array(primitive_to_conservative(rho_l_star,u,p))) q_r_star = np.squeeze(np.array(primitive_to_conservative(rho_r_star,u,p))) states = np.column_stack([q_l,q_l_star,q_r_star,q_r]) speeds = [[], ws[2], []] if wave_types[0] in ['shock','contact']: speeds[0] = ws[0] else: speeds[0] = (ws[0],ws[1]) if wave_types[2] in ['shock','contact']: speeds[2] = ws[3] else: speeds[2] = (ws[3],ws[4]) def reval(xi): r"""Returns the Riemann solution in primitive variables for any value of xi = x/t. """ rar1 = raref1(xi) rar3 = raref3(xi) rho_out = (xi<=ws[0] )*rho_l \ + (xi>ws[0])*(xi<=ws[1])*rar1[0] \ + (xi>ws[1])*(xi<=ws[2] )*rho_l_star \ + (xi>ws[2]) *(xi<=ws[3])*rho_r_star \ + (xi>ws[3])*(xi<=ws[4])*rar3[0] \ + (xi>ws[4] )*rho_r u_out = (xi<=ws[0] )*u_l \ + (xi>ws[0])*(xi<=ws[1])*rar1[1] \ + (xi>ws[1])*(xi<=ws[2] )*u \ + (xi>ws[2] )*(xi<=ws[3])*u \ + (xi>ws[3])*(xi<=ws[4])*rar3[1] \ + (xi>ws[4] )*u_r p_out = (xi<=ws[0] )*p_l \ + (xi>ws[0])*(xi<=ws[1])*rar1[2] \ + (xi>ws[1])*(xi<=ws[2] )*p \ + (xi>ws[2] )*(xi<=ws[3])*p \ + (xi>ws[3])*(xi<=ws[4])*rar3[2] \ + (xi>ws[4] )*p_r return primitive_to_conservative(rho_out,u_out,p_out) if phase_plane_curves: if wave_types[0] == 'raref': phi1 = lambda p: integral_curve_1(p, rho_l, u_l, p_l, gamma) elif wave_types[0] == 'shock': phi1 = lambda p: hugoniot_locus_1(p, rho_l, u_l, p_l, gamma) else: phi1 = lambda p: p if wave_types[2] == 'raref': phi3 = lambda p: integral_curve_3(p, rho_r, u_r, p_r, gamma) elif wave_types[2] == 'shock': phi3 = lambda p: hugoniot_locus_3(p, rho_r, u_r, p_r, gamma) else: phi3 = lambda p: p return states, speeds, reval, wave_types, (p, phi1, phi3) else: return states, speeds, reval, wave_types
5,345,568
def check_admin(): """ This function prevents non-admins from accessing this page and is called on every route """ if not current_user.is_admin: abort(403)
5,345,569
def show_edge_scatter(N, s1, s2, t1, t2, d, dmax=None, fig_ax=None): """Draw the cell-edge contour and the displacement vectors. The contour is drawn using a scatter plot to color-code the displacements.""" if fig_ax is None: fig, ax = plt.subplots() else: fig, ax = fig_ax plt.figure(fig.number) # Evaluate splines at window locations and on fine-resolution grid c1 = splineutils.splevper(t1, s1) c2 = splineutils.splevper(t2, s2) c1p = splev(np.linspace(0, 1, N + 1), s1) c2p = splev(np.linspace(0, 1, N + 1), s2) # Interpolate displacements # d = 0.5 + 0.5 * d / np.max(np.abs(d)) if len(d) < N + 1: d = np.interp(np.linspace(0, 1, N + 1), t1, d, period=1) if dmax is None: dmax = np.max(np.abs(d)) if dmax == 0: dmax = 1 # Plot results # matplotlib.use('PDF') lw = 1 s = 1 # Scaling factor for the vectors ax.plot(c1p[0], c1p[1], "b", zorder=50, lw=lw) ax.plot(c2p[0], c2p[1], "r", zorder=100, lw=lw) # plt.scatter(c1p[0], c1p[1], c=d, cmap='bwr', vmin=-dmax, vmax=dmax, zorder=50, s1=lw) # # plt.colorbar(label='Displacement [pixels]') for j in range(len(t2)): ax.arrow( c1[0][j], c1[1][j], s * (c2[0][j] - c1[0][j]), s * (c2[1][j] - c1[1][j]), color="y", zorder=200, lw=lw, ) # plt.arrow(c1[0][j], c1[1][j], s1 * u[0][j], s1 * u[1][j], color='y', zorder=200, lw=lw) # Show normal to curve ax.arrow( c1[0][0], c1[1][0], s * (c2[0][0] - c1[0][0]), s * (c2[1][0] - c1[1][0]), color="c", zorder=400, lw=lw, ) fig.tight_layout() return fig, ax
5,345,570
def aiobotocore_client(service, tracer): """Helper function that creates a new aiobotocore client so that it is closed at the end of the context manager. """ session = aiobotocore.session.get_session() endpoint = LOCALSTACK_ENDPOINT_URL[service] client = session.create_client( service, region_name="us-west-2", endpoint_url=endpoint, aws_access_key_id="aws", aws_secret_access_key="aws", aws_session_token="aws", ) Pin.override(client, tracer=tracer) try: yield client finally: client.close()
5,345,571
def get_A2_const(alpha1, alpha2, lam_c, A1): """Function to compute the constant A2. Args: alpha1 (float): The alpha1 parameter of the WHSCM. alpha2 (float): The alpha2 parameter of the WHSCM. lam_c (float): The switching point between the two exponents of the double power-laws in the WHSCM. A1 (float): The A1 constant of the WHSCM. Returns: A2 (float): The A2 constant of the WHSCM. """ A2 = A1 * (lam_c**(alpha2 - alpha1)) return A2
5,345,572
def dark(app): """ Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance. """ darkPalette = QtGui.QPalette() # base darkPalette.setColor(QtGui.QPalette.WindowText, QtGui.QColor(180, 180, 180)) darkPalette.setColor(QtGui.QPalette.Button, QtGui.QColor(53, 53, 53)) darkPalette.setColor(QtGui.QPalette.Light, QtGui.QColor(180, 180, 180)) darkPalette.setColor(QtGui.QPalette.Midlight, QtGui.QColor(90, 90, 90)) darkPalette.setColor(QtGui.QPalette.Dark, QtGui.QColor(35, 35, 35)) darkPalette.setColor(QtGui.QPalette.Text, QtGui.QColor(180, 180, 180)) darkPalette.setColor(QtGui.QPalette.BrightText, QtGui.QColor(180, 180, 180)) darkPalette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor(180, 180, 180)) darkPalette.setColor(QtGui.QPalette.Base, QtGui.QColor(42, 42, 42)) darkPalette.setColor(QtGui.QPalette.Window, QtGui.QColor(53, 53, 53)) darkPalette.setColor(QtGui.QPalette.Shadow, QtGui.QColor(20, 20, 20)) darkPalette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(42, 130, 218)) darkPalette.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor(180, 180, 180)) darkPalette.setColor(QtGui.QPalette.Link, QtGui.QColor(56, 252, 196)) darkPalette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(66, 66, 66)) darkPalette.setColor(QtGui.QPalette.ToolTipBase, QtGui.QColor(53, 53, 53)) darkPalette.setColor(QtGui.QPalette.ToolTipText, QtGui.QColor(180, 180, 180)) # disabled darkPalette.setColor(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, QtGui.QColor(127, 127, 127)) darkPalette.setColor(QtGui.QPalette.Disabled, QtGui.QPalette.Text, QtGui.QColor(127, 127, 127)) darkPalette.setColor(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, QtGui.QColor(127, 127, 127)) darkPalette.setColor(QtGui.QPalette.Disabled, QtGui.QPalette.Highlight, QtGui.QColor(80, 80, 80)) darkPalette.setColor(QtGui.QPalette.Disabled, QtGui.QPalette.HighlightedText, QtGui.QColor(127, 127, 127)) app.setPalette(darkPalette) _apply_base_theme(app)
5,345,573
def test_contract_manager_json(tmpdir): """ Check the ABI in contracts.json """ precompiled_path = Path(str(tmpdir)).joinpath('contracts.json') ContractManager(contracts_source_path()).compile_contracts(precompiled_path) # try to load contracts from a precompiled file contract_manager_meta(precompiled_path)
5,345,574
def args_parser(): """ Parese command line arguments Args: opt_args: Optional args for testing the function. By default sys.argv is used Returns: args: Dictionary of args. Raises: ValueError: Raises an exception if some arg values are invalid. """ # Construct the parser parser = argparse.ArgumentParser(description='NConv') # Mode selection parser.add_argument('--neighbor', type=int, default=2, help='the neighbors will be considered') parser.add_argument('--machine', type=str, default="local", help='choose the training machin, local or remote') parser.add_argument('--num-channels', type=int, help='choose the number of channels in the model') parser.add_argument('--output_type', type=str, default="normal", help='choose the meaning of output tensor, rgb or normal') parser.add_argument('--args', '-a', type=str, default='', choices=['defaults', 'json'], help='How to read args? (json file or dataset defaults)') parser.add_argument('--exp', '--e', help='Experiment name') parser.add_argument('--workspace', '--ws', default='', type=str, help='Workspace name') parser.add_argument('--resume', default=None, type=str, metavar='PATH', help='Path to latest checkpoint (default: none)') ########### General Dataset arguments ########## parser.add_argument('--dataset-path', type=str, default='', help='Dataset path.') parser.add_argument('--batch_size', '-b', default=8, type=int, help='Mini-batch size (default: 8)') parser.add_argument('--train-on', default='full', type=str, help='The number of images to train on from the data.') parser.add_argument('--sharp_penalty', default=1.5, type=float, help='penalty of sharp normal prediction') ########### KITTI-Depth arguments ########### parser.add_argument('--raw-kitti-path', type=str, default='', help='Dataset path') parser.add_argument('--selval-ds', default='selval', type=str, choices=['selval, selval, test'], help='Which set to evaluate on? ' + ' | '.join(['selval, selval, test']) + ' (default: selval)') parser.add_argument('--norm-factor', default=256, type=float, help='Normalization factor for the input data (default: 256)') parser.add_argument('--train-disp', default=False, type=bool, help='Train on disparity (1/depth) (default: False)') ########### Training arguments ########### parser.add_argument('--epochs', default=20, type=int, help='Total number of epochs to run (default: 30)') parser.add_argument('--optimizer', '-o', default='adam', choices=optimizers_list, help='Optimizer method: ' + ' | '.join(optimizers_list) + ' (default: sgd)') parser.add_argument('--lr', '--learning-rate', default=0.001, type=float, metavar='LR', help='Initial learning rate (default 0.001)') parser.add_argument('--momentum', default=0.9, type=float, help='SGD momentum.') parser.add_argument('--lr-scheduler', default='step', choices=lr_scheduler_list, help='LR scheduler method: ' + ' | '.join(lr_scheduler_list) + ' (default: step)') parser.add_argument('--lr-decay-step', default=5, type=int, help='Learning rate decay step (default: 20)') parser.add_argument('--lr-decay-factor', default=0.1, type=float, help='Learning rate decay factor(default: 0.1)') parser.add_argument('--weight-decay', '--wd', default=0, type=float, help='Weight decay (default: 0)') parser.add_argument('--loss', '-l', default='l1', choices=losses_list, help='Loss function: ' + ' | '.join(losses_list) + ' (default: l1)') parser.add_argument('--penalty', '-pena', default=1.2, help='penalty of output value which out of range [0-255]') ########### Logging ########### parser.add_argument('--print-freq', default=10, type=int, help='Printing evaluation criterion frequency (default: 10)') parser.add_argument('--tb_log', default=False, type=bool, help='Log to Tensorboard (default: False)') parser.add_argument('--tb_freq', default=1000, type=int, help='Logging Frequence to Tensorboard (default: 1000)') parser.add_argument('--save-selval-imgs', default=False, type=bool, help='A flag for saving validation images (default: False)') parser.add_argument('--eval_uncert', default=False, type=bool, help='Evaluate uncertainty or not') parser.add_argument('--angle_loss', default=False, type=bool, help='Calculate angle loss and plot') # Parse the arguments args = parser.parse_args() args = initialize_args(args) return args
5,345,575
def _parse_seq_tf_example(example, uint8_features, shapes): """Parse tf.Example containing one or two episode steps.""" def to_feature(key, shape): if key in uint8_features: return tf.io.FixedLenSequenceFeature( shape=[], dtype=tf.string, allow_missing=True) else: return tf.io.FixedLenSequenceFeature( shape=shape, dtype=tf.float32, allow_missing=True) feature_map = {} for k, v in shapes.items(): feature_map[k] = to_feature(k, v) parsed = tf.io.parse_single_example(example, features=feature_map) observation = {} restructured = {} for k in parsed.keys(): if 'observation' not in k: restructured[k] = parsed[k] continue if k in uint8_features: observation[k.replace('observation/', '')] = tf.reshape( tf.io.decode_raw(parsed[k], out_type=tf.uint8), (-1,) + shapes[k]) else: observation[k.replace('observation/', '')] = parsed[k] restructured['observation'] = observation restructured['length'] = tf.shape(restructured['action'])[0] return restructured
5,345,576
def unique_list(a_list, unique_func=None, replace=False): """Unique a list like object. - collection: list like object - unique_func: the filter functions to return a hashable sign for unique - replace: the following replace the above with the same sign Return the unique subcollection of collection. Example: data = [(1, 2), (2, 1), (2, 3), (1, 2)] unique_func = lambda x: tuple(sorted(x)) unique(data) -> [(1, 2), (2, 1), (2, 3)] unique(data, unique_func) -> [(1, 2), (2, 3)] unique(data, unique_func, replace=True) -> [(2, 1), (2, 3)] """ unique_func = unique_func or (lambda x: x) result = {} for item in a_list: hashable_sign = unique_func(item) if hashable_sign not in result or replace: result[hashable_sign] = item return list(result.values())
5,345,577
def update_topics (graph, frags, known_topics, topic_id, phrase, pub_id, rank, count): """ update the known topics """ if topic_id not in known_topics: t = { "uuid": topic_id, "label": phrase, "used": False, "pubs": [] } known_topics[topic_id] = t else: t = known_topics[topic_id] t["pubs"].append([pub_id, rank, count]) buf = [ TEMPLATE_TOPIC.format( t["uuid"], t["label"] ).strip() ] buf.append(".\n") frags[t["uuid"]] = buf
5,345,578
def airflow_runtime_instance(): """Creates an airflow RTC and removes it after test.""" instance_name = "valid_airflow_test_config" instance_config_file = Path(__file__).parent / "resources" / "runtime_configs" / f"{instance_name}.json" with open(instance_config_file, "r") as fd: instance_config = json.load(fd) md_mgr = MetadataManager(schemaspace=Runtimes.RUNTIMES_SCHEMASPACE_ID) # clean possible orphaned instance... try: md_mgr.remove(instance_name) except Exception: pass runtime_instance = md_mgr.create(instance_name, Metadata(**instance_config)) yield runtime_instance.name md_mgr.remove(runtime_instance.name)
5,345,579
def calculate_attitude_angle(eccentricity_ratio): """Calculates the attitude angle based on the eccentricity ratio. Parameters ---------- eccentricity_ratio: float The ratio between the journal displacement, called just eccentricity, and the radial clearance. Returns ------- float Attitude angle Examples -------- >>> from ross.fluid_flow.fluid_flow import fluid_flow_example >>> my_fluid_flow = fluid_flow_example() >>> calculate_attitude_angle(my_fluid_flow.eccentricity_ratio) # doctest: +ELLIPSIS 1.5... """ return np.arctan( (np.pi * (1 - eccentricity_ratio ** 2)**(1/2)) / (4 * eccentricity_ratio) )
5,345,580
def enc_obj2bytes(obj, max_size=4094): """ Encode Python objects to PyTorch byte tensors """ assert max_size <= MAX_SIZE_LIMIT byte_tensor = torch.zeros(max_size, dtype=torch.uint8) obj_enc = pickle.dumps(obj) obj_size = len(obj_enc) if obj_size > max_size: raise Exception( 'objects too large: object size {}, max size {}'.format( obj_size, max_size ) ) byte_tensor[0] = obj_size // 256 byte_tensor[1] = obj_size % 256 byte_tensor[2:2+obj_size] = torch.ByteTensor(list(obj_enc)) return byte_tensor
5,345,581
def featCompression (feats, deltas, deltas2): """ Returns augmented feature vectors for all cases. """ feats_total = np.zeros (78) for i in range (len (feats)): row_total = np.array ([]) feat_mean = np.mean (np.array (feats[i]), axis = 0) delt_mean = np.mean (np.array (deltas[i]), axis = 0) delt2_mean = np.mean (np.array (deltas2[i]), axis = 0) feat_std = np.std (np.array (feats[i]), axis = 0) delt_std = np.std (np.array (deltas[i]), axis = 0) delt2_std = np.std (np.array (deltas2[i]), axis = 0) row_total = np.hstack ((feat_mean, feat_std, delt_mean, delt_std, \ delt2_mean, delt2_std)) feats_total = np.vstack ((feats_total, row_total)) return feats_total[1:, :]
5,345,582
def _array_indexing(array, key, key_dtype, axis): """Index an array or scipy.sparse consistently across NumPy version.""" if np_version < parse_version('1.12') or issparse(array): # Remove the check for NumPy when using >= 1.12 # check if we have an boolean array-likes to make the proper indexing if key_dtype == 'bool': key = np.asarray(key) if isinstance(key, tuple): key = list(key) return array[key] if axis == 0 else array[:, key]
5,345,583
def retryable(fun: Callable[[Any], None], re_init_func: Callable[[], Any], max_tries: int, *args: Dict[str, Any]): """ Retries the function multiple times, based on the max_tries :param max_tries: max number of tries :type max_tries: ``int`` :param fun: main function to retry :type fun: ``Callable[[...], None]`` :param re_init_func: function to run after exception is raised :type re_init_func: ``Callable`` :param args: main function arguments """ for _ in range(max_tries): try: fun(*args) break except (ValueError, Exception): re_init_func() continue
5,345,584
def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False, check_serial_no=True): """get stock ledger entries filtered by specific posting datetime conditions""" conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format( operator) if previous_sle.get("warehouse"): conditions += " and warehouse = %(warehouse)s" elif previous_sle.get("warehouse_condition"): conditions += " and " + previous_sle.get("warehouse_condition") if check_serial_no and previous_sle.get("serial_no"): conditions += " and serial_no like '{}'".format( frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no")))) if not previous_sle.get("posting_date"): previous_sle["posting_date"] = "1900-01-01" if not previous_sle.get("posting_time"): previous_sle["posting_time"] = "00:00" if operator in (">", "<=") and previous_sle.get("name"): conditions += " and name!=%(name)s" return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry` where item_code = %%(item_code)s and ifnull(is_cancelled, 'No')='No' %(conditions)s order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s %(limit)s %(for_update)s""" % { "conditions": conditions, "limit": limit or "", "for_update": for_update and "for update" or "", "order": order }, previous_sle, as_dict=1, debug=debug)
5,345,585
def test_binary(test_data, model, criterion, batch_size, device, generate_batch=None): """Calculate performance of a Pytorch binary classification model Parameters ---------- test_data : torch.utils.data.Dataset Pytorch dataset model: torch.nn.Module Pytorch Model criterion: function Loss function bacth_size : int Number of observations per batch device : str Name of the device used for the model collate_fn : function Function defining required pre-processing steps Returns ------- Float Loss score Float: Accuracy Score """ # Set model to evaluation mode model.eval() test_loss = 0 test_acc = 0 # Create data loader data = DataLoader(test_data, batch_size=batch_size, collate_fn=generate_batch) # Iterate through data by batch of observations for feature, target_class in data: # Load data to specified device feature, target_class = feature.to(device), target_class.to(device).to(torch.float32) # Set no update to gradients with torch.no_grad(): # Make predictions output = model(feature) # Calculate loss for given batch loss = criterion(output, target_class.unsqueeze(1)) # Calculate global loss test_loss += loss.item() # Calculate global accuracy test_acc += (output.argmax(1) == target_class).sum().item() return test_loss / len(test_data), test_acc / len(test_data)
5,345,586
def linear_imputer(y, missing_values=np.nan, copy=True): """ Replace missing values in y with values from a linear interpolation on their position in the array. Parameters ---------- y: list or `numpy.array` missing_values: number, string, np.nan or None, default=`np.nan` The placeholder for the missing values. All occurrences of `missing_values` will be imputed. copy : bool, default=True If True, a copy of X will be created. If False, imputation will be done in-place whenever possible. Returns ------- `numpy.array` : array with `missing_values` imputed """ x = np.arange(len(y)) if missing_values is np.nan: mask_missing = np.isnan(y) else: mask_missing = y == missing_values imputed_values = np.interp(x[mask_missing], x[~mask_missing], y[~mask_missing]) if copy: yy = np.copy(y) yy[mask_missing] = imputed_values return yy else: y[mask_missing] = imputed_values return y
5,345,587
def dump_json(gto, k, verbose=False): """ Print out the json representation of some data :param gto: the json gto :param k: the key to dump (none for everything) :param verbose: more output :return: """ if k: if k in gto: print(json.dumps(gto[k], indent=4)) else: sys.stderr.write(f"{bcolors.RED}ERROR: {k} not found.{bcolors.ENDC}\n") else: print(json.dumps(gto, indent=4))
5,345,588
def gap2d_cx(cx): """Accumulates complexity of gap2d into cx = (h, w, flops, params, acts).""" cx["h"] = 1 cx["w"] = 1 return cx
5,345,589
def test_is_not_healthy(requests_mock): """ Test is not healthy response """ metadata = Gen3Metadata("https://example.com") def _mock_request(url, **kwargs): assert url.endswith("/_status") mocked_response = MagicMock(requests.Response) mocked_response.status_code = 500 mocked_response.text = "Not Healthy" mocked_response.json.return_value = {} mocked_response.raise_for_status.side_effect = HTTPError("uh oh") return mocked_response requests_mock.side_effect = _mock_request response = metadata.is_healthy() assert not response
5,345,590
def kernelTrans(X, A, kTup): """ 通过核函数将数据转换更高维的空间 Parameters: X - 数据矩阵 A - 单个数据的向量 kTup - 包含核函数信息的元组 Returns: K - 计算的核K """ m,n = np.shape(X) K = np.mat(np.zeros((m,1))) if kTup[0] == 'lin': K = X * A.T #线性核函数,只进行内积。 elif kTup[0] == 'rbf': #高斯核函数,根据高斯核函数公式进行计算 for j in range(m): deltaRow = X[j,:] - A K[j] = deltaRow*deltaRow.T K = np.exp(K/(-1*kTup[1]**2)) #计算高斯核K else: raise NameError('核函数无法识别') return K #返回计算的核K
5,345,591
def getBusEquipmentData(bhnd,paraCode): """ Retrieves the handle of all equipment of a given type (paraCode) that is attached to bus []. Args : bhnd : [bus handle] nParaCode : code data (BR_nHandle,GE_nBusHnd...) Returns: [][] = [len(bhnd)] [len(all equipment)] Raises: OlrxAPIException """ # get data res = [] vt = paraCode//100 val1 = setValType(vt,0) for bhnd1 in bhnd: r2 = [] while ( OLXAPI_OK == OlxAPI.GetBusEquipment( bhnd1, c_int(paraCode), byref(val1) ) ) : if vt==VT_STRING: r2.append((val1.value).decode("UTF-8")) else: r2.append(val1.value) res.append(r2) return res
5,345,592
def build_and_register( client: "prefect.Client", flows: "List[FlowLike]", project_id: str, labels: List[str] = None, force: bool = False, ) -> Counter: """Build and register all flows. Args: - client (prefect.Client): the prefect client to use - flows (List[FlowLike]): the flows to register - project_id (str): the project id in which to register the flows - labels (List[str], optional): Any extra labels to set on all flows - force (bool, optional): If false (default), an idempotency key will be used to avoid unnecessary register calls. Returns: - Counter: stats about the number of successful, failed, and skipped flows. """ # Finish preparing flows to ensure a stable hash later prepare_flows(flows, labels) # Group flows by storage instance. storage_to_flows = defaultdict(list) for flow in flows: storage = flow.storage if isinstance(flow, prefect.Flow) else None storage_to_flows[storage].append(flow) # Register each flow, building storage as needed. # Stats on success/fail/skip rates are kept for later display stats = Counter(registered=0, errored=0, skipped=0) for storage, flows in storage_to_flows.items(): # Build storage if needed if storage is not None: click.echo(f" Building `{type(storage).__name__}` storage...") try: storage.build() except Exception as exc: click.secho(" Error building storage:", fg="red") log_exception(exc, indent=6) red_error = click.style("Error", fg="red") for flow in flows: click.echo(f" Registering {flow.name!r}... {red_error}") stats["errored"] += 1 continue for flow in flows: click.echo(f" Registering {flow.name!r}...", nl=False) try: if isinstance(flow, box.Box): serialized_flow = flow else: serialized_flow = flow.serialize(build=False) flow_id, flow_version, is_new = register_serialized_flow( client=client, serialized_flow=serialized_flow, project_id=project_id, force=force, ) except Exception as exc: click.secho(" Error", fg="red") log_exception(exc, indent=4) stats["errored"] += 1 else: if is_new: click.secho(" Done", fg="green") click.echo(f" └── ID: {flow_id}") click.echo(f" └── Version: {flow_version}") stats["registered"] += 1 else: click.secho(" Skipped", fg="yellow") stats["skipped"] += 1 return stats
5,345,593
def helper_reset_page_retirements(handle, gpuId=0, reset_sbe=False): """ Helper function to reset non volatile page retirements. """ ret = dcgm_internal_helpers.inject_field_value_i64(handle, gpuId, dcgm_fields.DCGM_FI_DEV_RETIRED_DBE, 0, -30) # set the injected data to 30 seconds ago assert (ret == dcgm_structs.DCGM_ST_OK) if reset_sbe: ret = dcgm_internal_helpers.inject_field_value_i64(handle, gpuId, dcgm_fields.DCGM_FI_DEV_RETIRED_SBE, 0, -30) # set the injected data to 30 seconds ago assert (ret == dcgm_structs.DCGM_ST_OK)
5,345,594
def generate_path_to_bulk_roms( roms: List[models.BulkSystemROMS]) -> List[models.BulkSystemROMS]: """Creates the absolute path to where each rom should be downloaded""" for system in roms: for section in system.Sections: if not 'number' in section.Section: path: str = os.path.join(os.getcwd(), "ROMS", section.Section) section.Path = path else: path: str = os.path.join(os.getcwd(), "ROMS", system.System, '#') section.Path = path return roms
5,345,595
def parse_args(args=sys.argv[1:]): """ Get the parsed arguments specified on this script. """ parser = argparse.ArgumentParser(description="") parser.add_argument( 'path_to_xml', action='store', type=str, help='Ful path to tei file.') parser.add_argument( 'omeka_id', action='store', type=str, help='omeka id') parser.add_argument( 'name', action='store', type=str, help='name') return parser.parse_args(args)
5,345,596
def send_voting_location_sms(email, phone, fields): """Opts-in to SMS and sends caucus/polling location address text message. We do two Mobile Commons API calls: 1. Create or update profile, with a state-specific opt-in path. If the number is new to our national Mobile Commons campaign, this will subscribe the number to our national campaign and trigger a text message like: Team Warren: Thanks for confirming your caucus location! We'll follow-up when it's time to make your voice heard for Elizabeth. HELP4INFO/STOP2Quit/Msg&DataRatesMayApply If the number if already on our list, this will trigger nothing and no message. 2. Send a message with caucus/polling location name and address. """ phone = extract_phone_number(phone) if not phone: logging.info("Not sending SMS with voting location; no phone number") return state = fields["state_cd"] if not state: logging.info("Not sending SMS with voting location; no state") return language = fields.get("language", DEFAULT_LANGUAGE) details_for_language = VOTING_LOCATION_SMS_BY_LANGUAGE_STATE.get( language, VOTING_LOCATION_SMS_BY_LANGUAGE_STATE[DEFAULT_LANGUAGE] ) details_for_state = details_for_language.get(state, details_for_language["default"]) details = details_for_state.get( fields["preferred_voting_type"], details_for_state["default"] ) first_name, last_name = normalize_name( fields.get("firstname", ""), fields.get("lastname", "") ) profile_payload = { "phone_number": phone, "email": fields.get("email", ""), "postal_code": fields.get("zip", ""), "first_name": first_name, "last_name": last_name, "street1": fields.get("addr1", ""), "city": fields.get("city", ""), "state": state, "country": "US", "polling_location_name": fields.get("name_of_location"), "polling_address": fields.get("polling_address"), "polling_city": fields.get("polling_city"), "polling_state": fields.get("polling_state"), "polling_zip": fields.get("polling_zip"), "polling_time": fields.get("time_of_event"), "polling_precinct_id": fields.get("van_precinct_id"), "opt_in_path_id": details.get("opt_in_path_id"), } # Don't upload null or empty fields. keys_to_delete = [k for k, v in profile_payload.items() if not v] for k in keys_to_delete: del profile_payload[k] resp = create_or_update_mobile_commons_profile( settings.MOBILE_COMMONS_USERNAME, settings.MOBILE_COMMONS_PASSWORD, profile_payload, ) logging.debug(f"Response from mobile commons profile creation: {resp.text}") message_template = details["message"] message = Template(message_template).render(**fields) resp = send_sms( settings.MOBILE_COMMONS_USERNAME, settings.MOBILE_COMMONS_PASSWORD, MOBILE_COMMONS_CAMPAIGN_ID, phone, message, ) logging.debug(f"Response from mobile commons send: {resp.text}")
5,345,597
def creer_element_xml(nom_elem,params): """ Créer un élément de la relation qui va donner un des attributs. Par exemple, pour ajouter le code FANTOIR pour une relation, il faut que le code XML soit <tag k='ref:FR:FANTOIR' v='9300500058T' />" Pour cela, il faut le nom de l'élément (ici tag) et un dictionnaire de paramètres nommé param qui associe chaque clé à une valeur (ici {'k':'ref:FR:FANTOIR', 'v'='9300500058T'} :param nom_elem: :type nom_elem: str :param params: :type params: dict :return: élément XML désiré :rtype: xml.etree.ElementTree.Element """ # Initialisation de l'objet XML elem = ET.Element(nom_elem) ajouter_atrributs_element_xml(elem, params) return elem
5,345,598
def get_display(): """Getter function for the display keys Returns: list: list of dictionary keys """ return data.keys()
5,345,599