content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_all_entries(df, pdbid, cdr):
"""
Get all entries of a given PDBID and CDR.
:param df: dataframe.DataFrame
:rtype: pandas.DataFrame
"""
return df[(df['input_tag'].str.contains(pdbid)) & (df['CDR'] == cdr)] | 414eca4481bde0ccc5cdd6e143f7d4b06216a102 | 3,616,356 |
from tornado.ioloop import IOLoop
import functools
def asynchronous(method):
"""Wrap request handler methods with this if they are asynchronous.
This decorator is for callback-style asynchronous methods; for
coroutines, use the ``@gen.coroutine`` decorator without
``@asynchronous``. (It is legal for ... | 7915698f8db6251b147e4299e66b0c6c07b600ab | 3,616,357 |
def dynary(x, bases):
"""Represent the integer ``x`` with respect to the 'dynamical' ``bases``.
Gives a way to reliably enumerate and 'de-enumerate' the combination of
all different index values.
Examples
--------
>>> dynary(9, [2, 2, 2, 2]) # binary
[1, 0, 0, 1]
>>> dyna... | 8d86e6af07d2b31ff56145733012d550b92580f7 | 3,616,358 |
def download_from_db() -> BytesIO:
"""
Возвращает байтовый буфер с таблицой бд
в формате xlsx
"""
wb = init_wb()
categories = get_categories_list()
for app in get_applications():
if app[1] in categories[:3]:
wb["1"].append(app)
elif app[1] in categories[3:6] + cat... | c19246720f47a8d91c0a41d010bff6493ecd787f | 3,616,359 |
def calculate_request_checksum(game, pid, sid):
"""Calculate checksum of payment details to pass to payment API"""
secret_key = get_payment_secret()
checksum_string = CHECKSUM_REQUEST_FORMAT.format(pid, sid, game.price, secret_key)
return calculate_checksum(checksum_string) | 00809383d925ca74379e699eefe1359dbf58a569 | 3,616,360 |
def main(source_base, binary_base, num_threads=1):
"""Main entry point of the script."""
print 'Executing test for razers3'
print '==========================='
print
ph = app_tests.TestPathHelper(
source_base, binary_base,
'apps/razers3/tests') # tests dir
# =================... | 76f0c69d73e39add509a6207d59ff11e734595b1 | 3,616,361 |
def encode(input, errors='strict'):
"""Encode unicode as USMARC
"""
if errors not in set(['strict', 'replace', 'ignore']):
raise ValueError("Invalid errors argument %s" % errors)
result = []
rappend = result.append
uget = unicodemap.get
for u in input:
s = uget(u)
if ... | a9956b395104d186a0d1941b0deb32b6105a7917 | 3,616,362 |
import six
def has_dask_arrays(dataset):
"""
check whether or not a dataset contains dask arrays
Parameters
----------
dataset : xarray.Dataset
Returns
-------
bool :
True if dask arrays are found
"""
has_dask = False
for varname, var in six.iteritems(dataset.... | 8870be6815555aa0cb9cd925d22de23170a99711 | 3,616,363 |
def Put(entities, **kwargs):
"""Store one or more entities in the datastore.
The entities may be new or previously existing. For new entities, Put() will
fill in the app id and key assigned by the datastore.
If the argument is a single Entity, a single Key will be returned. If the
argument is a list of Enti... | 3d5e1bf702a4ee26864cfef4adcf91c206ff62c4 | 3,616,364 |
def classify_image(interpreter, image, top_k=1):
"""Returns a sorted array of classification results."""
set_input_tensor(interpreter, image)
interpreter.invoke()
output_details = interpreter.get_output_details()[0]
output = np.squeeze(interpreter.get_tensor(output_details['index']))
# If the model is quan... | 65562f0b9e6224e068938d018d65df4182b1e07c | 3,616,366 |
def _get_scheme_map(input_encoding, output_encoding):
"""Provides a caching layer on top of `SchemeMap` objects to allow faster
access to scheme maps we've instantiated once.
:param input_encoding: Input encoding. Must be defined in `SCHEMES`.
:param output_encoding: Input encoding. Must be defined in ... | e1618cf38ead4493de051fe58ec9e3554706185d | 3,616,367 |
def cooling_resource_activator(mdot_kgpers, T_sup_K, T_re_K, limits, cooling_resource_potentials, T_ground_K, prices, lca,
master_to_slave_variables, config, Q_cooling_req, locator):
"""
:param DCN_cooling:
:param Qc_available_from_lake_W:
:type Qc_available_from_lake_W: ... | 85034cae9835da1ed60a8cc9272b19fe46daa59a | 3,616,370 |
import glob
import numpy
def read_v70(fileglob):
"""Reads a location.pytxt sparse 70-vector that describes an extremum."""
files = glob.glob(fileglob)
if len(files) != 1:
raise ValueError('Got %d matches for glob %r: %r' % (
len(files), fileglob, files))
model = distillation.read_distillate_model(... | 2195e4214277bd9abf0368d9323ecdcbde60bd1e | 3,616,372 |
def merge_result(res):
"""
Merges all items in `res` into a list.
This command is used when sending a command to multiple nodes
and they result from each node should be merged into a single list.
"""
if not isinstance(res, dict):
raise ValueError("Value should be of dict type")
re... | 28d21ca00316303c0e2fc0400599921154253236 | 3,616,373 |
def verify_service_identity(cert_patterns, obligatory_ids, optional_ids):
"""
Verify whether *cert_patterns* are valid for *obligatory_ids* and
*optional_ids*.
*obligatory_ids* must be both present and match. *optional_ids* must match
if a pattern of the respective type is present.
"""
err... | a24b094d9d6bab6a705df821ace0939fab82c737 | 3,616,374 |
def point_cloud_actor(xyz,
size=100,
color=(0,0,0),
opacity=1):
"""function to make a vtk.vtkActor from a set of xyz points that renders them as spheres
Parameters
----------
xyz : np.array
a Nx3 array of points
size: float o... | dedde319dcc20391e53f52f1692608009aaa9a80 | 3,616,375 |
def Growth_factor_Linder(omega_m, z, gamma=0.55):
"""
Computes the unnormalised growth factor at redshift z given the present day value of omega_m. Uses the approximation
from Linder2005 with fixed gamma
:param omega_m: the matter density at the present day
:param z: the redshift we want the matter... | e9807a639b967a94d8a44d1fcb0a9f3ec6c039bf | 3,616,376 |
def get_redis_connection():
""" Get attribute to redis connecion object """
conn = getattr(g, "_redis_connection", None)
if conn is None:
url = current_app.config["REDIS_URL"]
conn = g._redis_connection = redis.from_url(url)
return conn | c307fa313df46875797a3942eb2c3739a3f2ab4e | 3,616,377 |
def _parse_oid_metric(metric):
# type: (OIDMetric) -> MetricParseResult
"""
Parse a fully resolved OID/name metric.
Example:
```
metrics:
- OID: 1.3.6.1.2.1.2.1
name: ifNumber
```
"""
name = metric['name']
oid = OID(metric['OID'])
parsed_symbol_metric = Parse... | c050959ee5a5db247177282bd4df1dffdf878ed3 | 3,616,378 |
from pathlib import Path
from typing import Dict
from typing import Any
def _parse_additional_json(dir_name: Path) -> Dict[str, Any]:
"""Parse additional json files in the directory."""
additional_json = {}
for filename in dir_name.glob("*.json*"):
key = filename.name.split(".")[0]
if key ... | 9745eaabe1169ffa52d5159782be3c88bf41c7b1 | 3,616,380 |
def load_iharm(harm_dump_name, gcov, gcon, compute_b=True):
""" does what you expect """
hfp = h5py.File(harm_dump_name,"r")
N1 = hfp["header"]["n1"][()]
N2 = hfp["header"]["n2"][()]
N3 = hfp["header"]["n3"][()]
rho = hfp["prims"][:,:,:,0]
UU = hfp["prims"][:,:,:,1]
U = hfp["prims"][:,:,:,2:5]
... | d04e70f0afd829a9c0b73a2dac01145ddaa91bd6 | 3,616,381 |
def ensure_vacuum(structure, vacuum):
"""
Adds padding to a slab or 2D material until the desired amount
of vacuum is reached.
Args:
structure (Structure): Structure to add vacuum to
vacuum (float): Final desired vacuum thickness in Angstroms
Returns:
Structure object with v... | ffbf44a67053a3903483d7ac9acc5ce31a4a3c21 | 3,616,382 |
from functools import reduce
def generateDF(keys, periods=20, amplitudes=[1, 1.5], frequencies=[1/6, 1/2],
ground=0, sample_rate=1e-2):
"""
Генерирует таблицу со столбцами из синусоид с заданным количеством периодов,
случайно изменяющейся амплитудой и случайно изменяющейся частотой.
Па... | 492304f1a5a1baedb1dfb1712d8bfeb26c67388c | 3,616,383 |
def get_file_section_name(section_key, section_label=None):
"""Build a section name as in the config file, given section key and label."""
return section_key + (" {0}".format(section_label) if section_label else "") | 01e1f46d2a949315ba2e927ddfab610064539e3b | 3,616,384 |
from typing import Callable
from typing import Any
def test_benchmark_blend_images_npy(benchmark: Callable[..., Any]) -> None:
"""Benchmark numpy implementation of alpha blending."""
def blend_images(img0: NDArrayByte, img1: NDArrayByte, alpha: float = 0.7) -> NDArrayByte:
"""Alpha-blend two images t... | 4ab85e194d8ca6e95d138480e74e7cebcd8d4def | 3,616,385 |
def inf_get_cc_size_b(*args):
"""
inf_get_cc_size_b() -> uchar
"""
return _ida_ida.inf_get_cc_size_b(*args) | ec9c35adbf6c1422471dc71d4feca0bb1e83cf6b | 3,616,386 |
def resnet18(pretrained=False, progress=True, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet18', DistillerBasicBl... | 2465471757663c00af2a6b069583386f0ed8a1eb | 3,616,387 |
def _get_test_stats_with_mi(feature_paths):
"""Get stats proto for MI test."""
result = statistics_pb2.DatasetFeatureStatistics()
for feature_path in feature_paths:
feature_proto = text_format.Parse(
"""
custom_stats {
name: "max_sklearn_adjusted_mutual_information"
... | 0134ea6f85568da9fecdf7d50c9865e90af153e1 | 3,616,388 |
def chist(l):
"""Simple counting histogram. Takes a list of items
and returns a list of (count,object) tuples."""
counts = {}
for c in l:
counts[c] = counts.get(c,0)+1
hist = [(v,k) for k,v in counts.items()]
return sorted(hist,reverse=1) | ac71b1251677186b0adf4f090d1f0a10da91964f | 3,616,389 |
import random
def make_random_constant(name=None, value=None, return_params=False):
"""Make a random Constant value."""
if name is None:
name = random_identifier()
if value is None:
const_type = random.choice([ParamType.FLOAT, ParamType.INT])
if const_type == ParamType.FLOAT:
... | 1be467740d87c45b2ff922bd0c47de548b89cc00 | 3,616,392 |
import pathlib
def recursive_search(path):
"""Perform recursive search for supported measurements"""
path = pathlib.Path(path).resolve()
path_in = []
# Get all candidates
cands1 = list(path.rglob("*")) + [path]
# Exclude all directories with the suffix _dm that contain drymass.cfg
cands2 =... | 7238f03e0c214fe5b786d4a8c19847f713829766 | 3,616,393 |
def rot_y2alpha(rot_y, x, FOCAL_LENGTH):
"""
Get alpha by rotation_y - theta + 180
rotation_y : Rotation ry around Y-axis in camera coordinates [-pi..pi]
x : Object center x to the camera center (x-W/2), in pixels
alpha : Observation angle of object, ranging [-pi..pi]
"""
alpha = rot_y - np.... | 7a4b736800f6fdd13228ac2d67c5c573c1f51563 | 3,616,394 |
def psi2name(psi, scale=fine_scale):
"""Map single `psi` value to Wentworth bin name."""
for name, upper_psi in scale[:-1]:
if psi <= upper_psi:
return name
return scale[-1][0] | c35fa0b0f65832cc1da168c8c36e65c0fbd4ff53 | 3,616,395 |
def download_video_files(
video_metadata,
local_video_directory='./videos',
video_filename_extension='mp4',
download_workers=4,
):
"""
Downloads videos from S3 to local directory tree and returns metadata with
local path information added.
Videos are specified as a list of dictionaries,... | 50d0e29fcf485f577c233741f7a96af3b4b35186 | 3,616,396 |
def cloud_motion_fast(im1,im2,mask1=None, mask2=None,ratio=0.7, threads=1):
"""
Determine cloud motion
Input: Images and masks for two frames
Output: Cloud motion vector, and max correlation
"""
####use this routine if the inputs are raw images
ny,nx=im2.shape
# if im1.dtype == ... | 16f549276e512925758bfddc491c53f1f38a942e | 3,616,397 |
import requests
import json
def get_demo_by_guid(guid):
"""
Retrieve a demo from the ERP system by guid.
:param guid: The demo's guid.
:return: An instance of the Demo.
"""
# Create and format request to ERP
url = '%s/api/v1/Demos/findByGuid/%s' % (get_service_url('lw-erp'), g... | 986a20893b0f2d1019beb4f8da3266a1d8f4aaf2 | 3,616,398 |
def preprocess_skeleton_frame(joint_collection, is_15_joint: bool, is_cad: bool = False,
to_edge: bool = True,
to_rotate: bool = False,
is_25_joint: bool = False) -> _np.ndarray:
"""Applies re-ordering, orientation standardzin... | 7eb511ac3a2bfef406a21f135ea0f0414701f49b | 3,616,399 |
def apply_patch(doc, patch, in_place=False):
"""Apply list of patches to specified json document.
:param doc: Document object.
:type doc: dict
:param patch: JSON patch as list of dicts or raw JSON-encoded string.
:type patch: list or str
:param in_place: While :const:`True` patch will modify ... | e9a9149b98a79d04627d2bdf133b0190ddc6b936 | 3,616,400 |
def _gt_mapping(D, W, Z):
"""Computes the mapping B(X) for a Guttman transform V X = B(X) Z."""
# Compute the Euclidean distances between all pairs of points
Dz = distance.cdist(Z, Z)
# Fill the diagonal of Dz, because *we don't want a division by zero*
np.fill_diagonal(Dz, 1e-5)
B = - W * D / ... | a47916098ffaccf8e1dddc8ee7a363791bb574c9 | 3,616,401 |
def schema(_request):
"""API schema"""
return JSONResponse({
'/': 'api root'
}) | 69dbc1e53acbca5ebb3491bc33186ef04973666f | 3,616,402 |
def cvar_historic(r, level =5):
"""
Computes the Conditional VaR of series or Dataframe
"""
if isinstance(r, pd.Series):
is_beyond = r <= -var_historic(r, level = level)
return -r[is_beyond].mean()
elif isinstance(r, pd.DataFrame):
return r.aggregate(cvar_historic, level=leve... | b11e37867b121c57cbf983d586709dfcf14e1b5a | 3,616,403 |
def excepting(selector, handler_fn):
"""
Selector is not necessarily just an `Exception` subclass.
Potentially it can be an id for any purpose, not just exception handling.
It also can be an iterable of these things to register general
handlers.
"""
def decorator(task):
task_meta =... | e868b46e41844b8c41223100bd212dc5e49a3496 | 3,616,404 |
def add_check_theta_generator(measure):
"""
This is a decorator to add a ValueError to a function if theta is not in the proper interval.
"""
include_0 = True
include_1 = True
measure = measure.upper()
# Should 0 be included
if measure in select_names(['PPV', 'FDR', 'MCC', 'MK', 'FM']):
... | c39ba359c3b3c1a7cea86752720e2376f6b99fd9 | 3,616,406 |
def get_function_id(functions_client: functions.FunctionsManagementClient,
app_id: str, function_name: str) -> str:
"""
Identifies function ID by its name
:param functions_client: OCI Functions client
:param app_id: OCI Functions app ID
:param function_name: OCI Functions functio... | 7e735035d24f89041516706a6e37a2228cbb9e12 | 3,616,407 |
def init_graphic_environment(screen_width=background_width, screen_height=background_height):
"""
Initialize the graphic environment.
:param screen_width: width of the screen.
:param screen_height: height of the screen.
:return: the screen, the backgrounds and the font.
"""
pygame.init()
... | 035c9a690c9945ea36be88a0c56915e6a60054c6 | 3,616,408 |
def ma(method, series, ma_period):
"""MA均线,直接调用pandas_ma的均线方法"""
return ta.ma(method, series, length=ma_period, min_periods=1) | 43f03b3c73902cb748b77e087ec2d7bceeb5884a | 3,616,409 |
def resnet152(num_classes, pretrained=False, **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
encoder = ResNetEncoder(Bottleneck, [3, 8, 36, 3])
if pretrained:
encoder.load_state_dict(model_zoo.load_url(model_u... | 0b66fcfa39a73667674c7fbb4e8e086329c1f996 | 3,616,410 |
def request_server_option():
"""
Is used to request the option and prints it.
Returns
-------
option: int
The option that has to be returned
"""
colors = decorators.Colors()
option = 0
try:
option = int(input(f"{colors.OK}Select what do you want to do: {colors.ENDC}"... | f58d432f49ee82ce60a08c49586a281c3be0e0a8 | 3,616,411 |
def getRectangles(conn, image):
"""
Returns a list of (x, y, width, height, zStart, zStop, tStart, tStop) of
each rectangle ROI in the image
"""
rois = []
roiService = conn.getRoiService()
result = roiService.findByImage(image.id, None)
for roi in result.rois:
x = None
... | d5f41fc93172bbb8e206391da075c842a3fb9d73 | 3,616,413 |
def IRONMAN_user(user):
"""helper to determine if user is associated with the IRONMAN org"""
# NB - not all systems have this organization!
iron_org = Organization.query.filter_by(name='IRONMAN').first()
if iron_org:
OT = OrgTree()
for org_id in (o.id for o in user.organizations if o.id)... | 1009247a970d582fc2afcdf0d6e2948dc16b11af | 3,616,415 |
def parse_date(text):
""" Attempts to parse date from text. Returns None on failure.
"""
result = dateparser.parse(text.strip())
if (result is not None) and hasattr(result,'date'):
return result.date()
else:
print("Could not parse %s as date. Returning None."%text)
return | 43905651b3dacac1ee8d49f6f6134f1e77a40180 | 3,616,416 |
def train_model(lrmodel, X, Y, devX, devY, devscores, verbose=0, epochs=100):
"""
Train model, using pearsonr on dev for early stopping
"""
done = False
best = -1.0
r = np.arange(1,6)
while not done:
# Every 300 epochs, check Pearson on development set
lrmodel.fit(X, Y,
... | 01211bcdf1c472e96261485b110c5d43da77cd39 | 3,616,417 |
from datetime import datetime
def _get_current_time():
"""Gets the current timestamp."""
return datetime.datetime.now() | 25ddd78e4cbd11cde826a9bb62a27afd3781ab22 | 3,616,418 |
def controller_put(id):
"""
Thing Manager Data Handler for PUT requests # Use type to know the serialization
"""
# Get the elements of the request
service = Service(request, id) # Call processRDF
service.put()
return 'put' | 653c586f7ccaa7334798cc3b50444b6955615c0a | 3,616,419 |
import torch
import math
def positionalencoding2d(pos_embed_dim, height, width):
"""
:param pos_embed_dim: dimension of the model embeddings
:param height: height of the positions
:param width: width of the positions
:return: height * width * pos_embed_dim matrix
"""
if pos_embed_dim % 4 !... | 685396742b965df3b409203656707f1868e30c45 | 3,616,420 |
def test_get_header():
""" Test of the get header function of the DataTable Class """
test_dictionary={'Data_Description':{'x':'X Distance in microns.',
'y':'y Distance in microns.','Notes':'This data is fake'},'Data':[[1,2],[2,3]]}
new_table=DataTable(**{'data_dictionary':test_dictionary})
header=n... | e15947852c40cec53ce391609fc9453a9fc95e32 | 3,616,422 |
import math
def sorted_list_to_BST(head: ListNode) -> TreeNode:
"""
- can have an empty head
Assumptions:
- values of the linked list are integers
Input: head = ListNode(-10)
list = [-10,-3, 0, 5, 9]
^ ^ ^ ^
Intuition:
- recursively s... | 32c95106b34ba40c856b4a27b714481a75f85a17 | 3,616,423 |
def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv1d:
"""3x3 convolution with padding"""
return nn.Conv1d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation) | a301bf80a297e47c5eedc573322f85a84d1aa7ba | 3,616,424 |
def short_desc(event, words=25, strip_html=False):
"""Takes an event object and returns a shortened description."""
if event.short_description:
description = event.short_description
else:
description = event.description
if strip_html:
description = unhtml(description)
return ... | 9dba787cdb0a481a16df1d4e249b741638fdc138 | 3,616,425 |
def ja_to_arabic(s: str, enable_validation: bool = True, accept_daiji: bool = True) -> int:
"""convert japanese number to arabic number
Args:
s (str): number in japanese format
enable_validation (bool, optional): Whether to enable validation or not. Defaults to True.
accept_daiji (bool,... | 0c27192380f9dc02bae486025b981935b7be67ff | 3,616,426 |
import random
def shades_of_jop():
"""Return a pretty colour."""
c1 = random.randint(127, 255)
c2 = random.randint(0, 127)
c3 = random.randint(0, 255)
return tuple(random.sample([c1, c2, c3], 3)) | 366bc5bada332b6de3561d6c906a1880119b02f2 | 3,616,427 |
def check(func=None, *, dt='', n=0):
""" A Decorator function that checks if the arguments are of the correct type an the right amount
n: --> number of arguments
dt: --> Data types of the arguments
"""
if func is None:
return partial(check, dt=dt, n=n)
@wraps(func)
def check... | a84932645783c20f04db69ae3b721ff9e4eac801 | 3,616,428 |
def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z)) | ebded90a57df53dd51edc4a7ba079824ec5c14ea | 3,616,429 |
import json
import io
import base64
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integra... | 60557aecdda4bb4eab6c23ab327b32653b37b982 | 3,616,430 |
def _final_frame_length(header, final_frame_bytes):
"""Calculates the length of a final ciphertext frame, given a complete header
and the number of bytes of ciphertext in the final frame.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param ... | b7029e3b705194ee7daa02b4400d124ffe6efc2a | 3,616,431 |
def real2complex(input_data):
"""
Parameters
----------
input_data : row x col x 2
Returns
-------
output : row x col
"""
return input_data[..., 0] + 1j * input_data[..., 1] | 9e359903f9653e8ea799a2baedcc9c274471f34f | 3,616,432 |
from typing import Dict
def dy_static_file_server_dynamic_sidecar_service(
docker_registry: str, node_meta_schema: Dict
) -> Dict[str, str]:
"""
Adds the below service in docker registry
itisfoundation/dy-static-file-server-dynamic-sidecar
"""
return _pull_push_service(
"itisfoundation... | 867353e7a7ecd266a4017a6bae1e171aeba36ee2 | 3,616,434 |
def check_is_paired(df, subject, group):
"""
Check if samples are paired.
:param df: pandas dataframe with samples as rows and protein identifiers as columns (with additional columns 'group', 'sample' and 'subject').
:param str subject: column with subject identifiers
:param str group: column with ... | 38f9b0722e77edb88ff44a7bc73eb24a8f1aa097 | 3,616,435 |
def norm_mac(mac):
"""Normalize a MAC Address from the pypowervm format to the neutron format.
That means that the format will be converted to lower case and will have
colons added.
:param mac: A pypowervm mac address. E.g. 1234567890AB
:returns: A mac that matches the standard neutron format.
... | b316d6bb6d72036955e01dab77860eef59b65a8f | 3,616,436 |
from scipy.stats import f as F
from scipy.special import gamma
def hyperellipsoid(P, y=None, z=None, pvalue=.95, units=None, show=True, ax=None):
"""
Prediction hyperellipsoid for multivariate data.
The hyperellipsoid is a prediction interval for a sample of a multivariate
random variable and is such... | ca3b2bceb2d30b5ba9c48d9fe625bd09a9bd3f7b | 3,616,437 |
import igl
import scipy
def get_mesh_laplacian_matrix_igl(mesh, fix_boundaries=True):
"""
Gets the laplace operator of the mesh
Parameters
----------
mesh: :class: 'compas.datastructures.Mesh'
fix_boundaries: bool
Returns
----------
:class: 'scipy.sparse.csr_matrix'
spars... | 7783c52e773c6d54975fe66c72078334a245b6fb | 3,616,438 |
import torch
def qsgd_compress(t, pnorm="inf", quan_bits=8):
"""
Quantize float32 into uint8 using QSGD algorithm.
Arguments:
* `t` - Input PyTorch CUDA Tensor to be quantized.
* `pnorm` - Order of norm used for QSGD compression. Default value is `inf`.
* `quan_bits` - Number of q... | 2ca1e5bd15b9bed4d8fbb4466f8d87a363e7e4a6 | 3,616,439 |
def permission_denied(request, exception, *args, **kwargs):
"""
Catch all 403 - Forbidden/Permission Denied
"""
return HttpResponseForbidden(**exception_response(request, 400, exception)) | 611cdfdb4316d0e7c46230f417f92ab8134d223a | 3,616,441 |
import rospkg.os_detect
def get_host_os():
"""Determines the name of the host operating system"""
os_detector = rospkg.os_detect.OsDetect()
return (os_detector.detect_os())[0] | 54ba91395ab1871168f353fff8a2560cc22a1138 | 3,616,443 |
def ascii(object: object) -> str:
"""ascii."""
return repr(object) | 44dc1a77ebd46215aa25a2fea91f9c7c41bd4e7a | 3,616,444 |
def perc(tags):
"""This function returns the ratio of the total of tags in repository
Args:
tags (List): Tags that are in the repository
Returns:
sum_of_perc*100 [float]:
"""
sum_of_perc=0
for tag in tags:
# print(tag)
if tag in store_tag:
sum_... | 4b95ddb96fd02243111f6865b00abb5ecdffeb83 | 3,616,445 |
def encode_labelmap(colour_img, colourlabelmap):
"""
Takes a colour image, where each colour represents one specific label-class and replaces
the colour value with label ids. The mapping is defined by array `colourlabelmap`.
"""
colour_img = colour_img.astype(int)
labels = np.zeros((colour_img.s... | 10a7601391177161df44245d9f781b2a801d9421 | 3,616,446 |
def compute_corrected_dhf(mp_entry: ComputedEntry) -> float:
"""
Compute corrected :math:`\\Delta H_f(0K)` in ev/atom for a material in
the Materials Project.
We apply two corrections as follows:
1. Elemental contributions as used in the Materials Project.
2. For carbonates, we apply a correct... | eaa1a3d3f81dd9d7dcc930d3115cb259bf617c53 | 3,616,448 |
def tmux(ctx):
"""
Show some informantion in your tmux status.
Output for tmux's status-right. As in, put this in ~/.tmux.conf::
set-option -g status-utf8 on
set-option -g status-fg green
set -g status-right '#(carml tmux)'
set -g status-interval 2
"""
cfg = ctx.obj... | 5ab465bf11a0637e58c5ab80c71c97dda177b56e | 3,616,449 |
def makefleetopts():
""" create option parser for events. """
parser = optparse.OptionParser(usage='usage: %prog [options] [list of bot names]', version=version)
parser.add_option('', '--apiport', type='string', default=False, dest='apiport', help="port on which the api server will run")
parser.add_opti... | f02a03827f122ad6342ca103839babdff45f3c37 | 3,616,450 |
import threading
import queue
def InitSharedStorage():
"""
Shared vars
"""
'''
All the methods in Python threading.events are atomic operations.
https://docs.python.org/3/library/threading.html
'''
SharedEvents = {}
SharedEvents['update'] = threading.Event()
SharedEvents['updat... | 3a973ad7ef27cc0ed776f6e34b67f273b4884c9a | 3,616,452 |
from typing import List
def translate_mav(wxdata: MavData, units: Units) -> List[MavPeriodTrans]:
"""Returns translations for a TafData object"""
data = []
for line in wxdata.forecast:
_data = _gfs_shared(line, units, MavPeriodTrans)
return data | 922621eaa4d27da73fca3eceb8f33e7d967322a0 | 3,616,454 |
def specific_heat(mat):
"""Calculate specifc heat"""
cw = 4183
mr = mat['m_heat']
mw = mat['m_w']
Tr = mat['Tr']
Tw = mat['Tw']
Te = mat['Te']
return (mw * cw * (Te - Tw)) / (mr * (Tr - Te)) | 7d3fbe3f67b3df593c94c93ab7d8523242d17b46 | 3,616,456 |
def get_first_day(histories: pd.DataFrame) -> pd.Timestamp:
"""
get_first_day gets the first day of the histories DataFrame in a way that is robust to outliers - for some
reason, a small number of user summaries are very far into the past or future
"""
return histories.day.nsmallest(50).iloc[-1] | ce4449a398a2ab16af73e4b8a4284c091bf717be | 3,616,457 |
def inner(A, B):
"""Inner product of matrix A with matrix B.
Parameters
----------
A : ndarray
First matrix of the inner product.
B : ndarray
Second matrix of the inner product.
Returns
-------
result : ndarray
Result of the inner product.
Examples
---... | e6be04a6b0babc5e8bbcbd5abf743891ba4f0437 | 3,616,459 |
import xml
def _parse_series(
study: xml.etree.ElementTree.Element,
) -> xml.etree.ElementTree.Element:
"""Get series xml element from study xml element."""
expected_length = 3 if len(study) == 7 else 4
return _check_xml(study[5], "series", expected_length) | 57c0714625b8a80f07f497716f5b4ae51f5416e5 | 3,616,460 |
def tail_correction(r, V, r_switch):
"""Apply a tail correction to a potential making it go to zero smoothly.
Parameters
----------
r : np.ndarray, shape=(n_points,), dtype=float
The radius values at which the potential is given.
V : np.ndarray, shape=r.shape, dtype=float
The potent... | eab44a4218b3d72bdcfa737e2310c564b2fd4cca | 3,616,462 |
def case_detail(request, pk):
"""
Retrieve, update, or delete an AssuranceCase, by primary key
"""
try:
case = AssuranceCase.objects.get(pk=pk)
except AssuranceCase.DoesNotExist:
return HttpResponse(status=404)
permissions = get_case_permissions(case, request.user)
if not per... | 36ec8c2ef9b597edac57c4473f5924ad896a1f1a | 3,616,463 |
from bs4 import BeautifulSoup
def wikitable(page):
"""
Exports a Wikipedia table parsed by BeautifulSoup. Deals with spanning:
multirow and multicolumn should format as expected.
"""
mediawikiapi = MediaWikiAPI()
page = mediawikiapi.page(page)
soup = BeautifulSoup(page.html(), 'html.pars... | b2adae70064296194b5f3c88188474aff84b507d | 3,616,464 |
def _flatten(suitable_for_isinstance):
"""
isinstance() can accept a bunch of really annoying different types:
* a single type
* a tuple of types
* an arbitrary nested tree of tuples
Return a flattened tuple of the given argument.
"""
types = set()
if not isinstance(sui... | 5ba63f39b2d22da78f5a362ce6821239714a9e6a | 3,616,465 |
def attach_tasks(queryset, as_field="tasks_attr"):
"""Attach tasks as json column to each object of the queryset.
:param queryset: A Django user stories queryset object.
:param as_field: Attach tasks as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""... | 02a7e189226f9fb5809d7b4d18f3055e5fbc5462 | 3,616,466 |
def create_padding_mask(seq):
"""
The padding mask is used in the Encoder and Decoder layers to mask padding tokens.
"""
seq = tf.cast(tf.math.equal(seq, 0), tf.float32)
# add extra dimensions to add the padding to the attention logits.
return seq[:, tf.newaxis, tf.newaxis, :] | c8a335388906b8ceae8e2766e889243ddbd3d9cb | 3,616,467 |
def decode_text(s):
"""
Decodes a PDFDocEncoding string to Unicode.
Adds py3 compatibility to pdfminer's version.
"""
if type(s) == bytes and s.startswith(b'\xfe\xff'):
return str(s[2:], 'utf-16be', 'ignore')
else:
ords = (ord(c) if type(c) == str else c for c in s)
retur... | a5107ae9a99a198ea648eec06b84c2094bd45af5 | 3,616,468 |
def create_schema(client):
"""The query which creates the schema
Parameters - it uses variables rather than the fluent style as an example
==========
client : a WOQLClient() connection
"""
base = WOQLQuery().doctype("EphemeralEntity", label="Ephemeral Entity", description="An entity... | 276c06eeb33144fca6b1895553eb946662fdd3f6 | 3,616,469 |
def process_cpc_testdata(path, variable='pr', lead_option='weekly', day_init=15, day_end=21, region=None):
"""
Open and process the CPC data for 11 ensemble members for training.
Args:
path (str): directory path to data.
variable (str): variable for analysis.
lead_option (str): ... | 95ccc78c9b6ed0b2cbeaaf06c2fe90faf6dc5d4d | 3,616,470 |
import time
from datetime import datetime
def trimap(
X,
triplets,
weights,
knn_tuple,
use_dist_matrix,
n_dims,
n_inliers,
n_outliers,
n_random,
distance,
lr,
n_iters,
Yinit,
weight_temp,
apply_pca,
opt_method,
verbose,
return_seq,
):
"""Appl... | eb45637992dceef11f51dcf406d06558333e42d3 | 3,616,471 |
def qtdmri_isotropic_scaling(data, q, tau):
""" Constructs design matrix for fitting an exponential to the
diffusion time points.
"""
dataclip = np.clip(data, 1e-05, 1.)
logE = -np.log(dataclip)
logE_q = logE / (2 * np.pi ** 2)
logE_tau = logE * 2
B_q = np.array([q * q])
inv_B_q = ... | ed896224a2cded0cd2683082d895ce935f8ab5c9 | 3,616,472 |
from typing import Dict
from typing import Any
from typing import Optional
import tqdm
def nested_cv_param_search( # pylint:disable=invalid-name
X: np.ndarray, # noqa
y: np.ndarray,
param_dict: Dict[str, Any],
pipeline: Pipeline,
outer_cv: BaseCrossValidator,
inner_cv: BaseCrossValidator,
... | 7cf91749a5cd9c22fc38ed03cd569ff58c106ba2 | 3,616,473 |
import re
def extract_positive_integer_value(text, key):
"""
Extract an integer value for a given key in a text
Args:
text (str): text to extract value from
key (str): key to extract value for
Raises:
ValueError: value is not a positive integer
Returns:
int: extrace... | 28242d3445cb94511070eca6934ad2985283d4b3 | 3,616,474 |
def delete_from_s3(s3_path: str) -> bool:
"""Delete a path from s3
Args:
s3_path: Full path on s3 in format "s3://<bucket_name>/<obj_path>".
Returns:
Boolean of whether the delete was successful.
"""
bucket, key = decompose_s3_path(s3_path)
s3_client = boto3.client("s3")
tr... | 35c54fcff723e01c5f555b77cb8804649af58369 | 3,616,475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.