content
stringlengths
22
815k
id
int64
0
4.91M
def close_user_channels(pk): """ Closes channels for the given user pk. """ async_to_sync(CHANNEL_LAYER.group_send)( get_group_user_key(pk), {'type': 'websocket.disconnect', 'code': 3}, )
51,700
def get_two_body_decay_scaled_for_chargeless_molecules( ion_pos: Array, ion_charges: Array, init_ee_strength: float = 1.0, register_kfac: bool = True, logabs: bool = True, trainable: bool = True, ) -> Jastrow: """Make molecular decay jastrow, scaled for chargeless molecules. The scale f...
51,701
async def on_ready(): """Changes discord presence to "Playing TravelFeed.io" when the bot comes online""" try: await bot.change_presence(game=discord.Game(name='TravelFeed.io')) except: logger.warning("Could not change Discord presence") logger.info("Login to Discord successful")
51,702
def compute_huffman_code(message_probs): """ The input is a dictionary of messages, and their relative probabilities (which must add to 1). The output is a dictionary of each message and it's new codeword (a bytestring) in the Huffman encoding. """ return tree_to_encoding(message_tree(message...
51,703
def genomics_cnn(batch_size: int, len_seqs: int, num_motifs: int, len_motifs: int, num_denses: int, num_classes: int = 10, embed_size: int = 4, one_hot: bool = True, l2_weight: float =...
51,704
def plot_stats_for_all_selectors(stats: Dict[str, SimulationStatsDistribution], y_attr_names: List[str], y_attr_labels: List[str], title: str = '', x_label: str = '', ...
51,705
def repository_path(repo, rev="HEAD", in_repo_path=""): """ Build a path (for further use in sys.path) from a repository reference :param repo: a pygit2 repository object or a path to a git repository :param rev: the revision which should be used. Acceptable values are all valid git revisions such as '...
51,706
def process_repo(repo_dir): """parse markdown code snippets. Args: repo_dir (str): directory name. Returns: List<Dict> """ snippets = [] snippets_dir = os.path.join(repo_dir, "snippets") for idx, file in enumerate(os.listdir(snippets_dir), start=1): name, ext = os.p...
51,707
def setDuration(*args): """setDuration(ALInterpolationBangBangAcceleration pObject, float pDuration)""" return _almathinternal.setDuration(*args)
51,708
def regex(pattern): """ Does a pattern search using the system's `find` utility :param pattern: a pattern you intend to search for :return: String """ cmd = "find " + MIGRATION_FOLDER + " -type f -exec grep -il " + pattern + " {} +" out = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stder...
51,709
def _mp_fabber_options(wsp): """ :return: General Fabber options for multiphase decoding """ # General options. note that the phase is always PSP number 1 options = { "method" : "vb", "noise" : "white", "model" : "asl_multiphase", "data" : wsp.asldata, "mask" ...
51,710
def get_player_objects_from_challenge_info(player, should_be_completed=False, search_by_discord_name=True): """ Search for a challenge in the DB corresponding to the player param str/int player: The gamertag or id of the player to search for param bool should_be_completed: If the challenge should alrea...
51,711
def get_python_version(python_bin): """Returns the version of a python binary as a tuple of integers. Args: python_bin (str): Python binary. Returns: Integer tuple containing the major, minor, and micro of the version. None if version checking fails. """ # <><><><><><><><><...
51,712
def get_output(interpreter, score_threshold, labels): """Returns list of detected objects.""" boxes = output_tensor(interpreter, 0) class_ids = output_tensor(interpreter, 1) scores = output_tensor(interpreter, 2) count = int(output_tensor(interpreter, 3)) def get_label(i): id = int(clas...
51,713
def provide_session(func): """ Function decorator that provides a session if it isn't provided. If you want to reuse a session or run the function as part of a database transaction, you pass it to the function, if not this wrapper will create one and close it for you. """ @wraps(func) de...
51,714
def encode_urlencoded_form(fields): """ Encode dict of fields as application/x-www-form-urlencoded. """ body = urlencode(fields, doseq=1) headers = {'Content-Type': 'application/x-www-form-urlencoded'} return body, headers
51,715
def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None, **args): """Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and registers it". Auxiliary function: clients should use the specialized DEFINE_<t...
51,716
def process_wrapper(row, seq, cds_seq, seq_lookup, tile_begins, tile_ends, qual, locate_log, mutrate, base, posteriorQC, adjusted_er): """ Wrapper function to process each line (pair of reads) """ mut_parser = locate_mut.MutParser(row, seq, cds_seq, seq_lookup, tile_begins, tile_ends...
51,717
def main(): """ Perform run example_app analysis based on command line arguments """ parser = argparse.ArgumentParser(description='Run example_app') parser.add_argument('--in1', help='value for in1. Missing if not specified') parser.add_argument('--in2', help='value for in2. Missing if not speci...
51,718
def default_cfg(): """ Set parameter defaults. """ # Simulation specification cfg_spec = dict( nfreq=20, start_freq=1.e8, bandwidth=0.2e8, start_time=2458902.33333, integration_time=40., ntimes=4...
51,719
def merge_outputs(*streams: Stream) -> OutputStream: """Include all given outputs in one ffmpeg command line.""" return MergeOutputsNode(streams).stream()
51,720
def softmax(vector, theta=1.0): """Takes an vector w of S N-element and returns a vectors where each column of the vector sums to 1, with elements exponentially proportional to the respective elements in N. Parameters ---------- vector : array of shape = [N, M] theta : float (defa...
51,721
def scaled_elementary_effect_i( model, i_python, init_input_pars, stepsize, sd_i, sd_model ): """Scales EE by (SD_i / SD_M)""" ee_i = elementary_effect_i(model, i_python, init_input_pars, stepsize) return ee_i * (sd_i / sd_model)
51,722
def arch_mnasnet_b1(variant, feat_multiplier=1.0, **kwargs): """Creates a mnasnet-b1 model. Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet Paper: https://arxiv.org/pdf/1807.11626.pdf. Args: feat_multiplier: multiplier to number of channels per layer. """ ...
51,723
def accession(data, location): """ Generate an accession for the given location in data. """ return "{ac}:{gene}".format( ac=parent_accession(location), gene=data["gene"], )
51,724
def poly_oval(x0,y0, x1,y1, steps=20, rotation=0): """return an oval as coordinates suitable for create_polygon""" # x0,y0,x1,y1 are as create_oval # rotation is in degrees anti-clockwise, convert to radians rotation = rotation * pi / 180.0 # major and minor axes a = (x1 - x0) / 2.0 b = (...
51,725
def process_file(input_file, output_file, model, targets, gradients, device, log_queue, preserve_structure=False, sensor=None): """ Process input file. Args: input...
51,726
def test_s3_list_object_versions(test_bucket): """Happy path: required args.""" iterator = slurp_items( S3_CLIENT, 'list_object_versions', **{'Bucket': test_bucket}) assert getattr(iterator, '__iter__', False)
51,727
def not_found(request): """Error page for 404.""" response = render(request, "projectile/404.html") response.status_code = 404 return response
51,728
def _sympy_to_z3_rec(variable_map, expr): """Recursively convert sympy expression to z3 expressions.""" # Adapted from # https://stackoverflow.com/questions/22488553/how-to-use-z3py-and-sympy-together rv = None # TODO(yl): For some reason, # GreaterThan and LessThan are not subclasses of Expr? # if not ...
51,729
def write_numeric(fmt, value, buff, byteorder="big"): """Write a numeric value to a file-like object.""" try: buff.write(fmt[byteorder].pack(value)) except KeyError as exc: raise ValueError("Invalid byte order") from exc
51,730
def reset_universe_id(): """ reset_universe_id() Resets the auto-generated unique Universe ID counter to 10000. """ return _openmoc.reset_universe_id()
51,731
def native_mean(data: Union[list, np.ndarray, pd.Series]) -> float: """ Calculate Mean of a list. :param data: Input data. :type data: list, np.ndarray, or pd.Series :return: Returns the mean. :rtype: float :example: *None* :note: *None* """ data = _remove_nan(data=_to_list(da...
51,732
def dataset_info_4_biogps(request, ds_id): """ get information about a dataset """ ds = adopt_dataset(ds_id) if ds is None: return general_json_response(GENERAL_ERRORS.ERROR_NOT_FOUND, "dataset with this id not found") s = json.dumps(ds, cls=Comp...
51,733
def _set_reducemax_attrs(desc_d, attrs): """Add addition attributes for ReduceMax.""" backend = desc_d['process'] if backend == 'cuda' and _reducemax_pattern(desc_d)[0]: attrs['enable_tile_c0'] = True elem_per_thread = 4 blockdim_x = 64 blockdim_y = 16 griddim_x = 1 ...
51,734
def read_env(): """ Reads a INI file named .env in the same directory manage.py is invoked and loads it as environment variables. Note: At least one section must be present. If the environment variable TEST_ENV is not set then the [DEFAULT] section will be loaded. More info: https://docs.python....
51,735
def getTail(compiler,version): """ Function which generates the Tail of a Compiler module file. @input compiler :: compiler name ('intel','pgi',..) @input version :: version of the compiler @return :: list of Lua lines """ strA = 'local version = "{0}"'.format(version) ...
51,736
def make_attr_string(attr): """Returns an attribute string in the form key="val".""" attr_string = ' '.join('%s="%s"' % (k, v) for k, v in attr.items()) return '%s%s' % (' ' if attr_string != '' else '', attr_string)
51,737
def set_config_user_value(config_data, key, value): """Set a user-defined value in the config file. The `value` must be an instance of `str`, `float`, `bool`, or `int`, and it will be set for the given `key` in the corresponding section ``user_strings``, ``user_reals``, ``user_loigcals``, or ``user_ints...
51,738
def fixture_test_dir() -> Generator[str, None, None]: """ Creates the directory used for testing and sets up the base box if not already set up. Creates a directory in a temporary location and checks if there is a base box under the `TEST_BOX_NAME`. If needed it downloads it. This is ran once ...
51,739
def optimize_weights(instrument, sample): """Optimize the weights on a particular sample""" guess = [1.0] * sample.shape[1] bounds = [(0.0,5.0)] * sample.shape[1] def function(w, instrument, sample): """This is the function that is minimized iteratively using scipy.optimize.minimize to find the ...
51,740
def fill(nioshtic_data): """ Fill out several Wikidata items based on NIOSHTIC data @param nioshtic_data: a dictionary with lots of NIOSHTIC data """ for entry in nioshtic_data['entries']: if 'Wikidata' in entry: wd = WikidataEntry(entry, nioshtic_data['retrieved']) ...
51,741
def set_up(): """Function responsible to make the enviroment ready to be executed.""" xmls_path = 'xmls/' if glob.glob(xmls_path) == []: os.mkdir(xmls_path)
51,742
def get_random_image_from_database(): """Returns full image path of a random image from the database, if available""" logging.debug('get_random_image_from_database()') dir_path = os.path.join(os.environ['LOCALAPPDATA'],'WarietyWallpaperImages') os.makedirs(dir_path, exist_ok=True) db_file =...
51,743
def voto(ano): """ FUNÇÃO QUE VALIDA A IDADE DO ELEITOR :param ano: ano de nascimento :return: idade menor que 16 anos: NÃO VOTA idade entre 16 e 17 anos e acima de 65 anos: VOTO OPCIONAL idade entre 18 e 65: APTO A VOTAR """ from datetime import date idade = date.t...
51,744
def new_border_and_win(ws): """ Returns two curses windows, one serving as the border, the other as the inside from these *_FRAME tuples above. """ return ( curses.newwin(ws[1][1], ws[1][0], ws[0][1], ws[0][0]), curses.newwin(ws[1][1] - 2, ws[1][0] - 2, ws[0][1] + 1, ws[0][0] + 1), )
51,745
def parse_command_line(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description="Start a MongoDB cluster in a distributed environment" ) parser.add_argument("-d", "--debug", action="store_true", help="enable debug output") parser.add_argument("--log-file", help="p...
51,746
def merge_models(l): """ (c)rude merging """ # TODO this is going meta, the merging can be done with a clustering # algorithm, why not a DP(G)MM? # Currently using a nearest neighbor's search on means n_clusters = min([len(mixt.params.keys()) for mixt in l]) # TODO change n_mixt = len(l) p...
51,747
async def test_flow_user_works(opp): """Test a config flow initiated by the user. Best case scenario with no errors or locks. """ device = get_device("Living Room") mock_api = device.get_mock_api() result = await opp.config_entries.flow.async_init( DOMAIN, context={"source": config_ent...
51,748
def mk_sock(mcast_host, mcast_ip, mcast_port): """ multicast socket setup """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt( socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, ...
51,749
def count_signals(): """Function counts transaction signals Returns: list: list of dictionaries with signals 1. Dictionary for buy signals 2. Dictionary for sell signals 3. Dictionary for close long position 4. Dictionary for close short position """ filenames = ...
51,750
async def test_handler_google_actions_disabled(hass, mock_cloud_fixture): """Test handler Google Actions when user has disabled it.""" mock_cloud_fixture._prefs[PREF_ENABLE_GOOGLE] = False with patch("hass_nabucasa.Cloud.start", return_value=mock_coro()): assert await async_setup_component(hass, "c...
51,751
def next_line_start_or_here(text, pos): """Find next line start, or `pos` if `pos` is already a line start """ if pos == 0 or (pos-1 < len(text) and text[pos-1] == "\n"): return pos return next_line_start(text, pos)
51,752
def sync_test_data(): """ Update data from remote Git repository. :return: """ if not os.path.exists(os.path.join(volume_root, ".git")): # Directory is not yet a git repo args = ["git", "lfs", "clone", ENDATA_TEST_REPO, volume_root] print(" ".join(args)) r = sp.call(...
51,753
def itersubrepos(ctx1, ctx2): """find subrepos in ctx1 or ctx2""" # Create a (subpath, ctx) mapping where we prefer subpaths from # ctx1. The subpaths from ctx2 are important when the .hgsub file # has been modified (in ctx2) but not yet committed (in ctx1). subpaths = dict.fromkeys(ctx2.substate, c...
51,754
def getimdata(cubenm, verbose=False): """Get fits image data """ if verbose: print(f'Getting image data from {cubenm}') with fits.open(cubenm, memmap=True, mode='denywrite') as hdu: dxas = hdu[0].header['CDELT1']*-1*u.deg dyas = hdu[0].header['CDELT2']*u.deg n...
51,755
def N(latitude): """ Transverse radius of curvature. Returns radius of curvature in east-west direction. latitude: Latitude in radians. """ return a/math.sqrt(1-e2*pow(math.sin(latitude),2.0))
51,756
def doBoxPlots(data,ycols, xcols= (), stripIt=False): """ data = dataframe ycols= columns to show xcols= columns into which to break down stripIt : if True add a stripPlot showing datapoints """ for ycol in ycols: for xcol in xcols: if stripIt: box...
51,757
def cmd(command_id): """ A helper function for identifying command functions """ def decorator(func): func.__COMMAND_ID__ = command_id return func return decorator
51,758
def getBatchExperiments(): """ return the information related to the experiments of a batch :return: informations of the experiment :rtype: Dict """ data = request.json['data'] experiments = [] for key in data: batch_experiments = queueManager.getBatchExperiments(key) fo...
51,759
def noiseProb(ksStat, Ntot): """pvalue = noiseProb(ksStat, Ntot) Returns probability of being in same distribution for given K-S statistic""" s = Ntot*pow(ksStat, 2) # For d values that are in the far tail of the distribution (i.e. # p-values > .999), the following lines will speed up the computatio...
51,760
def _check_nmant(np_type, nmant): """ True if fp type `np_type` seems to have `nmant` significand digits Note 'digits' does not include implicit digits. And in fact if there are no implicit digits, the `nmant` number is one less than the actual digits. Assumes base 2 representation. Parameters ...
51,761
def nativeSetCrossHairColor(self, r, g, b): """ TOWRITE :param `r`: Red value :type `r`: quint8 :param `g`: Green value :type `g`: quint8 :param `b`: Blue value :type `b`: quint8 """ self.setSettingsDisplayCrossHairColor(qRgb(r, g, b)) self.updateAllViewCrossHairColors(qRgb(...
51,762
def timeboard_send_steps_list(self, steps, scenario_name, timeout): """ Change all steps in timeboard :param steps: The list of steps extracted from the scenario json file :type steps: list :param scenario_name: name of the scenario to which the steps belong :type scenario_name: string :par...
51,763
def monte_carlo_interpretation(**sample_inputs): """ Context manager to set ``monte_carlo.sample_inputs`` and install the :func:`monte_carlo` interpretation. """ old = monte_carlo.sample_inputs monte_carlo.sample_inputs = OrderedDict(sample_inputs) try: with interpretation(monte_carl...
51,764
def create_dns_records(ips): """ Create DNS records Args: ips (list): List if IPs for creating DNS records """ logger.info("creating DNS records") aws = AWS() dns_record_names = [ f"api.{config.ENV_DATA.get('cluster_name')}", f"*.apps.{config.ENV_DATA.get('cluster_n...
51,765
def get_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]: """ Retrieve a dict of characters and escape codes with their real index into the string as the key. """ codeindices = get_code_indices(s) if not codeindices: # This function is not for non-escape-code stuff, but okay. ...
51,766
def parse_shortcodes(post_body): """ I stole this shortcode regex from Wordpress's source. It is very confusing. """ tagregexp = '|'.join([re.escape(t) for t in TAGS_WE_CAN_PARSE.keys()]) pattern = re.compile( '\\[(\\[?)(' + tagregexp + ')\\b([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:...
51,767
def gp_eval_make_motif_plots(args, motif_plots_folder, ch_info_dic, all_features, si2sc_dic, idx2id_dic, seqs_dic, worst_win_pert_dic, worst_win_pos_dic, got_saliencies=False, ...
51,768
def on_start(func: Callable) -> FunctionCallback: """Decorator for creating a callback from a function. The function will be executed when the `Events.START` is triggered. The function should take :class:`argus.engine.State` as the first argument. Example: .. code-block:: python i...
51,769
def receive_input(s, game_port): """ 接收控制台输入,向客户端发送命令 """ # a = get_color_text('>>>', Color.GREEN) while True: strs = input('>>>') command = encode_message(strs) s.sendto(command, (game_ip, game_port))
51,770
def conditional_entropy(cond_counts): """ Compute the conditional entropy of a conditional multinomial distribution given a list of lists of counts or Counters for x given each y: H(x|y) = \sum_y p(y) \sum_x p(x|y) \log (1 / p(x|y)) """ if isinstance(cond_counts, dict): cond_counts =...
51,771
async def walk_thing_nodes( parent_id, tn_append_list, src_append_list, snk_append_list, src_attached_metadata_dict, snk_attached_metadata_dict, tn_attached_metadata_dict, open_async_test_client, ): """Recursively walk thingnodes""" response_obj = ( await open_async_test...
51,772
def xover_selection(snakes, survivors, opts, num_survivors): """ Picks parents from the current generation of snakes for crossover params: snakes: list, current generation of snakes of class Snake survivors: list, snakes of class Snake that survived opts: dict, contains hyperparamters ...
51,773
def rgb2hsv(image): """ Convert RGB image to HSV. Parameters ---------- image : af.Array - A 3 D arrayfire array representing an 3 channel image, or - A multi dimensional array representing batch of images. Returns -------- output : af.Array - A RGB image...
51,774
def use_step_import_modules(step_container): """Redirect any step/type registration to the runner's step-context object during step imports by using fake modules (instead of using module-globals). This allows that multiple runners can be used without polluting the global variables in problematic module...
51,775
def make_colormap(seq,cmapname='CustomMap'): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for...
51,776
def _interp_fit(y0, y1, y_mid, f0, f1, dt): """Fit coefficients for 4th order polynomial interpolation. Args: y0 (Tensor) : Function value at the start of the interval. y1 (Tensor) : Function value at the end of the interval. y_mid (Tensor) : Function value at th...
51,777
def test_complex012_complex012_v6_xml(mode, save_output, output_format): """ xsi:nil on complex type with mixede content (not specific to 1.1) All combinations of xsi:nil with value present or absent """ assert_bindings( schema="saxonData/Complex/complex012.xsd", instance="saxonData/...
51,778
def test_regional_user_cannot_update_user_not_in_region( api_client, regional_user, user_in_other_region ): """Test regional staff cannot update users not in their region.""" assert regional_user.region.id != user_in_other_region.stt.region.id api_client.login(username=regional_user....
51,779
def interleave_value(t0,series,begin=False,end=False): """Add t0 between every element of *series*""" T = [] if begin: T += [t0] if len(series) > 0: T += [series[0]] for t in series[1:]: T += [t0,t] if end: T += [t0] return T
51,780
def menu(): """Menu grafico testuale per programma di gestione Immobili """ x = 1 while x !=0 : print (" Menu'") print(" Gestione Immobiliare") print(" INSERIMENTO IMMOBILE .........digita 1 --> ") print(" MODIFICA IMMOBILE .........digita 2 --> ") print(" CAN...
51,781
def named(new_name): """ Sets given string as command name instead of the function name. The string is used verbatim without further processing. Usage:: @named('load') def do_load_some_stuff_and_keep_the_original_function_name(args): ... The resulting command will be a...
51,782
def remove_junk_chars(bucket_name): """Remove characters that shouldn't or won't be in a bucket name""" name = bucket_name names = [] #Remove junk chars junk_chars = ["'", '"', "&#39;", "!"] for junk_char in junk_chars: name = name.replace(junk_char, "") #Remove domains (this can b...
51,783
def create_2x2_arrays(num_arrays): """This creates a multi-dimensional array of n 2x2 arrays Arguments: num_var {[int]} -- [this is the number of desired arrays] Returns: [numpy array] -- [a zero filled n dimensional array with n 2x2 arrays] """ temp_list = [2] for temp in rang...
51,784
def calculate_gr(fr_pattern, density, composition): """ Calculates a g(r) pattern from a given F(r) pattern, the material density and composition. :param fr_pattern: F(r) pattern :param density: density in g/cm^3 :param composition: composition as a dictionary with the elements as k...
51,785
def mc_integrate(func: Callable, limits: ztyping.LimitsType, axes: Optional[ztyping.AxesTypeInput] = None, x: Optional[ztyping.XType] = None, n_axes: Optional[int] = None, draws_per_dim: int = 40000, max_draws=800_000, tol: float = 1e-6, method: str = None, dtype: Type = ztypes.float, ...
51,786
def dump_model(bucket_name, object_to_dump, output_path): """Pickle the object and save to the output_path. Args: object_to_dump: Python object to be pickled output_path: (string) output path which can be Google Cloud Storage Returns: None """ # with open(output_path, 'wb') as mode...
51,787
def test_successful_installation_on_text_trigger( kvm_scsi_system, os_any_ubuntu, creds, tmpdir, good_log): """Test Debian succeed when a special line is provided""" model = AutoinstallMachineModel(*os_any_ubuntu, kvm_scsi_system, creds) hyp = plat_kvm.PlatKvm.create_hypervisor(model) pl...
51,788
async def add(ctx): """test""" await ctx.send('Pong!')
51,789
def resolve_path_or_url(path_or_url, allow_caching=True): """ Given either a path (absolute or relative), or a URL, attempt to resolve it. Returns a tuple consisting of: a :py:class:`slicedimage.backends._base.Backend`, the basename of the object, and the baseurl of the object. """ try: ...
51,790
def get_batch(data_bucket, bucket_id, batch_size=1): """ Return one batch to feed into the model """ # only pad to the max length of the bucket encoder_size, decoder_size = config.BUCKETS[bucket_id] encoder_inputs, decoder_inputs = [], [] for _ in range(batch_size): encoder_input, decoder_i...
51,791
def get_report_formatter(format_name): """ Get the correct report table output function for a named format Args: format_name (str): Name of the desired format Returns: A formatting output function if the format is recognized, or None if it is not. """ format_name = get_...
51,792
def print_rule_tree(rt: Set['FlowRule']): """ Recursively explore rt-contained rules' parents. """ rt = rt.copy() res = [] seen = set() while rt: rule = rt.pop() if rule in seen: continue seen.add(rule) res.insert(0, rule) for parent_rule...
51,793
def sort(request): """ Valid values for the 'sort' parameter used in the Index setops methods (intersection, union, etc.) Caution: Don't confuse this one with the "sort" fixture used for DataFrame.append or concat. That one has parameters [True, False]. We can't combine...
51,794
def date_string_to_utc_float_string(date_string, timezone=None): """Return a utc_float_string for a given date_string - date_string: string form between 'YYYY' and 'YYYY-MM-DD HH:MM:SS.f' """ dt = None s = None for fmt in [ '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d %H', '%Y-%m-%d...
51,795
def _find_nested(d1, d2): """ Find paths in d1 that are nested inside paths in d2. Returns tuples with keys `(d1_key, d2_key)` where `d1_path` was a subdirectory of `d2_path`. """ # Copy to ensure we don't alter # original dicts in parent scope d1 = d1.copy() d2 = d2.copy() # Make ...
51,796
def safe(method): """ Decorator to return safe in case of error. """ def ret(*args, **kw): try: return method(*args, **kw) except Exception as e: log.exception(e) # return result return ret
51,797
def flashpoint_alert_list_command(client: Client, args: dict) -> CommandResults: """ List alerts from Flashpoint. :param client: Client object :param args: The command arguments :return: Standard command result or no records found message. """ args = validate_alert_list_args(args) respo...
51,798
def geerate_tile_def_from_feature(features, zooms, projected='mercator'): """ yield [x, y, z, xmin, ymin, xmax, ymax] @param features a list geojson features (i.e. polygon) objects @param zooms a list of zoom levels @param projected 'mercator' or 'geo...
51,799