content
stringlengths
22
815k
id
int64
0
4.91M
def validate_get_arguments(kwargs): # type: (Dict[Text, Any]) -> None """Verify that attribute filtering parameters are not found in the request. :raises InvalidArgumentError: if banned parameters are found """ for arg in ("AttributesToGet", "ProjectionExpression"): if arg in kwargs: ...
13,600
def _get_transmission(self,d,E='config'): """ calculate the transmittion after thickness d (in m) of material at energy E (in eV).""" return np.exp(-d*1e6/self.absorption_length(E))
13,601
def calculate_density( input_layer, field=None, cell_size=None, cell_size_units="Meters", radius=None, radius_units=None, bounding_polygon_layer=None, area_units=None, classification_type="EqualInterval", num_classes=10, output_name...
13,602
def reverse(operation): """ decorator that returns sa.not_ for sending operation""" def decorated(*args, **kwargs): return sqlalchemy.not_(operation(*args, **kwargs)) return decorated
13,603
def disable_static_generator(view_func): """Decorator which prevents caching the response from a view on disk Flags the view with a ``disable_static_generator`` attribute so staticgenerator won't ever save its response on the filesystem. Example:: @disable_static_generator def myview(...
13,604
def create_lengths(text): """Create a data frame of the sentence lengths from a text""" lengths = [] for sentence in tqdm(text): lengths.append(len(sentence)) return pd.DataFrame(lengths, columns=['counts'])
13,605
def basic_auth_string(key, value): """Returns basic auth string from key and value""" key_pass = b":".join((_to_bytes(key), _to_bytes(value))) token = b64encode(key_pass).decode() return f"Basic {token}"
13,606
def main(argv = None): """ Main function for the ``amplimap`` executable. This function: - parses command line arguments - reads, merges and checks each of these config files, if they exist: + ``config_default.yaml`` in the amplimap package + ``/etc/amplimap/VERSION/config.yaml`` (where...
13,607
def measureit(_func=None, *, output: Output = None, number: int = 1): """ Measure the energy consumption of monitored devices during the execution of the decorated function (if multiple runs it will measure the mean energy) :param output: output instance that will receive the power consummation data :p...
13,608
def plot_distribution(dof_names, mean, upper_bound, lower_bound): """Plots a given probability distribution. """ figures_per_plot = np.min([4, mean.shape[0]]) for index in range(mean.shape[0]): if(index % figures_per_plot == 0): fig = plt.figure() new_plot = plt.subplot(fig...
13,609
def csv_template(n_types, n_type_covariates, initialize_coeffs=True): """Creates a template for the parameter specification. Parameters ---------- n_types : int, optional Number of types in the model. Default is one. n_type_covariates : int, optional Number of covariates to predict ...
13,610
def test_wpas_mesh_secure_no_auto(dev, apdev): """wpa_supplicant secure MESH network connectivity""" check_mesh_support(dev[0], secure=True) dev[0].request("SET sae_groups 19") id = add_mesh_secure_net(dev[0]) dev[0].mesh_group_add(id) dev[1].request("SET sae_groups 19") id = add_mesh_secur...
13,611
def get_surround(ppath, recordings, istate, win, signal_type, recalc_highres=False, tstart=0, tend=-1, ma_thr=20, ma_state=3, flatten_tnrem=False, nsr_seg=2, perc_overlap=0.95, null=False, null_win=[0.5,0.5], p_iso=0, pcluster=0, clus_event='waves', psave=False): ...
13,612
def load_quantized_bert_base(batch_size=1, seq_len=384): """ Load the quantized bert-base model from TLCBench, possibly downloading it from github and caching the converted int8 QNN module to disk. In addition to returing the relay module and its parameters, it also returns input name and shape inf...
13,613
def projects(ctx): """Display and download projects from Kimai""" if config.get('ApiKey') is None: print_error( '''kimai-cli has not yet been configured. Use \'kimai configure\' first before using any other command''' ) ctx.abort()
13,614
def test_check_transform_not_matrix_2d() -> None: """verify raised exception for 2d non-matrix arguments""" xform = AutomataTransforms(base_universe_instance_2d()) not_matrix = not_matrix_typeerror_2d() for case in not_matrix: # minimal check: details verified in tests for validate_matrix, valid...
13,615
def setup(app): """A temporary setup function so that we can use it for backwards compatability. This should be removed after a deprecation cycle. """ # To avoid circular imports we'll lazily import from . import setup as jssetup js.logger.warning( ( "`jupyter-sphinx` wa...
13,616
def test_all_rank_logging_ddp_spawn(tmpdir): """Check that all ranks can be logged from.""" model = TestModel() all_rank_logger = AllRankLogger() model.training_epoch_end = None trainer = Trainer( strategy="ddp_spawn", gpus=2, default_root_dir=tmpdir, limit_train_batc...
13,617
def hinge_loss(logit, target, margin, reduce='sum'): """ Args: logit (torch.Tensor): (N, C, d_1, d_2, ..., d_K) target (torch.Tensor): (N, d_1, d_2, ..., d_K) margin (float): """ target = target.unsqueeze(1) tgt_logit = torch.gather(logit, dim=1, index=target) loss = logi...
13,618
def setTimeSync(state): """ Set the state of host/guest time synchronization using vmware-toolbox-cmd. Returns None on success and an error message on failure. """ # Translate the boolean to a string for vmware-toolbox-cmd if state: setStr = 'enable' else: setStr = 'disable' ...
13,619
def do_cleanup(ips, args): """ :param ips: :param args: :return: None """ def _cleanup_single_node(ip): def _rpc(cmd): return rpc(ip, cmd, args.user, args.password, args.key, suppress_output=not args.verbose) # TODO: (Make this more targeted) # Stop services...
13,620
def getargopts(): """Parse command line arguments.""" opts = argparse.ArgumentParser() opts.add_argument('--port', type=int, help="Port to listen to (default 8888)", default=8888) opts.add_argument('srcbase', help="Base source directory.") opts.add_argumen...
13,621
def test_fetch_local_no_local_registry(): """Test that local fetch fails when no local registry.""" with TemporaryDirectory() as tmp_dir: with cd(tmp_dir): runner = CliRunner() result = runner.invoke( cli, ["fetch", "--local", "fetchai/my_first_aea...
13,622
def roc(model, image, mask, ignore=None, sky=None, n_mask=1, seed=1, thresholds=np.linspace(0.001, 0.999, 500), dilate=False, rad=1): """ evaluate model on test set with the ROC curve :param model: deepCR object :param image: np.ndarray((N, W, H)) image array :param mask: np.ndarray((N, W, H)) ...
13,623
def parse_testconfig(conffile): """Parses the config file for the whole testsuite.""" repo_path, drop_caches, tests_dir, testlog_dir = '', '', '', '' basebranch, baserev, repo_prof_path, repo_gprof_path = '', '', None, None fileopen = open(conffile, 'r') for line in fileopen: line = line.spl...
13,624
def get_filtered_df(df, vocab_file): """ Return a data frame with only the words present in the vocab file. """ if vocab_file: vocab = open(vocab_file).readlines() vocab = [v.strip() for v in vocab] # Get the set of words. words = pd.Series(df.word.values.ravel()).unique() ...
13,625
def test_update(session): """ Test the role repository update function. """ # Arrange test_model = RoleRepository.create(Role(name='Super User')) test_model_id = test_model.id update_fields = ('name',) # Act result = RoleRepository.update( test_model_id, update_fields, name=...
13,626
def pkcs5_pad(data): """ Pad data using PKCS5 """ pad = KEYCZAR_AES_BLOCK_SIZE - len(data) % KEYCZAR_AES_BLOCK_SIZE data = data + pad * chr(pad).encode("utf-8") return data
13,627
def fmul_rd(x, y): """ See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmul_rd.html :param x: Argument. :type x: float32 :param y: Argument. :type y: float32 :rtype: float32 """
13,628
def preview(handler, width, height): """ Preview camera stream """ handler.stitch_feeds(False, None, width, height, None)
13,629
def add_to_shelf(book, shelf): """Add entry to data-base so that ``book`` appears in ``shelf``.""" shelf_content = ShelfContent( ShelfName=shelf, ContentId=f"file:///mnt/onboard/contents/{book.name}", DateModified=datetime.today(), _IsDeleted=False, _IsSynced=False, )...
13,630
def chdir(path) -> Any: """ Change current directory. """ ...
13,631
def gatherData(data, neat, gen, hyp, fileName, savePop=False): """Collects run data, saves it to disk, and exports pickled population Args: data - (DataGatherer) - collected run data neat - (Neat) - neat algorithm container .pop - [Ind] - list of individu...
13,632
def impute_bad_concentration_fits(c_lgtc, c_lgtc_min=0.1): """Overwrite bad concentration parameter fit values.""" c_lgtc = np.where(c_lgtc < c_lgtc_min, c_lgtc_min, c_lgtc) return c_lgtc
13,633
def _build_sub_nics(all_nics): """ Aggregate all sub nics into their sub groups. I.E. All nic\.X.\.*\.Y nics go into a list where all Y's are the same. :param all_nics: All nics to consider. :type all_nics: list """ sub_nics = {} for nic in all_nics['nics']: possible_sub_nic = g...
13,634
def pearsonr(a0, a1): """Pearson r, product-moment correlation coefficient, of two samples. Covariance divided by product of standard deviations. https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#For_a_sample """ n = len(a0) assert n == len(a1) if n == 0: ...
13,635
def __column(matrix, i): """Returns columns from a bidimensional Python list (a list of lists)""" return [row[i] for row in matrix]
13,636
def datamask(fmri_data, mask_data): """ filter the data by a ROI mask Parameters: fmri_data : array The fMRI data. The shape of fmri_data is [nx, ny, nz]. nx, ny, nz represent the size of the fMRI data. mask_data : array The mask data. The shape of mask_data is [nx,...
13,637
def make_global_batch_norm_tests(options): """Make a set of tests to do batch_norm_with_global_normalization.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2], [3, 4, 5, 4]], "epsilon": [0.1, 0.0001], "scale_after": [True, False], }] def build_graph(parameter...
13,638
def write_stats_file(run_output_dict): """Writes a dummy PolyChord format .stats file for tests functions for processing stats files. This is written to: base_dir/file_root.stats Also returns the data in the file as a dict for comparison. Parameters ---------- run_output_dict: dict ...
13,639
def dict_serialize(seqlen_dist_dict): """ dict->str Turns {1:'a',2:'b'}->"[[1,'a'],[2,'b']]" Why? Because this format plays nice with shell script that runs xlmr_bench. Avoids curly braces and spaces that makes shell script str input unhappy. """ seqlen_dist_lst = list(seqlen_dist_dict.ite...
13,640
def pi_cdecimal(): """cdecimal""" D = C.Decimal lasts, t, s, n, na, d, da = D(0), D(3), D(3), D(1), D(0), D(0), D(24) while s != lasts: lasts = s n, na = n+na, na+8 d, da = d+da, da+32 t = (t * n) / d s += t return s
13,641
def image2file(image, path): """ Writes an image in list of lists format to a file. Will work with either color or grayscale. """ if isgray(image): img = gray2color(image) else: img = image with open(path, 'wb') as f: png.Writer(width=len(image[0]), height=len(image)).wri...
13,642
def e_list(a_list: AList) -> set[E]: """Unique elements in adjacency list.""" return set(e for n in a_list for nb in a_list[n] for e in a_list[n][nb])
13,643
def load_complete_state(options, cwd, subdir, skip_update): """Loads a CompleteState. This includes data from .isolate and .isolated.state files. Never reads the .isolated file. Arguments: options: Options instance generated with process_isolate_options. For either options.isolate and options...
13,644
def GDAL_QUERY(filename, sql, data={}): """ GDAL_QUERY """ res = [] sql = sformat(sql, data) ds = ogr.OpenShared(filename) if ds: try: layer = ds.ExecuteSQL(sql) definition = layer.GetLayerDefn() n = definition.GetFieldCount() for featu...
13,645
def auto_fav(q, count=100, result_type="recent"): """ Favorites tweets that match a certain phrase (hashtag, word, etc.) """ result = search_tweets(q, count, result_type) for tweet in result["statuses"]: try: # don't favorite your own tweets if tweet["user"]["sc...
13,646
def get_event_bpt_hea(): """ Get hardware address for BREAKPOINT event @return: hardware address """ ev = ida_dbg.get_debug_event() assert ev, "Could not retrieve debug event" return ida_idd.get_event_bpt_hea(ev)
13,647
def solve_maxent_ce(payoffs, steps=1000000, lams=None, lr=None): """Calculates the maximum-entropy correlated equilibrium as defined in Ortiz et al. (2007). payoffs (torch.Tensor): Joint payoff tensor. steps (int, optional): Number of SGD steps to use in calculations (default: 1000000)....
13,648
def d_latlon(p1, p2): """ 计算两点间的距离。原文件使用了较复杂的算法,代价较高 这里使用较为相对简单的算法代替,精度不会损失很多 """ lon_diff, lat_diff = p1 - p2 lon_diff *= cos((p1[1] + p2[1]) * 0.00872664625997165) return sqrt(lat_diff * lat_diff + lon_diff * lon_diff) * earth_radians
13,649
def _path_list_creator(path, file_prefix_name, number_of_digits_zfill, file_suffix_name): """Creates a list of paths where the files have a predefined prefix, an incremental number and a predefined suffix on their name, respectively. Eg.: img01.zdf Args: path: a path that leads to the f...
13,650
def determine_paths(env): """ Fill the 'CUDA_TOOLKIT_PATH' into environment if it is not there. @return: the paths. @rtype: tuple """ import sys import os from warnings import warn home = os.environ.get('HOME', '') programfiles = os.environ.get('PROGRAMFILES', '') homedrive ...
13,651
def crosscorrelation(array1, array2, std1, std2, **kwargs): """ Compute crosscorrelation. """ _ = std1, std2, kwargs xp = cp.get_array_module(array1) if CUPY_AVAILABLE else np window = array1.shape[-1] pad_width = [(0, 0)] * (array2.ndim - 1) + [(window//2, window - window//2)] padded = xp.pad(a...
13,652
def score_max_depths(graph, max_depths): """ In order to assess the quality of the approximate partitioning method we've developed, we will run it with different values for max_depth and see how it affects the norm_cut score of the resulting partitions. Recall that smaller norm_cut scores correspond...
13,653
def build_multi(mapping, inserts, key_residues, pdbfnames, chains): """Superimpose multiple structures onto a reference, showing equivalent selected residues in each. To reduce clutter, only show residues deviating from the reference side chain by at least `threshold` Angstroms RMS. """ # TODO ...
13,654
def tamper(payload, **kwargs): """ Replaces instances of UNION with -.1UNION Requirement: * MySQL Notes: * Reference: https://raw.githubusercontent.com/y0unge/Notes/master/SQL%20Injection%20WAF%20Bypassing%20shortcut.pdf >>> tamper('1 UNION ALL SELECT') '1-.1UNION ALL SELECT' ...
13,655
def svn_wc_transmit_prop_deltas(*args): """ svn_wc_transmit_prop_deltas(char path, svn_wc_adm_access_t adm_access, svn_wc_entry_t entry, svn_delta_editor_t editor, void baton, apr_pool_t pool) -> svn_error_t """ return _wc.svn_wc_transmit_prop_deltas(*args)
13,656
def error_exit() -> NoReturn: """Exit with return code 1.""" if logger.isEnabledFor(logging.DEBUG): traceback.print_exc() logger.debug("Exited with error code 1.") sys.exit(1)
13,657
def patch_model_checkpoint(trainer): """ Save last checkpoint when key interrupt occurs. """ for callback in trainer.callbacks: if isinstance(callback, pl.callbacks.ModelCheckpoint): old_on_keyboard_interrupt = callback.on_keyboard_interrupt def on_keyboard_interrupt(self...
13,658
def save_model_audits(sender, **kwargs): """ The signal handler, `save_model_audits`, saves the audit logs when the original model is saved. """ instance = kwargs['instance'] if hasattr(instance, '_django_fsm_audits'): for audit in instance._django_fsm_audits: audit.save()
13,659
def _make_immutable(obj): """Recursively convert a container and objects inside of it into immutable data types.""" if isinstance(obj, (text_type, binary_type)): return obj elif isinstance(obj, Mapping): temp_dict = {} for key, value in obj.items(): if isinstance(value, ...
13,660
def get_source_tokens_tensor(src_tokens): """ To enable integration with PyText, src_tokens should be able to support more features than just token embeddings. Hence when dictionary features are passed from PyText it will be passed as a tuple (token_embeddings, dict_feat, ..). Thus, in this case whe...
13,661
def init(db): """ Register the dumper """ db.add_format('nestedini', parse_nested_ini_file)
13,662
def merge_config_and_args(config, args): """ Creates a configuration dictionary based upon command line arguments. Parameters ---------- config : dict configurations loaded from the config file args : object arguments and there values which could be \ passed in the c...
13,663
def test_python_script(database: Path, migrations: Path) -> None: """It should run without errors.""" (migrations/"1_test.up.py").write_text(""" USER_VERSION = 1 def main(db): db.execute("CREATE TABLE Test (key)") """) (migrations/"1_test.down.py").write_text(""" USER_VERSION = 0 def main(db): ...
13,664
def save_augmented_data( original_raw_data: np.ndarray, new_path: str, new_filename: str, mult_factor: int, write_period: int = 200, max_samples: int = 20000, data_types: List[str] = ["signal", "frequencies"], ) -> None: """ """ # TODO: Is this method finished? total_counter = 0 ...
13,665
def contemp2pottemp(salt, tcon, tpot0=None, **rootkwargs): """Calculate conservative temp -> potential temp. Calculate the potential temperature from the absolute salinity and conservative temperature. Applies either Newton's method or Halley's method. See `aux.rootfinder` for details on implementation...
13,666
def get_random_string(length: int) -> str: """ With combination of lower and upper case """ return ''.join(random.choice(string.ascii_letters) for i in range(length))
13,667
def _write_callback(connection_id, data_buffer, data_length_pointer): """ Callback called by Secure Transport to actually write to the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type containing the data to write :param ...
13,668
def cache(**kwargs): """ Cache decorator. Should be called with `@cache(ttl_sec=123, transform=transform_response)` Arguments: ttl_sec: optional,number The time in seconds to cache the response if status code < 400 transform: optional,func The transform function of the wrapp...
13,669
def RegisterTensorTransformer(name): """Registers a dataset.""" def decorator(obj): TENSOR_TRANSFORMER_REGISTRY[name] = obj obj.name = name return obj return decorator
13,670
def read_token(): """Reads and returns the authentication token. It tries to read the token from a already existing config file first. If there is no token it will get one from the putio api and store it in a config file. Location of the config file:: ~/.putiodown :returns: putio aut...
13,671
def create_help(tool, model): """ create help section of the Galaxy tool @param tool the Galaxy tool @param model the ctd model @param kwargs """ help_node = add_child_node(tool, "help") help_node.text = CDATA(utils.extract_tool_help_text(model))
13,672
def handler_factory( jinja_template_rendered: BytesIO, base_dir: Path, events: list = None, username: str = "thqm", password: str = None, oneshot: bool = False, allow_custom_events: bool = False, ): """Create a HTTPHandler class with the desired properties. Events should appear foll...
13,673
def add(): """This is a temporary function to allow users to easily add tracks, mainly for testing.""" form = SQLFORM(db.memo) if form.process().accepted: redirect(URL('default', 'index')) return dict(form=form)
13,674
async def test_update_failed( project: Project, server: Server, client: Client, environment: str, agent_factory: Callable[ [UUID, Optional[str], Optional[Dict[str, str]], bool, List[str]], Agent ], function_temp_dir: str, cache_agent_dir: str, ): """ This test creates a f...
13,675
def is_valid_mac(mac): """ Validate mac address :param mac: :return: boolean """ res = False if isinstance(mac, str): if mac: res = mac_address.match(mac.lower()) is not None return res
13,676
def run_test_shape(): """ Tests the shape function. """ print() print('--------------------------------------------------') print('Testing the SHAPE function:') print('--------------------------------------------------') print() print('Test 1 of shape: r=7') shape(7) prin...
13,677
def test_skip_all_stages(tmp_path, caplog): """ Skips all stages but the last one, which prints "All stages run". """ jobname = "test_job" stagefile = get_stagefile_path(jobname, tmp_path) stagefile.parent.mkdir(parents=True) stagefile.write_text("\n".join(STAGE_NAMES[:-1])) with caplog....
13,678
def get_model(tokenizer, lstm_units): """ Constructs the model, Embedding vectors => LSTM => 2 output Fully-Connected neurons with softmax activation """ # get the GloVe embedding vectors embedding_matrix = get_embedding_vectors(tokenizer) model = Sequential() model.add(Embedding...
13,679
def annotation_multi_vertical_height(_img, _x, _y_list, _line_color, _text_color, _text_list, _thickness=1, _with_arrow=True): """ 纵向标注多个高度 :param _img: 需要标注的图像 :param _x: 当前直线所在宽度 :param _y_list: 所有y的列表 :param _line...
13,680
def test_passing_url(): """Test passing URL directly""" httpbin = AnyAPI("http://httpbin.org") assert ( httpbin.GET(url="http://httpbin.org/anything").json()["url"] == "https://httpbin.org/anything" )
13,681
def _parse_indentation(lines: Iterable[str]) -> Iterable[Tuple[bool, int, str]]: """For each line, yield the tuple (indented, lineno, text).""" indentation = 0 for lineno, line in enumerate(lines): line = line.replace("\t", " ") line_indentation_match = LEADING_WHITESPACE.match(line) ...
13,682
async def list_(hub, ctx, registry_name, resource_group, **kwargs): """ .. versionadded:: 3.0.0 Lists all the replications for the specified container registry. :param registry_name: The name of the container registry. :param resource_group: The name of the resource group to which the container r...
13,683
def dbrg(images, T, r): """ Segmentation by density-based region growing (DBRG). Parameters ---------- n : int Number of blurred images. M : np.ndarray The mask image. r : int Density connectivity search radius. """ n = len(images) M = _generate_init_mask...
13,684
def latest_window_partition_selector( context: ScheduleEvaluationContext, partition_set_def: PartitionSetDefinition[TimeWindow] ) -> Union[SkipReason, Partition[TimeWindow]]: """Creates a selector for partitions that are time windows. Selects latest time window that ends before the schedule tick time. "...
13,685
def env_or_val(env, val, *args, __type=str, **kwargs): """Return value of environment variable (if it's defined) or a given fallback value :param env: Environment variable to look for :type env: ``str`` :param val: Either the fallback value or function to call to compute it :type val: ``str`` or a ...
13,686
def test_bakery_caching_for_AuthorizedSession(engine, oso, fixture_data): """Test that baked relationship queries don't lead to authorization bypasses for AuthorizedSession.""" from sqlalchemy.orm import Session basic_session = Session(bind=engine) all_posts = basic_session.query(Post) assert a...
13,687
def html(i): """ Input: { (skip_cid_predix) - if 'yes', skip "?cid=" prefix when creating URLs } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 ...
13,688
def multi_particle_first_np_metafit(n): """Fit to plots of two-body matrix elements from various normal-ordering schemes, where only the first n points are taken from each scheme """ name = b'multi_particle_first_{}p_metafit'.format(n) def mpfnp(fitfn, exp_list, **kwargs): return multi_part...
13,689
def readJSONLFile(file_name: Union[str, Path]) -> List[Dict]: """ Read a '.jsonl' file and create a list of dicts Args: file_name: `Union[str,Path]` The file to open Returns: The list of dictionaries read from the 'file_name' """ lines = ( open(file_name, 'r',...
13,690
def set_hash(node, nuc_data): """ This function sets the hash of a dataset or group of datasets in an hdf5 file as an attribute of that node. Parameters ---------- node : str String with the hdf5 node name nuc_data : str path to the nuc_data.h5 file """ the_hash = c...
13,691
def test_md033_bad_configuration_allowed_elements(): """ Test to verify that a configuration error is thrown when supplying the allowed_elements value with an integer that is not a string. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md0...
13,692
def _dtype_from_cogaudioformat(format: CogAudioFormat) -> np.dtype: """This method returns the numpy "data type" for a particular audio format.""" if COG_AUDIO_IS_INT(format): if COG_AUDIO_FORMAT_DEPTH(format) == COG_AUDIO_FORMAT_DEPTH_S24: return np.dtype(np.uint8) elif COG_AUDIO_FO...
13,693
def makeSiteWhitelist(jsonName, siteList): """ Provided a template json file name and the site white list from the command line options; return the correct site white list based on some silly rules """ if 'LHE_PFN' in jsonName: siteList = ["T1_US_FNAL"] print("Overwritting SiteWh...
13,694
def loadConfig(configFilePath: str) -> {}: """Loads configuration""" config = {} with open(configFilePath) as configFile: config = json.load(configFile) configSchema = {} with open(CONFIG_SCHEMA_FILE_PATH, "r") as configSchemaFile: configSchema = json.load(configSchemaFile) jso...
13,695
def version_info(): """ Get version of vakt package as tuple """ return tuple(map(int, __version__.split('.')))
13,696
def dacl(obj_name=None, obj_type="file"): """ Helper function for instantiating a Dacl class. Args: obj_name (str): The full path to the object. If None, a blank DACL will be created. Default is None. obj_type (str): The type of object. Default is 'File...
13,697
def max_crossing_sum(lst: List[int], mid: int, n: int) -> int: """ Parameter <mid> is the floor middle index of <lst>. Parameter <n> is the length of the input list <lst>. Pre: <lst> is a list of integers and len(lst) >= 2. Post: returns the maximum contiguous crossing sum starting from the middle o...
13,698
def reset_session_vars(): """ resets all image flask session variables """ session.pop("id", None) session.pop("filename", None) session.pop("image_path", None) session.pop("colors", None) session.pop("palette", None) session["max_colors"] = 8 session["sensitivity"] = 75
13,699