content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def stage_grid(
Dstg,
A,
dx_c,
tte,
min_Rins=None,
recamber=None,
stag=None,
resolution=1.
):
"""Generate an H-mesh for a turbine stage."""
# Change scaling factor on grid points
# Distribute the spacings between stator and rotor
dx_c = np.array([[dx_c[0], dx_c[1] / 2.... | e19e07e61be0079559ee597475ce017f8f0a6189 | 3,646,130 |
def get_best_trial(trial_list, metric):
"""Retrieve the best trial."""
return max(trial_list, key=lambda trial: trial.last_result.get(metric, 0)) | c5ddbb9ad00cddaba857d0d0233f6452e6702552 | 3,646,131 |
def make_registry_metaclass(registry_store):
"""Return a new Registry metaclass."""
if not isinstance(registry_store, dict):
raise TypeError("'registry_store' argument must be a dict")
class Registry(type):
"""A metaclass that stores a reference to all registered classes."""
def _... | c1c0426e4d47323ccd3ab80ff3917253858f1b0c | 3,646,132 |
def bind11(reactant, max_helix = True):
"""
Returns a list of reaction pathways which can be produced by 1-1 binding
reactions of the argument complex. The 1-1 binding reaction is the
hybridization of two complementary unpaired domains within a single complex
to produce a single unpseudoknotted prod... | 45c74105e2f9733092aba3b55edd4dbaa8e9e26e | 3,646,133 |
def get_all_movie_props(movies_set: pd.DataFrame, flag: int, file_path: str):
"""
Function that returns the data frame of all movie properties from dbpedia
:param movies_set: data set of movies with columns movie id and movie dbpedia uri
:param flag: 1 to generate the data frame from scratch and 0 to re... | f3b85ce0d5b0e0fa8f28a2f3e8ee7d69c2002ee1 | 3,646,134 |
def convert_to_clocks(duration, f_sampling=200e6, rounding_period=None):
"""
convert a duration in seconds to an integer number of clocks
f_sampling: 200e6 is the CBox sampling frequency
"""
if rounding_period is not None:
duration = max(duration//rounding_period, 1)*rounding_period
... | 602b00af689cc25374b7debd39264b438de44baa | 3,646,135 |
def account_approved(f):
"""Checks whether user account has been approved, raises a 401 error
otherwise .
"""
def decorator(*args, **kwargs):
if not current_user:
abort(401, {'message': 'Invalid user account.'})
elif not current_user.is_approved:
abort(401, {'mess... | e9f9e7bd15bd1df22540a6a42db95501a26fcce2 | 3,646,136 |
def multiply(x):
"""Multiply operator.
>>> multiply(2)(1)
2
"""
def multiply(y):
return y * x
return multiply | 77d983090e03820d03777f1f69cfc7b0ef6d88a2 | 3,646,137 |
def tally_transactions(address, txs):
"""Calculate the net value of all deposits, withdrawals and fees
:param address: Address of the account
:param txs: Transactions JSON for the address
:returns: The total net value of all deposits, withdrawals and fees
"""
send_total = 0
for item in txs... | 6eaca1e7be11f9af254bcc491ff661413d8745f4 | 3,646,138 |
def expose(policy):
"""
Annotate a method to permit access to contexts matching an authorization
policy. The annotation may be specified multiple times. Methods lacking any
authorization policy are not accessible.
::
@mitogen.service.expose(policy=mitogen.service.AllowParents())
de... | 74caed36885e5ea947a2ecdac9a2cddf2f5f51b0 | 3,646,139 |
def _bytes_feature(value):
"""Creates a bytes feature from the passed value.
Args:
value: An numpy array.
Returns:
A TensorFlow feature.
"""
return tf.train.Feature(
bytes_list=tf.train.BytesList(
value=[value.astype(np.float32).tostring()])) | e13ac22bef91af7847aecdb558e849de27e89623 | 3,646,140 |
from typing import Union
from typing import OrderedDict
def get_cell_phase(
adata: anndata.AnnData,
layer: str = None,
gene_list: Union[OrderedDict, None] = None,
refine: bool = True,
threshold: Union[float, None] = 0.3,
) -> pd.DataFrame:
"""Compute cell cycle phase scores for cells in the po... | 9b379c42cd409893d51885f5580b26b9700547bf | 3,646,141 |
def variational_lower_bound(prediction):
"""
This is the variational lower bound derived in
Auto-Encoding Variational Bayes, Kingma & Welling, 2014
:param [posterior_means, posterior_logvar,
data_means, data_logvar, originals]
posterior_means: predicted means for the posterior
... | bcbc9a660f07fe677f823ee3aeb284817e94601d | 3,646,142 |
import base64
def didGen(vk, method="dad"):
"""
didGen accepts an EdDSA (Ed25519) key in the form of a byte string and returns a DID.
:param vk: 32 byte verifier/public key from EdDSA (Ed25519) key
:param method: W3C did method string. Defaults to "dad".
:return: W3C DID string
"""
if vk ... | 9991491ab486d8960633190e3d3baa9058f0da50 | 3,646,143 |
import pickle
def load_dataset(datapath):
"""Extract class label info """
with open(datapath + "/experiment_dataset.dat", "rb") as f:
data_dict = pickle.load(f)
return data_dict | 3a0d8ef9c48036879b32ab0e74e52429418297c0 | 3,646,144 |
def deleteupload():
"""Deletes an upload.
An uploads_id is given and that entry is then removed from the uploads table
in the database.
"""
uploads_id = request.args.get('uploads_id')
if not uploads.exists(uploads_id=uploads_id):
return bad_json_response(
'BIG OOPS: Somethi... | df18801b287569f1fa1114fc7059a415b82913d0 | 3,646,145 |
from typing import Dict
from pathlib import Path
import json
def load_json(filename: str) -> Dict:
"""Read JSON file from metadata folder
Args:
filename: Name of metadata file
Returns:
dict: Dictionary of data
"""
filepath = (
Path(__file__).resolve().parent.parent.joinpat... | 37d9f08344cf2a544c12fef58992d781556a9efd | 3,646,147 |
def get_riemann_sum(x, delta_x):
"""
Returns the riemann `sum` given a `function` and
the input `x` and `delta_x`
Parameters
----------
x : list
List of numbers returned by `np.linspace` given a lower
and upper bound, and the number of intervals
delta_x :
The inter... | dd80d12581533fa4074411845050f29193a03432 | 3,646,148 |
def MPO_rand(n, bond_dim, phys_dim=2, normalize=True, cyclic=False,
herm=False, dtype=float, **mpo_opts):
"""Generate a random matrix product state.
Parameters
----------
n : int
The number of sites.
bond_dim : int
The bond dimension.
phys_dim : int, optional
... | 22220095b5cfcb3625edf3cde59e03fa37cd5423 | 3,646,149 |
def get_short_size(size_bytes):
"""
Get a file size string in short format.
This function returns:
"B" size (e.g. 2) when size_bytes < 1KiB
"KiB" size (e.g. 345.6K) when size_bytes >= 1KiB and size_bytes < 1MiB
"MiB" size (e.g. 7.8M) when size_bytes >= 1MiB
size_bytes: File siz... | ebc9ba25c01dedf0d15b9e2a21b67989763bc8c8 | 3,646,150 |
def score_from_srl(srl_path, truth_path, freq, verbose=False):
"""
Given source list output by PyBDSF and training truth catalogue,
calculate the official score for the sources identified in the srl.
Args:
srl_path (`str`): Path to source list (.srl file)
truth_path (`str`): Path to tra... | 87cfdd7ed7c1a42fc3a4080289e7e34be6a2a85a | 3,646,152 |
def get_feature_read(key, max_num_bbs=None):
"""Choose the right feature function for the given key to parse TFRecords
Args:
key: the feature name
max_num_bbs: Max number of bounding boxes (used for `bounding_boxes` and `classes`)
max_num_groups: Number of pre-defined groups (used f... | 6ec7f06e900baedec19950c0f4742da9c4df1514 | 3,646,153 |
import numpy
import time
def kernel(cc, eris, t1=None, t2=None, max_cycle=50, tol=1e-8, tolnormt=1e-6,
verbose=logger.INFO):
"""Exactly the same as pyscf.cc.ccsd.kernel, which calls a
*local* energy() function."""
if isinstance(verbose, logger.Logger):
log = verbose
else:
lo... | 24917c48cbdb2062914462ad3f354cdd0e4e6318 | 3,646,154 |
async def getAllDestinyIDs():
"""Returns a list with all discord members destiny ids"""
select_sql = """
SELECT
destinyID
FROM
"discordGuardiansToken";"""
async with (await get_connection_pool()).acquire(timeout=timeout) as connection:
result = await conne... | 22e94165cc0f50c8458be152d77231f30f7383b8 | 3,646,156 |
def login():
"""Handles login for Gello."""
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return red... | 5000c52d652c114a5b69b403fca9809dfa9e6bca | 3,646,157 |
def create_loss_functions(interconnector_coefficients, demand_coefficients, demand):
"""Creates a loss function for each interconnector.
Transforms the dynamic demand dependendent interconnector loss functions into functions that only depend on
interconnector flow. i.e takes the function f and creates g by... | 1522b4506d4dad40e2b3d16bdd8ebd92d9b46401 | 3,646,158 |
def num2proto(pnum):
"""Protocol number to name"""
# Look for the common ones first
if pnum == 6:
return "tcp"
elif pnum == 17:
return "udp"
elif pnum == 1:
return "icmp"
elif pnum == 58:
# Use the short form of icmp-ipv6 when appropriate
return "icmpv6"
... | ad68b0fe530d63de62087eb23e5cacca0d48b996 | 3,646,159 |
def get_problem_size(problem_size, params):
"""compute current problem size"""
if callable(problem_size):
problem_size = problem_size(params)
if isinstance(problem_size, (str, int, np.integer)):
problem_size = (problem_size, )
current_problem_size = [1, 1, 1]
for i, s in enumerate(pr... | c71394f081a7f0d00fcae653dffc439bc7b1b3b1 | 3,646,160 |
def interpolate(x,
size=None,
scale_factor=None,
mode='nearest',
align_corners=False,
align_mode=0,
data_format='NCHW',
name=None):
"""
This op resizes a batch of images.
The input must be a 3-D ... | a9e03ecc89cdb623922984d3cce9b6cb114419b9 | 3,646,162 |
from datetime import datetime
def encode_auth_token(user_id):
"""
Generates the Auth Token
:return: string
"""
try:
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=90),
'iat': datetime.datetime.utcnow(),
'sub': user_id
}
... | 5239b2d85e3c4c1f4c6f74297118295c0bf7d532 | 3,646,163 |
from typing import List
from typing import Tuple
from typing import Dict
def build_docs_for_packages(
current_packages: List[str],
docs_only: bool,
spellcheck_only: bool,
for_production: bool,
jobs: int,
verbose: bool,
) -> Tuple[Dict[str, List[DocBuildError]], Dict[str, List[SpellingError]]]:... | c4196c139fda703c90c60507156cce8cb29da98e | 3,646,164 |
def _inspect_output_dirs_test(ctx):
"""Test verifying output directories used by a test."""
env = analysistest.begin(ctx)
# Assert that the output bin dir observed by the aspect added by analysistest
# is the same as those observed by the rule directly, even when that's
# under a config transition ... | de14b2d4514792d4b2427ff3ef4fae6e7af8e31d | 3,646,165 |
import ray
def wait(object_refs, num_returns=1, timeout=None):
"""Return a list of IDs that are ready and a list of IDs that are not.
This method is identical to `ray.wait` except it adds support for tuples
and ndarrays.
Args:
object_refs (List[ObjectRef], Tuple(ObjectRef), np.array(ObjectRe... | e56ffd1700715049cc899d27735bb98da47fa2b6 | 3,646,166 |
def train(
data,
feature_names,
tagset,
epochs,
optimizer,
score_func=perceptron_score,
step_size=1,
):
"""
Trains the model on the data and returns the parameters
:param data: Array of dictionaries representing the data. One dictionary for each data point (as created by the
... | 51a0a506deecf56067ef185848d7f706c9da0d3e | 3,646,167 |
def summed_timeseries(timeseries):
"""
Give sum of value series against timestamps for given timeseries containing several values per one timestamp
:param timeseries:
:return:
"""
sum_timeseries = []
for i in range(len(timeseries)):
if len(timeseries[i])>1:
sum_timeserie... | 618505f8f0960900a993bb6d9196d17bf31d02a6 | 3,646,168 |
import pathlib
def path_check(path_to_check):
"""
Check that the path given as a parameter is an valid absolute path.
:param path_to_check: string which as to be checked
:type path_to_check: str
:return: True if it is a valid absolute path, False otherwise
:rtype: boolean
"""
path = p... | 41b3537b0be2c729ba993a49863df4a15119db8b | 3,646,169 |
from typing import Union
from typing import Sequence
from typing import Optional
from typing import Dict
from typing import Any
from datetime import datetime
from typing import List
def _path2list(
path: Union[str, Sequence[str]],
boto3_session: boto3.Session,
s3_additional_kwargs: Optional[Dict[str, Any]... | 542d41ce29f71e3209d702eab157a75fa40650c0 | 3,646,170 |
import torch
def e_greedy_normal_noise(mags, e):
"""Epsilon-greedy noise
If e>0 then with probability(adding noise) = e, multiply mags by a normally-distributed
noise.
:param mags: input magnitude tensor
:param e: epsilon (real scalar s.t. 0 <= e <=1)
:return: noise-multiplier.
"""
if... | e2e9f8f49e7d3e6b2319aaa6a869f24aa3047946 | 3,646,171 |
def beam_area(*args):
"""
Calculate the Gaussian beam area.
Parameters
----------
args: float
FWHM of the beam.
If args is a single argument, a symmetrical beam is assumed.
If args has two arguments, the two arguments are bmaj and bmin,
the width of the major and min... | 93c4616018a098199a47fb25038cb88707444864 | 3,646,172 |
def get_settlement_amounts(
participant1,
participant2
):
""" Settlement algorithm
Calculates the token amounts to be transferred to the channel participants when
a channel is settled.
!!! Don't change this unless you really know what you are doing.
"""
total_available_deposit ... | e4bddfccbced0235b1d5265519208cef5167013d | 3,646,173 |
import time
def timefunc(f):
"""Simple timer function to identify slow spots in algorithm.
Just import function and put decorator @timefunc on top of definition of any
function that you want to time.
"""
def f_timer(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
... | 56d5d052fa559e1b7c797ed00ee1b82c8e2126d6 | 3,646,174 |
def rdr_geobox(rdr) -> GeoBox:
""" Construct GeoBox from opened dataset reader.
"""
h, w = rdr.shape
return GeoBox(w, h, rdr.transform, rdr.crs) | 0c22ff869faa2988e63a4b13d17c8f5ba7343ffc | 3,646,175 |
def sequence(lst: Block[Result[_TSource, _TError]]) -> Result[Block[_TSource], _TError]:
"""Execute a sequence of result returning commands and collect the
sequence of their response."""
return traverse(identity, lst) | d228237edc95a4d2c4ef1c9591af41a639c42a6d | 3,646,176 |
def keyword_dct_from_block(block, formatvals=True):
""" Take a section with keywords defined and build
a dictionary for the keywords
assumes a block that is a list of key-val pairs
"""
key_dct = None
if block is not None:
block = ioformat.remove_whitespace(block)
key_va... | 929defe8d07fff4bf50f1167c0749a6e19d9ecb2 | 3,646,177 |
def get_geocode(args):
"""
Returns GPS coordinates from Google Maps for a given location.
"""
result = Geocoder.geocode(args.address)
lat, lon = result[0].coordinates
lat = round(lat, 6)
lon = round(lon, 6)
return (lat, lon) | 1ef5d89a1157bbbe381ac1e4500e198735b71898 | 3,646,178 |
def mice(data, **kwargs):
"""Multivariate Imputation by Chained Equations
Reference:
Buuren, S. V., & Groothuis-Oudshoorn, K. (2011). Mice: Multivariate
Imputation by Chained Equations in R. Journal of Statistical Software,
45(3). doi:10.18637/jss.v045.i03
Implementation follows th... | e2046350d071a1cc17bc23077c0be2d0939371b5 | 3,646,179 |
from functools import reduce
def get_next_code(seen, server_ticket=0):
"""Find next unused assertion code.
Called by: SConstruct and main()
Since SConstruct calls us, codes[] must be global OR WE REPARSE EVERYTHING
"""
if not codes:
(_, _, seen) = read_error_codes()
if server_ticket:... | b2aeef05725137208e8aaef213f1bf68eb673e06 | 3,646,182 |
import asyncio
def getEnergyUsage():
"""Query plug for energy usage data. Runs as async task.
:return: json with device energy data
"""
energy_data = asyncio.run(plug.get_emeter_realtime())
return energy_data | 43fe5814de6776052c8c48ac65e9df8893956ef6 | 3,646,183 |
def get_sequence_from_kp(midi):
"""
Get the reduced chord sequence from a kp KP-corpus file.
Parameters
==========
midi : pretty_midi
A pretty_midi object representing the piece to parse.
Returns
=======
chords : list
The reduced chord sequence from the give... | fd11658607e44151fbd6eaec08bff4ce510e8ba5 | 3,646,184 |
def get_bw_range(features):
"""
Get the rule-of-thumb bandwidth and a range of bandwidths on a log scale for the Gaussian RBF kernel.
:param features: Features to use to obtain the bandwidths.
:return: Tuple consisting of:
* rule_of_thumb_bw: Computed rule-of-thumb bandwidth.
* bws: Li... | 2e954badf9e529bd0c62449c34a631d5be87950b | 3,646,185 |
def gen_endpoint(endpoint_name, endpoint_config_name):
"""
Generate the endpoint resource
"""
endpoint = {
"SagemakerEndpoint": {
"Type": "AWS::SageMaker::Endpoint",
"DependsOn": "SagemakerEndpointConfig",
"Properties": {
"EndpointConfigName": ... | bc658e6aebc41cfddefe0e77b2d65748a84789c5 | 3,646,186 |
def read_dataframe(df, smiles_column, name_column, data_columns=None):
"""Read molecules from a dataframe.
Parameters
----------
df : pandas.DataFrame
Dataframe to read molecules from.
smiles_column : str
Key of column containing SMILES strings or rdkit Mol objects.
name_column ... | d27e01e38132818f0bb740fc0033f22949e9fa79 | 3,646,188 |
from typing import List
def dummy_awsbatch_cluster_config(mocker):
"""Generate dummy cluster."""
image = Image(os="alinux2")
head_node = dummy_head_node(mocker)
compute_resources = [
AwsBatchComputeResource(name="dummy_compute_resource1", instance_types=["dummyc5.xlarge", "optimal"])
]
... | ff9c24e90faf92758a83c3529d261c901b614b01 | 3,646,189 |
def float_or_none(val, default=None):
"""
Arguments:
- `x`:
"""
if val is None:
return default
else:
try:
ret = float(val)
except ValueError:
ret = default
return ret | 00beabbd2fe4633e6738fea2220d55d096bfa91e | 3,646,190 |
def user_get_year_rating(user_id: int):
"""
Get the last step user was at
:param user_id:
:return: str
"""
try:
con = psconnect(db_url, sslmode='require')
cursor = con.cursor()
cursor.execute("SELECT year,rating FROM users WHERE uid = %s", (user_id,))
result = cur... | 4911d5d0ea8f99b1d889d048aa31825452b3f3fe | 3,646,191 |
from pymco import message
def msg_with_data(config, filter_):
"""Creates :py:class:`pymco.message.Message` instance with some data."""
# Importing here since py-cov will ignore code imported on conftest files
# imports
with mock.patch('time.time') as time:
with mock.patch('hashlib.sha1') as sh... | 3bb50370512e58fce6c098ed2144b7406cc6eab4 | 3,646,192 |
def api_connect_wifi():
""" Connect to the specified wifi network """
res = network.wifi_connect()
return jsonify(res) | 1a8832bb67bb1d5b73357b9b1359f6c1835f3c85 | 3,646,194 |
from typing import List
async def get_sinks_metadata(sinkId: str) -> List: # pylint: disable=unused-argument
"""Get metadata attached to sinks
This adapter does not implement metadata. Therefore this will always result
in an empty list!
"""
return [] | 458b674cc59a80572fd9676aec81d0a7c353a8f3 | 3,646,195 |
def fn_lin(x_np, *, multiplier=3.1416):
""" Linear function """
return x_np * multiplier | e64f112b486ea6a0bdf877d67c98417ae90f03b3 | 3,646,196 |
def get_MACD(df, column='Close'):
"""Function to get the EMA of 12 and 26"""
df['EMA-12'] = df[column].ewm(span=12, adjust=False).mean()
df['EMA-26'] = df[column].ewm(span=26, adjust=False).mean()
df['MACD'] = df['EMA-12'] - df['EMA-26']
df['Signal'] = df['MACD'].ewm(span=9, adjust=Fal... | b5eb25c9a5097fb2a0d874d62b6ab1957bbe3f11 | 3,646,197 |
def from_pyGraphviz_agraph(A, create_using=None):
"""Returns a EasyGraph Graph or DiGraph from a PyGraphviz graph.
Parameters
----------
A : PyGraphviz AGraph
A graph created with PyGraphviz
create_using : EasyGraph graph constructor, optional (default=None)
Graph type to create. If g... | 66f57a2864f87342c84452336da647fb7489ec66 | 3,646,198 |
from typing import Collection
import copy
def get_textbox_rectangle_from_pane(pane_rectangle: GeometricRectangle, texts: Collection[str],
direction: str) -> GeometricRectangle:
"""
Args:
pane_rectangle:
texts:
direction:
Returns:
"""
n... | 9e0a3bb2f0a93312d17096fe36d1b0529b5b47e6 | 3,646,199 |
def spawn_shell(shell_cmd):
"""Spawn a shell process with the provided command line. Returns the Pexpect object."""
return pexpect.spawn(shell_cmd[0], shell_cmd[1:], env=build_shell_env()) | 07de3ae221b427baddb0b47f1d52e3eae91035e7 | 3,646,200 |
from collections import OrderedDict
import sep
from grizli import utils
import tqdm
def analyze_image(data, err, seg, tab, athresh=3.,
robust=False, allow_recenter=False,
prefix='', suffix='', grow=1,
subtract_background=False, include_empty=False,
... | b90920ac00a995fde90c43b07cae45a752786c15 | 3,646,201 |
def get_experiment_table(faultgroup, faultname, tablename):
"""
Get anny table from a faultgroup
"""
node = faultgroup._f_get_child(faultname)
table = node._f_get_child(tablename)
return pd.DataFrame(table.read()) | 16c78e6925d3da227402e2e17e00bac38ff72ab7 | 3,646,203 |
def kjunSeedList(baseSeed, n):
"""
generates n seeds
Due to the way it generates the seed, do not use i that is too large..
"""
assert n <= 100000
rs = ra.RandomState(baseSeed);
randVals = rs.randint(np.iinfo(np.uint32).max+1, size=n);
return randVals; | 6d98adfba2917ede64d0572c21d6fe1041327241 | 3,646,204 |
import PIL
def filter_sharpen(image):
"""Apply a sharpening filter kernel to the image.
This is the same as using PIL's ``PIL.ImageFilter.SHARPEN`` kernel.
Added in 0.4.0.
**Supported dtypes**:
* ``uint8``: yes; fully tested
* ``uint16``: no
* ``uint32``: no
* ``uin... | 28b83153dc8931430e22f63f889cf195f01f80da | 3,646,205 |
async def zha_client(hass, config_entry, zha_gateway, hass_ws_client):
"""Test zha switch platform."""
# load the ZHA API
async_load_api(hass)
# create zigpy device
await async_init_zigpy_device(
hass,
[general.OnOff.cluster_id, general.Basic.cluster_id],
[],
None,
... | ba659195dc2e3d8d3510c25edcf4850a740483c1 | 3,646,206 |
import random
def summary_selector(summary_models=None):
"""
Will create a function that take as input a dict of summaries :
{'T5': [str] summary_generated_by_T5, ..., 'KW': [str] summary_generted_by_KW}
and randomly return a summary that has been generated by one of the summary_model in summary_model
if summar... | b8a2336546324d39ff87ff5b59f4f1174e5dd54c | 3,646,207 |
import collections
from datetime import datetime
def handle_collectd(root_dir):
"""Generate figure for each plugin for each hoster."""
result = collections.defaultdict(lambda: collections.defaultdict(dict))
for host in natsorted(root_dir.iterdir()):
for plugin in natsorted(host.iterdir()):
... | 48eb4f2ad5976d51fbe1904219e90620aea1a82c | 3,646,208 |
def create_policy_case_enforcement(repository_id, blocking, enabled,
organization=None, project=None, detect=None):
"""Create case enforcement policy.
"""
organization, project = resolve_instance_and_project(
detect=detect, organization=organization, project=projec... | 60864cd51472029991a4bb783a39007ea42e4b58 | 3,646,209 |
def svn_fs_new(*args):
"""svn_fs_new(apr_hash_t fs_config, apr_pool_t pool) -> svn_fs_t"""
return apply(_fs.svn_fs_new, args) | 6ade0887b16e522d47d70c974ccecf8f8bec1403 | 3,646,210 |
def least_similar(sen, voting_dict):
"""
Find senator with voting record least similar, excluding the senator passed
:param sen: senator last name
:param voting_dict: dictionary of voting record by last name
:return: senator last name with least similar record, in case of a tie chooses first alphabe... | 8bcc8cde75e9ce060f852c0e7e03756d279491f0 | 3,646,212 |
import logging
def _send_req(wait_sec, url, req_gen, retry_result_code=None):
""" Helper function to send requests and retry when the endpoint is not ready.
Args:
wait_sec: int, max time to wait and retry in seconds.
url: str, url to send the request, used only for logging.
req_gen: lambda, no parameter fu... | d6856bf241f857f3acd8768fd71d058d4c94baaa | 3,646,213 |
def load_file(path, types = None):
"""
load file in path if file format in types list
----
:param path: file path
:param code: file type list, if None, load all files, or not load the files in the list, such as ['txt', 'xlsx']
:return: a list is [path, data]
"""
ext = path.split(".")[-1]... | dab404cf2399e3b87d23babb1a09be2b94c3d924 | 3,646,214 |
import numpy
def get_dense_labels_map(values, idx_dtype='uint32'):
"""
convert unique values into dense int labels [0..n_uniques]
:param array values: (n,) dtype array
:param dtype? idx_dtype: (default: 'uint32')
:returns: tuple(
labels2values: (n_uniques,) dtype array,
values2labe... | cd9f2884e26fa22785e24598f0f485d2931427d8 | 3,646,215 |
from typing import Match
def _replace_fun_unescape(m: Match[str]) -> str:
""" Decode single hex/unicode escapes found in regex matches.
Supports single hex/unicode escapes of the form ``'\\xYY'``,
``'\\uYYYY'``, and ``'\\UYYYYYYYY'`` where Y is a hex digit. Only
decodes if there is an odd number of b... | 3fdb275e3c15697e5302a6576b4d7149016299c0 | 3,646,217 |
def predict_next_location(game_data, ship_name):
"""
Predict the next location of a space ship.
Parameters
----------
game_data: data of the game (dic).
ship_name: name of the spaceship to predicte the next location (str).
facing: facing of the ship (tuple)
Return
------
predic... | 996b58e0ac8d8754a49020e0e5df830fa472be99 | 3,646,218 |
def check_answer(guess, a_follower, b_follower):
"""Chcek if the user guessed the correct option"""
if a_follower > b_follower:
return guess == "a"
else:
return guess == "b" | acd1e78026f89dd1482f4471916472d35edf68a7 | 3,646,220 |
def respond(variables, Body=None, Html=None, **kwd):
"""
Does the grunt work of cooking up a MailResponse that's based
on a template. The only difference from the lamson.mail.MailResponse
class and this (apart from variables passed to a template) are that
instead of giving actual Body or Html param... | 214513edf420dc629603cc98d1728dec8c81aee9 | 3,646,222 |
from typing import Dict
def canonical_for_code_system(jcs: Dict) -> str:
"""get the canonical URL for a code system entry from the art decor json. Prefer FHIR URIs over the generic OID URI.
Args:
jcs (Dict): the dictionary describing the code system
Returns:
str: the canonical URL
""... | f111a4cb65fa75799e799f0b088180ef94b71cc8 | 3,646,223 |
def correspdesc_source(data):
"""
extract @source from TEI elements <correspDesc>
"""
correspdesc_data = correspdesc(data)
try:
return [cd.attrib["source"].replace("#", "") for cd in correspdesc_data]
except KeyError:
pass
try:
return [cd.attrib[ns_cs("source")].repla... | 18a2fe1d0daf0f383c8b8295105ad0027b626f31 | 3,646,224 |
def leaders(Z, T):
"""
(L, M) = leaders(Z, T):
For each flat cluster j of the k flat clusters represented in the
n-sized flat cluster assignment vector T, this function finds the
lowest cluster node i in the linkage tree Z such that:
* leaf descendents belong only to flat cluster j (i.e. T[p... | 7b72b33b87e454138c144a791612d7af8422b0a6 | 3,646,225 |
from typing import List
def create_unique_views(rows: list, fields: List[str]):
"""Create views for each class objects, default id should be a whole row"""
views = {}
for r in rows:
values = [r[cname] for cname in fields]
if any(isinstance(x, list) for x in values):
if all(isin... | 24b311c8b013f742e69e7067c1f1bafe0044c940 | 3,646,226 |
from typing import List
import torch
def check_shape_function(invocations: List[Invocation]):
"""Decorator that automatically tests a shape function.
The shape function, which is expected to be named systematically with
`〇` instead of `.`, is tested against the corresponding op in
`torch.ops.*` f... | be237f2209f1e2007b53a1ecbe0c277bf2b37fe7 | 3,646,227 |
def _prepare_images(ghi, clearsky, daytime, interval):
"""Prepare data as images.
Performs pre-processing steps on `ghi` and `clearsky` before
returning images for use in the shadow detection algorithm.
Parameters
----------
ghi : Series
Measured GHI. [W/m^2]
clearsky : Series
... | 9433cce0ccb9dae5e5b364fce42f8ed391adf239 | 3,646,228 |
import numpy
def interleaved_code(modes: int) -> BinaryCode:
""" Linear code that reorders orbitals from even-odd to up-then-down.
In up-then-down convention, one can append two instances of the same
code 'c' in order to have two symmetric subcodes that are symmetric for
spin-up and -down modes: ' c +... | e9b178165c8fe1e33d880dee056a3e397fa90bce | 3,646,229 |
from sklearn.neighbors import NearestNeighbors
def nearest_neighbors(data, args):
"""
最近邻
"""
nbrs = NearestNeighbors(**args)
nbrs.fit(data)
# 计算测试数据对应的最近邻下标和距离
# distances, indices = nbrs.kneighbors(test_data)
return nbrs | d91014d082f7a15a26e453d32272381b7578c9de | 3,646,230 |
def gradient(v, surf):
"""
:param v: vector of x, y, z coordinates
:param phase: which implicit surface is being used to approximate the structure of this phase
:return: The gradient vector (which is normal to the surface at x)
"""
x = v[0]
y = v[1]
z = v[2]
if surf == 'Ia3d' or su... | 2105c491f122508531816d15146801b0dd1c9b75 | 3,646,231 |
def authenticated_client(client, user):
"""
"""
client.post(
'/login',
data={'username': user.username, 'password': 'secret'},
follow_redirects=True,
)
return client | 5f96ef56179848f7d348ffda67fc08cfccb080ed | 3,646,232 |
def viterbi(obs, states, start_p, trans_p, emit_p):
"""
請參考李航書中的算法10.5(維特比算法)
HMM共有五個參數,分別是觀察值集合(句子本身, obs),
狀態值集合(all_states, 即trans_p.keys()),
初始機率(start_p),狀態轉移機率矩陣(trans_p),發射機率矩陣(emit_p)
此處的states是為char_state_tab_P,
這是一個用來查詢漢字可能狀態的字典
此處沿用李航書中的符號,令T=len(obs),令N=len(trans_p.key... | 42f3037042114c0b4e56053ac6dfc6bd77423d39 | 3,646,233 |
def add_merge_variants_arguments(parser):
"""
Add arguments to a parser for sub-command "stitch"
:param parser: argeparse object
:return:
"""
parser.add_argument(
"-vp",
"--vcf_pepper",
type=str,
required=True,
help="Path to VCF file from PEPPER SNP."
... | 5fd6bc936ba1d17ea86a49499e1f6b816fb0a389 | 3,646,234 |
import graph_scheduler
import types
def set_time_scale_alias(name: str, target: TimeScale):
"""Sets an alias named **name** of TimeScale **target**
Args:
name (str): name of the alias
target (TimeScale): TimeScale that **name** will refer to
"""
name_aliased_time_scales = list(filter... | 889f2b70735a11ce8330e58b7294d3d115334d5f | 3,646,235 |
def find_bounding_boxes(img):
"""
Find bounding boxes for blobs in the picture
:param img - numpy array 1xWxH, values 0 to 1
:return: bounding boxes of blobs [x0, y0, x1, y1]
"""
img = util.torch_to_cv(img)
img = np.round(img)
img = img.astype(np.uint8)
contours, hierarchy = cv2.fin... | 7b7de4d163b18b099721c39b69721e477c473c16 | 3,646,236 |
from typing import Optional
from datetime import datetime
def resolve_day(day: str, next_week: Optional[bool] = False) -> int:
"""Resolves day to index value."""
week = ['monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
... | d09aba564f0293ac8b92699427199998bf7e869f | 3,646,237 |
import logging
def get_gsheet_data():
"""
Get's all of the data in the specified Google Sheet.
"""
# Get Credentials from JSON
logging.info('Attempting to read values to Google Sheet.')
creds = ServiceAccountCredentials.from_json_keyfile_name('TrackCompounds-1306f02bc0b1.json', SCOPES)
lo... | 872671a1bc9b17fec5e6db3fb4a7172567da4eff | 3,646,239 |
def name_tensor(keras_tensor, name):
"""
Add a layer with this ``name`` that does nothing.
Usefull to mark a tensor.
"""
return Activation('linear', name=name)(keras_tensor) | 9ac83e8974efa2e48ab14d150a5da47ac7c23fb5 | 3,646,240 |
import operator
def pluck(ind, seqs, default=no_default):
""" plucks an element or several elements from each item in a sequence.
``pluck`` maps ``itertoolz.get`` over a sequence and returns one or more
elements of each item in the sequence.
This is equivalent to running `map(curried.get(ind), seqs)... | 9bb31f94115eec0ba231c3c2bf9c067a52efca52 | 3,646,241 |
def shape_metrics(model):
"""""
Calculates three different shape metrics of the current graph of the model.
Shape metrics: 1. Density 2. Variance of nodal degree 3. Centrality
The calculations are mainly based on the degree statistics of the current
graph
For more information one is referred to... | 003e72145ade222a7ec995eae77f6028527e8ba9 | 3,646,242 |
def calculate_actual_sensitivity_to_removal(jac, weights, moments_cov, params_cov):
"""calculate the actual sensitivity to removal.
The sensitivity measure is calculated for each parameter wrt each moment.
It answers the following question: How much precision would be lost if the kth
moment was ex... | 30f51ecc2c53126b6e46f5301bef857d104381cf | 3,646,243 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.