content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
def valid_region(images, mask_value=None):
"""
Return valid data region for input images based on mask value and input image path
"""
mask = None
for fname in images:
logging.info("Valid regions for %s", fname)
# ensure formats match
with rasterio.open(str(fn... | 303b8f51f09c75f288db12afac9d37e771b5bd0c | 78,781 |
import click
def load_model(path_or_handle):
"""Read a metabolic model.
Adapted from cameo.
Parameters
----------
path_or_handle : path
file path of a model file
"""
if isinstance(path_or_handle, str):
# Open the given file
path = path_or_handle
handle = ... | c75eb566e725292897371e81d068e9d63ea75c9b | 78,782 |
def euclidean_distance(v: Vector, w: Vector) -> float:
""" """
distance = 0.0
for i in range(len(row1)-1):
distance += (row1[i] - row2[i])**2
return sqrt(distance) | 01f328d7f973e64ad2132690d010dcfc87265292 | 78,783 |
def caller_to_colour(calls):
"""
Assign colours to different callers in the input file
Set the attribute of the class instances
return a list of indices for which each caller is found uniquely and all callers
sorted by callers
"""
colours = plt.rcParams['axes.prop_cycle'].by_key()['color'] ... | c63a38fc323b1f5e2b1776a5094136f668b14825 | 78,784 |
def array2colormap(x, cmap='inferno', clim=None, alpha=1.0, vmin=None,
vmax=None, under='dimgray', over='darkred',
translucent=None, faces_render=False):
"""Transform an array of data into colormap (array of RGBA).
Parameters
----------
x: array
Array of da... | f511472c975f19073cf704300f4fa68dfc6f95b5 | 78,787 |
def build_bell_circuit():
"""Returns a circuit putting 2 qubits in the Bell state."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
return qc | 4cbe1a1f4abeaee51fb4ba0e092c4b0203350c94 | 78,790 |
def align_by_eq(lines):
"""make a nice aligned unit file """
max_len, out, kvs = 0, [], []
def add_kvs(out, kvs, m=0):
if not kvs:
return
kls = [len(kv[0]) for kv in kvs if isinstance(kv, tuple)]
if kls:
m = max(kls)
ind = ' ' * (m + 3)
for kv... | bfc51541b2522411a45e9c7626122a25a371e8fb | 78,791 |
import re
def framework_version_from_tag(image_tag):
"""Extract the framework version from the image tag.
Args:
image_tag (str): Image tag, which should take the form
'<framework_version>-<device>-<py_version>'
Returns:
str: The framework version.
"""
tag_pattern = re... | 0afa3f81b39e83d27add154fc1040da451469255 | 78,793 |
def test_compute_cycle_error_unknown_GT() -> None:
"""Ensure cycle error is computed correctly within a triplet, when ground truth is known.
Imagine 3 poses, all centered at the origin, at different orientations.
Ground truth poses:
Let i0 face along +x axis (0 degrees in yaw)
Let i2 have a ... | fa0219255801eb99dfc8c64b207ee4f2ffe13bd6 | 78,794 |
def txout_decompress(x):
""" Decompresses the Satoshi amount of a UTXO stored in the LevelDB. Code is a port from the Bitcoin Core C++
source:
https://github.com/bitcoin/bitcoin/blob/v0.13.2/src/compressor.cpp#L161#L185
:param x: Compressed amount to be decompressed.
:type x: int
:return: T... | f34dc5e830f5dee6367022b39e7bee8fe7e9d748 | 78,797 |
def map_china(ax=None, lakes_and_rivers=False, xticks =[80, 90, 100, 110],
yticks=[30, 35, 40, 45, 50], ):
"""
DESCRIPTION
===========
Draws a maps of china including administrative districts.
Takes a cartopy.geoaxes as argument
USAGE
=====
ax = map_te... | bbe81e4ba6ade5171a1b1f11bfe8441592eb2359 | 78,798 |
def parse_value(s):
"""
Quick-and-dirty way to parse C-style float literal strings into d-attribute
compatible strings.
"""
if s.endswith("f"):
return s[0:-1]
else:
return s | 4464cc49137a198c8ac0707f6a5d0cafc82b758f | 78,799 |
def evalRec(env, rec):
"""Quality check"""
if rec.Proband_GQ < env.gq:
return False
elif rec.FS > env.fs:
return False
elif rec.QD < env.qd:
return False
return True | b76525a4078d77db28edd3e8623b9641fabc96bb | 78,800 |
def read_icd_list(infile, G, conv, children=True):
"""
Read a list of ICD-10 codes, and gather all children
"""
with open(infile) as f:
terms = f.readlines()
terms = [x.rstrip() for x in terms]
children = [get_children(G, conv[t]) for t in terms]
children = [item for sublist in... | d4860e7f6b69b2118986e87efe16bac764b31f43 | 78,801 |
import hashlib
def sha1sum(input_file_name):
"""Computes the SHA1 hash of a binary file
Returns the digest string or '' if an error occurred reading the file"""
chunk_size = 1048576 # 1 MB
file_sha1 = hashlib.sha1()
try:
with open(input_file_name, "rb") as f:
byte = f.read(chun... | e8d1b0379bb9fc13eb0324dfe5b2a24935e7ad54 | 78,802 |
from typing import List
def collect_executable_variable_definitions(
schema: "GraphQLSchema", operation: "OperationDefinitionNode",
) -> List["ExecutableVariableDefinition"]:
"""
Go recursively through all variable definition AST nodes to convert them as
executable variable definition.
:param sche... | cc43e66e4827fc6303b924cdf27cc6919447ce7d | 78,803 |
def computeStop():
"""Stop the execution of a workflow.
---
tags:
- services
consumes:
- application/json
parameters:
- name: signature
in: query
description: Signature of (consumerAddress+jobId+documentId) to verify the consumer of
this compute job/ass... | 0b288fd1c6aec9eb8f677dea41764cf79d7f88e7 | 78,804 |
def load_los_lookup(path=FLOOKUP):
"""
Return line of sight lookup at path.
Parameters
----------
path (optional: str): Path to los lookup file containing xarray.Dataset
Returns
-------
los_lookup (4D array): Shadow lookup (dims: rms, cinc, az, theta)
"""
try:
ext = pat... | d0b98c14ecfbdf827379b6abca1d418d795b33d9 | 78,805 |
import gettext
import locale
def get_i18n_content(fmt, local, **kw):
"""
Get multilingual data structure according to format parameter id.
reference
- https://docs.python.org/2/library/gettext.html
:param fmt: Multilingual key string. like _('This is a translatable string.')
:param l... | f43523517978cb14c4664f17b7eef28b29d413ad | 78,807 |
def uncompress_dimension(indptr,indices):
"""converts an index pointer array into an array of coordinates"""
uncompressed = np.empty(indices.shape[0],dtype=np.intp)
position = 0
for i in range(len(indptr)-1):
inds = indices[indptr[i]:indptr[i+1]].shape[0]
uncompressed[np.arange(position... | f6abec2f088af46ac169f662270610a728c7fba8 | 78,808 |
def regs_as_vals(int_dependant_init):
""" Decorates a function so arguments of type register are converted to their int values. """
def get_register_value(arg):
if isinstance(arg, ArmRegister):
return arg.value()
else:
return arg
def new_init(self, *args, **kwargs):
... | 5781aa119f9973c6375c3e6dbae26867a121047b | 78,810 |
from typing import NamedTuple
def move_api_columns_to_end(
df: pd.DataFrame,
api_column_names: NamedTuple,
error_handling: ErrorHandlingEnum = ErrorHandlingEnum.LOG,
) -> pd.DataFrame:
"""
Move non-human-readable API columns to the end of the dataframe
"""
api_column_names_dict = api_colum... | 3e7c6805752cc95feb75e238d27de15fd44fb796 | 78,811 |
def signRFC6979(privateKey, inHash):
"""
signRFC6979 generates a deterministic ECDSA signature according to RFC 6979
and BIP 62.
"""
N = Curve.N
k = nonceRFC6979(privateKey, inHash, ByteArray(b''), ByteArray(b''))
inv = crypto.modInv(k, N)
r = Curve.scalarBaseMult(k)[0] % N
if r ==... | b859dca80a8152f2585012211008f38c43162f1e | 78,812 |
def get_tool_shed_repository_status_label( app, tool_shed_repository=None, name=None, owner=None, changeset_revision=None, repository_clone_url=None ):
"""Return a color-coded label for the status of the received tool-shed_repository installed into Galaxy."""
if tool_shed_repository is None:
if name is ... | d099cc8b2073834cf6f0a8df42d93e512b4a05eb | 78,813 |
from typing import Sequence
from typing import Optional
from typing import List
import functools
import operator
def tensor_buffer_to_list_of_tensors(
x: oneflow._oneflow_internal.BlobDesc,
out_shape: Sequence[int],
out_dtype: flow.dtype,
dynamic_out: Optional[bool] = False,
name: Optional[str] = ... | f9856c716c06d6d341c525ff296df6a5af32f4b1 | 78,814 |
def softmax_loss(x, y):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth
class for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Re... | b78933a9f991acb583e4e5a6461a7ceb68c47bd4 | 78,815 |
def get_uppercase_string(str_len):
"""
Generates a random upper case string eg. BHJBVYDFOWEKLS
"""
str_len = check_string_length(str_len)
return generate_random_sample(UPPER_CASE_LETTERS, str_len) | e343c485a85ff2cf31055e1943f52e67bd127b48 | 78,816 |
def register(tag):
"""Registers converter by given tag."""
def reg(cls):
"""Registers given class."""
CONVERTERS[tag] = cls
CONVERTERS[tag.lower()] = cls
CONVERTERS[tag.upper()] = cls
return cls
return reg | bb51d968c27332d3a96e6e34e30f9e817e74aa01 | 78,817 |
def main():
"""
main function
"""
print(args)
if args.proto == None or args.model == None or args.mean == None or args.images == None:
usage_info()
return None
# deploy caffe prototxt path
net_file = args.proto
# trained caffemodel path
caffe_model = args.model
... | 820b8055c06811675239800bae6dd76eee6e0826 | 78,818 |
import statistics
def _skew(values):
""" This function calculates the skew value of the list
of values which represents the difference between the mean
and median which also corresponds to the skewness.
Using the following formula ,
(1/((n-1)*(n-2)))*(sum over i { ((values[i]-mean(values))/(std_dev))**3) }
n ->... | bf564cc138a9e7a2196793fb4b27b00ed6ab4599 | 78,819 |
def random_scale(img_scales, mode='range'):
"""Randomly select a scale from a list of scales or scale ranges.
Args:
img_scales (list[tuple]): Image scale or scale range.
mode (str): "range" or "value".
Returns:
tuple: Sampled image scale.
"""
num_scales = len(img_scales)
... | 9a1d2cc0d83f68d0b3d2a93a24ecc98adbdc1edd | 78,820 |
def _driver(path=''):
"""
:param path: default path atual
:return: o driver para fechar no loop
"""
link = "Chromedriver/chromedriver.exe"
chrome_options = Options()
# chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-notifications")
chrome_options.add... | 7294b24f0823aa92b4caaa6ed097f017b2b2966e | 78,821 |
def rotoreflection(angle: float, axis: Array) -> PGSymmetry:
"""Returns a rotoreflection by `angle` degrees around `axis`."""
angle = np.radians(angle)
axis = np.asarray(axis) / np.linalg.norm(axis)
rot_matrix = (
np.cos(angle) * np.eye(3)
+ np.sin(angle) * np.cross(np.eye(3), axis)
... | e8ec842e72193e1d86a67c43053c77b73592a7b0 | 78,822 |
def decode(value, encoding='utf-8'):
"""Decode given bytes value to unicode with given encoding
:param bytes value: the value to decode
:param str encoding: selected encoding
:return: str; value decoded to unicode string if input is a bytes, original value otherwise
>>> from pyams_utils.unicode im... | 8cef7b6d0367d5bff48f5c9b9cb2b5d7c4a883d9 | 78,824 |
from typing import Dict
def values_from_bucket(bucket: Dict[str, float]) -> set:
"""Get set of price formatted values specified by min, max and interval.
Args:
bucket: dict containing min, max and interval values
Returns:
Formatted set of values from min to max by interval
"""
rng = ... | 848af64d3396cc77c3fa109821d72eb80961eec0 | 78,825 |
import json
def arg_string_from_dict(arg_dict, **kwds):
"""
This function takes a series of ditionaries and creates an argument
string for a graphql query
"""
# the filters dictionary
filters = {
**arg_dict,
**kwds,
}
# return the correctly formed string
ret... | ea5d2a393e55cc104311e657758076587c78373e | 78,826 |
def shout_all(word1, word2):
"""Return a tuple of strings"""
# Concatenate word1 with '!!!': shout1
shout1 = word1 + '!!!'
# Concatenate word2 with '!!!': shout2
shout2 = word2 + '!!!'
# Construct a tuple with shout1 and shout2: shout_words
shout_words = (shout1, shout2)
# Ret... | 222f825daca03e7525e4269e9a6bdbee52c38421 | 78,827 |
def df_to_formatted_json(df, sep="."):
"""
The opposite of json_normalize
"""
result = []
for idx, row in df.iterrows():
parsed_row = {}
for col_label, v in row.items():
keys = col_label.split(".")
current = parsed_row
for i, k in enumerate(keys):... | 7d89a99e02e019c7c960fb176408ce1cd95c98be | 78,828 |
def conv_2d(incoming, nb_filter, filter_size, strides=1, padding='same',
activation='linear', bias=True, weights_init='uniform_scaling',
bias_init='zeros', regularizer=None, weight_decay=0.001,
trainable=True, restore=True, reuse=False, scope=None,
name="Conv2D"):
"""... | 8e37afea76a1e426d6b1c5c0e2fd80b809d27e27 | 78,829 |
def resolve(obj):
"""
Helper function.
Check whether the given object is callable. If yes, return its return
value, otherwise return the object itself.
"""
return obj() if callable(obj) else obj | 80172ffce9c5f5fe8699980ad86a98794b4d436c | 78,830 |
def valid_email(mail):
"""
Checks if the mail is valid
Parameter:
------
mail: string
the email address to check
Return:
------
- true or false
"""
if (
validate_email(mail)
and mail.find("help") == -1
and mail.find("info") == -1
and mail... | 6a48c54df00e7f60745a457311c39ef158a6c58b | 78,831 |
import logging
import collections
def get_mapping_per_user(fn):
"""
mapping_per_user is {'user_id': [{'user_id': xxx, 'image_id': xxx, 'class': xxx} ... {}],
'user_id': [{'user_id': xxx, 'image_id': xxx, 'class': xxx} ... {}],
} or
[{'user_i... | 750337ce325cb1a49e423d71afd46bf29ae6eb17 | 78,832 |
def get_si_factor(ci, li, conc='ini19'):
"""S_i factor defined in FONDECYT Regular or Iniciacion"""
# import pdb; pdb.set_trace()
if conc in ['ini19', 'reg19']:
si = li*((1 + ci)**0.5)
else:
raise ValueError('Not implemented for this concurso: {}.'.format(conc))
return si | 95e0b8f932d14ae6212b299e2331881877f425c6 | 78,834 |
def index(request):
"""
Some description here.
"""
if not request.user.is_authenticated:
return redirect('/')
context = {}
context['resource_url'] = request.session.get('resource')
token_manager = TokenManager(
resource=request.session.get('resource'),
... | bc3e002aeb3864dfba6e01bde9ee904257410def | 78,835 |
import re
def attrs_from_mmm(mmm):
"""Returns dictionary of attributes from MMM file."""
def convert_tags(tree):
"""Converts MMM attribute tags into their associated HTML tags."""
for tagname in 'keyword', 'const', 'var', 'mono':
for element in tree.iterfind('.//' + tagname):
... | 0a4035721df2f9cedb3110ad1a2c99b3f176919d | 78,836 |
def compute_max_addresses(DZG,tile_size,level,overlap):
"""
input:
- Tile generator DZG
- The size of the tile
- the level of observation
- the value of overlap
output:
- the max value of the adresses for a tile in the slide
"""
lvl_dim = DZG.level_dimensions
#size of t... | 0e823a9b3581172cca1d75d2f3c48b22ad52aa34 | 78,839 |
def tcp_session(address, port: int =7450):
"""Create a msgpack-rpc session from a tcp address/port."""
return session("tcp", address, port) | 4b725922b1a6af28b4e4afcc0bcac5e674ad8e57 | 78,840 |
def read_and_preprocess_image(path,width,height):
"""Reads image from path using ``PIL.Image``.
Args:
path (str): path to an image.
Returns:
PIL image
"""
RandErasing = RandomErasing()
got_img = False
rgb_mean = [0.485, 0.456, 0.406]
rgb_std = [0.229, 0.224, 0.225]
... | 56d16125df9c25078e9621e1e211373767c53716 | 78,841 |
async def get_all_poketypes():
"""
## Retrieves a PokeType List.
Path Parameters
---------------
None
Body Parameters
---------------
None
Returns
-------
List[PokeType]
"""
return await PokeTypeRepository.get_all() | 2905f6ddf3cbf750e2d6fb071fb91ecd1a85afb5 | 78,842 |
from netCDF4 import Dataset
import numpy as np
def extractZtVariableFromNetcdfFiles(variable, listOfFilenames, numFiles, numAltitudes):
""" Pull one profile per netcdf file and glue them together in an array."""
# Find number of time steps in each simulation
data = Dataset( listOfFilenames[0], "r" ) ... | ea1c5b18191b5e22a7c0a1b6837906d80f2fd3c1 | 78,843 |
def unwarpProj(img, fname, imgpoints, scale=1):
"""
Unwarps the image through rotation, flipping, Matrix Transformation (M) and saves it as a file.
Args:
img (Array): Array of the image to unwarp
fname (str): Filename of the newly created image
imgpoints (ArrayofArrays): Imagepoints... | db69a2b2df9fef6699f9b143aa169eccf31d0b12 | 78,844 |
def drivers_license_raw():
"""Post an image file for text data to be extracted
Parameters
----------
None
Returns
-------
json format - text data extracted from the image png or jpg
"""
imagefile = request.files.get('imagefile', None)
text = ''
if n... | c523244471f954b394b6504ad80a2de8b2a11166 | 78,846 |
def camel_dict_to_snake_dict(camel_dict, reversible=False, ignore_list=()):
"""
reversible allows two way conversion of a camelized dict
such that snake_dict_to_camel_dict(camel_dict_to_snake_dict(x)) == x
This is achieved through mapping e.g. HTTPEndpoint to h_t_t_p_endpoint
where the default woul... | 31d7b43bb1b371d6395f5bb90b5f272710a62625 | 78,847 |
def quadrant_scatter(df
, x='Out_degree_wg'
, y='In_degree_wg'
, z='Pagerank'
, skip = None
, prefix = 'Rank of'
, divide_canvas = True
, annotate = True
):
... | 98d0dae587eb6443f4f368aaa97e74d26f82cc74 | 78,849 |
def length_is(value, arg):
"""Returns a boolean of whether the value's length is the argument."""
try:
return len(value) == int(arg)
except (ValueError, TypeError):
return '' | b2e80ffb2f0834e0d2999eb60235b85304f0dcd4 | 78,850 |
from typing import Tuple
def Analyze_list(Population_list: list, num_states: int, **kwargs) -> Tuple[list, list, float]:
""" This function runs the analyze for the case when we want to fit the experimental data. (fig 11)"""
tHMMobj_list = [tHMM(X, num_states=num_states, **kwargs) for X in Population_list] #... | 4fb35c006f8f20d38b332f9b17a85fbf0cbf8b16 | 78,851 |
def _numeric_arrays(arrays, kinds='buifc'):
"""
See if a list of arrays are all numeric.
Parameters
----------
ndarrays : array or list of arrays
arrays to check if numeric.
numeric_kinds : string-like
The dtypes of the arrays to be checked. If the dtype.kind of
the ndar... | 7cd326227f00d256866a1aca8606ca215822c414 | 78,852 |
def transform_data(node, **kwargs):
"""Transforms a RELAX NG data into a new XML structure
"""
data_type = etree.Element("type")
data_type.attrib["name"] = node.get("type")
return data_type | d54253765c04fee6d6c693f2fc040f1004c95b47 | 78,853 |
def plotprepare(p, q, nel0, nel1, C0, C1, P, W, plotpoints):
"""
Build re-usable X and Y arrays for plotting.
"""
l = plotpoints.size
B0 = al.bernstein(p, plotpoints)
B1 = al.bernstein(q, plotpoints)
N0 = np.einsum("ijl, kl", C0, B0)
N1 = np.einsum("ijl, kl", C1, B1)
arrshape = np.a... | b03378a59b906d2071d604b32ee4639c5e270dbe | 78,854 |
def initialize_system_data(websession):
"""Setup default config and create folders."""
config = CoreConfig(websession)
# homeassistant config folder
if not config.path_config.is_dir():
_LOGGER.info(
"Create Home-Assistant config folder %s", config.path_config)
config.path_co... | 4c8af640f73ab02a48d269580cb7de4cbafd9a9a | 78,855 |
def adaptive_avg_pool2d_annotate_fn(expr): # pylint: disable=unused-variable
"""Check if nn.adaptive_avg_pool2d is supported by TensorRT."""
attrs, args = expr.attrs, expr.args
if not is_supported_trt_dtype(args):
return False
if len(attrs.output_size) == 0 or any([size != 1 for size in map(in... | 803f1eef5fb8eec189d11c9f5ff2a0bafb90cb9c | 78,856 |
def check_class_method(obj, name):
"""
检查对象是否有某个属性
:return:
"""
try:
return getattr(obj, str(name))
except Exception as e:
print(f"对象{obj} 没有方法{str(name)}")
return None | 45c323db327f08a7c70fb4935aad3524fe491a0a | 78,857 |
def mark_as_skip(case_ids, skips):
"""Mark cases to skip.
:param case_ids: Parameter list for pytest.mark.parametrize.
:param xfails: List of parameters in case_ids to mark for skip.
:return: case_ids with added marks.
"""
return _mark_cases(case_ids, xfails, pytest.mark.skip) | 302df31e809f51777d28d030563617522f1e0669 | 78,858 |
def permission_denied(request, exception):
"""Forbidden actions."""
context = {'exception': exception}
response = render_to_response('403.html', context, context_instance=RequestContext(request))
response.status_code = 403
return response | 794ae6b0c17ef2cc47bb6b02dfde8b2f149c92ba | 78,859 |
def create_order_delivery_information(delivery_information):
"""Extract delivery information from a request
Parameters
----------
delivery_information: oseo.DeliveryInformationType
Returns
-------
oseoserver.models.DeliveryInformation
"""
if delivery_information.mailAddress is no... | 28a6332d94da6fbe8081c30ccf0e2b1c5856303a | 78,860 |
import msgpack
def load(fp, resource=None, full_clean=True, default_to_not_supplied=False):
"""
Load a from a MessagePack encoded file.
See :py:meth:`loads` for more details of the loading operation.
:param fp: a file pointer to read MessagePack data from.
:param resource: A resource instance or... | d0c6737e9834611369c51d109a5b9f9bdaf52f1d | 78,861 |
import yaml
def local_loader(path):
""" loads yaml config files, such as defaults """
with open(path, 'r') as fp:
return yaml.safe_load(fp) | b001d8b73806a88a6c1125495b799989e64c8776 | 78,862 |
def get_player_input(player_char, char_list):
"""Get a players move until it is a valid move on the board with no piece currently there."""
while True:
#Get user input
player_move = int(input(player_char + ": Where would you like to place your piece (1-9): "))
#Move is on board
i... | 2e2d1ac0b8e4fe6a2467a378dfb9e1821525cddb | 78,863 |
import torch
def gpu_mem_usage():
"""
Compute the GPU memory usage for the current device (GB).
"""
if torch.cuda.is_available():
mem_usage_bytes = torch.cuda.max_memory_allocated()
else:
mem_usage_bytes = 0
return mem_usage_bytes / 1024 ** 3 | 16bc71e21cff1e86b8c78fc321a43131f0915c7b | 78,864 |
from typing import Optional
from typing import Callable
from typing import List
from typing import Tuple
def sample_anchor_positive_pairs(
text: str,
num_anchors: int,
num_positives: int,
max_span_len: int,
min_span_len: int,
sampling_strategy: Optional[str] = None,
tokenizer: Optional[Cal... | c3ce5827328e4037067c82a5da2b5e662436d24c | 78,865 |
def pad_sequence(vector_sequence, pad_vector, sent_length=64):
"""
Padding a sequence with pad vectors.
:param vector_sequence: np matrix
:param pad_vector: np vector
:param sent_length: int - length of the sequence
:return:
"""
delta = sent_length - vector_sequence.shape[0]
return... | d655a9eeb1f1e37382e809d384bcb02aebea00d3 | 78,866 |
def formulakilltail(sn):
"""
公式杀尾
:return:
"""
# { 'pid': 33631, 'exp': {'offset': 4, 'expression': '0h 1t 3t 4h 5a', 'sort': 'nosize'}, 'rat': 92.142 }
formula = {"expression": "0h 1t 3t 4h 5a", "offset": 4, "sorttype": "nosize"}
killtail = Common.tail(Common.formula_expression_hander(for... | 9a25218870526719180f197b2ca78be81660a0db | 78,867 |
def compute_character_error_rate_for_list_of_output_reference_pairs(
outputs_as_strings: list, references_as_strings: list, include_word_separators: bool):
"""
When computing the character error rate for a list of [output,reference] pairs,
one should sum the Levensthein distances for the pairs and d... | 933fadde356703a29ca2d06c1cba69239c37be31 | 78,868 |
def normalized(vectors):
""" normalize vector(s) such that ||vectors|| == 1 """
lengths = veclen(vectors)
return vectors / lengths[..., np.newaxis] | dc3d4fca7dfef6a1fc5930e73ee0858d30d4fc63 | 78,869 |
import torch
def cosh(x: Tensor):
"""Computes the element-wise cosh
Args:
x (Tensor): input tensor.
Returns: element-wise cosh
Examples:
>>> cosh(to_tensor([[1,0.5],[-0.25,-0.75]])).cpu()
tensor([[1.5431, 1.1276],
[1.0314, 1.2947]])
"""
return torch.... | fd01b80555a21bba2f97e40eb1dfb84075173bec | 78,870 |
def put_archive(request, pid):
"""MNStorage.archive(session, did) → Identifier."""
d1_gmn.app.views.assert_db.is_not_replica(pid)
d1_gmn.app.views.assert_db.is_not_archived(pid)
d1_gmn.app.sysmeta.archive_sciobj(pid)
return pid | 90dc27c2f6bfbb528e1afc6e71d92996fe1e8606 | 78,871 |
def f_get_mass(m_star2, m_star1, period, e0, k1):
""" Computes the difference between the input radial velocity semi-amplitude
of the primary star and the value corresponding to the provided orbital parameters.
Supporting function to get_planet_mass subroutine
:param m_star2: mass of the secondary/plan... | f481ba5323d85c47c1da14e526a9136816391608 | 78,872 |
def get_object_type(type) :
"""get_object_type(string: type) -> ObjectType. From
a type name like "Standard - Line" return the
factory to create objects of that type, see:
DiaObjectType"""
#global _dia
return dia.get_object_type(type) | 4f01e60ad2e5e9485954dbf47dc12f68c930b549 | 78,873 |
import hashlib
def get_checksum(requirements: str):
"""Determine the hash from the contents of the requirements."""
hash_ = hashlib.md5()
hash_.update(requirements.encode("utf-8"))
return hash_.hexdigest() | 59896edc566725cc1ced4b9e247c5949f36f0fd8 | 78,874 |
import array
from operator import concat
def load_FIRe_files(file_, append=False, save_files=False, res_path=None, seq_len=160, gain_value=None,
flen=1e-6, irrad=None, continuous=False, light_step=False, single_turnover=True):
"""
Process the raw data file (.000 format) and convert to a ... | 953abbe19e8f8402350be1a60b00f389e8d810f4 | 78,875 |
import torch
import math
def rand_perlin_2d(shape, res, fade=lambda t: 6 * t**5 - 15 * t**4 + 10 * t**3):
"""Generate a random image containing Perlin noise. PyTorch version."""
delta = (res[0] / shape[0], res[1] / shape[1])
d = (shape[0] // res[0], shape[1] // res[1])
grid = torch.stack(torch.meshgr... | 5bfceb8b23558ebac9debccbe88a0f955911dd16 | 78,876 |
import time
def fullSimBulkStd(mat, ctg, ctgThickNm, det, e0, nTraj, outPath,
dim=5.0e-6, lt=100, pc=1.0, emiSize=512, ctd=False):
"""
fullSimBulkStd(mat, ctg, ctgThickNm, det, e0, nTraj, outPath,
dim=5.0e-6, lt=100, pc=1.0, emiSize=512, ctd=False)
Use mc3 simulation to simulate an uncoated standard... | 7e4738b7254e9f2d5566845e074408b02db337eb | 78,877 |
def sample_user(name):
"""
handle Create a sample user
:return: [User object]
"""
user = get_user_model().objects.create_user(
f'{name}@gmail.com',
f'user_{name}',
'T35tP45w0rd'
)
user.is_verified = True
user.save()
return user | c9f35e0ebdb0261e14dfc96477f9ce9bec9640c2 | 78,879 |
def charfoleTransaction(myList = charfoleSqlList):
"""transaction function for MySQL
arguments
-----------
methods : 'POST'
You can upload the transaction statement(string) through POST method
to implement the basic function of MySQL.
action : 'execute'
execute the SQL stat... | bdc7ed69bd6d893e21af5a27fed9880fdfffa2dc | 78,880 |
import torch
from typing import Dict
from typing import Tuple
from typing import Any
def serialize_tensor_quantization(
tensor: torch.Tensor, weights: Dict, pcq_prefix: str
) -> Tuple[Dict, Dict]:
"""
Args:
tensor: The tensor from which we try to extract quantization information.
weights: ... | f49c30a4b547a309f940cfa9705cad2c683f75ec | 78,881 |
def variantsAndConfidence(refWindow, refSequence, cssSequence, aligner="affine"):
"""
Compute the confidence for each position, and compare
the consensus and reference in this window, returning a list of variants
"""
refId, refStart, refEnd = refWindow
if aligner == "affine":
align = cc... | 02052fa4dd7ecb9c90adeded249aff7bc3cc9216 | 78,883 |
def piecewise_linear_transformation(img, funcs, break_points):
"""
Apply piecewise linear transformation on input image.
The following conditions should be satisfied
1. each function is an increasing linear function
2. len(funcs) - len(break_points) = 1
3. for each element b in break... | 7383acc8ca159e42917251d897dca5f34f424396 | 78,885 |
def next_departure(bus_id: int, min_time: int) -> int:
"""Compute the next departure of ``bus_id`` leaving earliest at ``min_time``."""
# ERROR (pschanely, 2021-04-19):
# When min_time is zero we get ZeroDivisionError here.
wait_time = bus_id % min_time
return min_time + wait_time | a6d850b1f8a297603e93ae9083c854c066d1e709 | 78,886 |
def previous_saturday(dt):
"""
If holiday falls on Sunday, Monday or Tuesday, Saturday there is no trading
"""
if dt.weekday() == MONDAY:
return dt - timedelta(2)
elif dt.weekday() == TUESDAY:
return dt - timedelta(3)
elif dt.weekday() == SUNDAY:
return dt - timedelta(1)
... | 8fe9d03173cb65ded22af73e101e32c8af2777ed | 78,887 |
def apply_backspaces_and_linefeeds(text):
"""
Interpret backspaces and linefeeds in text like a terminal would.
Interpret text like a terminal by removing backspace and linefeed
characters and applying them line by line.
If final line ends with a carriage it keeps it to be concatenable with next
... | 2e04000b38bbb967b220f0c2246bf6d8d70ef0f4 | 78,888 |
def getfilename(path):
"""This function extracts the file name without file path or extension
Args:
path (file):
full path and file (including extension of file)
Returns:
name of file as string
"""
return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0] | a2df0c39836f4f04003e412e9b6a8b8f4e1c7081 | 78,890 |
def short_right_turn(delta_br, delta_w):
"""Scenario: short right turn."""
t_warmup = 2
t_rise_b = 2
t_rise_w = 1
t_hold = 5
t_fall = 1
t_settle = 5
inputs = {
"delta_br": simulation.linear_control([
(t_warmup + t_rise_w + t_hold, 0),
(t_rise_b, delta_br),... | 4fcf5cd89967791230a5697f11b3bcd980d90da5 | 78,892 |
def segm_mean_accuracy(label_hmask,
pred_imask):
"""
The segmentation mean accuracy.
Parameters:
----------
label_hmask : np.array
Ground truth one-hot mask.
pred_imask : np.array
Predicted index mask.
Returns:
-------
float
MA metric ... | 147632032cc0afd9b9e15d3b9e39a94b0ad9354f | 78,893 |
def cohens_kappa(y_pred1, y_pred2):
"""Calculates Cohen's kappa."""
assert len(y_pred1) == len(y_pred2), "Arrays must be the same length."
y_pred1 = np.array(y_pred1)
y_pred2 = np.array(y_pred2)
p_a = np.mean(y_pred1 == y_pred2)
p_e = np.sum([np.mean(y_pred1 == category) *
np... | 8c27482d75531df64063332a8c9d5a9c772c9c12 | 78,894 |
def mutual_exclusive(lock):
""" Mutex decorator. """
def wrap(f):
"""Decorator generator."""
def function(*args, **kw):
"""Decorated functionality, mutexing wrapped function."""
lock.acquire()
try:
return f(*args, **kw)
finally:
... | d94bb7fba63bcec6a2e4e49206c15c8254f84bb6 | 78,895 |
import re
def reactants(reac):
"""Extract reactant from a reaction."""
rl = {}
for x in reac.split(':'):
v = x.split('.')
try:
n = int(v[0])
except BaseException:
continue
c = v[1]
c = re.sub('\[', '', re.sub('\]', '', c))
# c = re.su... | 4c9f650e4d9ec4339a8a70d1be83ce81533af122 | 78,896 |
def encode(str):
""" encodes a str acording to
the ROT 13 way or ROT N deending on length of str
"""
chr_set = "abcdefghijklmnopqrstuvwxyz" # would would be faster with ASCII,
# but dont have acces to ASCII table
# ROT 13
if len(str) % 2 == 1:
rot... | ea28c68db88c251b25ca4b61f9d04835c7d608cb | 78,897 |
def thresholds():
"""Return a Hypothesis strategy which yields valid clustering thresholds."""
floats_or_integers = one_of(floats(min_value=1e-6), integers())
return floats_or_integers.map(abs).filter(lambda x: x) | f99b85cab811dafefcfa0ac01230335e4c15d3aa | 78,898 |
def lookAt(base, aim, up=None, primaryAxis=toVec3((1, 0, 0)), secondaryAxis=toVec3((0, 1, 0)), invertTerz=False):
"""convert a minimal of 2 positions to an aim matrix
:param Base: base position of the mmatrix
:type Base: MVector
:param aim: position the matrix needs to point towards
:type aim: M... | 8761e1db9e091ca274cc261eb463e8c09d2f76f6 | 78,899 |
from cv2 import cvtColor, COLOR_RGB2GRAY
from PIL import Image
def rgb2gray(img):
"""
Convert an RGB image to grayscale
:param img: image to convert
:return:
"""
if OPENCV_AVAILABLE:
return cvtColor(img, COLOR_RGB2GRAY)
elif PILLOW_AVAILABLE:
return np.array(Image.fromarray... | 4c7901d09719fc2627f4fb1aa71971d8f3aab3c8 | 78,900 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.