content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 os
def create_data_set(data_dir, csv_name, valid_size_frac):
"""
# Import image folder and csv file to create dataset.
:param data_dir: directory of data.
:param csv_name: Image file and the corresponding steering angle.
:param valid_size_frac: Ratio of dividing the data set into validatio... | 253bba42728df94102add97c178c69dfb7f9d933 | 3,622,704 |
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 |
import tqdm
def timelockanalysis(data, trials=None):
"""Prototype function for averaging :class:`~syncopy.AnalogData` across trials
Parameters
----------
data : Syncopy :class:`~syncopy.AnalogData` object
Syncopy :class:`~syncopy.AnalogData` object to be averaged across trials
trials ... | 6fa7c57e0d81cc437b2f4f0d8b635dfbcb43e353 | 3,622,724 |
def generate_navigator_js(os=None, navigator=None, platform=None,
device_type=None):
"""
Generates web navigator's config with keys corresponding
to keys of `windows.navigator` JavaScript object.
:param os: limit list of oses for generation
:type os: string or list/tuple o... | 14b849e6f1c1466e3307a2b4bd0f082b3071c7b9 | 3,622,725 |
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 live_ticket(db, live_taxpayer):
"""Return an authentication ticket usable with AFIP's test servers.
AFIP doesn't allow requesting tickets too often, so we after a few runs
of the test suite, we can't generate tickets any more and have to wait.
This helper generates a ticket, and saves it to disk i... | 0437267a71f87305150423e77e2c23065cac3199 | 3,622,745 |
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 |
from distutils.version import LooseVersion
from PyQt5.QtCore import QT_VERSION_STR
def qt_551_plus():
""" Return True if Qt version is 5.5.1+ """
return LooseVersion(QT_VERSION_STR) >= LooseVersion("5.5.1") | c6bbf7f65b5cbbbc9566a74df2df6ec976214687 | 3,622,764 |
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 argparse
def parse_args():
"""Parse command line arguements.
Parameters:
Nothing
Returns:
arguments: argparse.Namespace object
An object containing all of the added arguments.
Outputs:
Nothing
"""
input_help = 'Images to tweak back to flts. Defaul... | a9846a5dac59d038ed0500d629850549638a9cdf | 3,622,766 |
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 |
def sniff(
resource: bytes,
mime_type_string: str = "unknown/unknown",
no_sniff: bool = False,
check_for_apache_bug: bool = False) -> str:
"""
Implementation of algorithm in:
https://mimesniff.spec.whatwg.org/#determining-the-computed-mime-type-of-a-resource
The main met... | e94ba58c9ea30cd9a8c32d87055c29d30d2a1473 | 3,622,776 |
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 |
def read():
"""Return the contents of the Windows Common Setup as a string"""
setup_in = open(PATH)
try:
return setup_in.read()
finally:
setup_in.close() | 212044cb72fab10ef030c0d26c2298a16b178e7e | 3,622,781 |
from typing import List
def longest_subarray(numbers: List[int], limit: int) -> int:
"""https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/"""
# monotone increasing queue with indices that could become the sliding window minimum
min_queue = deque()
... | 42fc854fd2362d359d144c247b54403fde1eb9ee | 3,622,782 |
def ris_defaultValue_get(fieldsTuple):
"""
params: fieldsTuple, ()
return: fieldVaule_dict, {}
"""
#
ris_element = fieldsTuple[0]
if len(fieldsTuple[1]) != 0:
default_value = fieldsTuple[1][0]
else:
default_value = []
fieldValue_dict = {}
fieldValue_dict[ris_eleme... | 0551462066eb984c796ef7ee08d640e9bc4373e5 | 3,622,783 |
import torch
def project_to_2d(X, camera_params):
"""
Project 3D points to 2D using the Human3.6M camera projection function.
This is a differentiable and batched reimplementation of the original MATLAB script.
Arguments:
X -- 3D points in *camera space* to transform (N, *, 3)
camera_para... | 0727efaeecfa48540590461f7d9222c8e6071f6d | 3,622,784 |
import csv
def read_header_keywords_table(filepath):
""" Read a table of .fits keywords from a .csv file into a
HeaderKeywordList of HeaderKeyword objects.
:param filepath: The location of the .csv file containing the header
keyword table.
:type filepath: str
"""
# Op... | 0a3385e30eed06fbc1df12929fe3002be0bd4b50 | 3,622,785 |
def compara(chave, lst):
"""Compara usuários da lista lst através da chave
A comparacão ocorre montando um dicionário de listas de usuário
temporáriamente em dic. Uma vez que todo o dicionário está montado
os índices do dicionário que contém mais do que um elemento são
copiados para o dicionário de... | 4e3145465b853354bf194754538a6947e3c8d14f | 3,622,786 |
from typing import List
def exists(bucket: str, key: str) -> bool:
"""Checks if there is an object in the object store with the given key
Args:
bucket (dict): Bucket containing data
key (str): Prefix for key in object store
Returns:
bool: True if exists in store
"""
# Get ... | 3918bffc09f26e392566452a34f72fd6ab30b141 | 3,622,787 |
def format_element_to_matlab_confusion_matrix(row, col, confusion_matrix):
"""
Return a string for the element on row, col location for
confusion_matrix to either
number of observation\npercentage of observations or
percentage_correct_classifications\npercentage_incorrect_classifications
per cla... | 5cba4be1a70a88d28ac558cb9de24c4f2befdfdb | 3,622,788 |
def add_lazy_nh4_pm25(d, dict_sum):
"""Calculates sum of particulate NH4.
Parameters
----------
d : xarray.Dataset
RRFS-CMAQ model data
Returns
-------
xarray.Dataset
RRFS-CMAQ model data including new NH4 calculation
"""
keys = _get_keys(d)
allvars = Series(di... | c0e6b4853824a137b48e8d072ac2eaae693a817e | 3,622,789 |
def record(episode,
episode_reward,
worker_idx,
global_ep_reward,
total_loss,
num_steps):
"""Helper function to store score and print statistics.
Arguments:
episode: Current episode
episode_reward: Reward accumulated over the current episode
... | c767352be49b63e9be046e7df6eedaf03a8061ad | 3,622,790 |
from scipy.spatial import cKDTree
from scipy.stats import entropy
def transform_cav2im3d_entropy(cavity_coords, grid_min, grid_shape, pharmaco):
"""
Takes coordinates of grid points and outputs an im3d for skimage
Uses entropy at 3A of pharmacophores as values to set the "greyscale"
"""
# First we simply the ph... | f8305ed08620716286b064ebfab1cb3ede9c1c7d | 3,622,791 |
def _normalize_title(key: str) -> str:
"""MediaWiki treats the first character of article names as upper-case."""
if not key: # Empty string
return ""
key = _normalize_spaces(key)
return key[0].upper() + key[1:] | 1e542d82f0a72e13bbfe89b5b56f13c01c1cba5c | 3,622,792 |
def n_coeffs_to_degree(n_coeffs):
"""what is degree if 2d polynomial has n_coeffs coefficients"""
delta_sqrt = int((8 * n_coeffs + 1.)**.5 + 0.5)
if delta_sqrt**2 != (8*n_coeffs+1.):
raise ValueError('Wrong input in n_coeffs_to_degree(): {:}'.format(n_coeffs))
return int((delta_sqrt - 3.) / 2. +... | 29a767668579d7a9d7c9c871cdb3168c7db3c6c1 | 3,622,793 |
def load():
"""Loads settings static configuration.
As the configuration is static and immutable, it is loaded only once from the disk.
Returns an instance of the `Settings` class.
"""
global _SETTINGS
if _SETTINGS is not None:
return _SETTINGS
s = _load_yaml(SUBSTRA_TESTS_CONFIG_... | 8e3a6fc4301e0263ef2a927b6286d134bb5b84c7 | 3,622,794 |
def modinv(a, b):
""" Returns x such that (x * a) (mod b) == 1
reference: https://stackoverflow.com/questions/4798654/modular-multiplicative-inverse-function-in-python
"""
g, x, _ = egcd(a, b)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % b | 6372a204dbdd840cb4e4b1d6f8b73b2cdc286d88 | 3,622,795 |
def keygen():
"""
Generate private and public keys for the "greased", bootstrappable encryption scheme.
The main idea here is that we want to minimize computation during decryption because it originally contains
an expensive modulus operation (c % p) that is too much for our somewhat homomorphic en... | 76093133a20deecc680c7c7b38f2a1bf09d7c7e4 | 3,622,796 |
def process_image(image_path):
"""
Given a path to a file, pre-process that image in preparation for making a prediction.
:param image_path: the path to the image file
:return: the image represented by a flattened numpy array
"""
im_transforms = TRANSFORM_TEST_VALIDATION
# Open image
im = Image.open(image_path... | 5005b66fe99e09ff79435b71cf2be899212b292c | 3,622,797 |
import hashlib
def checksum_md5(filename, blocksize=8192):
"""Calculate md5sum.
Parameters
----------
filename : str or pathlib.Path
input filename.
blocksize : int
MD5 has 128-byte digest blocks (default: 8192 is 128x64).
Returns
-------
md5 : str
calculated ... | 759c0c5cbc37ebe0cc85eb8156127308eff354bc | 3,622,798 |
from pyunifi.controller import Controller, APIError
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Unifi Controller."""
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
site_id = config.get(CONF_SITE_ID)
... | e99d6090d5c365dd96d632e76fa01197bcdd72e7 | 3,622,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.