content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def wfFormIndex(text, lang, lowercase = True, contract = True, stopWords = False):
"""Returns the Formality Score of a text.
This function returns a value based on the weight that each kind of word
(adjective, noun, pronoun, etc.) has within the text.
"""
diffWords = stats.wordClass(text,... | 400cf83f5ea7eec82a9db8dd7ddfb6d9c35c23d8 | 38,000 |
import os
import pickle
def load_project_data():
"""
Load project data from downloaded pickle file
- returns: data dictionnary
"""
if os.path.exists("final_project_dataset.pkl"):
with open("final_project_dataset.pkl", "r") as data_file:
return pickle.load(data_file)
el... | 3ac808d4f6ead575a5d362212d041210150a83bc | 38,001 |
def showtables(hcaturi, dbname='default', username='hdfs'):
"""
hcat.showtables
Args:
hcaturi (str): uri for webhcat host, eg hive.myorg.com:50111
dbname (Optional[str]): database name, defaults to 'default'
username (Optional[str]): user name defaults to hdfs
Returns:
list: list of available tables for t... | c5c577068882813fb4b7ff7f32da3dab4cbad6a9 | 38,002 |
import os
import sys
def list_subcommands():
"""List all datalabframework subcommands
searches PATH for `datalabframework-name`
Returns a list of datalabframework's subcommand names, without the `datalabframework-` prefix.
Nested children (e.g. datalabframework-sub-subsub) are not included.
"""
... | a37171511f171c0d7ece5cebb56ae0a573935486 | 38,003 |
def fourier_gaussian(input, sigma, n = -1, axis = -1, output = None):
"""Multi-dimensional Gaussian fourier filter.
The array is multiplied with the fourier transform of a Gaussian
kernel. If the parameter n is negative, then the input is assumed to be
the result of a complex fft. If n is larger or eq... | c71f7ede1be4a36b4ef17ce2744eff3b28ebbb67 | 38,004 |
def amplitude_kurtosis(data):
"""
(list) -> float
pass in an array or list and return the kurtosis value of data. Using Pearson's definition
>signal_skewness([3,7,8,9,1])
1.4904
"""
return stats.kurtosis(data, fisher=False) | d2db4844a5af8f16ea185a77d6de2e9c4a3e96d9 | 38,005 |
import numba
def mh_sample(
logtarget,
x0,
sigma=None,
discrete=None,
args=(),
n_burn=1000,
n_steps=1000,
tune_interval=100,
variable_names=None,
return_acceptance_rate=False,
):
"""
Parameters
----------
logtarget : function
The function to compute the ... | 2d17487960f8fd54f387044fb4ca4e652bf6faa5 | 38,006 |
from io import StringIO
def load(data):
"""loads the given byte-string representation to an object"""
stream = StringIO(data)
return _load(stream) | 0858e4ed8fd8631afbdb346e6733281b7893ce1b | 38,007 |
import torch
def drop_path(x, drop_prob: float = 0., training: bool = False):
"""
Obtained from: github.com:rwightman/pytorch-image-models
Drop paths (Stochastic Depth) per sample (when applied in main path
of residual blocks).
This is the same as the Dro... | 20c9321efd7763f8f6aa25b1e69c6db48dbf8a70 | 38,008 |
import json
def get_db_object(db_name) -> object:
"""
:type db_name: object
:return: pymongo client object
"""
db_handle = db_cache.get_db_cache(db_name)
if not __is_empty(db_handle):
__logger.info("sending db object from cache!")
return db_handle
else:
__logger.... | 32fe6cd2577553e593eda6727913fcd324b5e89f | 38,009 |
import torch
def test_value_network():
"""
Test if the CartPole value network is invariant
"""
network = BasisCartpoleNetworkWrapper(1, [64, 64])
layer = BasisCartpoleLayer(64, 1, out="invariant")
representations = get_cartpole_state_group_representations()
p_m2 = representations[1].deta... | dd9093ab1669ce82cc6cbbd3aa1718d50868f08b | 38,010 |
def tokenize(obj, tokenizer, max_seq_len):
"""Recursively convert to tokens."""
if isinstance(obj, str):
toks = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj)[:max_seq_len])
assert all(
[t < len(tokenizer.encoder) for t in toks]
) # all(toks < len(tokenizer.encoder)... | 9e8ae8a4c1af0df29d95afcef183851792af2b43 | 38,011 |
import glob
import sys
import os
def setup(*args, **kwargs):
"""decorator for distutils.core.setup - use as:
args_to_cb_dot_build = []
mysetup = cb.setup(*args_to_cb_build)
mysetup(args_to_distutils_setup)"""
def wrapped(*setupargs, **setupkwargs):
global final_prefix
# check if we're trying to... | c24ae33154000c8055feca479dde94ef106be675 | 38,012 |
def manifest_to_file_list(manifest_fn):
"""
Open a manifest file and read it into a list.
Entries in the list are relative, i.e. no leading
slash.
manifest_fn -- the manifest file to read
"""
image_manifest_list = []
with open(manifest_fn) as image:
image_manifest_list = [x[1:] ... | 982f02e0b00fad20af8d50d44673d65d9bba5a37 | 38,013 |
import warnings
def perform_climatology_esp(
model_name, forecast_date, forecast_duration, workdir=None, **kwds
):
"""
This function takes the model setup and name as well as forecast data and duration and returns
an ESP forecast netcdf. The data comes from the climatology data and thus there is a mec... | 29a91ef8867fe361a5a640a648b5a0737fd5cc88 | 38,014 |
import os
def get_source_directories(proj_path, project_name, module_name=None):
"""Return the source and test source directory from the pom (or one of the pom)
Arguments
-------------
- proj_path: the path for the project
"""
look_for = project_name if not module_name else module_name
i... | e1e7c3d225ce020ca42a84e3e88a5f2f421050a8 | 38,015 |
def get_fp(list_of_smi):
""" Function to get fingerprint from a list of SMILES"""
fingerprints = []
mols = [Chem.MolFromSmiles(x) for x in list_of_smi]
# if rdkit can't compute the fingerprint on a SMILES
# we remove that SMILES
idx_to_remove = []
for idx,mol in enumerate(mols):
try:... | 1ff1541f7e50b01a1ab2332dca9fd6af8d7c6ddc | 38,016 |
def intersect (sequence_a, sequence_b):
"""Return true if the two sequences contain items in common
If sequence_a is a non-sequence then return false.
"""
try:
for item in sequence_a:
if item in sequence_b:
return 1
except TypeError:
return 0
return 0 | f28c3b6258584fdc1821c65867b4d89a1c33373a | 38,017 |
import os
def _config():
"""Wrap configuration so that module can be imported without
environment variables set.
"""
nightwatch_exclude = resource_filename('desitransfer',
'data/desi_nightwatch_transfer_exclude.txt')
engineering = os.path.realpath(os.path... | 5ac49f4900a65152a396cdbd84d2a78602f87d0f | 38,018 |
def compileOverlapData(uniA,uniB,sigA,sigB,chrList):
"""
Piles-up the overlap coverage data for the fisher exact test.
:param uniA: Interval Universe A
:param uniB: Interval Universe B
:param sigA: Interval Significant A
:param sigB: Interval Significant B
:param chrList: List of chromosome... | 10aade88348682e31ebffc3d435eb92db943eeb0 | 38,019 |
def get_location_dictionary(deployment):
""" Construct location dictionary from ui deployment information.
"""
try:
have_location_dict = False
latitude = None
longitude = None
location = None
depth = None
orbitRadius = None
if 'depth' in deployment:
... | 3c2b00c97c681d89628ca8c6708545b73bf84649 | 38,020 |
def __insert_color(txt,s,c):
"""insert HTML span style into txt. The span will change the color of the
text located between s[0] and s[1]:
txt: txt to be modified
s: span of where to insert tag
c: color to set the span to"""
return txt[:s[0]]+'<span style="color: {0};">'.format(c)+\
t... | 013c011737f9b763aa8682a945883c934c99b5cd | 38,021 |
def legacy_do_linear_gst(dataFilenameOrSet, targetModelFilenameOrObj,
prepStrsListOrFilename, effectStrsListOrFilename,
gaugeOptParams=None, advancedOptions=None, comm=None,
memLimit=None, output_pkl=None, verbosity=2):
"""
Perform Linea... | cfedd3db88329a815ed1fb0ea5ab4a7de99f8931 | 38,022 |
def StopAddHeaders(builder, headers):
"""This method is deprecated. Please switch to AddHeaders."""
return AddHeaders(builder, headers) | b849725aae10132d5b41f316643cdc75a35c2d70 | 38,023 |
from typing import List
def select_dominoes(dominoes: List[str], order: int, num_players: int) -> str:
"""Randonly generate a set of dominoes for a player
- If the number of players is 3, each player gets 9 dominoes,
plus a 10th dominoe that is to be played first (all players will get it)
- If the num... | c96d1a5b54e3623807ca57a3684f63fa3ff6737c | 38,024 |
def fspecial_average(hsize=3):
"""Smoothing filter"""
return np.ones((hsize, hsize))/hsize**2 | ba095b58c994a1b12646093ebc05cd49b2854143 | 38,025 |
from typing import Union
from typing import List
from typing import Optional
async def getTwitchChannelUsers(cls:"PhaazebotTwitch", **search) -> Union[List[TwitchUserStats], int]:
"""
Get channel levels and stats.
Returns a list of TwitchUserStats().
Optional 'search' keywords:
---------------------------
* `u... | cf4c1e3ac2c8b3399ac64a41dcfc52cceb187067 | 38,026 |
def normalize_times(times, events):
"""Given a list of times and event ids, normalize the times (i.e. calculate
the time since the start of each event).
:param times: list of times
:type times: list
:param events: list of event ids
:type events: list
:return: list of normalized times
:... | 97a65dcd3fffcb8f9d686649e31a579ff104eb64 | 38,027 |
import hashlib
import hmac
def salted_hmac(key_salt, value, secret):
"""
Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret. A different key_salt should be passed in for every application of HMAC.
"""
assert secret, f"secret must be provided."
key_salt = bytes(... | 6b8a3cb4998f2c00d25ae1cee3f88bd39fabe6fe | 38,028 |
import dis
def _opcode(name):
"""Return the opcode by name from the dis module."""
return dis.opmap[name] | d2c8612138c94da68adcc1b8979395987090157c | 38,029 |
def validate_compare_input(message):
"""
validate input for function that compare two songs
:param message: message received by microservice
:type message: `dict`
:return: tuple with status and error message
:rtype: `tuple`
"""
input_schema = {
"type": "object",
"require... | 117fcbe275b795bacb82232c7a5ae10110b213a8 | 38,030 |
from typing import Union
from pathlib import Path
import os
import secrets
def bundle_project(
working_area: Union[str, Path],
spec: RuntimeSpec,
privkey=None,
stash=False,
current=False,
) -> ProjectBundleFile:
"""
It's in charge of bundle all the files needed to build a runtime.
This... | 6b82efacdce684f381b5f71b45939a595198369e | 38,031 |
def _gcp_agent_singleton(**kwargs):
"""Manage singleton of agents to particular apis.
This treates the agent instances as singletons based on their configuration.
The reason for this is simply to reduce logging noise on the creation.
This is possible since agents are stateless.
Args:
kargs: [kwarg... | 1ec653d4de200070f2bf0b11d97b6ae713991e82 | 38,032 |
def get_media_playlist_uris(master_playlist, target_qualities):
"""From a master playlist, extract URIs of media playlists of interest.
Returns {stream name: uri}.
Note this is not a general method for all HLS streams, and makes twitch-specific assumptions,
though we try to check and emit warnings if these assumpti... | 1cb7302eb14c5b980e77a8a5907edb9cbcddb279 | 38,033 |
import argparse
def parse_args():
"""to add show versions args in parser"""
parser = argparse.ArgumentParser(
prog="discordRebot", description="Tools for helping with discord-rebot"
)
parser.add_argument("-v", "--version", action="store_true", help="shows the library version")
parser.set_... | 57ffc6515e104d9aaf51d758259cd255ca368c94 | 38,034 |
def layer_stack_from_hparams(hparams, prefix):
"""Create a layer stack based on the hyperparameter values."""
layers = hparams.get(prefix + "layers")
return transformer.LayerStack(
[layers_registry[l](hparams, prefix) for l in layers],
dropout_rate=hparams.layer_prepostprocess_dropout,
norm_epsi... | 220d4f71a4e270985d6d7560719f7c7f83e99781 | 38,035 |
def resample_profile(profile, periods):
"""
Resamples a profile to have the number of periods defined by periods.
Uses the mean of the period. The end point of the period is used as the
index.
Parameters
----------
profile : np.Array, pd.Series or pd.DataFrame
An array like object ... | 7cd49aeec0cf43b49c1e884483830fd9485d5202 | 38,036 |
def rs_compose_add(p1, p2):
"""
compute the composed sum ``prod(p2(x - beta) for beta root of p1)``
Examples
========
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import rs_compose_add
>>> R, x = ring('x', QQ)
>>> f ... | c82c3c19087fea7230f20f0da14b4facce4b4a49 | 38,037 |
import ibmsecurity.utilities.tools
def _check(isamAppliance, name, description, authenticateCallbacks, signInCallbacks, localIdCallbacks, signOutCallbacks,
authnPolicyCallbacks):
"""
Check and return True if update needed
"""
update_required = False
poc_id = None
ret_obj = get(isamA... | f0ee4333d37bc29d7cd7533b30023871e47e3e20 | 38,038 |
import re
def remove_citation(paragraph: str) -> str:
"""Remove all citations (numbers in side square brackets) in paragraph"""
return re.sub(r'\[\d+\]', '', paragraph) | dc88606e69187143d767215ddc098affdbd185d5 | 38,039 |
def parse_proxy(line):
"""Parses proxies from a string.
Args:
contents: The string that should be parsed.
Returns:
The parsed proxy.
"""
proxy = None
if not (line.strip().startswith('#') or line.strip().startswith('//')):
tokens = line.replace('\n', '').split(' ')
try:
... | 1a5583c689a6cd655265c308d3cfc9b84783f7aa | 38,040 |
import ctypes
def sg_get_pdt_str(pdt):
"""
Yield string associated with peripheral device type (pdt). Returns
'buff'. If 'pdt' out of range yields "bad pdt" string.
"""
buff = _get_buffer(48)
libsgutils2.sg_get_pdt_str(pdt, 48, ctypes.byref(buff))
return buff.value.decode('utf-8') | 4b1a45d43c3a848dfd814d18ade300712b081b28 | 38,041 |
import os
import zipfile
import shutil
def upload_zip(self, index, *args, **kwargs):
"""
Celery task which unzips files in a .zip archive and ignores folder
structure, taking each file to the top level of the output folder.
"""
self.index = index
self.index.status = "STARTED"
self.index.sa... | e0ec7adc15a2856624d740f00da2abf4a6376897 | 38,042 |
def simulation_positions(simulation):
"""
Return atomic coordinates.
Parameters
----------
simulation : Simulation or Context object.
Returns
-------
ndarray
"""
state = simulation_state(simulation, 'positions')
return state.getPositions(asNumpy=True) | f83e042010b65bd9bfab150b90b5821c66b555e6 | 38,043 |
def regex(value, regexflags=None):
"""OpenEmbedded 'regex' type
Acts as a regular expression, returning the pre-compiled regular
expression pattern object. To use this type, set the variable type flag
to 'regex', and optionally, set the 'regexflags' type to a space separated
list of the flags to c... | 18eea0ed097dc530f98fddd88816e133e8ef5e54 | 38,044 |
import torch
def normalized_distance(x, y):
"""Distance between two vectors normalized by the number of elements and
the norm of the first vector"""
return distance(x, y) / torch.sqrt(norm(x) * norm(y)) | 846d176a5c536d93ef164a63b582fa541d304686 | 38,045 |
def LoadDebugger(dbgname, use_remote):
"""
Load the debugger
@param dbgname: debugger module name Examples: win32, linux, mac.
@param use_remote: 0/1: use remote debugger or not
@note: This function is needed only when running idc scripts from the command line.
In other cases IDA loads ... | d9afd2a18ffa0339a2234e30c4c92e4f5c6f36fe | 38,046 |
def lv_encode(data: bytes) -> bytes:
"""Encodes data as length-value"""
return serialize_length(len(data)) + data | 1858d3165c7fb714877be2c3448fe162678ceaa4 | 38,047 |
def normalize_t(lc: LightCurve, fit: Fit) -> Transit:
""" Normalizer a light curve given a continuum fit.
TODO: more details
Args:
lc: a LightCurve object
fit: a Fit object
Returns:
transit: a LightCurve object
"""
lc_normalized = None
if lc and isinstance(lc, Lig... | cd80a3e935322b4e24c87bd9ed76e7428f2427c9 | 38,048 |
def get_model_field(model):
""" get the verbose_name of all fields in the model """
field_dict = dict()
for field in model._fields:
attr = getattr(model, field)
if hasattr(attr, 'verbose_name'):
verbose_name = attr.verbose_name
if verbose_name:
field_d... | 8ec9a4f9b571483c13d5a23330e98691279c12ad | 38,049 |
from typing import Callable
def _get_create_str_fn(opt: str) -> Callable:
""" A tool function to create either a str or bytes from a 8-bit string. """
def _create_str_bytes(name: bytes) -> bytes:
return name
def _create_str_str(name: bytes) -> str:
return name.decode("latin-1")
if op... | fab4e8065cfc450eda5bcccdce1888941f2f7f25 | 38,050 |
def admin_required(func):
"""
This is a decorator that can be applied to a Controller method that needs to allow request to process only if checks
are successful.
It checks:
- if the user is logged in (And)
- if the user is an admin
The current object is fetched using the Controller in... | a8d25f7c9b515c10b3fc71bd1b1819dbc2f37a8d | 38,051 |
def get_expected_tetranuc_freq(tetranuc, trinuc_freqs, dinuc_freqs):
"""
Returns the expected frequency for the given tetranucleotide.
Args:
tetranuc:
trinuc_freqs:
dinuc_freqs:
Returns:
"""
# get prefix of len 3 of tetranucleotide (n1n2n3)
first3bases = tetranuc[:3]
... | 35c99fa43e771bb5744aa0dd0f2877bcacc7e478 | 38,052 |
import math
def computeLengthsAndAngles(periodicBoxVectors):
"""Convert periodic box vectors to lengths and angles.
Lengths are returned in nanometers and angles in radians.
"""
if is_quantity(periodicBoxVectors):
(a, b, c) = periodicBoxVectors.value_in_unit(nanometers)
else:
a, b... | a18601a111b1ef624e828e87dd4b0ddb1fa44e76 | 38,053 |
def compute_info( image ):
""" Compute information on resampled and original images """
old_size, old_spac, old_orig = image.GetSize(), image.GetSpacing(), \
image.GetOrigin()
new_size, new_spac, new_orig = [], [], old_orig
for i in range(len(old_size)):
new_size.append( int(np.ceil( 1... | 3989149b2bbeb89ffea62ec13161f10c00b285d5 | 38,054 |
def macro_EmbedObject(macro, target=wikiutil.required_arg(unicode), pagename=None,
width=wikiutil.UnitArgument(None, float, ['px', 'em', 'pt', 'in', 'mm', '%'], defaultunit='px'),
height=wikiutil.UnitArgument(None, float, ['px', 'em', 'pt', 'in', 'mm', '%'], defaultunit='px')... | 0c69842efcd1cb9240053fca9c291be0fa5eeaa5 | 38,055 |
def lnprior(theta, y, lower_t_bound, upper_t_bound, transit_params,
skip_priors):
"""
Log prior for `emcee` runs.
Parameters
----------
theta : list
Fitting parameters
y : `numpy.ndarray`
Fluxes
lower_t_bound : float
Earliest in-transit time [JD]
uppe... | 5a35211e8a0138757ad490fa77f31e515ec69181 | 38,056 |
def job_metadata_filename(metadata):
"""Construct relative filename to job metadata."""
return "data/{metadata}".format(metadata=metadata) | bb5e8dc6c0ec50fed6801b9c67f8234d9115372a | 38,057 |
def get_db_cols(cur, table_name, schema='public', type_map=True):
"""
Gets the column names of a given table
if type_map is true, returns also a dictionary
mapping each column name to the corresponding
postgres column type
"""
db_cols_sql = """SELECT column_name, data_type
FROM in... | 936952ea0bbc0c165f089e700828ea876d30ec16 | 38,058 |
def wrap_elemwise(func, **kwargs):
""" Wrap up numpy function into dask.array """
f = partial(elemwise, func, **kwargs)
f.__doc__ = func.__doc__
f.__name__ = func.__name__
return f | ae480423fba7e1c01a41de5e4b61c629439dd1e5 | 38,059 |
def parse_player_node(player_node):
"""Parses a player XML node
Parameters
----------
player_node : lxml node
The player node to parse
Returns
-------
A Player database object
"""
db_player = Player(player_id=player_node.get('id'),
first=player_node.g... | e69dd475cdfc9ff4017a0c76b0387a959f25a590 | 38,060 |
import six
def is_fits(input, **kwargs):
"""
Determine whether input is in FITS format
"""
if isinstance(input, six.string_types):
if input.lower().endswith(('.fits', '.fits.gz',
'.fit', '.fit.gz',
'.fits.Z', '.fit.Z')):
... | e504fac14f3fe4d470bd84a600e622abc17da609 | 38,061 |
def calc_moverscore(gold_references, model_generations, n_gram=2, batch_size=16):
"""
Calculate MoverScore
:param gold_references: list of target sections
:param model_generations: list of generated sections
:param n_gram: unigram-based MoverScore (n-gram=1), bigram-based MoverScore (n-gram=2)
... | b4deaaf8a0a1c79dee00c5c920b0d832e7f2545a | 38,062 |
def base62_encode(raw_bytes):
"""
Encodes raw bytes into base-62 representation. URL-safe and human safe.
Encode your Unicode strings to a byte encoding before base-62-encoding
them.
Convenience wrapper for consistency.
:param raw_bytes:
Bytes to encode.
:returns:
Base-62 encoded bytes.
"... | 020a0746088902d87a217b0771096e9e41c89dbf | 38,063 |
import torch
def cmc_score_count(
distances: torch.Tensor, conformity_matrix: torch.Tensor, topk: int = 1,
) -> float:
"""
Function to count CMC from distance matrix and conformity matrix.
Args:
distances: distance matrix shape of (n_embeddings_x, n_embeddings_y)
conformity_matrix: bi... | 14519d349a55f3b5ea6f87f830af183441b86573 | 38,064 |
def is_valid(zma):
""" is this a valid vmatrix?
"""
ret = True
try:
assert _is_sequence_of_quadruples(zma)
syms, key_mat, name_mat, val_mat = zip(*zma)
automol.create.zmat.from_data(syms, key_mat, val_mat, name_mat)
except AssertionError:
ret = False
return ret | 128b5ba429b35400cccd5110ffb2a47a86e85d07 | 38,065 |
import os
def _read_dot_file(filename, section, username, password):
"""
Handles the parsing of the configuration file for the username
and password.
:param str filename: Path and name of INI file.
:param str section: Name of the section in the INI file to find credentials.
:param str usernam... | 16105103ef9c0173d918d2a67395c431bb8bcb0b | 38,066 |
import json
def copy_db_snapshot_instance(source_db_snapshot_identifier,
destination_db_snapshot_identifier, snapshot_tags,
option_group_name=None, kms_key=None):
"""Function to create a copy of a rds snapshot, copying tags by default.
Args:
... | b7ea3885f87bae18325ea65b3b0766a13ed7f121 | 38,067 |
def w_alpha():
"""
Real Name: b'W ALPHA'
Original Eqn: b'1'
Units: b''
Limits: (None, None)
Type: constant
b''
"""
return 1 | d76e0dca2ff8c6f01be262272c21fda7bf89d844 | 38,068 |
import subprocess
def posh_execute_enabled(tmp_path_factory):
"""Return check value for whether Powershell script execution is enabled.
Posh may be available interactively, but the security settings may not allow
execution of script files.
# Enable with: PS> Set-ExecutionPolicy -scope currentuser -... | 2ecfee4dc754d617069fe11944fb21f20a8e93cb | 38,069 |
def calc_grad(X, Y, theta):
"""Compute the gradient of the loss with respect to theta."""
count, _ = X.shape
probs = 1. / (1 + np.exp(-X.dot(theta)))
grad = (Y - probs).dot(X)
return grad | 2469a8ce9b993cdf0d778493c358a43a10e90389 | 38,070 |
def _docsubst(f):
"""Perform docstring substitutions"""
f.__doc__ = f.__doc__.format(**_doc_snippets)
return f | 570178ea04a874b14d8a0cbc2e9297ae6c5234a5 | 38,071 |
import logging
def getSourceListOptDict(parser, wildcards = True):
"""
Get the list of tuples and the dictionary with options
returns:
sourceList: a list of tuples with one list element per file
the first tuple entry being the root file,
the second a list o... | 8f478a4bc32abb63ed109047c88593300bcaa582 | 38,072 |
def get_capacities(topology):
"""
Returns a dictionary with all link capacities.
Parameters
----------
topology : Topology
The topology whose link delays are requested
Returns
-------
capacities : dict
Dictionary of link capacities keyed by link.
Examples
-----... | 0244eb3683139fe8dc77fee7ad9d5a44a109903f | 38,073 |
def make_modbusmap_channel(i, chan, device_type_name):
"""Make a channel object for a row in the CSV."""
json_obj = {
"ah": "",
"bytary": None,
"al": "",
"vn": chan['subTitle'], # Name
"ct": "number", # ChangeType
"le": "16", # Length(16 or 32)
"grp": ... | cd53f32f47653e791893b90bbbf27e540d741268 | 38,074 |
import os
def send_img(string):
"""
Handle image request from client.
:param string: image file name
:type string: str
:returns: image file path
:rtype: str
"""
return send_from_directory(os.path.join(os.path.join(execution_path,'static'),'img'), string) | b19ec6d759d86234fc80d9607420e8327c2bd729 | 38,075 |
def select_variables(n=50):
"""12 August 2021 Variables
excluded: ('cropland', 0.8299824473544954),
"""
l = [('nlcd', 0.7202826917050348),
('cultivated', 0.6893999449547821),
('slope', 0.36318373989279606),
('evi_3', 0.21911480248421414),
('nw_3', 0.21308324029642675)... | e52199ced0293f80fcb4f6b652fa04abfd20224e | 38,076 |
def CleanData_CB(X,drop_feature):
"""
This function is to clean the data for training and testing with CatBoost.
X : dataframe type for train
y : dataframe type for test
drop_feature : feature name that is wanted to be dropped , e.g., ['Time']
"""
x_new = X.drop... | b6c77e29147dfbdf012f787e29ba4ac364b37fa7 | 38,077 |
def add_ind_price_plan(phone_number, ind_price_plan, exp_date=''):
"""
Adds an Individual Price Plan from the line
"""
action = 1
result = ModUserIndiPricePlan(
phone_number, ind_price_plan, action, exp_date)
return result | 270f98d0d419559ea1a20869bf6547d3feb6a190 | 38,078 |
def EventsAsEOTimes(events):
"""
:param events:
KernelTime's sorted by ktime.start_time_usec
:return:
"""
TimeType = None
psec_in_usec = None
category_eo_times = np.empty(2*len(events), dtype=py_config.NUMPY_TIME_USEC_TYPE)
for i, ktime in enumerate(events):
if psec_in_us... | d4d8d878e9929a245ad18ab37ff7d0ff142848fd | 38,079 |
def dct(A):
"""
params: A matrix Nx1
output: compute dct 1D of the matrix A
"""
N = A.shape[0]
C = np.zeros(N, dtype=np.float64)
for k in range(0, N):
a_k = np.sqrt(1.0 / N) if k == 0 else np.sqrt(2.0 / N)
sum = 0
for j in range(N):
sum = sum + A[j] * np... | 08429719fe737fc39cabe23d5f33b6c88a01043d | 38,080 |
import logging
def get_valid_tax_number_job(request_id: str):
"""
Route for retrieving job status of a tax number validity from the queue.
:param request_id: the id of the job.
"""
try:
raise NotImplementedError()
except NotImplementedError:
logging.getLogger().info("Could not ... | 5a25793b10686833695b0ccdf5e479f6b3c1a0cc | 38,081 |
def all_models(awhere_api_key, awhere_api_secret):
"""Fixture that returns a dataframe containing all aWhere models.
"""
# Get all models
models = awm.get_models(key=awhere_api_key, secret=awhere_api_secret)
# Return crops
return models | 79050d6706c51c3e197d2c4f835b076a57548a48 | 38,082 |
def parse_title(df: pd.DataFrame, source: str, target: str) -> pd.DataFrame:
"""Transformer extracting a person's title from the name string implemented as wrapped stateless function."""
def get_title(name: str) -> str:
"""Auxiliary method for extracting the title."""
if '.' in name:
... | d0d6d7b7889c7c794782e16b13a4b4977b854601 | 38,083 |
import os
import json
from typing import Counter
def train(shortforms, additional=None, n_jobs=1):
"""Train a deft model and produce quality statistics"""
if additional is None:
additional = []
# gather needed data
groundings_path = os.path.join(DATA_PATH, 'groundings')
texts_path = os.pat... | 6428f83f34ddcd99e3444aa9f4ad5db5773970a0 | 38,084 |
import os
def _GetMakeConfGenericPath():
"""Get the path to the make.conf.generic-target file."""
return os.path.join(_CHROMIUMOS_CONFIG, 'make.conf.generic-target') | 2d35bc47438b6f4f0cdff9ae2cf175ee54a65205 | 38,085 |
def levenshtein_ratio_and_distance(s, t, ratio_calc=False):
""" levenshtein_ratio_and_distance:
Calculates levenshtein distance between two strings.
If ratio_calc = True, the function computes the
levenshtein distance ratio of similarity between two strings
For all i and j, distance[... | f132aa0a3a6462881b0104648e81f14d50f45922 | 38,086 |
async def __resource_group_exists(clients, args):
"""
Check if the given Resource Group Exists
"""
try:
await clients.resource_client.resource_groups.get(args.resource_group_name)
except ResourceNotFoundError:
return False
return True | 68a60c2bfc593a1b9b3b0d8d3bc1b42a19638cb2 | 38,087 |
def dca(freq_table):
"""
Distinctive Collexeme Analysis
Parameters
----------
freq_table : dict
A frequency table in the format of:
{
C1: {L1: freq, L2: freq, ...},
C2: {L1: freq, L2: freq, ...}
}
where C1 & C2 are labels fo... | ea03bf7589d0a219e521b1eb1b003827fc765fd4 | 38,088 |
import torch
def get_paddings_indicator(actual_num, max_num, axis=0):
"""Create boolean mask by actual number of a padded tensor.
Args:
actual_num ([type]): [description]
max_num ([type]): [description]
Returns:
[type]: [description]
"""
actual_num = torch.unsqueeze(actu... | 0cf2614c2d4ddc35f90a1f6175e9e18eb59298bb | 38,089 |
def create_ffxml_file(
gaff_mol2_filenames,
frcmod_filenames,
ffxml_filename=None,
override_mol2_residue_name=None,
):
"""Process multiple gaff mol2 files and frcmod files using the XML conversion and write to an XML file.
Parameters
----------
gaff_mol2_filenames : list of str
T... | 7e4d00151aa25da765e5f3edb614804c69ae2014 | 38,090 |
def get_state_names_and_ids(zfill=False):
""""! Get list of federal state names and IDs sorted according to state ID.
@param zfill [Default: False] Defines whether state IDs are zero-filled to
two digits and returned as a string or returned as an integer.
@return List of federal names and IDs sorte... | 9605d6bc9f86f225215593cc164734474b28100a | 38,091 |
from typing import Dict
def get_api_name(config: Dict[str, ConfigVO] = None) -> str:
""" 获取API名字 """
key = const.Key.Api.NAME.value
vo = config.get(key) if config else dao.get_config(key)
return vo.value if vo and vo.value else const.Key.Api._NAME_WALLHAVEN.value | 0c88d57d8c86f32e3cdec67368496458c5fc64be | 38,092 |
import math
def agree_within_layers(layer_heights, surface_normal = np.array([0, 0, 1]), cutoff_above_top = None, cutoff_below_bottom = None):
"""Assign mobile atoms to agreement groups based on their layer in the material.
In a system with fixed layers, like a surface slab (especially one with a
fixed b... | 16fd10a58f2a3b479633e3bc35dd62e6d5a2f303 | 38,093 |
def split_indexes(indexes):
"""Split indexes list like 1 2 5 in 1 2 and 5."""
left, right = [indexes[0], ], []
left_now = True
for i in range(1, len(indexes)):
prev = indexes[i - 1]
curr = indexes[i]
if curr > prev + 1 and left_now:
left_now = False
if left_no... | 1bdb3b57226737280b83dbdfa3226dc344eb47c0 | 38,094 |
def _build_path(source: Source, fmt: Format) -> str:
""" Create the relative path for source and fmt """
return f"{_Path[fmt.name].value}/{source.value}.{fmt.value}" | 15e3f17a6d5ceb845eb796c08fbfbde94a021e29 | 38,095 |
def handle_button_click(event):
"""Handles response based on action of 'CARD_CLICKED'
Args:
event:
The 'CARD_CLICKED' being parsed by handler
Returns:
dict
dictionary containing event response
"""
event_action = event['action']['actionMethodName']
user_data = get_us... | 5395519464e042cd69db1e81dd3a3a90cac82a15 | 38,096 |
def set_cookies(response: Response, data: dict) -> None:
"""
Update a :class:`.Response` with cookies in controller data.
Contollers seeking to update cookies must include a 'cookies' key
in their response data.
"""
# Set the session cookie.
cookies = data.pop('cookies')
if cookies is N... | 6ac902dabe26cc863f284e7f22d578527289c23c | 38,097 |
import os
def identify(path):
"""Work out what an image is."""
if not os.path.exists(path):
return {}
out, _ = util.execute(None,
'qemu-img info %s' % path)
data = {}
for line in out.split('\n'):
line = line.lstrip().rstrip()
elems = line.split(... | d3aa53315ba80e2b0d77428b82b4e7fefa629b8c | 38,098 |
def convolve_functions(fn1, fn2, interval, dt, padding_f=0.1, name=None):
"""
Convolve fn1 with fn2.
Parameters
----------
fn1 : sympy expr
An expression that is a function of t only.
fn2 : sympy expr
An expression that is a function of t only.
interv... | 6aa1c2cd4d074f0ac40cbd12fb1b069a7034578f | 38,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.