content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def gaussian(nm, a, x0, sigma):
"""
gaussian function
"""
gaussian_array = a * np.exp(- ((nm - x0) ** 2.0) / (2 * (sigma ** 2.0)))
return gaussian_array | 2c8ba6bb93565ff9ae79f0a0b6643994730bb672 | 19,502 |
def list_to_filename(filelist):
"""Returns a list if filelist is a list of length greater than 1,
otherwise returns the first element
"""
if len(filelist) > 1:
return filelist
else:
return filelist[0] | 32a88235196e104fa043d2b77af1f09d4e9164e9 | 19,503 |
from datetime import datetime
import six
def _get_expiration_seconds(expiration):
"""Convert 'expiration' to a number of seconds in the future.
:type expiration: int, long, datetime.datetime, datetime.timedelta
:param expiration: When the signed URL should expire.
:rtype: int
:returns: a timesta... | 3eb2c56211b3cfab8f35634b83ef8c77e4ea2221 | 19,504 |
import click
def parse_encoding(format_, track, supplied_encoding, prompt_encoding):
"""Get the encoding from the FLAC files, otherwise require the user to specify it."""
if format_ == "FLAC":
if track["precision"] == 16:
return "Lossless", False
elif track["precision"] == 24:
... | d56ad0d15176a963e62a33d4b4cd799d1e68281e | 19,505 |
def disaggregate(model, mains, model_name, num_seq_per_batch, seq_len,
appliance, target_scale, stride=1):
"""
Disaggregation function to predict all results for whole time series mains.
:param model: tf model object
:param mains: numpy.ndarray, shape(-1,)
:param model_name: name... | 2053e9dc74d188ab41dbeb2fc1af8cd4bbd6dfae | 19,507 |
import pathlib
from pathlib import Path
def set_path_to_file(categoria: str) -> pathlib.PosixPath:
"""
Receba uma string com o nome da categoria da lesgilação e retorna
um objeto pathlib.PosixPath
"""
fpath = Path(f"./data/{categoria}")
fpath.mkdir(parents=True, exist_ok=True)
return fpath | 98455978e695d34deb27dc59807e06f1a4daff96 | 19,508 |
def transpose_nested_dictionary(nested_dict):
"""
Given a nested dictionary from k1 -> k2 > value
transpose its outer and inner keys so it maps
k2 -> k1 -> value.
"""
result = defaultdict(dict)
for k1, d in nested_dict.items():
for k2, v in d.items():
result[k2][k1] = v
... | 39f8faa319063ac533b375c5ae0ac1c10a8fd770 | 19,509 |
def auth_code():
"""
Функция для обработки двухфакторной аутентификации
:return: Код для двухфакторной аутентификации
:rtype: tuple(str, bool)
"""
tmp = input('Введи код: ')
return tmp, True | 8b0ae26cfdd1aa9f7b9c7a0433075494fe354185 | 19,510 |
from typing import cast
def graph_file_read_mtx(Ne: int, Nv: int, Ncol: int, directed: int, filename: str,\
RemapFlag:int=1, DegreeSortFlag:int=0, RCMFlag:int=0, WriteFlag:int=0) -> Graph:
"""
This function is used for creating a graph from a mtx graph file.
compared with t... | 7babe91d1daad745a94ea542ebda0cff9eaedf4b | 19,511 |
def compute_inliers (BIH, corners):
"""
Function: compute_inliers
-------------------------
given a board-image homography and a set of all corners,
this will return the number that are inliers
"""
#=====[ Step 1: get a set of all image points for vertices of board coords ]=====
all_board_points = []
for ... | 431e5e82e127f404b142940de79c8bed79021423 | 19,513 |
def plotPayloadStates(full_state, posq, tf_sim):
"""This function plots the states of the payload"""
# PL_states = [xl, vl, p, wl]
fig8, ax11 = plt.subplots(3, 1, sharex=True ,sharey=True)
fig8.tight_layout()
fig9, ax12 = plt.subplots(3, 1, sharex=True, sharey=True)
fig9.tight_layout()
... | 56018bbb5dfaca76dae62940c572aacfef31ad1e | 19,514 |
def draw(p):
"""
Draw samples based on probability p.
"""
return np.searchsorted(np.cumsum(p), np.random.random(), side='right') | 84b087c9eb6bfdac4143a464399f85cad0169000 | 19,515 |
import functools
def _autoinit(func):
"""Decorator to ensure that global variables have been initialized before
running the decorated function.
Args:
func (callable): decorated function
"""
@functools.wraps(func)
def _wrapped(*args, **kwargs):
init()
return func(*args,... | b39242a9f600a7bbeaf43d73ae3529dcad9c3857 | 19,516 |
from datetime import datetime
def export_testing_time_result():
"""
Description:
I refer tp the answer at stockoverFlow:
https://stackoverflow.com/questions/42957871/return-a-created-excel-file-with-flask
:return: A HTTP response which is office excel binary data.
"""
target_info = reques... | ab0505449361b036ed94eb919a3c876a8776b839 | 19,517 |
def profile_view(user_request: 'Queryset') -> 'Queryset':
"""
Функция, которая производит обработку данных пользователя и выборку из БД
вакансий для конкретного пользователя
"""
user_id = user_request[0]['id']
area = user_request[0]['area']
experience = user_request[0]['experience']
sala... | 6ec9a6c00cead62c2d30dcb627a575b072bcde60 | 19,518 |
def config_vrf(dut, **kwargs):
"""
#Sonic cmd: Config vrf <add | delete> <VRF-name>
eg: config_vrf(dut = dut1, vrf_name = 'Vrf-test', config = 'yes')
eg: config_vrf(dut = dut1, vrf_name = 'Vrf-test', config = 'no')
"""
st.log('Config VRF API')
if 'config' in kwargs:
config = kwargs['... | 9d6d7e85762610103277345d1e12d4ef2c3f3d9f | 19,519 |
def _worker_command_line(thing, arguments):
"""
Create a worker command line suitable for Popen with only the
options the worker process requires
"""
def a(name):
"options with values"
return [name, arguments[name]] * (arguments[name] is not None)
def b(name):
"boolean op... | 945e9da452b438b08aacbf967b93f10f717c5003 | 19,520 |
from typing import Optional
def get_endpoint(arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEndpointResult:
"""
Resource Type Definition for AWS::S3Outposts::Endpoint
:param str arn: The Amazon Resource Name (ARN) of the endpoint.
"""
__ar... | 518fbd1ca92373bcbea5d10a44605b4990242d02 | 19,521 |
def append_child(node, child):
"""Appends *child* to *node*'s children
Returns:
int: 1 on success, 0 on failure
"""
return _cmark.node_append_child(node, child) | 70770596cf470987ff20abbe94f8b97c0050f86a | 19,523 |
def run_chain(init_part, chaintype, length, ideal_population, id, tag):
"""Runs a Recom chain, and saves the seats won histogram to a file and
returns the most Gerrymandered plans for both PartyA and PartyB
Args:
init_part (Gerrychain Partition): initial partition of chain
chaintype (Str... | 5b6db6ede5e8b7c8bcc46f91131fafed22741775 | 19,524 |
def cliquenet_s2(**kwargs):
"""CliqueNet-S2"""
model = cliquenet(input_channels=64, list_channels=[36, 80, 150, 120], list_layer_num=[5, 5, 6, 6])
return model | 6b99b3575d9bd245aea615eedbffa95ca7fd3076 | 19,525 |
def decConvert(dec):
"""
This is a number-word converter, but for decimals.
Parameters
-----
dec:str
This is the input value
numEngA: dict
A dictionary of values that are only up to single digits
frstDP: int
The first decimal place
scndDP: int
The second decimal place
Returns... | dedfb67448e4bd2402acb4c561ebb4669d7bc58d | 19,526 |
import time
def fit(data, weights, model_id, initial_parameters, tolerance=None, max_number_iterations=None, \
parameters_to_fit=None, estimator_id=None, user_info=None):
"""
Calls the C interface fit function in the library.
(see also http://gpufit.readthedocs.io/en/latest/bindings.html#python)
... | 54c0f3a740589509d908e8c68625e33dccfbe1f8 | 19,528 |
import json
def json_get(cid, item):
"""gets item from json file with user settings"""
with open('data/%s.json' %cid) as f:
user = json.load(f)
return user[item] | dedb369aba555ca5359e291bc39504dd4b14a790 | 19,529 |
import random
def adaptive_monte_carlo(func, z_min, z_max, epsilon):
"""
Perform adaptive Monte Carlo algorithm to a specific function. Uniform random variable is used in this case.
The calculation starts from 10 division of the original function range. Each step, it will divide the region which has the l... | 7735c9e3df1ddfb912dd9a2dfcf01699a56262d8 | 19,531 |
import scipy.stats
def compute_statistics(measured_values, estimated_values):
"""Calculates a collection of common statistics comporaring the measured
and estimated values.
Parameters
----------
measured_values: numpy.ndarray
The experimentally measured values with shape=(number of data p... | cde9fd0094a6d8330f552ec98c11647c0a76bc42 | 19,532 |
def num_encode(n):
"""Convert an integer to an base62 encoded string."""
if n < 0:
return SIGN_CHARACTER + num_encode(-n)
s = []
while True:
n, r = divmod(n, BASE)
s.append(ALPHABET[r])
if n == 0:
break
return u''.join(reversed(s)) | bd0f34122fa490cfafea2a5b60d6a919a7a8c253 | 19,533 |
import torch
def hard_example_mining(dist_mat, labels, return_inds=False):
"""For each anchor, find the hardest positive and negative sample.
Args:
dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N]
labels: pytorch LongTensor, with shape [N]
return_inds: whether to ... | d3e36f7c7088b1a1d457869701c99d2c2013a283 | 19,534 |
from typing import Optional
from typing import cast
from typing import Sized
def CodedVideoGrain(src_id_or_meta=None,
flow_id_or_data=None,
origin_timestamp=None,
creation_timestamp=None,
sync_timestamp=None,
rate=Frac... | 5ab51dbbcaaff04f9c56434998d49434aec6f58e | 19,536 |
def test_log_likelihood(model, X_test, y_test):
""" Marginal log likelihood for GPy model on test data"""
_, test_log_likelihood, _ = model.inference_method.inference(
model.kern.rbf_1, X_test, model.likelihood.Gaussian_noise_1, y_test,
model.mean_function, model.Y_metadata)
return test_log_... | 61c04b4b3cb12472769699f37601154398df0959 | 19,537 |
from airfs._core.io_base_raw import ObjectRawIOBase
from airfs._core.io_base_buffered import ObjectBufferedIOBase
from airfs._core.io_random_write import (
ObjectRawIORandomWriteBase,
ObjectBufferedIORandomWriteBase,
)
def test_object_buffered_base_io():
"""Tests airfs._core.io_buffered.Object... | e72324d158ae9dfc8b859e5ce055230da83819fe | 19,538 |
def fov_geometry(release='sva1',size=[530,454]):
"""
Return positions of each CCD in PNG image for
a given data release.
Parameters:
release : Data release name (currently ['sva1','y1a1']
size : Image dimensions in pixels [width,height]
Returns:
list : A list of [id, x... | a7e118ed223a91d5e939b24baa8bbfb0858064b9 | 19,539 |
def parse_descriptor(desc: str) -> 'Descriptor':
"""
Parse a descriptor string into a :class:`Descriptor`.
Validates the checksum if one is provided in the string
:param desc: The descriptor string
:return: The parsed :class:`Descriptor`
:raises: ValueError: if the descriptor string is malforme... | b82c04f6cdc6d4e9b5247463e6fcbdcf12c5ffc7 | 19,540 |
def HHMMSS_to_seconds(string):
"""Converts a colon-separated time string (HH:MM:SS) to seconds since
midnight"""
(hhs,mms,sss) = string.split(':')
return (int(hhs)*60 + int(mms))*60 + int(sss) | f7a49ad5d14eb1e26acba34946830710384780f7 | 19,541 |
def fetch_user_profile(user_id):
"""
This function lookup a dictionary given an user ID. In production, this should be replaced
by querying external database.
user_id: User ID using which external Database will be queried to retrieve user profile.
return: Returns an user profile corresponding to th... | c9ee521dc909f865232ec5d39b456bafd0c996dc | 19,543 |
def _replace_token_range(tokens, start, end, replacement):
"""For a range indicated from start to end, replace with replacement."""
tokens = tokens[:start] + replacement + tokens[end:]
return tokens | 2848a3ad2d448e062facf78264fb1d15a1c3985c | 19,544 |
def norm(a):
"""normalizes input matrix between 0 and 1
Args:
a: numpy array
Returns:
normalized numpy array
"""
return (a - np.amin(a))/(np.amax(a)-np.amin(a)) | 6c246926b8a5c91ea5a674447679a7d1cf7a2c8e | 19,546 |
def collect_path(rf, method="quick", verbose=True):
"""
Collect paths from RandomForest objects. This function is the most time-consuming part.
Output:
A list of outputs from get_path_to_max_prediction_terminal_node.
"""
n_tree = len(rf)
result = []
if method == "quick":
... | d2ecb0f277eafb483d38376278635f1143c5e7f2 | 19,547 |
def calculate_variance(beta):
"""
This function calculates variance of curve beta
:param beta: numpy ndarray of shape (2,M) of M samples
:rtype: numpy ndarray
:return variance: variance
"""
n, T = beta.shape
betadot = gradient(beta, 1. / (T - 1))
betadot = betadot[1]
normbetad... | 179ae9dde0979f909525c44c94ea11ded7a776d5 | 19,548 |
def get_datastore_mo(client, soap_stub,
datacenter_name, datastore_name):
"""
Return datastore managed object with specific datacenter and datastore name
"""
datastore = get_datastore(client, datacenter_name, datastore_name)
if not datastore:
return None
datastore_mo... | f759dccd61caa7cd290a2a00b0ebbcb80dc8fa7e | 19,549 |
def _merge_dictionaries(dict1: dict, dict2: dict) -> dict:
"""
Recursive merge dictionaries.
:param dict1: Base dictionary to merge.
:param dict2: Dictionary to merge on top of base dictionary.
:return: Merged dictionary
"""
for key, val in dict1.items():
if isinstance(val, dict):
... | 322cd1e3cf01d97ebc8ecb450772ca328afee121 | 19,550 |
def integrate_profile(rho0, s0, r_s, r_1, rmax_fac=1.2, rmin_fac=0.01,
r_min=None, r_max=None):
"""
Solves the ODE describing the to obtain the density profile
:returns: the integration domain in kpc and the solution to the density profile in M_sun / kpc^3
"""
G = 4.3e-6 # u... | af139c2f8211f11d2a71e1da73ebdd3f9f6c4fe7 | 19,551 |
def create_eval_dataset(
task,
batch_size,
subset):
"""Create datasets for evaluation."""
if batch_size % jax.device_count() != 0:
raise ValueError(f"Batch size ({batch_size}) must be divisible by "
f"the number of devices ({jax.device_count()}).")
per_device_batch_size = batc... | 4446f322d38a736942125a9427db1e68bb008e5e | 19,552 |
def rad2deg(angle):
"""
Converts radians to degrees
Parameters
----------
angle : float, int
Angle in radians
Returns
-------
ad : float
Angle in radians
Examples
--------
>>> rad2deg(pi)
180.000000000000
>>> rad2deg(pi/2)
... | e8bdc1d914c139d7d3847223ecfb8b0399eda5ca | 19,553 |
def center_crop(im, size, is_color=True):
"""
Crop the center of image with size.
Example usage:
.. code-block:: python
im = center_crop(im, 224)
:param im: the input image with HWC layout.
:type im: ndarray
:param size: the cropping size.
:type size: int
:param is... | ac280efd4773613f08632fe836eecc16be23adf8 | 19,554 |
def read_json(file_path: str) -> Jelm:
"""reads from a json file path"""
with open(file_path) as fp:
dump = fp.read()
return reads_json(dump) | a3166cbe3bc98478a89574af7493a740826ab366 | 19,555 |
def fillCells(cell_bounds, rdx, rdy, rdbathy, dlim=0.0, drymin=0.0,
drymax=0.99, pland=None, rotated=False,
median_depth=False, smc=False, setadj=False):
"""Returns a list of depth and land-sea data to correspond
with cell bounds list"""
print('[INFO] Calculating cell depths... | b40a8c3d5171c40cebf397b93e697dfaef1820ec | 19,556 |
import six
import math
import warnings
def spatial_pyramid_pooling_2d(x, pyramid_height, pooling_class=None,
pooling=None):
"""Spatial pyramid pooling function.
It outputs a fixed-length vector regardless of input feature map size.
It performs pooling operation to the inpu... | fd64c335afe43a35a8917cf8079ae41d410f9dc4 | 19,558 |
from typing import OrderedDict
async def retrieve_seasons_and_teams(client, url): # noqa: E999
"""
Retrieves seasons and teams for a single player.
"""
doc = await get_document(client, url)
teams = doc.xpath(
"//table[@id='stats_basic_nhl' or @id='stats_basic_plus_nhl']" +
"/tbody... | b68d95a46b5f036ec53826fa0321273b168d2261 | 19,559 |
def array_match_difference_1d(a, b):
"""Return the summed difference between the elements in a and b."""
if len(a) != len(b):
raise ValueError('Both arrays must have the same length')
if len(a) == 0:
raise ValueError('Arrays must be filled')
if type(a) is not np.ndarray:
a = np... | b82a6e36bdfe2757bc1a86bb4d95c156ac847474 | 19,560 |
def data_len(system: System) -> int:
"""Compute number of entries required to serialize all entities in a system."""
entity_lens = [entity.state_size() + entity.control_size() for entity in system.entities]
return sum(entity_lens) | 8ebc98e713052dd215ffaecfd5338535e4662bd2 | 19,561 |
def keep_row(row):
"""
:param row: a list for the row in the data
:return: True if we should keep row; False if we should discard row
"""
if row[_INDICES["Actor1CountryCode"]] in _COUNTRIES_OF_INTEREST or \
row[_INDICES["Actor2CountryCode"]] in _COUNTRIES_OF_INTEREST:
return True
... | 5124583806c02034c0c11518b25639ebd61aaccf | 19,562 |
def _grad_shapelets(X, y, n_classes, weights, shapelets, lengths, alpha,
penalty, C, fit_intercept, intercept_scaling,
sample_weight):
"""Compute the gradient of the loss with regards to the shapelets."""
n_samples, n_timestamps = X.shape
# Derive distances between s... | fb16c9aaaf06ae322f9781d8089fd084fc7d299a | 19,563 |
from typing import List
import requests
def get_tags_list(server_address: str, image_name: str) -> List[str]:
"""
Returns list of tags connected with an image with a given name
:param server_address: address of a server with docker registry
:param image_name: name of an image
:return: list of tags... | 3c20ef85f77689cdbc25a131bbe1f1cc1431528a | 19,564 |
def build_graph(graph_attrs, meta_data, nodes, edges):
""" Build the Graph with specific nodes and edges.
:param graph_attrs: dictionary with graph attributes
:param nodes: list of nodes where each node is tuple (node_name, type, attrs)
nodes=[
('input', 'Parameter'... | 9238da38d6b8d65f9bff7c344d2fe8d4ed71dc90 | 19,565 |
from typing import Callable
from typing import Any
import pickle
def cached_value(func: Callable[[], Any], path) -> Any:
"""
Tries to load data from the pickle file. If the file doesn't exist, the func() method is run and its results
are saved into the file. Then the result is returned.
"""
if ex... | b74c9b79cf74c32c5d1befaad293cdc2dbf3b5c3 | 19,566 |
def expensehistory():
"""Show history of expenses or let the user update existing expense"""
# User reached route via GET
if request.method == "GET":
# Get all of the users expense history ordered by submission time
history = tendie_expenses.getHistory(session["user_id"])
# Get the... | 15ce57d9b246fd81bc8f38fcda11330de3ff50a5 | 19,567 |
def resize(a, new_shape):
"""resize(a,new_shape) returns a new array with the specified shape.
The original array's total size can be any size.
"""
a = ravel(a)
if not len(a): return zeros(new_shape, a.typecode())
total_size = multiply.reduce(new_shape)
n_copies = int(total_size / len(a))
... | fcbce959a0ff6bd31a269be89b50956ccc6f6883 | 19,568 |
def rotate180(image_np):
"""Rotates the given image by 180 degrees."""
if image_np is None:
return None
return np.fliplr(np.flipud(image_np)) | d851314620d527b6c33e19389b5fc19035edcdb3 | 19,569 |
def check_y(y, allow_empty=False, allow_constant=True):
"""Validate input data.
Parameters
----------
y : pd.Series
allow_empty : bool, optional (default=False)
If True, empty `y` raises an error.
allow_constant : bool, optional (default=True)
If True, constant `y` does not raise... | 570aa15347377bddbe96919cc1560157905c91ce | 19,572 |
def preprocess_features(features):
"""Row-normalize feature matrix and convert to tuple representation"""
rowsum = np.array(features.sum(1), dtype=float)
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
features = r_mat_inv.dot(features)
return s... | dba875e19918cb11bae31a575f35d79519d2d897 | 19,573 |
def dataset_prediction_results(dataset, event, model_factory_fn=pohmm_factory,
min_history=90, max_history=None, out_name=None):
"""
Obtain predictions for each model.
Create stratified folds
Train on 1-n_folds. Use the last fold to make predictions for each event
"""... | 4e11a6e3b144c4b37529465c3517481666bebd78 | 19,575 |
def num(value):
"""Parse number as float or int."""
value_float = float(value)
try:
value_int = int(value)
except ValueError:
return value_float
return value_int if value_int == value_float else value_float | a2ea65c2afa0005dbe4450cb383731b029cb68df | 19,576 |
def __format_event_start_date_and_time(t):
"""Formats datetime into e.g. Tue Jul 30 at 5PM"""
strftime_format = "%a %b %-d at %-I:%M %p"
return t.strftime(strftime_format) | 4db0b37351308dfe1e7771be9a9ad8b98f2defa6 | 19,577 |
def collect_properties(service_instance, view_ref, obj_type, path_set=None,
include_mors=False):
"""
Collect properties for managed objects from a view ref
Check the vSphere API documentation for example on retrieving
object properties:
- http://goo.gl/erbFDz
Args:
... | 39abeff44fefc6b93284b7ec10e66a8a224ce73d | 19,578 |
from typing import List
from typing import MutableMapping
def parse_template_mapping(
template_mapping: List[str]
) -> MutableMapping[str, str]:
"""Parses a string template map from <key>=<value> strings."""
result = {}
for mapping in template_mapping:
key, value = mapping.split("=", 1)
result[key] ... | 49eb029a842be7c31d33444235452ecad4701476 | 19,580 |
def select_dim_over_nm(max_n, max_m, d, coef_nd, coef_md, coef_nm, coef_n, coef_m, rest, max_mem):
"""Finds the optimal values for `n` and `m` to fit in available memory.
This function should be called for problems where the GPU needs to hold
two blocks of data (one of size m, one of size n) and one kernel... | a4a824ab19a5d102461d565312ec9874a8c4e513 | 19,582 |
def _compute_net_budget(recarray, zonenamedict):
"""
:param recarray:
:param zonenamedict:
:return:
"""
recnames = _get_record_names(recarray)
innames = [
n for n in recnames if n.startswith("FROM_") or n.endswith("_IN")
]
outnames = [
n for n in recnames if n.starts... | e5e14bef5663af22f5547e36b305f858de372232 | 19,586 |
def bg_white(msg):
""" return msg with a white background """
return __apply_style(__background_colors['white'],msg) | 1e5aca8b0e506420b921c6833704aa32ba0c599f | 19,587 |
def read_image_from_s3(bucket_name, key):
"""S3 to PIL Image"""
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)
object = bucket.Object(key)
response = object.get()
return Image.open(response['Body']) | 6d7e62e007b493f1d124c07ab0b19abe9c6bc308 | 19,588 |
import typing
from typing import Counter
def count_indra_apis(graph: BELGraph) -> typing.Counter[str]:
"""Count the APIs reported by INDRA."""
return Counter(
api
for _, _, d in graph.edges(data=True)
if ANNOTATIONS in d and 'INDRA_API' in d[ANNOTATIONS]
for api in d[ANNOTATION... | 9743f59cd51506fe1157397a4096f48b3258afcc | 19,589 |
import numpy
def integrate_sed(wavelength, flambda, wlmin=None, wlmax=None):
"""
Calculate the flux in an SED by direct integration.
A direct trapezoidal rule integration is carried out on the flambda values
and the associated wavelength values.
Parameters
----------
wavelength: A ... | e2fd2c3905bba104f8d4bc376cd56585b40332bf | 19,590 |
def computeMSSIM(groundTruth, recovered):
"""
Compute Mean Structural SImilarity Measure (MSSIM) between
the recovered and the corresponding ground-truth image
Args:
:param groundTruth: ground truth reference image.
numpy.ndarray (Height x Width x Spectral_Dimension)
:param ... | a8f24531de784d3ada684b7a5841c8a5a247c6ff | 19,591 |
def test_cache_memoize_ttl(cache, timer):
"""Test that cache.memoize() can set a TTL."""
ttl1 = 5
ttl2 = ttl1 + 1
@cache.memoize(ttl=ttl1)
def func1(a):
return a
@cache.memoize(ttl=ttl2)
def func2(a):
return a
func1(1)
func2(1)
assert len(cache) == 2
key1,... | 87d274517c6166db6d174281e6785809e45609b8 | 19,592 |
def queues(request):
"""
We get here from /queues
"""
return render("queues.html", request, { "queuelist" : request.jt.queues()}) | b8f09a074ef496a9b51d001ec8441305b51ea933 | 19,593 |
def shorten_str(string, length=30, end=10):
"""Shorten a string to the given length."""
if string is None:
return ""
if len(string) <= length:
return string
else:
return "{}...{}".format(string[:length - end], string[- end:]) | d52daec3058ddced26805f259be3fc6139b5ef1f | 19,594 |
def A2cell(A):
"""Compute unit cell constants from A
:param A: [G11,G22,G33,2*G12,2*G13,2*G23] G - reciprocal metric tensor
:return: a,b,c,alpha, beta, gamma (degrees) - lattice parameters
"""
G,g = A2Gmat(A)
return Gmat2cell(g) | ddec7e3f70ee2de4963f67155bda5ee8743d418d | 19,595 |
from typing import Any
def update_user_post(
slug: str,
post: schemas.PostCreate,
db: Session = Depends(get_db),
current_user: schemas.User = Depends(get_current_active_user),
) -> Any:
"""
Update a user Post if its owner
"""
post_data = get_post(db, slug)
if post_data is None:
... | 629e580924a676cd74e728e31df6467367763a0e | 19,596 |
from backend.caffe.path_loader import PathLoader
def loadNetParameter(caffemodel):
""" Return a NetParameter protocol buffer loaded from the caffemodel.
"""
proto = PathLoader().importProto()
net = proto.NetParameter()
try:
with open(caffemodel, 'rb') as f:
net.ParseFromString... | 2b0a12cb479ed1a9044da587c1673fc5f3f89e6b | 19,597 |
def extract_keywords(header, *args):
"""
For a given header, find all of the keys and return an unnested dict.
"""
try:
header = pvl.load(header)
except:
header = pvl.loads(header)
res = {}
# Iterate through all of the requested keys
for a in args:
try:
... | 2d1313befa8779b5b8f6efc686f92fd213c7dfa5 | 19,598 |
def dot(p, q):
"""
Compute dot product between two 3D vectors
p: array
Cartesian coordinates for one of the vectors
q: array
Cartesian coordinates for one of the vectors
"""
return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] | 28a073690e1e89128a997ae75b8782ee0cfb7252 | 19,600 |
import click_completion.core
import click
def install_completion(ctx, attr, value): # pragma: no cover
"""Install completion for the current shell."""
if not value or ctx.resilient_parsing:
return value
shell, path = click_completion.core.install()
click.secho("{0} completion installed in {... | b6c84744161d90cc1d33ac6effd5b7aec083c151 | 19,602 |
from datetime import datetime
def _extractSetsSingleUser(df, time_window):
"""Get activity set and trip set for each individual."""
# total weeks and start week
weeks = (df["endt"].max() - df["startt"].min()).days // 7
start_date = df["startt"].min().date()
aSet = pd.DataFrame([], columns=["useri... | 40f92857cd5684b8fbf8b01565ede7aeffab1fe8 | 19,603 |
def _ed25519():
"""Edwards curve Ed25519.
Link: https://en.wikipedia.org/wiki/EdDSA#Ed25519
"""
q = 2 ** 255 - 19
order = 2 ** 252 + 27742317777372353535851937790883648493
gf = GF(q)
ed = CurveParams(name="ED25519", order=order, gf=gf, is_cyclic = True)
ed.set_constants(a=gf(-1), d=gf(-... | f1a07b9ebcb6033968f0e7d9c66ee2ff71f138e0 | 19,604 |
import json
def from_raw_bytes(raw_bytes):
"""Take raw bytes and turn it into a DmailRequest"""
return from_json(json.loads(raw_bytes.decode(encoding='UTF-8'))) | 01e989dfddcad20125ff608cdfa42673b1c0d0d8 | 19,605 |
def BRepApprox_TheMultiLineToolOfApprox_FirstPoint(*args):
"""
:param ML:
:type ML: BRepApprox_TheMultiLineOfApprox &
:rtype: int
"""
return _BRepApprox.BRepApprox_TheMultiLineToolOfApprox_FirstPoint(*args) | 26b8a2bffe094a8cc1e41edf56b92b75be75dc37 | 19,606 |
import time
def push_message(token, user, message, **kwargs):
"""
Send message to selected user/group/device.
:param str token: application token
:param str user: user or group id to send the message to
:param str message: your message
:param str title: your message's title, otherwise your ap... | 97b278482fb1ff88eea5f95c45f47563b61c905f | 19,607 |
def _rrv_div_ ( s , o ) :
"""Division of RooRealVar and ``number''
>>> var = ...
>>> num = ...
>>> res = var / num
"""
if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve ()
elif hasattr ( o , 'getVal' ) : o = o.getVal ()
#
v = ... | bef100fa354dc1e090a7e1cb2ad66bc8c7144d1b | 19,608 |
def getWindowsAt(x: int, y: int, app: AppKit.NSApplication = None, allWindows=None):
"""
Get the list of Window objects whose windows contain the point ``(x, y)`` on screen
:param x: X screen coordinate of the window(s)
:param y: Y screen coordinate of the window(s)
:param app: (optional) NSApp() o... | 009a4d439e7948fc3829e132118716ea808b5185 | 19,609 |
def find_closest_vertices(surface_coords, point_coords):
"""Return the vertices on a surface mesh closest to some given coordinates.
The distance metric used is Euclidian distance.
Parameters
----------
surface_coords : numpy array
Array of coordinates on a surface mesh
point_coords : ... | 62adc1082d24ff70e8f285a6a457b6bff0768854 | 19,610 |
def blob_utils_get_loss_gradients(model, loss_blobs):
"""Generate a gradient of 1 for each loss specified in 'loss_blobs'"""
loss_gradients = {}
for b in loss_blobs:
loss_grad = model.net.ConstantFill(b, [b + '_grad'], value=1.0)
loss_gradients[str(b)] = str(loss_grad)
return loss_gradie... | 2543dc532469405ad0ae1b1288b9956841565238 | 19,611 |
def _list_indexing(X, key, key_dtype):
""" Index a Python list """
if np.isscalar(key) or isinstance(key, slice):
# key is a slice or a scalar
return X[key]
if key_dtype == 'bool':
# key is a boolean array-like
return list(compress(X, key))
# key is a integer array-like o... | 47a5ae6be9db172c5ac194c7989540c79a27f89f | 19,612 |
import json
import requests
def credit_rating():
"""
credit_rating http api
"""
return_dict = {'rescode': '200', 'credit-rating': '1', 'description': 'Good credit'}
if request.get_data() is None:
return_dict['rescode'] = '5004'
return json.dumps(return_dict, ensure_ascii=False)
... | 06a12b6f0801a1b56b17eb53ec4009c4ab5777f5 | 19,614 |
def updateGlobalInventory(D_SKUs: pd.DataFrame, inventoryColumn: str):
"""
Update the global inventory of the warehouse
Args:
D_SKUs (pd.DataFrame): Input SKUs dataframe.
inventoryColumn (str): column name with the inventory.
Returns:
D_inventory (pd.DataFrame): Output DataFram... | 7e9d824de8830b40a88ae5fbbffac89e69a57869 | 19,615 |
from datetime import datetime
def _query_checks(start, end, owner_id=''):
"""Get the number of rules checks from `start` to `end` in 1-day windows"""
series = []
assert (isinstance(end, datetime.datetime) and
isinstance(start, datetime.datetime))
while start < end:
stop = start + d... | 9df5e7dd9a6ea2f2bb1f4f1a6a89db6b16d6814b | 19,616 |
def _FilterManufacturedEvents(results):
"""Return a list of results where first question is 'MANUFACTURED'.
Manufactured events are either Recording events that correspond to
an instrumented event in the browser, or Showed notification events
that correspond to when the user was invited to take a survey.
Ar... | 51fb34402e17249b63b8061bf70a2879925c8fba | 19,617 |
def Max(data):
"""Returns the maximum value of a time series"""
return data.max() | 0d4781da4384eae65de4e13860995848ae8de678 | 19,618 |
def clean_words(words, remove_stopwords=False, language='portuguese'):
"""Stems and removes stopwords from a set of word-level tokens using the RSLPStemmer.
Args:
words (list): Tokens to be stemmed.
remove_stopwords (bool): Whether stopwords should be removed or not.
language (str): Ide... | 4dd721a691e832dc3b8160c678fe7e1c05b6a015 | 19,619 |
def parse_healing_and_target(line):
"""Helper method that finds the amount of healing and who it was provided to"""
split_line = line.split()
target = ' '.join(split_line[3:split_line.index('for')])
target = target.replace('the ', '')
amount = int(split_line[split_line.index('for')+1])
return... | 3f11c0807ab87d689e47a79fc7e12b32c00dbd95 | 19,621 |
from typing import Optional
from typing import Sequence
def _decode_and_center_crop(
image_bytes: tf.Tensor,
jpeg_shape: Optional[tf.Tensor] = None,
image_size: Sequence[int] = (224, 224),
) -> tf.Tensor:
"""Crops to center of image with padding then scales."""
if jpeg_shape is None:
jpeg_shape = ... | 7a7ad3eb36099d560da126011845426bdcd1f326 | 19,622 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.