content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import resource
def read(hash, args={}):
"""
Read allowance by hash
"""
return resource.read(**{**{
'type': 'allowance',
'key': hash,
}, **args}) | 52889a507e367eefc283275c9f984597e0d88242 | 3,622,673 |
def predict(request: PredictRequest):
"""
Predict allergens from request
:param request: incoming api request
:return:
"""
check_model_exists(request)
response = modelResolver.predict(model_name=request.model,
data=preprocessor.process(request.data),
... | 6fa566ab36ac4f665a43ce06478acbfa6b4ec91b | 3,622,674 |
import numpy
def validate(data, labels, toStandardise=False,
overSamplingPercentages = None, toShuffle=False,
saveFile = False, randomState=None, samplingMethodology=smoteTransform, kfolds=10):
"""Generates data-points (fp and tp) for generating a ROC curve through oversampling and und... | 9ed24a7e7c8b30199d050e5ce8b8c0259cb8911e | 3,622,675 |
def is_select(a):
"""Return `True` if `a` is a Z3 array select application.
>>> a = Array('a', IntSort(), IntSort())
>>> is_select(a)
False
>>> i = Int('i')
>>> is_select(a[i])
True
"""
return is_app_of(a, Z3_OP_SELECT) | 712c1acc5984cf558eb46161d80c3a29f77fe7a6 | 3,622,676 |
def log_vector(tag, values):
"""
log_histogram
Logs a vector of values.
"""
values = np.array(values).flatten()
# Fill fields of histogram proto
hist = HistogramProto()
hist.min = 0
hist.max = len(values) - 1
hist.num = len(values)
hist.sum = float(np.sum(np.arange(hist.num)... | a0de2f0fef23ee555ea3d31095c4877203a0cc30 | 3,622,677 |
def subtract_mean_vector(frame):
"""
Re-center the vectors in a DataFrame by subtracting the mean vector from
each row.
"""
return frame.sub(frame.mean(axis='rows'), axis='columns') | 4a6207889b958aebd608c349ad889e109ab3f4a9 | 3,622,678 |
def reduce_level(ast):
"""
The function removes from the abstract syntax tree a declaration current level (pointer or array). For instance it
makes from AST of 'int *a' it makes AST for 'int a'.
:param ast: Current abstract syntax tree.
:return: Abstract syntax tree for the pointer or an array elem... | 6d7e61265555106efe9f0733ec5f40b51bdaedf8 | 3,622,679 |
def to_location(maiden: str, center: bool = False) -> tuple[float, float]:
"""
convert Maidenhead grid to latitude, longitude
Parameters
----------
maiden : str
Maidenhead grid locator of length 2 to 8
center : bool
If true, return the center of provided maidenhead grid square... | fddcbdab4f3e0f812dd7fac3509e66bc63f8fb84 | 3,622,680 |
def threshold_amplitude(x, metric, samples, percentile, frange, Fs, filter_fn=None, filter_kwargs=None):
"""
Exclude from analysis the samples in which the amplitude falls below a defined percentile
Parameters
----------
x : numpy array
raw time series
metric : numpy array
s... | a1e4165877862134f174c54f23ab14edf8290792 | 3,622,681 |
def opcode_by_value(val: int) -> OpCode:
"""
Mapping: Retrieves the OpCode object with the given value.
Throws:
LookupError: if there is no opcode defined with the given value.
"""
if val not in BYTECODES:
raise LookupError("No opcode with value '0x{:02X}'.".format(val))
return BY... | 8d438a282cb642dc409c7d14dd382433659304a3 | 3,622,682 |
import math
def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, numb... | 8ffd7ea8a1c019fbc8d3b78e634128af8cf8978c | 3,622,683 |
def flipDP(directionPointer: int) -> int:
"""
Cycles the directionpointer 0 -> 1, 1 -> 2, 2 -> 3, 3 -> 0
:param directionPointer: unflipped directionPointer
:return: new DirectionPointer
"""
if directionPointer != 3:
return directionPointer + 1
return 0 | 928347a5c1934c822c77434ca9a91d913ef7f3b5 | 3,622,684 |
def projection_type_validator(x):
"""
Property: Projection.ProjectionType
"""
valid_types = ["KEYS_ONLY", "INCLUDE", "ALL"]
if x not in valid_types:
raise ValueError("ProjectionType must be one of: %s" % ", ".join(valid_types))
return x | 049945caf31378648814034953dfab1ea8199816 | 3,622,685 |
def extract_dataset(filepath, dataset_name=''):
"""
extracts the dataset of the dataset you are interested in
:param filepath: the .mat filepath
:param dataset_name: the name of the dataset you are interested in
:return: a n-dimensional array for the dataset.
"""
# print(dataset_name)
wi... | 8cfafc898254490ed85660becb9b22985b751b04 | 3,622,686 |
def get_datatype(data):
"""
rules defining the sidtype, based on the data dict of the sid.
The keys are always given.
The values can be empty.
:param data:
:return:
"""
subtype = "project"
if "entity" in data.keys():
subtype = "entity"
if data.get("type"):
subt... | a7677db6d6aa9a9ccdcbdd9f6fd9d87032fcd18f | 3,622,687 |
async def app():
"""
For start gunicorn in production
:return:
"""
return create_app() | c49c61426914631db6ea79c0120e149e0222fed9 | 3,622,689 |
def pre_process_data_frame(data_frame, convert_categorical_to_numeric=False):
"""Pre-process the passed data frame"""
# replace the missing values
data_frame = replace_missing_values(data_frame)
# normalize numeric columns
data_frame = normalize_numeric_columns(data_frame)
# convert categori... | 34442a0558694a0693757eca437214290e845605 | 3,622,690 |
from datetime import datetime
def datestr(then, now=None):
"""
Converts a (UTC) datetime object to a nice string representation.
>>> from datetime import datetime, timedelta
>>> d = datetime(1970, 5, 1)
>>> datestr(d, now=d)
'0 microseconds ago'
>>> for t, v in {
... | 6087b5ef4299d0162fb61d6a243fceca65b21251 | 3,622,691 |
def main(input_file):
"""Solve puzzle and connect part 1 with part 2 if needed."""
inp = read_input(input_file)
transformations = get_all_transformations(inp)
p1 = part_1(inp, transformations)
print(f"Solution to part 1: {p1}")
p2 = part_2(transformations)
print(f"Solution to part 2: {p2}")
... | 0fe8bbc00c91f2af1574f1ae105873cd5b31448f | 3,622,692 |
def wshed_raw(labels, im):
"""
return wshed lines
"""
ia = lambda x: sitk.GetImageFromArray(x)
ai = lambda x: sitk.GetArrayFromImage(x)
feature_img = ia(im)
ws_img = sitk.MorphologicalWatershed(feature_img, level=0, markWatershedLine=True, fullyConnected=True)
ws = ai(ws_img)
ws = ws... | a147282e1c7a61fdc0428652c094f84818cf4ab5 | 3,622,693 |
def process_link(link):
"""
Get text and link from an anchor
"""
return link.text_content(), link.get('href') | 34429289076c8518b076fdf0f228eb6948109c6c | 3,622,694 |
from typing import Optional
from typing import Union
import json
def update_stack(
profile: Optional[Union[str, bool]] = False,
region: Optional[Union[str, bool]] = False,
replace: bool = False,
local_path: Union[str, bool] = False,
root: bool = False,
wait: bool = False,
extra: bool = Fal... | 5001ec30d3141d3598865e2496f775091435c603 | 3,622,695 |
from typing import Optional
def dot_product_attention(
query: jnp.ndarray,
key: jnp.ndarray,
value: jnp.ndarray,
*,
bias: Optional[jnp.ndarray] = None,
bias_kv: Optional[jnp.ndarray] = None,
broadcast_dropout: bool = True,
dropout_rate: float = 0.1,
dtype: jnp.dtype = jnp.float32,
... | c4c291f89b2744854c96b750550c771baa3bf92c | 3,622,696 |
def stringify_children(node):
"""Read and stringify the children of each nxml node."""
section_parts = []
for ch in node.getchildren():
string_text = ''
ch_tag = ch.tag
if ((ch_tag == 'title') or (ch_tag == 'p')):
sec_tree = ch.xpath("text()")
for txt in sec_tree:
txt = txt.rstrip()
if len(txt) >... | 82336915ea6b8451de430ec41ece94e21d08adc5 | 3,622,697 |
def convolutional_block(X, f, filters, stage, block, s=2):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for \
the main path
filters ... | bf16ba5429bf377fb048ccb863f0ab5c6c893ac3 | 3,622,698 |
from typing import Optional
def get_alarm_history_collection(alarm_historytype: Optional[str] = None,
alarm_id: Optional[str] = None,
timestamp_greater_than_or_equal_to: Optional[str] = None,
timestamp_less_than: Option... | 55dc491d63b9e1a28fde1b234d61abc4a204e6d0 | 3,622,699 |
def σ(input, axis=1):
"""Softmax on an axis
Softmax on an axis
Arguments:
input {Tensor} -- input Tensor
Keyword Arguments:
axis {number} -- axis on which to take softmax on (default: {1})
Returns:
Tensor -- Softmax output Tensor
"""
input_size = input.size()
... | 6642f7c4631877e2dd04a06af1b79d51a480f66e | 3,622,700 |
def get_xps_list(xps_dict):
"""Convert XPs from internal format to API format"""
xps_list = []
for (filetype, xp) in xps_dict.items():
item = dict(language=get_language_name(filetype), xp=xp)
xps_list.append(item)
return xps_list | 8b3e0f862e210fb10dac08e9cc6c2faf7be9a181 | 3,622,701 |
import numpy
def gesvdj(a, full_matrices=True, compute_uv=True, overwrite_a=False):
"""Singular value decomposition using cusolverDn<t>gesvdj().
Factorizes the matrix ``a`` into two unitary matrices ``u`` and ``v`` and
a singular values vector ``s`` such that ``a == u @ diag(s) @ v*``.
Args:
... | 786041c693f0eae14a9ac3a275f6369bedc18b53 | 3,622,702 |
def decide_collocational(accum):
"""
accum is the n-grams sized windows of list of tokens to be analysed.
N-grams size are given in function `decide`
Decide whether there is a collocational evidence against an intervening sentence boundary
"""
global CONTEXT_SIZE, collocations
center = CONT... | 579ff8ab1340ae35fd1fdddfeeb4fc01c99e0c4c | 3,622,703 |
import torch
from typing import Tuple
from typing import List
from pathlib import Path
def cluster_generated_images(
images: torch.Tensor,
activations: torch.Tensor,
selected_neuron_idx: int,
num_clusters: int = 8,
show: bool = False,
) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
"""Clus... | 2803f8e294f6e384e10d831e4ca5542246528ff2 | 3,622,705 |
def get_list_of_all_forks():
"""gets the list of all the forked repos"""
url = "https://api.github.com/orgs/mlh-fellowship/repos?type=forks"
all_repos = []
for i in range(1, 6):
each_url = url + '&page=' + str(i)
result = github_api(each_url)
for repo in result.json():
... | 762baa7d57be674b36b2938df0515922d97a09ff | 3,622,706 |
from numpy import interp
def linear(x, y, xref):
"""
Linear interpolation.
:param x:
:param y:
:param xref:
:return:
"""
return interp(xref, x, y, left=None, right=None, period=None) | 16ffc3dd0d73b8bdb395a067bb1962e70d9a255b | 3,622,707 |
from datetime import datetime
import pytz
import traceback
import json
def getMappedObjectsJson(request, object_name, filter=None, range=0, isLive=False, force=False):
""" Get the object json information to show in table or map views.
"""
try:
try:
THE_OBJECT = LazyGetModelByName(getat... | bc5e665cc3f285b62dd3747ed66bbe4d5f550ada | 3,622,708 |
def generate_grid_ds(
ds,
axes_dims_dict,
axes_coords_dict=None,
position=None,
boundary_discontinuity=None,
pad="auto",
new_name=None,
):
"""
Add c-grid dimensions and coordinates (optional) to observational Dataset
Parameters
----------
ds : xarray.Dataset
Dataset... | 4dfbfbf45fcfeed4b9d42772339f8d2323a7eec6 | 3,622,709 |
def slugify(value):
"""Coerce a value to a slug."""
if value is None:
raise vol.Invalid("Slug should not be None")
slg = utility_slugify(str(value))
if len(slg) > 0:
return slg
raise vol.Invalid("Unable to slugify {}".format(value)) | 4ed89a9300393a49b45f40ff9b77ba5c0163611b | 3,622,710 |
def is_td3_policy(policy):
"""Check whether a policy is for designed to support TD3."""
return policy in [
TD3FeedForwardPolicy,
TD3GoalConditionedPolicy,
TD3MultiFeedForwardPolicy,
] | c8250d8acfc09a7e219dc40ce936b74198a3ef20 | 3,622,711 |
def get_generator():
""" construct and return generator """
g_net = gluon.nn.Sequential()
with g_net.name_scope():
g_net.add(gluon.nn.Conv2DTranspose(
channels=512, kernel_size=4, strides=1, padding=0, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.L... | c29c3779f56d39e87b8ef8f53d92426f0be764c3 | 3,622,712 |
from typing import Type
def is_wrapped(env: Type[gym.Env], wrapper_class: Type[gym.Wrapper]) -> bool:
"""
Check if a given environment has been wrapped with a given wrapper.
:param env: Environment to check
:param wrapper_class: Wrapper class to look for
:return: True if environment has been wrap... | d3fa03f33d1ece76a8f43555e2feb9f2206ed9ab | 3,622,713 |
def get_appliance_nat_maps(
self,
ne_id: str,
cached: bool,
) -> dict:
"""Get Edge Connect appliance NAT maps configuration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - nat
- GET
- /nat/{neId}/maps?cache... | 320db1e240babd7998a1462669a7d5e36d69bebb | 3,622,714 |
def status() -> str:
"""Returns the status battery ('Full', 'Charging' or 'Discharging')"""
return _get_value("status") | ece2f4dec15c0d434d44cc712c0f00e1bd0a0754 | 3,622,715 |
def half_gauss_density(data, sd):
""" Takes a sequence of spike times and produces a non-normalised density
estimate by summing Half-gaussian (asymetric) defined by sd at each spike
time. The range of the output is guessed from the extent of the data (which
need not be ordered), the resolution is autom... | 83a45b64b0d411da0068260c3fee190032a8364d | 3,622,716 |
import json
def json_loader(file) -> dict:
"""
Returns json data given a valid filepath. Returns {} if error occurs
"""
try:
with open(file) as my_file:
data = my_file.read()
return json.loads(data)
except Exception as e:
capture_message(str(e), level="error")
return error_msg("T... | 4f772283435213919e0856545d9216395831be71 | 3,622,717 |
def get_user_by_email(db_session: Session, email: str) -> Users:
"""Get the User from its email."""
return db_session.query(Users).filter_by(email=email).first() | 4c1e55dc91ecb5bd5abfdc2de93565e0523ae4ea | 3,622,718 |
def merge_unique(list1, list2):
"""
Merge two list and keep unique values
"""
for item in list2:
if item not in list1:
list1.append(item)
return list1 | ecfd32178541dcb5956d4c1c74dc9cea2ab1fa45 | 3,622,719 |
def increment(number: int) -> int:
"""Increment a number.
Args:
number (int): The number to increment.
Returns:
int: The incremented number.
"""
return number + 1 | 27f4becd9afb747b22de991ab4cf030b14d3dac5 | 3,622,720 |
def mi(T, Y, num_classes=10):
"""
Computes the mutual information I(T; Y) between predicted T and true labels Y
as I(T;Y) = H(Y) - H(Y|T) = H_Y - H_cond_YgT
@param T: vector with dimensionality (num_instances,)
@param Y: vector with dimensionality (num_instances,)
@param num_classes: number of c... | e3dd7da0d19e481cd0df17e7ac344f540d83a2e0 | 3,622,721 |
import xml
def render(canvas, fobj=None, animation=False):
"""Render the SVG representation of a canvas.
Parameters
----------
canvas: :class:`toyplot.canvas.Canvas`
The canvas to be rendered.
fobj: file-like object or string, optional
The file to write. Use a string filepath to wri... | ed5088b354bce2bd080c1d6f16338e50ad8a6e2b | 3,622,722 |
def by_dist_time_speed(
move_data,
label_id=TRAJ_ID,
max_dist_between_adj_points=3000,
max_time_between_adj_points=7200,
max_speed_between_adj_points=50.0,
drop_single_points=True,
label_new_tid=TID_PART,
inplace=True,
):
"""
Splits the trajectories into segments based on distanc... | c5e56337bea0470ec690d20db0cf400c93b66cdd | 3,622,723 |
def stillinger_weber_neighborlist(displacement,
box_size=None,
A=7.049556277,
B=0.6022245584,
p=4,
lam=21.0,
epsilon... | 39e95d37a17b6f6efd8fbb09c393dc58a559af19 | 3,622,726 |
def sentences(s):
"""Split the string s into a list of sentences."""
try:
s + ""
except TypeError:
print "s must be a string"
pos = 0
sentence_list = []
l = len(s)
while pos < l:
try:
p = s.index('.', pos)
except:
p = l + 1
try:... | eb5fff5b7ba19ed80b55057a620f8c77652808e8 | 3,622,727 |
import functools
def skip_if_import_exception(function):
"""Assist in skipping tests failing because of missing dependencies."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except ImportError as err:
pytest.skip(str... | 4cac8c41fb48c1399d05d75489ea3152cb3561d1 | 3,622,728 |
def closest_pair(points):
"""
input: a list of points represented by tuples (x_coordinate, y_coordinate)
output: a tuple(the closest distance, the closest pair)
runtime: O(nlog(n))
"""
# sort only once, keep the sorted copy
points_x = sorted(points, key=lambda p: p[0]) # sort by x_coordinat... | 334bf1f339c768afd0f94afaace8010ed086a652 | 3,622,729 |
def CPP(record):
""" "Channel Process if Passive": a CP input link will be treated as
a channel access link and if the linking record is passive,
the linking passive record will be processed any time the linked record
is updated.
Example (Python source)
-----------------------
`my_record.IN... | 047f19b90e3eb89c8b6f298e1d4ecbf9b035040a | 3,622,730 |
def get_mcc_lite_v3(df_c, df_mc, base_call_cutoff):
"""
"""
# get mcc matrix with kept bins and nan values for low coverage sites
df_c_nan = df_c.copy()
df_c_nan[df_c < base_call_cutoff] = np.nan
df_mcc = df_mc/df_c_nan
return df_mcc | a136f8363343c37f182c82c196186dce2d9fb532 | 3,622,731 |
from typing import Optional
from typing import Sequence
from typing import get_args
def main(args: Optional[Sequence[str]] = None) -> int:
"""Main entrypoint."""
parsed_args, remainder_args = get_args(args=args)
# Detect which CI environment, if any, we are in
ci_env = detect_ci_platform(parsed_args,... | bbaf1bbe4a949e025ea7ce722a42686d80545178 | 3,622,732 |
def hist(x, bins=500, title=None, show=0, stats=0, ax=None, fig=None,
w=1, h=1, xlims=None, ylims=None, xlabel=None, ylabel=None):
"""Histogram. `stats=True` to print mean, std, min, max of `x`."""
def _fmt(*nums):
return [(("%.3e" % n) if (abs(n) > 1e3 or abs(n) < 1e-3) else
(... | 47adf36b72dc7bc36792392f5f4ef0d17bba912c | 3,622,733 |
def GetJValuesDataset( FileStr='GEOSChem.JValues.*', wd=None ):
"""
Wrapper to get NetCDF photolysis rates (Jvalues) output as a Dataset
Parameters
----------
wd (str): Specify the wd to get the results from a run.
FileStr (str): a str for file format with wildcards (?, *)
Returns
-----... | 2193662f766961b0c4eea523c3867f8ab9d2e253 | 3,622,734 |
def _h1_pdf_convex_decreasing_ ( h1 , degree , *args , **kwargs ) :
"""Parameterize/fit histogram with convex decreasing polynomial
>>> h1 = ...
>>> results = h1.pdf_convex_decreasing ( 3 ,)
>>> results = h1.pdf_convex_decreasing ( 3 , draw = True , silent = True )
>>> print results[ 0] ## fit r... | 6b7b57e13958d582e4993ed04cba42b63bd6052d | 3,622,735 |
def create_read_supported_services_cmd() -> list:
"""Create TaiSEIA device services request protocol data."""
return SAInfoRequestPacket.create(
sa_info_type=SARegisterServiceIDEnum.READ_SUPPORTED_SERVICES
).to_pdu() | 9fa199405e1d908210effbb015f9be04fdcba275 | 3,622,736 |
import re
def normalize_name(name: str) -> str:
"""Replace hyphen (-) and slash (/) with underscore (_) to generate valid
C++ and Python symbols.
"""
name = name.replace('+', '_PLUS_')
return re.sub('[^a-zA-Z0-9_]', '_', name) | 46624c7180b1303e715d73aefe75cdd8e49b4a22 | 3,622,737 |
def cross_validation(*, task,
pipeline,
X,
y,
cv_method,
metrics,
inverse=None):
"""
Performs cross validation.
-------------------------
Parameters
... | 8731f2a9a56b1bfdb1e2f0e970ca2a7da8892c68 | 3,622,738 |
def generate_host_key(args):
"""Generate SSH host keys with ssh-keygen."""
key_paths = [
args.output_dir / ssh_host_key_filename(algorithm)
for algorithm, _ in HOST_KEYS
]
okay = True
for key_path in key_paths:
if key_path.exists():
LOG.error('attempt to overwrit... | ef18a47336c5992a3f2aca7264591fb9511b4e67 | 3,622,739 |
from typing import Optional
def get_replication_configuration(registry_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetReplicationConfigurationResult:
"""
The AWS::ECR::ReplicationConfiguration resource configures the replication destinat... | e75d09f9a8fc1aee1f41c16215f4416c39cd96b3 | 3,622,740 |
import json
def _GetTokenScopes(access_token):
"""Return the list of valid scopes for the given token as a list."""
url = _OAUTH2_TOKENINFO_TEMPLATE.format(access_token=access_token)
response = apitools_base.MakeRequest(
apitools_base.GetHttp(), apitools_base.Request(url))
if response.status_c... | efe360444e535ca8735254d5ce38a9e63d399edc | 3,622,741 |
def sample(f1, f2, f3, f4):
"""
@see: field 1
@note : is it a field? has space before colon
@param f1: field 3 with an arg
@type f1: integer
@param f2 : is it a field? has space before colon
@return: some value
@param f3: another one
"""
return 1 | 20326992b0a03916b37360edc2a306df706075b3 | 3,622,742 |
def read_tree(attributes, data):
"""
Read the attibutes and create the pickle and tree files
"""
att_trees = []
index = 0
for attribute in attributes:
if attributes[attribute].get('qi', False):
if attributes[attribute].get('category', False):
categories = get_... | 2171a18a95886e4c94d8da355f2a087613947166 | 3,622,743 |
def cexpr_operands(self):
"""
return a dictionary with the operands of a cexpr_t.
"""
if self.op >= cot_comma and self.op <= cot_asgumod or \
self.op >= cot_lor and self.op <= cot_fdiv or \
self.op == cot_idx:
return {'x': self.x, 'y': self.y}
elif self.op == cot_tern:
... | 7817a77f2b6457a25bb28b4a4b8892625376a47d | 3,622,744 |
def define_model():
"""
This model is a little less accurate than the best one I found.
But it also has onlya quarter the paramenters so its a lot smaller.
"""
model = k.Sequential()
model.add(k.layers.Conv2D(filters=15, kernel_size=(3,3), strides=(1, 1), padding="valid", input_shape=(40, 24, 1)... | 965013329a0a76df67ca3aa7289267ade3c69d9f | 3,622,746 |
def volume_opt(src, dest, require=True):
"""Return a volume's argument for docker run
Don't use volume_opt with hard-coded linux paths, it will make Windows try and mkdir in
C:\\WINDOWS\\system32 and fail. volume_opt can handle C:\\... syntax correctly. Instead,
just use '-v /linux/path:/mount/point an... | b4c8d807b600c8c9767b2da0243575f24f4a81f3 | 3,622,747 |
import math
def _project_rf(input, output, offset_x=0, offset_y=0, return_pos=False):
"""Project one-hot output gradient, using back-propagation, and return its bounding box at the input."""
# create one-hot output gradient tensor, with 1 in the center (spatially)
pos = [0] * len(output.shape) # index 0th bat... | e1067692ab5f615e7a1d930c6a614b917101e5a5 | 3,622,748 |
def fill_ts_missing_entries(start, end, timeseries, interpolation_method, timestep):
"""
:param start: "YYYY-MM-DD HH:MM:SS" the starting timestamp of the timeseries index
:param end: "YYYY-MM-DD HH:MM:SS" the last timestamp of the timeseries index
:param timeseries: list of [time, value] lists
:pa... | b2d7db300db835a807ac372ee818a2f6af729919 | 3,622,749 |
def play_game(iterations, initialize_game):
"""
Simulate gameplay and record number of rounds and trains used each time
"""
winners = []
records = {}
for i in range(iterations):
record = {}
game, players = initialize_game()
record["deck"] = game.cards
record["des... | 3e2813d17bea49336fd3bc4b5b88125161cec318 | 3,622,750 |
import unittest
def check_tf_min_version(min_required_version, message=""):
""" Skip if tf_version < min_required_version """
config = get_test_config()
reason = _append_message("conversion requires tf >= {}".format(min_required_version), message)
return unittest.skipIf(config.tf_version < LooseVersio... | 90f1856c7c1720be3b164a26e1225ade43e38c00 | 3,622,751 |
from typing import Union
def filt2(
kernel: np.ndarray,
im1: np.ndarray,
reflect_style: Union[str, int, float] = "odd",
) -> np.ndarray:
"""
Improved version of filter2 in MATLAB, which includes reflection.
Default style is 'odd'. Also can be 'even', or 'wrap'.
Args:
kernel: Kerne... | fb8d5b29b2c04875e5074fa76ed7c70ddd453561 | 3,622,752 |
def getAccountASABalance(account: Addr, assetId: Int) -> TealType.uint64:
"""
This subroutine returns the amount of ASA held by a certain
account. Note that the asset id must also be passed in the ``foreignAssets``
field in the outer transaction (otherwise you will get a reference error)
:param Add... | 88342a2c7653be4b2ada06cc1fd4e2f47fe3120a | 3,622,753 |
import re
def get_package_version():
"""get version from top-level package init"""
version_file = read('pywcmp/__init__.py')
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
ra... | 5cb15a4cc785f11e79772cfddf88d059aec781e6 | 3,622,754 |
def copyFilesToEOS(directory, destination, filenames):
""" Copy the given filenames to EOS.
Files which failed are returned so that these files can be saved and the admin can be alerted to take
additional actions.
Args:
directory (str): Path to the directory where the files are stored locally.... | acf6e623c5fcbe0a99839cb398415b308f26674b | 3,622,755 |
from datetime import datetime
def random_date_strf() -> str:
"""Generate a random date."""
year = random_year()
day_of_year = random_day_of_year(year=year)
return datetime.strptime(f"{year}-{day_of_year}", "%Y-%j").strftime("%Y-%m-%d") | 9024f67de3ba6e99e2327ff24005eb61628b6829 | 3,622,756 |
def __sample(data, labels, sampling_rate):
"""subsample data"""
indices = []
for i in set(labels):
idxs = [x for x in range(len(labels)) if labels[x] == i]
n = len(idxs)
s = int(np.ceil(len(idxs) * sampling_rate))
aux = np.random.permutation(n)[0:s]
indices += [idxs[x... | 8cf48e251dc2498f659998c020cd2bc07125dd5b | 3,622,757 |
def format_span_json(span):
"""Helper to format a Span in JSON format.
:type span: :class:`~opencensus.trace.span.Span`
:param span: A Span to be transferred to JSON format.
:rtype: dict
:returns: Formatted Span.
"""
span_json = {
'displayName': _get_truncatable_str(span.name),
... | 38d49fe859c05e1032573f0bd208a1f960cf89d0 | 3,622,758 |
import json
async def main(req: func.HttpRequest, starter: str) -> func.HttpResponse:
"""This function starts up the orchestrator from an HTTP endpoint. It retrieves
the user requested entity state and returns it back as a HTTP response.
Args:
req (func.HttpRequest): An HTTP Request object, it ca... | 4fca83553d0e7317e7261735d7e2f48927fe01ed | 3,622,759 |
import math
import PIL
def slide_to_img(slide, new_mpp=0.5, return_np=True, return_sizes=False):
"""
Scale slide image based on desired microns per pixel
"""
old_mpp_x = np.float(slide.properties['openslide.mpp-x'])
old_mpp_y = np.float(slide.properties['openslide.mpp-y'])
new_mpp = np.fl... | a0f4dd8afaa97049c7e12920176534599b6525e9 | 3,622,760 |
def get_table2(res):
"""
Puts columns for table 2 together in a Dataframe and adds labels
Args:
res(list): list of arrays containing the subject
specific paramater estimates
Returns:
table2(Pd.DataFrame): Dataframe containing table 2
"""
rownames = [
"mean... | 6af5e40dcc5107ee42520afb330066ac309dc9c4 | 3,622,761 |
def decode_dist_anchor(det_residual, det_angle_cls, det_angle_res, batch_anchors_3d, is_training):
"""
Decode bin loss anchors:
Args:
det_residual: [bs, points_num, 6]
det_angle_cls: [bs, points_num, -1]
det_angle_res: [bs, points_num, -1]
batch_anchors_3d: [bs, points_num, 7... | cc91f9c7b4730b364b99424aa8d8c7db4b58a2eb | 3,622,762 |
def refund_query():
"""
swagger-doc: 'do refund query'
required: []
req:
page_limit:
description: 'records in one page 分页中每页条数'
type: 'integer'
page_no:
description: 'page no, start from 1 分页中页序号'
type: 'integer'
order_id:
description: '订单编号'
... | 3971df1ef82b54055bbaa2e259846b488f16bc73 | 3,622,763 |
def dist_to_pixel(val_dist, mode,
d_max=D_MAX, d_min=D_MIN):
""" Returns pixel value from distance measurment
Args:
val_dist: distance value (m)
mode: 'inverse' vs 'standard'
d_max: maximum distance to consider
d_min: minimum distance to consider
Returns:
... | 3253d07cf69db7eb8685f8c6b1751bd38f6d431f | 3,622,765 |
import math
def normal_probability_plot(data):
"""Plot the distribution of normal probabilities of errors."""
norm = distributions.normal_distribution()
n = len(data["delta_hl"])
if n <= 10:
a = 3 / 8
else:
a = 0.5
y = flex.sorted(flex.double(data["delta_hl"]))
x = [norm.... | 371521d576a0d8b6c6fd2c94952cca290cbec24f | 3,622,767 |
import time
def save_data_with_time_stamp(signal):
"""
Save signal in time-stamped file.
Creates a filename using the current time.
Args:
signal: array of ellipsometer readings
Returns:
filename of the file created
"""
t = time.localtime()
time_stamp_name = time.strft... | b10cf9c2b70b96e116f1def611fe180edf5ed8e7 | 3,622,768 |
import math
def calc_vega(
asset_price, asset_volatility, strike_price, time_to_expiration, risk_free_rate
):
"""The first-order partial-derivative with respect to the underlying asset volatility of
the Black-Scholes equation is known as vega. Vega refers to how the option value
changes when there is ... | 6c97dc9f29b355935be4232e4872db870c943117 | 3,622,769 |
import urllib
import requests
def get_short_doi(doi, cache={}, verbose=False):
"""
Get the shortDOI for a DOI. Providing a cache dictionary will prevent
multiple API requests for the same DOI.
"""
if doi in cache:
return cache[doi]
quoted_doi = urllib.request.quote(doi)
url = 'http... | 53f3f17fffd7ede782f441fa9845b2da5eb3fdd4 | 3,622,770 |
def calculate_payments(yearly_payments_percentage, cost_reductions,
days_with_payments, days_for_discount_rate):
""" Calculates payments for a participant/investor """
return [period_payment(yearly_payments_percentage, ccr,
days_with_payments[i], days_for_disco... | b5a5facb5cbbbbba67892477fc78c1e992ec51f7 | 3,622,771 |
def draw_random(G, **kwargs):
"""Draw networkx graph with random layout.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See hvplot.networkx.draw() for a description of optional
keywords, with the exception of the pos parameter which is not
us... | 1fd4a60455574e94c59d350de5926d9b9226d5c7 | 3,622,772 |
def test_preprocessor_visit_one_children(patch, magic, preprocessor):
"""
Check that a single inline_expression is found
"""
tree = magic()
c1 = magic()
replace = magic()
c1.children = [magic()]
tree.children = [c1]
def is_inline(n):
return n == c1
preprocessor.visit(tre... | 4e450c7dbeff77069281fb63d495f0e4770f5fd3 | 3,622,773 |
def connect_to_contract(address):
"""Helper function for connecting to a contract at an address"""
url = "https://mainnet.infura.io/v3/1a09c4705f114af2997548dd901d655b"
endpt = RPCEndpoint(network=network, provider=provider, url=url)
endpt.connect()
c = Contract(node=endpt, address=address, abi=tel... | d07905be0dadbf3bc64d1370bbccef77b5bf84d0 | 3,622,774 |
import json
import select
def get_user():
"""Retreives a single user from a Database, and render it using a HTML template"""
try:
data = json.loads(request.data)
except ValueError:
return '', 400
else:
email = data['customer']['email']
# For more complex queries, consider ... | 6efe5059c36eb6f28a96af49748be56cd5e2eb10 | 3,622,775 |
import base64
def decrypt(key, enc, use_base64=True):
"""Optionally base64-decode and decrypt."""
decoded = enc
if use_base64:
decoded = base64.b64decode(enc)
raw = _cipher(key).decrypt(decoded)
return _unpad(raw).decode("utf-8") | e3c62ff9cacc8977c0b622a54da809ac5ff835e3 | 3,622,777 |
def create_rng(random_state):
"""
Creates a random state object
Parameters
----------
random_state : int or NoneType or np.random.RandomState
Input to create RNG
Returns
-------
rng : np.random.RandomState
Pseudo-random number generator
"""
if random_state is N... | c6712ae2efe79e90b458b26c685d815e8e1888d6 | 3,622,778 |
def read_header(file_handle):
"""Reads a CPHD header from a file.
Parameters
----------
file_handle
Readable File object, i.e., ``file_handle = open(filename, 'rb')``.
Handle of the CPHD file that is to be read
Returns
-------
Dict
Dictionary containing CPHD header val... | 533b9041d90e8980dd23cfcde6a4bdc57a532bf8 | 3,622,779 |
async def validate_input(hass: core.HomeAssistant, conf):
"""Validate the user input allows us to connect."""
try:
info = await async_get_discovery_info(
hass,
conf[CONF_HOST],
conf[CONF_PORT],
conf.get(CONF_SECURE, False),
conf[CONF_ACCESS_TOK... | 5afaf296c151b0dd1a35b376a49a8d4f4bc10b29 | 3,622,780 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.