content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def safe_run(*args, **kwargs):
"""Call run(), catch exceptions."""
try: worker(*args, **kwargs)
except Exception as e:
print("error: %s run(*%r, **%r)" % (e, args, kwargs)) | 44,000 |
async def test_config_entry_no_authentication(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the BSBLan configuration entry not ready."""
aioclient_mock.post(
"http://example.local:80/1234/JQ?Parameter=6224,6225,6226",
exc=aiohttp.ClientError,
)
entry =... | 44,001 |
def numpy_to_rdkit(adj, nf, ef, sanitize=False):
"""
Converts a molecule from numpy to RDKit format.
:param adj: binary numpy array of shape (N, N)
:param nf: numpy array of shape (N, F)
:param ef: numpy array of shape (N, N, S)
:param sanitize: whether to sanitize the molecule after conversion... | 44,002 |
def get_path(key: str, **kwargs: Dict[str, Any]) -> Path:
"""Get a file path string system variable as a pathlib.Path instance.
See signature of get() for parameter details."""
return Path(get(key, **kwargs)) | 44,003 |
def run_competition(builders=[], task=BalanceTask(), Optimizer=HillClimber, rounds=3, max_eval=20, N_hidden=3, verbosity=0):
""" pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them!
Arguments:
task (Task): task to compete at
Optimizer (class): pybrain.O... | 44,004 |
def set_output(output):
"""
Set whether results are output to files or not. The default is True.
Most functions also have their own optional output keyword argument to give more control over which output files are created.
"""
assert type(output) is bool
global _output
_output = output | 44,005 |
def get_reduced_tree(tree, reduce_by):
"""
Given a tree decomposition in tree and a required
size of reduction, produces a new tree decomposition
with treewidth reduced by the requested size and a list
of eliminated nodes.
We use a greedy algorithm to find nodes to eliminate.
This algorithm ... | 44,006 |
def temp_path(suffix=""):
"""Return the path of a temporary directory."""
directory = mkdtemp(suffix=suffix)
return Path(directory) | 44,007 |
def maybe_utf8(value):
"""Encode to utf-8, only if the value is Unicode."""
if isinstance(value, unicode):
return value.encode("utf-8")
return value | 44,008 |
def parse_id_as_interval(id_string, regex):
""" The fasta ids contain the locus information. """
match = regex.match(id_string)
genome = match.group("genome")
seqid = match.group("seqid")
start_tmp = int(match.group("start"))
end_tmp = int(match.group("end"))
start = min([start_tmp, end_tm... | 44,009 |
def map_sentences_to_indices_of_vectors(sentences, word_to_index_glove, unknown_token):
""" map senteces to integers that represent the index of each word in the glove vocabulary """
# the list to be returned
mapped_sentences = []
# get the index of the unknown token
unknown_token_index = w... | 44,010 |
def ruler(inputdict_unchecked):
"""
This program calculates reduced transition probabilities. (RULER readme)
Parameters
----------
inputdict_unchecked : dictionary
dictionary that must have the following key-pair values:
input_file : string, input ensdf file
output f... | 44,011 |
def importsettings(importfile, verbose):
"""
Import developer account from an existing settings.json
"""
settings = json.load(importfile)
if verbose:
click.echo('Got settings from input file: ')
click.echo(settings)
# write into settings.json
with open(pwd.getpwuid(os.getuid(... | 44,012 |
def jordan_wigner_dual_basis_jellium(grid, spinless=False,
include_constant=False):
"""Return the jellium Hamiltonian as QubitOperator in the dual basis.
Args:
grid (Grid): The discretization to use.
spinless (bool): Whether to use the spinless model or not.... | 44,013 |
def boxcar_decay(tbins, t0, area_box, height_box, area_decay):
"""
Compute the lightcurve from one or more boxcar-decay functions.
Parameters
----------
tbins : array
edges of the time bins used for the lightcurve
t0 : float or array
start times of the boxcar-decays
area_box... | 44,014 |
def updateShaderState(self):
"""Updates all shader program variables. """
if not self.ready():
return
opts = self.opts
self.shader.load()
voxValXform = self.imageTexture.voxValXform
voxValXform = [voxValXform[0, 0], voxValXform[0, 3], 0, 0]
invNumLabels = 1.0 / (opts.lut.max() ... | 44,015 |
def format_file(filename):
"""Executes clang-format on the file to reformat it according to our
project's standards. If -format_in_place is defined, the file will be
formatted in place, with the results overwriting the previous version
of the file. Otherwise the result of the file reformat will be logged
to ... | 44,016 |
def test_s3_hook_does_not_exists(client_hook_s3_storage_1: object) -> None:
"""Testing GET resource
Args:
client_hook_s3_storage_1 (fixture): The test client.
"""
params = {'filename': 'non-existent-file.txt'}
response: Result = client_hook_s3_storage_1.simulate_get('/middleware', params=pa... | 44,017 |
def entries(maze : Maze) -> Iterable:
"""Convert a maze to a sequence of rows in a JSONL-encoded table."""
if is_context(maze):
values, contexts = partition(maze.mazes(), is_context)
# pre-populate the entry with the values
entry = {value.symbol : value.value for value in value... | 44,018 |
def _getMinGWInstallDir():
"""Returns the MinGW install directory.
Typically: 'C:\MinGW'.
@return: The path to the MinGW install directory.
@rtype: string
@raise WindowsError: If MinGW is not installed.
"""
import _winreg
from cake.registry import queryString
possibleSubKeys = [
r"SOF... | 44,019 |
def nextbus(a, r, c="vehicleLocations", e=0):
"""Returns the most recent latitude and
longitude of the selected bus line using
the NextBus API (nbapi)
Arguments: a=agency, r=route, c=command,
e=epoch timestamp for start date of track,
0 = the last 15 minutes
"""
nbapi = "http://webservic... | 44,020 |
def skip_sync_only(request):
"""Skip async_only tests if running async."""
sync_only = request.node.get_closest_marker('sync_only')
if _is_async_mode() and sync_only:
pytest.skip("running with --async_only") | 44,021 |
def latest_blog_posts(context, num):
"""
Displays the most recent blog posts. It takes an argument, num
and displays so many posts depending on the value.
"""
latest_blog_posts = Post.objects.all()[:num].select_related()
return {
'latest_blog_posts': latest_blog_posts
} | 44,022 |
def _expand_array_paths_to_preserve(paths: List[DetailedPath]) -> Dict[str, List[int]]:
"""
Used by "filter_element_match" - Returns a dictionary of string paths mapped to array indices that we want
to preserve.
:param paths: A list of lists of detailed paths (containing strings and array indices) to e... | 44,023 |
def get_request_fixture_names(request):
"""Get list of fixture names for the given FixtureRequest.
Get the internal and mutable list of fixture names in the enclosing scope of
the given request object.
Compatibility with pytest 3.0.
"""
return request._pyfuncitem._fixtureinfo.names_closure | 44,024 |
def _unique(values, *, return_inverse=False):
"""Helper function to find unique values with support for python objects.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : ndarray
Values to check for unknowns.
return_inve... | 44,025 |
def _create_range_tool(
data,
min_time,
max_time,
plot_range,
width,
height,
time_column: str = None,
y: str = "y_index",
):
"""Create plot bar to act as as range selector."""
ext_min = min_time - ((max_time - min_time) * 0.15)
ext_max = max_time + ((max_time - min_time) * 0.... | 44,026 |
def pivot(df, index, column, value):
"""
Pivot a dataframe. Reverse operation of melting. Useful for configuring evolution
See pandas' pivot_table documentation for more details
Args:
- index (list): indexes argument of pd.pivot_table
- column (str): column name to pivot on
- val... | 44,027 |
def split_pdf_image_into_row_image_block(pdf_image):
"""
split the whole pdf image into row image block
:param pdf_image: the whole color pdf image
:return:
"""
gray_image = cv2.cvtColor(pdf_image, cv2.COLOR_BGR2GRAY)
binarized_image = cv2.adaptiveThreshold(
src=gray_image,
m... | 44,028 |
def get_tokens():
""" Get all the active tokens in the datbase."""
return query_db('select token from token') | 44,029 |
def setup(app):
"""Setup sphinx-gallery sphinx extension"""
sphinx_compatibility._app = app
app.add_config_value('sphinx_gallery_conf', DEFAULT_GALLERY_CONF, 'html')
for key in ['plot_gallery', 'abort_on_example_error']:
app.add_config_value(key, get_default_config_value(key), 'html')
app.... | 44,030 |
def on_one_time_product_notification(event, context):
"""This endpoint handles messages published by RTDN (specifically OneTimeProductNotification for now).
RTDN only works with subscription changes or PENDING purchases, you will not receive messages about one time
purchases in most cases (see https://devel... | 44,031 |
def get_stats(beta0, n, sigma, lam, pen, ntrials=100, maxiter=100):
"""
run ntrials regression problems
return mean of the mse, and 95% confidence interval
"""
if pen is None:
mses = run_trials_ols(beta0, n, sigma, ntrials=ntrials)
else:
mses = run_trials(beta0, n, sigm... | 44,032 |
def logwrap(
func: None = None,
*,
log: logging.Logger = logger,
log_level: int = logging.DEBUG,
exc_level: int = logging.ERROR,
max_indent: int = 20,
spec: typing.Optional[typing.Callable[..., typing.Any]] = None,
blacklisted_names: typing.Optional[typing.List[str]] = None,
blacklis... | 44,033 |
def squeeze_output_dim_0(initial_ndims, point_types):
"""Determine if the output needs to squeeze a singular dimension 0.
The dimension 0 is squeezed iff all input parameters:
- contain one sample,
- have the corresponding dimension 0 squeezed,
i.e. if all input parameters have ndim strictly less t... | 44,034 |
def quaternion_from_matrix(matrix, isprecise=False):
"""Return quaternion from rotation matrix.
If isprecise is True, the input matrix is assumed to be a precise rotation
matrix and a faster algorithm is used.
"""
M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]
if isprecise:
... | 44,035 |
def _cant_read_parents_when_priv_dropped(result):
"""Make sure that we can't read our parents maps file
when privileges are dropped."""
# Change to nobody user
os.setuid(pwd.getpwnam('nobody').pw_uid)
# Make sure can't read parents process (owned by root)
result.value = True if _maps_readable(... | 44,036 |
def check_version(stdout):
"""Check version of Ensembl-VEP.
Example of the first part of an output from the command `vep --help`:
#----------------------------------#
# ENSEMBL VARIANT EFFECT PREDICTOR #
#----------------------------------#
Versions:
ensembl : 104.1af1dce
... | 44,037 |
def test_multiple_search():
"""
Test searching for multiple packages at once.
"""
reset_env()
output = run_pip('search', 'pip', 'INITools')
assert 'pip installs packages' in output.stdout
assert 'Tools for parsing and using INI-style files' in output.stdout | 44,038 |
def tf_config():
""" Default tensorflow config. """
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return config | 44,039 |
def distribution(installed_sdks=('18', '19'),
installed_build_tools=('19.1.0',),
files=('android.jar',),
executables=('aapt', 'zipalign')):
"""Mock Android SDK Distribution.
:param tuple[strings] installed_sdks: SDK versions of the files being mocked.
:param tup... | 44,040 |
def parse_cli_args():
"""
These flags are the ones required by the Stream Deck SDK's registration procedure.
They'll be set by the Stream Deck desktop software when it launches our plugin.
"""
parser = argparse.ArgumentParser(
description='Stream Deck Google Meet Plugin')
parser.add_arg... | 44,041 |
def op(scalars_layout, collections=None):
"""Creates a summary that contains a layout.
When users navigate to the custom scalars dashboard, they will see a layout
based on the proto provided to this function.
Args:
scalars_layout: The scalars_layout_pb2.Layout proto that specifies the
layout.
... | 44,042 |
def customize_response_cros(data):
"""定制跨域响应体"""
response = make_response(jsonify(data))
# 设置响应请求头
response.headers["Access-Control-Allow-Origin"] = '*' # 允许使用响应数据的域。也可以利用请求header中的host字段做一个过滤器。
response.headers["Access-Control-Allow-Methods"] = 'POST' # 允许的请求方法
response.headers["Access-Contro... | 44,043 |
def shortdateformat(value, default_value=None):
"""
Example value: datetime.strptime("2018-07-25 10:15:00", "%Y-%m-%d %H:%M:%S")
Example output: '25 July'
"shortdateformat" was designed for use in summary tables where space is tight and dates are shown on their own line.
The original intended use w... | 44,044 |
def distributed_cmd_run(
worker_fn: Callable, distributed: bool = True, *args, **kwargs
) -> None:
"""
Distributed run
Args:
worker_fn: worker fn to run in distributed mode
distributed: distributed flag
args: additional parameters for worker_fn
kwargs: additional key-val... | 44,045 |
def read_csv(
filepath_or_buffer: _io.BytesIO,
dtype: Dict[Literal["numbers", "names", "more_numbers"], type],
):
"""
usage.dask: 2
"""
... | 44,046 |
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
order = sort_characters(text)
... | 44,047 |
def load_page(content_path, page_path):
"""Load the page file and return the path, URL and contents"""
# Extract the part of the page_path that will be used as the URL path
pattern = URL_PATH_REGEX % content_path
matches = re.match(pattern, page_path)
if matches:
url_path = matches.group('p... | 44,048 |
def compute_auc(dip, tmin=-np.inf, tmax=np.inf):
"""Compute the AUC values for a DipoleFixed object."""
from mne.utils import _time_mask
if not isinstance(dip, DipoleFixed):
raise TypeError('dip must be a DipoleFixed, got "%s"' % (type(dip),))
pick = pick_types(dip.info, meg=False, dipole=True)
... | 44,049 |
def left_join(ht1, ht2):
"""
:param ht1: left hash table
:param ht2: right hash table
:return: list of joined values from both hash tables
"""
results = []
for item in ht1.table:
while item is not None:
key = item.val[0]
joined = [key, ht1.get(key), ht2.get(k... | 44,050 |
def load_pretrained_cifar10_model(
path: str, resnet_size: int = 32,
) -> Tuple[nn.Module, DifferentiableNormalize]:
"""
Loads a pretrained CIFAR-10 ResNet from the given path along with its
associated normalizer.
"""
model: nn.Module = getattr(cifar_resnets, f'resnet{resnet_size}')()
model_s... | 44,051 |
def CrossValidation(mymodel, f_train, test_loader, n_splits, n_epochs, target_vec, string_vec, batchs,
patience_early=40, patience=10, lr_decay=0.5, num_atoms=True, use_hydrogen_bonding=False,
use_acid_base=False, name_model='mymodel'):
"""
Function that does the cro... | 44,052 |
def find(path):
"""Find files in the filesystem in order
Expands and normalizes relative paths.
Ignores unreadable files and unexplorable directories.
:param dir_path: Path to a config file or dir containing configs
:returns: List of full paths of the files in the directory in lex. order
"""
... | 44,053 |
def create_project(**kwargs): # noqa: E501
"""Creates a project with an original network file.
Creates a project with an original network file. # noqa: E501
:param designation:
:type designation: str
:param description:
:type description: str
:param network_designation:
:type network_... | 44,054 |
def _get_boto_client(cluster, access_key, secret_key):
"""
Returns a boto client object that can be used to communicate with the Object
Storage cluster.
"""
client = boto.connect_s3(aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
... | 44,055 |
def triangleArea(a: Vec3, b: Vec3, c: Vec3) -> float:
"""
Calculate area of triangle
:return: area
"""
return cross3(b - a, c - a).length() / 2.0 | 44,056 |
async def read_object_name(app, device_id, addr):
"""
Execute a single request using `ReadPropertyRequest`.
This will read the `objectName` property of a remote device.
:param app: An app instance
:param device_id: BACnet device id (integer number)
:param addr: The network address of the remote ... | 44,057 |
def app():
"""Create and configure a new app instance for each test."""
# Setup
tempdir = tempfile.mkdtemp(prefix="rest-api-server-")
app = create_app({"TESTING": True, "UPLOAD_FOLDER": tempdir})
# Generate 'Fake' test files
testfiles = {"animals.txt": "mouse dog cat cow dog elephant dog camel ... | 44,058 |
def task_bml_include_cache():
"""Populate the bml include cache."""
input_bml_file_paths = glob("*.bml")
def calc_include_deps_and_cache(file_dep) -> None:
bml_path = Path(file_dep)
bml_deps = bml_include_dependencies(bml_path)
update_bml_includes_cache(bml_path, bml_deps)
for ... | 44,059 |
def jws_omex_dict():
""" Returns dictionary of available JWS combine archives.
:return: { id: download_url } dict
"""
jws_omex = {}
num_omex = 0
for page_iter in range(NUM_PAGES):
url = URL.format(page_iter+1) # 1 based counting
page = requests.get(url)
if page.status_c... | 44,060 |
def test_vorticity_4d(data_4d):
"""Test vorticity on a 4D (time, pressure, y, x) grid."""
vort = vorticity(data_4d.u, data_4d.v, data_4d.dx, data_4d.dy)
truth = np.array([[[[-5.83650490e-05, 3.17327814e-05, 4.57268332e-05, 2.00732350e-05],
[2.14368312e-05, 1.95623237e-05, 4.15790182e... | 44,061 |
def ztrsv(A,
x,
Uplo=CblasLower,
TransA=CblasNoTrans,
Diag=CblasNonUnit):
"""
returns x'
This function computes inv(op(A)) x for x, where op(A) = A, A^T, A^H
for TransA = CblasNoTrans, CblasTrans, CblasConjTrans. When Uplo is
CblasUpper then the upper triangl... | 44,062 |
def get_trainable_vars(name=None):
"""Return the trainable variables.
Parameters
----------
name : str
the scope
Returns
-------
list of tf.Variable
trainable variables
"""
return tf.compat.v1.get_collection(
tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, scope... | 44,063 |
def test_abc_subclasses_are_not_registered():
"""Test registration of ``BaseDatabaseConfiguration`` abstract subclasses.
Ensures ``BaseDatabaseConfiguration`` abstract subclasses are not
registered.
"""
vendor = 'abstract_subclass'
# creates abstract subclasss
type('DatabaseConfiguration', ... | 44,064 |
def player_to_string(game: reversi.ReversiGame, player_colour: str, player: ai_players.Player) \
-> str:
""" Returns the string representation of the type of the player.
Preconditions:
- player_colour in {'white', 'black'}
"""
if game.get_human_player() == 1 and player_colour == 'black'... | 44,065 |
def test_mbv_false_simple():
""" tests function returns false on unbalanced case"""
assert multi_bracket_validation('(') == False | 44,066 |
def encode_pd_timestamp(v: pd.Timestamp) -> Any:
"""
Specializes :func:`encode` for invocations where ``v`` is an instance of
the :class:`~pandas.Timestamp` class.
"""
return {
"__kind__": kind_inst,
"class": "pandas.Timestamp",
"args": encode([str(v)]),
"kwargs": {"f... | 44,067 |
async def getWebUserAmount(cls:"WebIndex", where:str="1=1", values:tuple=()) -> int:
""" simply gives a number of all matched user """
res:list = cls.Web.BASE.PhaazeDB.selectQuery(f"SELECT COUNT(*) AS `I` FROM `user` WHERE {where}", values)
return res[0]['I'] | 44,068 |
def test_analyze_concatenation(english_ipa_fst: FST):
"""
Test that concatenation of the analysis works as expected when all
elements include epsilons.
"""
result, = english_ipa_fst.analyze('rough')
assert result == ('ɹʌf',) | 44,069 |
def test_50e(dbcursor):
"""See about parsing 50E properly"""
utcnow = utc(2014, 8, 11, 18, 55)
ugc_provider = {}
nwsli_provider = {
"ASP": dict(lon=-83.39, lat=44.45),
"ECK": dict(lon=-82.72, lat=43.26),
"GRR": dict(lon=-85.50, lat=42.79),
}
tp = parser(
get_test... | 44,070 |
def randomise_spikes(spiketrain, n_surrogates=1, decimals=None):
"""
Generates surrogates of a spike train by spike time randomization.
The surrogates are obtained by keeping the spike count of the original
`spiketrain`, but placing the spikes randomly in the interval
`[spiketrain.t_start, spiketra... | 44,071 |
def interface_PSO(theta, args):
"""
Function to interface the PSO with the ANFIS. Each particle has its own
ANFIS instance.
theta (nPop, n_var)
learners (nPop, )
J (nPop, )
"""
args_PSO = (args[0], args[1])
learners = args[2]
nPop = theta.shape[0]
... | 44,072 |
def corr2d(X, K):
"""计算二维互相关运算。"""
h, w = K.shape
Y = mnp.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
for i in range(Y.shape[0]):
for j in range(Y.shape[1]):
Y[i, j] = (X[i:i + h, j:j + w] * K).sum()
return Y | 44,073 |
def test_install_with_pcre(pkgs):
"""
Test pkg.install to install a package with pcre=True argument
"""
parsed_targets = (
OrderedDict((("gettext-runtime", None), ("p5-Mojolicious", None))),
"repository",
)
pkg_cmd = MagicMock(return_value={"retcode": 0})
pkgs_mock = MagicMoc... | 44,074 |
def history(history_db, library_db, current_scene_db):
"""displays the notebook history of the sceen"""
from src.praxxis.sqlite import sqlite_scene
from src.praxxis.sqlite import sqlite_notebook
from src.praxxis.display import display_scene
curr_scene = sqlite_scene.get_current_scene(history_db)
... | 44,075 |
def get_optimal_parameters_from_dict(selected_dict, num_features):
""" Find optimal parameters from dictionary of selected features
Arguments
---------
selected_dict: dictionary
keys = parameters
values = dictionary
keys = task index
values = list of list of sel... | 44,076 |
def test_error_beforelogin(active_user, beforelogin_app):
"""Test errors from BeforeLogIn event."""
res = beforelogin_app.get('/login')
post_data = {
'email': DEFAULT_USER['email'],
'password': DEFAULT_USER['password'],
'csrf_token': res.form['csrf_token'].value
}
res = befor... | 44,077 |
async def _get_input_dialog(self: 'TelegramClient', dialog):
"""
Returns a :tl:`InputDialogPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
"""
try:
if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'InputDialogPeer... | 44,078 |
def kep_to_sat(kep,epoch,bstar=0.21109E-4,whichconst=wgs72,afspc_mode=False):
"""kep_to_sat(kep,epoch,bstar=0.21109E-4,whichconst=wgs72,afspc_mode=False)
Converts a set of keplerian elements into a Satellite object.
Args:
kep(1x6 numpy array): the osculating keplerian elements at epoch
... | 44,079 |
def enumerate ():
""" Returns an iterator to the features map.
"""
return __all_features.iteritems () | 44,080 |
def _create_forward(out_node):
"""Create a user-friendly forward function.
Ensures that a single value instead of a tuple is returned if the user asked
for the gradient with respect to only one input.
Args:
out_node: The function definition AST.
Returns:
The function definition with potentially cha... | 44,081 |
def error(flow: mitmproxy.http.HTTPFlow):
"""
An HTTP error has occurred, e.g. invalid server responses, or
interrupted connections. This is distinct from a valid server HTTP
error response, which is simply a response with an HTTP error code.
""" | 44,082 |
def get_geos_install_prefix():
"""Return GEOS installation prefix or None if not found."""
env_candidate = os.environ.get("GEOS_DIR", None)
if env_candidate is not None:
candidates = [env_candidate]
else:
candidates = [os.path.expanduser("~/local"), os.path.expanduser("~"),
... | 44,083 |
def _get_trip_from_id(trip_obj_list, trip_id):
""" Get a trip from a list, based on a trip id """
found_trip_obj = None
for trip_obj in trip_obj_list:
if trip_obj.id == trip_id:
found_trip_obj = trip_obj
break
return found_trip_obj | 44,084 |
def density_plot(df, y_column, models, model_names=(), columns_to_exclude=()):
"""This function creates the density plot of predicted positive class probability on actual positive and negative
data by each model in models in the same plot. It also computes the difference between the distributions on
p... | 44,085 |
def append(
cut_manifests: List[Pathlike],
output_cut_manifest: Pathlike,
):
"""
Create a new CutSet by appending the cuts in CUT_MANIFESTS. CUT_MANIFESTS are iterated position-wise (the
cuts on i'th position in each manfiest are appended to each other).
The cuts are appended in the order in whi... | 44,086 |
def clip_chk(x, lb, ub, allow_nan=False):
"""Clip all element of `x` to be between `lb` and `ub` like :func:`numpy:numpy.clip`, but also check
:func:`numpy:numpy.isclose`.
Shapes of all input variables must be broadcast compatible.
Parameters
----------
x : :class:`numpy:numpy.ndarray`
... | 44,087 |
def grid_arc_seconds_1d_to_grid_pixel_indexes_1d(grid_arc_seconds_1d, shape, pixel_scales, origin=(0.0, 0.0)):
""" Convert a grid of (y,x) arc second coordinates to a grid of (y,x) pixel 1D indexes. Pixel coordinates are \
returned as integers such that they are the pixel from the top-left of the 2D grid going ... | 44,088 |
def silent_deprecation():
"""*Deprecated* but not yet loudly.
RF and Libdoc don't consider this being deprecated.
""" | 44,089 |
def step_impl(context):
"""
Args:
context (behave.runner.Context): The test context.
"""
context.project_measurements = {
'fluid_density': context.project.fluid_density,
'azimuth': context.project.azimuth,
'center_x': context.project.project_center().x,
'center_y'... | 44,090 |
def make_test_run_filter(
complete: bool = False, failed: bool = False, incomplete: bool = False,
name: str = None,
newer_than: dt.datetime = None, older_than: dt.datetime = None,
passed: bool = False, result_error: bool = False,
show_skipped: bool = False, sys_name: str = None, ... | 44,091 |
def get_runnable_tasks(graph):
"""Parse a graph and return all runnable tasks."""
tasks = []
to_remove = []
# tasks that follow task that raises an error
following_err = dict()
for tsk in graph.sorted_nodes:
if tsk not in graph.sorted_nodes:
continue
# since the list ... | 44,092 |
def get_defaults(lang):
"""Get the language-specific defaults, if available in spaCy. This allows
using lexical attribute getters that depend on static language data, e.g.
Token.like_num, Token.is_stop, Doc.noun_chunks etc.
lang (unicode): ISO 639-1 language code.
RETURNS (Language.Defaults): The l... | 44,093 |
def h2(*text, **kwargs):
"""Return a header 2"""
return tydoc().h2(*text, **kwargs) | 44,094 |
def update_comment(comment_id, data):
"""
update comment using its id.
"""
comment = Comment.query.get(comment_id)
for attribute in data:
setattr(comment, attribute, data[attribute])
db.session.commit()
return comment_schema.dump(comment).data | 44,095 |
def logs_sidecars_jobs(job_uuid, job_name, log_lines):
"""Signal handling for sidecars logs."""
handle_job_logs(job_uuid=job_uuid,
job_name=job_name,
log_lines=log_lines)
publisher.publish_job_log(
log_lines=log_lines,
job_uuid=job_uuid,
job_na... | 44,096 |
def countOriginals(subfolderPath):
"""return count of original vids"""
items = os.listdir(subfolderPath)
count = 0
for file in items:
if file.startswith("Original_") and file.endswith(".description"):
count = count + 1
return count | 44,097 |
def RMSE(A, A_tilde):
"""
Root mean square error. Gives the standard deviation of the residuals
(prediction errors).
Parameters
----------
A : ndarray
Forecast.
A_tilde : ndarray
Observation.
Returns
-------
float
Root mean square error.
"""
ret... | 44,098 |
def remove_punct(tokens):
"""
Remove punctuation marks from lists of tokens
Parameters
----------
tokens: list
a nested list containing lists of tokens or a list of spacy docs
Returns
-------
filtered_comments: list
nested lists of tokens
"""
filtered_comments... | 44,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.