content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import collections
import math
def compute_bleu(reference_corpus,
translation_corpus,
max_order=4,
smooth=False):
"""Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of lists of references for ea... | 4a7f45ea988e24ada554b38cea84083effe164bd | 3,658,953 |
def rf_agg_local_mean(tile_col):
"""Compute the cellwise/local mean operation between Tiles in a column."""
return _apply_column_function('rf_agg_local_mean', tile_col) | d65f6c7de674aac10ee91d39c8e5bc4ea6284e58 | 3,658,954 |
import json
def Shot(project, name):
"""
샷 정보를 가지고 오는 함수.
(딕셔너리, err)값을 반환한다.
"""
restURL = "http://10.0.90.251/api/shot?project=%s&name=%s" % (project, name)
try:
data = json.load(urllib2.urlopen(restURL))
except:
return {}, "RestAPI에 연결할 수 없습니다."
if "error" in data:
return {}, data["error"]
return da... | 6bd7ac1e3663faf8b120c03a1e873255557bc30d | 3,658,955 |
def inversion_double(in_array):
"""
Get the input boolean array along with its element-wise logical not beside it. For error correction.
>>> inversion_double(np.array([1,0,1,1,1,0,0,1], dtype=np.bool))
array([[ True, False, True, True, True, False, False, True],
[False, True, False, Fal... | 84253bdec88d665ad8f68b0eb252f3111f4a91ac | 3,658,956 |
def solution(N):
"""
This is a fairly simple task.
What we need to do is:
1. Get string representation in binary form (I love formatted string literals)
2. Measure biggest gap of zeroes (pretty self explanatory)
"""
# get binary representation of number
binary_repr = f"{N:b}"
# in... | 54b9dffe219fd5d04e9e3e3b07e4cb0120167a6f | 3,658,957 |
from typing import Tuple
def distributed_compute_expectations(
building_blocks: Tuple[cw.ComplexDeviceArray],
operating_axes: Tuple[Tuple[int]],
pbaxisums: Tuple[Tuple[cw.ComplexDeviceArray]],
pbaxisums_operating_axes: Tuple[Tuple[Tuple[int]]],
pbaxisum_coeffs: Tuple[Tuple[float]],
num_discret... | d26c7595c604f7c52b3546083837de35ef4b4202 | 3,658,958 |
def extractStudents(filename):
"""
Pre: The list in xls file is not empty
Post: All students are extract from file
Returns students list
"""
list = []
try:
# open Excel file
wb = xlrd.open_workbook(str(filename))
except IOError:
print ("Oops! No file "... | e10d942c4e1742b4e8de9ec6a1248f27b2a4b1d5 | 3,658,959 |
def clean_ip(ip):
"""
Cleans the ip address up, useful for removing leading zeros, e.g.::
1234:0:01:02:: -> 1234:0:1:2::
1234:0000:0000:0000:0000:0000:0000:000A -> 1234::a
1234:0000:0000:0000:0001:0000:0000:0000 -> 1234:0:0:0:1::
0000:0000:0000:0000:0001:0000:0000:0000 -> ::1:0:... | f0828e793a3adfef536bf7cb76d73a9af097aa00 | 3,658,961 |
def meta_caption(meta) -> str:
"""makes text from metadata for captioning video"""
caption = ""
try:
caption += meta.title + " - "
except (TypeError, LookupError, AttributeError):
pass
try:
caption += meta.artist
except (TypeError, LookupError, AttributeError):
... | 6ef117eb5d7a04adcee25a755337909bfe142014 | 3,658,963 |
def ticket_id_correctly_formatted(s: str) -> bool:
"""Checks if Ticket ID is in the form of 'PROJECTNAME-1234'"""
return matches(r"^\w+-\d+$|^---$|^-$")(s) | 2bb1624ac2080852badc6ab2badcb2e1229f5fcc | 3,658,964 |
def test_1():
"""
f(x) = max(.2, sin(x)^2)
"""
test_graph = FunctionTree('Test_1')
max_node = Max('max')
const_node = Constant('0.2', .2)
square_node = Square('square')
sin_node = Sin('sin')
test_graph.insert_node(max_node, 'Output', 'x')
test_graph.insert_node(square_node, 'max'... | c6b47e386cdb7caa2290df2250fee3ad6aecbab7 | 3,658,965 |
def export_vector(vector, description, output_name, output_method='asset'):
"""Exports vector to GEE Asset in GEE or to shapefile
in Google Drive.
Parameters
----------
vector : ee.FeatureCollection
Classified vector segments/clusters.
description : str
Description of the expor... | 19cfa1a907aec4f25b1d8392f02a628f9e07ed7c | 3,658,966 |
def optimize_centers_mvuiq(A, B, Q, centers, keep_sparsity=True):
""" minimize reconstruction error after weighting by matrix A and make it unbiased
min_{c_i} \|A.(\sum_i Q_i c_i) - B\|_F^2 such that sum(B-A(\sum_i Q_i c_i)) = 0
"""
num_levels = len(centers)
thr = sla.norm(A) * 1e-6
# 1- co... | 5a059bf9a88ed31a6cc75cecd2b0f7ef4273c5af | 3,658,967 |
def container_instance_task_arns(cluster, instance_arn):
"""Fetch tasks for a container instance ARN."""
arns = ecs.list_tasks(cluster=cluster, containerInstance=instance_arn)['taskArns']
return arns | ca5f0be6aa054f7d839435a8c32c395429697639 | 3,658,968 |
def benchmark(pipelines=None, datasets=None, hyperparameters=None, metrics=METRICS, rank='f1',
distributed=False, test_split=False, detrend=False, output_path=None):
"""Evaluate pipelines on the given datasets and evaluate the performance.
The pipelines are used to analyze the given signals and l... | 09e7ebda30d0e9eec1b11a68fbc566bf8f39d841 | 3,658,969 |
def notNone(arg,default=None):
""" Returns arg if not None, else returns default. """
return [arg,default][arg is None] | 71e6012db54b605883491efdc389448931f418d0 | 3,658,970 |
def get_scorer(scoring):
"""Get a scorer from string
"""
if isinstance(scoring, str) and scoring in _SCORERS:
scoring = _SCORERS[scoring]
return _metrics.get_scorer(scoring) | fbf1759ae4c6f93be036a6af479de89a732bc520 | 3,658,971 |
from typing import Iterator
def triangle_num(value: int) -> int:
"""Returns triangular number for a given value.
Parameters
----------
value : int
Integer value to use in triangular number calculaton.
Returns
-------
int
Triangular number.
Examples:
>>> trian... | f22554b2c220d368b1e694021f8026162381a7d0 | 3,658,972 |
import torch
def locations_sim_euclidean(image:DataBunch, **kwargs):
"""
A locations similarity function that uses euclidean similarity between vectors. Predicts the anatomical locations of
the input image, and then returns the eucliean similarity between the input embryo's locations vector and the
lo... | d45c33641ac6327963f0634878c99461de9c1052 | 3,658,973 |
def _butter_bandpass_filter(data, low_cut, high_cut, fs, axis=0, order=5):
"""Apply a bandpass butterworth filter with zero-phase filtering
Args:
data: (np.array)
low_cut: (float) lower bound cutoff for high pass filter
high_cut: (float) upper bound cutoff for low pass filter
fs... | 706770bbf78e103786a6247fc56df7fd8b41665a | 3,658,974 |
def transform_and_normalize(vecs, kernel, bias):
"""应用变换,然后标准化
"""
if not (kernel is None or bias is None):
vecs = (vecs + bias).dot(kernel)
return vecs / (vecs**2).sum(axis=1, keepdims=True)**0.5 | bb32cd5c74df7db8d4a6b6e3ea211b0c9b79db47 | 3,658,975 |
def mpesa_response(r):
"""
Create MpesaResponse object from requests.Response object
Arguments:
r (requests.Response) -- The response to convert
"""
r.__class__ = MpesaResponse
json_response = r.json()
r.response_description = json_response.get('ResponseDescription', '')
r.error_code = json_response.get('e... | e416030d39411ce19aee28735465ba035461f802 | 3,658,976 |
def swap_flies(dataset, indices, flies1=0, flies2=1):
"""Swap flies in dataset.
Caution: datavariables are currently hard-coded!
Caution: Swap *may* be in place so *might* will alter original dataset.
Args:
dataset ([type]): Dataset for which to swap flies
indices ([type]): List of ind... | 1f1941d8d6481b63efd1cc54fcf13f7734bccf8b | 3,658,977 |
def periodic_kernel(avetoas, log10_sigma=-7, log10_ell=2,
log10_gam_p=0, log10_p=0):
"""Quasi-periodic kernel for DM"""
r = np.abs(avetoas[None, :] - avetoas[:, None])
# convert units to seconds
sigma = 10**log10_sigma
l = 10**log10_ell * 86400
p = 10**log10_p * 3.16e7
g... | 14dc89fbbf501ee42d7778bd14a9e35d22bc69ea | 3,658,978 |
def emails(request):
"""
A view to send emails out to hunt participants upon receiving a valid post request as well as
rendering the staff email form page
"""
teams = Hunt.objects.get(is_current_hunt=True).real_teams
people = []
for team in teams:
people = people + list(team.person_... | 93cc8099e8f73b2607ab736a2aae4ae59ca1fe4d | 3,658,979 |
def _stochastic_universal_sampling(parents: Population, prob_distribution: list, n: int):
"""
Stochastic universal sampling (SUS) algorithm. Whenever more than one sample is to be drawn from the distribution
the use of the stochastic universal sampling algorithm is preferred compared to roulette wheel algor... | fb6b58cbdedbd133a7ba72470c2fc6586265ed4c | 3,658,980 |
def _add_simple_procparser(subparsers, name, helpstr, func, defname='proc',
xd=False, yd=False, dualy=False, other_ftypes=True):
"""Add a simple subparser."""
parser = _add_procparser(subparsers, name, helpstr, func, defname=defname)
_add_def_args(parser, xd=xd, yd=yd, dualy=dualy... | d7ba916453921d4ad362367c43f597f81fb2db9b | 3,658,982 |
def comprspaces(*args):
"""
.. function:: comprspaces(text1, [text2,...]) -> text
This function strips (from the beginning and the end) and compresses
the spaces in its input.
Examples:
>>> table1('''
... ' an example with spaces ' 'another example with spaces '
... | 7cf4d23dac7fb0d36f9224598f103b5918167bd5 | 3,658,985 |
import socket
def find_available_port():
"""Find an available port.
Simple trick: open a socket to localhost, see what port was allocated.
Could fail in highly concurrent setups, though.
"""
s = socket.socket()
s.bind(('localhost', 0))
_address, port = s.getsockname()
s.close()
r... | 1d81ff79fa824bc8b38c121a632890973f0639ea | 3,658,986 |
def merge_deep(dct1, dct2, merger=None):
"""
Deep merge by this spec below
:param dct1:
:param dct2:
:param merger Optional merger
:return:
"""
my_merger = merger or Merger(
# pass in a list of tuples,with the
# strategies you are looking to apply
# to each ty... | 1257e7a8242fde6a70feb3cfe373979bbf439726 | 3,658,988 |
def step(
context, bind_to, data, title='', area=False, x_is_category=False,
labels=False, vertical_grid_line=False, horizontal_grid_line=False,
show_legend=True, zoom=False, group_tooltip=True, height=None,
width=None
):
"""Generates javascript code to show a 'step' chart.
... | e135f1315dc635cc12dec403b3b6a268ed1c0a2b | 3,658,989 |
from typing import List
def get_baseline_y(line: PageXMLTextLine) -> List[int]:
"""Return the Y/vertical coordinates of a text line's baseline."""
if line_starts_with_big_capital(line):
return [point[1] for point in line.baseline.points if point[1] < line.baseline.bottom - 20]
else:
return... | 7195f801e3012f5514b0d4eea7d5df9a36764412 | 3,658,991 |
import time
def get_device_type(dev, num_try=1):
""" Tries to get the device type with delay """
if num_try >= MAX_DEVICE_TYPE_CHECK_RETRIES:
return
time.sleep(1) # if devtype is checked to early it is reported as 'unknown'
iface = xwiimote.iface(dev)
device_type = iface.get_devtype()
... | 0caec78baeeb3da7ba3b99d68d80b9d1439af294 | 3,658,992 |
def index():
"""
This is the grocery list.
Concatenates the ingredients from all the upcoming recipes
The ingredients dict that we pass to the template has this structure
{
"carrot": {
"g": 200,
"number": 4,
"str": "200g, 4number",
},
"salt... | 343f54d097c95e92bbca1bbe087168a348d42771 | 3,658,993 |
def test_Fit_MinFunc():
"""
There are times where I don't pass just a simple function to the fitting algorithm.
Instead I need to calculate the error myself and pass that to the model. This tests
that ability.
"""
init = {
'm': 20,
'b': -10
}
def func(X, *args):
... | 4884302ad03cb04e4d293e05b743f1d2aaf51141 | 3,658,994 |
def BOP(data):
"""
Balance of Power Indicator
:param pd.DataFrame data: pandas DataFrame with open, high, low, close data
:return pd.Series: with indicator data calculation results
"""
fn = Function('BOP')
return fn(data) | 14502e0c1fd6f5224edfa403ae58e75a4056c74c | 3,658,995 |
def get_infinite(emnist_client_data, num_pseudo_clients):
"""Converts a Federated EMNIST dataset into an Infinite Federated EMNIST set.
Infinite Federated EMNIST expands each writer from the EMNIST dataset into
some number of pseudo-clients each of whose characters are the same but apply
a fixed random affine ... | 68b4ed0643e48adba2478022eff10a52222f75df | 3,658,996 |
def create_plot(df, title, carbon_unit, cost_unit, ylimit=None):
"""
:param df:
:param title: string, plot title
:param carbon_unit: string, the unit of carbon emissions used in the
database/model, e.g. "tCO2"
:param cost_unit: string, the unit of cost used in the database/model,
e.g. "USD"... | e320a523bbdbfc12a3e84948935803da5304624e | 3,658,997 |
def get_app(name, **kwargs):
"""Returns an instantiated Application based on the name.
Args:
name (str): The name of the application
kwargs (dict): Keyword arguments used for application instantiation
Returns:
deepcell.applications.Application: The instantiated application
"""
... | 1fe9d1e300a086b7184760556c65470c62a0cc14 | 3,658,998 |
def worker_complete():
"""Complete worker."""
participant_id = request.args.get('participant_id')
if not participant_id:
return error_response(
error_type="bad request",
error_text='participantId parameter is required'
)
try:
_worker_complete(participant_... | e30b45e84025b11bcf6640931f72d9fc4f4f9873 | 3,658,999 |
def combine(connected_events):
"""
Combine connected events into a graph.
:param connected_events: see polychronous.filter
:return: graph_of_connected_events
"""
graph_of_connected_events = nx.Graph()
graph_of_connected_events.add_edges_from(connected_events)
return (graph_of_connected_e... | 99471930f70bea0583d36d3c0c13fc62b23d6fe8 | 3,659,000 |
import hashlib
def calculate_hash(filepath, hash_name):
"""Calculate the hash of a file. The available hashes are given by the hashlib module. The available hashes can be listed with hashlib.algorithms_available."""
hash_name = hash_name.lower()
if not hasattr(hashlib, hash_name):
raise Exception... | 975fe0a2a4443ca3abc67ed950fb7200409f2497 | 3,659,001 |
def default_mp_value_parameters():
"""Set the different default parameters used for mp-values.
Returns
-------
dict
A default parameter set with keys: rescale_pca (whether the PCA should be
scaled by variance explained) and nb_permutations (how many permutations to
calculate emp... | 0dcac3981154fbf0cc1fa0eeed6e83a1e1b63294 | 3,659,003 |
def svn_wc_diff(*args):
"""
svn_wc_diff(svn_wc_adm_access_t anchor, char target, svn_wc_diff_callbacks_t callbacks,
void callback_baton,
svn_boolean_t recurse, apr_pool_t pool) -> svn_error_t
"""
return _wc.svn_wc_diff(*args) | c4fbc11d26b6da2d595cb79314b0d901b084eb52 | 3,659,005 |
import re
def _FindResourceIds(header, resource_names):
"""Returns the numerical resource IDs that correspond to the given resource
names, as #defined in the given header file."
"""
pattern = re.compile(
r'^#define (%s) _Pragma\S+ (\d+)$' % '|'.join(resource_names))
with open(header, 'r') as f:
... | 24847b1d4374a2022ae12f5161bd9df4becd110d | 3,659,006 |
import re
def resolve_request_path(requested_uri):
"""
Check for any aliases and alter the path accordingly.
Returns resolved_uri
"""
for key, val in PATH_ALIASES.items():
if re.match(key, requested_uri):
return re.sub(key, val, requested_uri)
return requested_uri | 5405a795a95279a354d455f3702dbf2c3dc6f1e0 | 3,659,007 |
def apim_api_delete(
client, resource_group_name, service_name, api_id, delete_revisions=None, if_match=None, no_wait=False):
"""Deletes an existing API. """
cms = client.api
return sdk_no_wait(
no_wait,
cms.delete,
resource_group_name=resource_group_name,
service_n... | 4be4f895ae576ee1ffd08af31abcdad193b84b2c | 3,659,008 |
def deep_copy(obj):
"""Make deep copy of VTK object."""
copy = obj.NewInstance()
copy.DeepCopy(obj)
return copy | c00c4ff44dad5c0c018152f489955f08e633f5ed | 3,659,009 |
def get_dunn_index(fdist, *clusters):
"""
Returns the Dunn index for the given selection of nodes.
J.C. Dunn. Well separated clusters and optimal fuzzy
partitions. 1974. J.Cybern. 4. 95-104.
"""
if len(clusters)<2:
raise ValueError, "At least 2 clusters are required"
intra_dist =... | c78c5302d78b5d5969a5edf9e19b81ee6f68bfbf | 3,659,010 |
import random
def sample(words, n=10) -> str:
"""Sample n random words from a list of words."""
return [random.choice(words) for _ in range(n)] | cad435238c776b5fcda84d50295ac50298bf3ab2 | 3,659,011 |
def cov_dense(n_features=100, scale=0.5,
edges='ones', pos=True, force_psd=True, random_state=None):
"""
Returns a covariance matrix with a constant diagonal and whose off diagnale elements are obtained from adj_mats.complete_graph()
Parameters
----------
n_features: int
scale: f... | 48b8f5fec91ea11acaf9ce026d8b1742b5185604 | 3,659,013 |
def measure_fwhm(array):
"""Fit a Gaussian2D model to a PSF and return the FWHM
Parameters
----------
array : numpy.ndarray
Array containing PSF
Returns
-------
x_fwhm : float
FWHM in x direction in units of pixels
y_fwhm : float
FWHM in y direction in units of... | e3ee047b453b979387505a19bdfebb75950a3916 | 3,659,014 |
def exists(profile, bucket, name):
"""Check if a file exists in an S3 bucket.
Args:
profile
A profile to connect to AWS with.
bucket
The name of the bucket you want to find the file in.
name
The name of a file.
Returns:
True if it exis... | 5269cca9198a1d100b76b13f6e2fbf7314d948fd | 3,659,015 |
def project_login(driver):
"""
針對多綫程執行設定不同樣本編號,若修改問卷,也許提供該問卷樣本編號的第一順位號碼。
"""
SAMPLE_NUMBER = 20200101+sample_add
try:
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, '//*[@name="{}"][1]'
.format(str(SAMPLE_NUMBER))))).click() # 選擇樣本編號作答
sleep(1)
... | db3ef26e1769cb991c887509427f9d809047398d | 3,659,017 |
def convert_convolutionfunction_to_image(cf):
""" Convert ConvolutionFunction to an image
:param cf:
:return:
"""
return create_image_from_array(cf.data, cf.grid_wcs, cf.polarisation_frame) | 6f5819abce6a987665ff49af9e5fca70f586a478 | 3,659,018 |
def macro(libname):
"""Decorator for macros (Moya callables)."""
def deco(f):
exposed_elements[libname] = f
return f
return deco | c4d06d2b9e3fa7913445554794027e68328ab918 | 3,659,019 |
import logging
import torch
def get_dataloaders(dataset, mode='train', root=None, shuffle=True, pin_memory=True,
batch_size=8, logger=logging.getLogger(__name__), normalize=False, **kwargs):
"""A generic data loader
Parameters
----------
dataset : {"openimages", "jetimages", "eva... | 6bb40b3eb1bc004418dd8910dab1432cd3984ca5 | 3,659,020 |
def stats_file(filename, shape, dtype=None, file_format='raw',
out_of_core=True, buffer_size=None, max_memory=None,
progress_frequency=None):
"""stats_file(filename, shape, dtype=None, file_format='raw',
out_of_core=True, buffer_size=None, max_memory=None,
... | 750b4d334aa25a2423e5278eab7cd5ee43385303 | 3,659,021 |
def _weight_func(dist):
"""Weight function to replace lambda d: d ** -2.
The lambda function is not valid because:
if d==0 then 0^-2 is not valid."""
# Dist could be multidimensional, flatten it so all values
# can be looped
with np.errstate(divide="ignore"):
retval = 1.0 / dist
ret... | 9052b68592f2f6cf4c59c623a3561f77d3d2b933 | 3,659,023 |
def two_poles(time_limit=_DEFAULT_TIME_LIMIT, random=None,
environment_kwargs=None):
"""Returns the Cartpole Balance task with two poles."""
physics = Physics.from_xml_string(*get_model_and_assets(num_poles=2))
task = Balance(swing_up=True, sparse=False, random=random)
environment_kwargs = environ... | b5236731d61464067073c3275cdd03d493f17821 | 3,659,024 |
def process_topic_entity(entity: dict, language: str) -> bool:
"""
Given a topic entity, gather its metadata
:param entity
:param language:
:type entity dict
:type language str
:returns bool
"""
try:
# Get ID
remote_id = entity["title"]
print("%s\t%s" % ("ID"... | 2f03c0d24f35e49cd05ac11389b91345cc43de6e | 3,659,025 |
import math
import torch
def _no_grad_trunc_normal_(tensor: Tensor, mean: float, std: float, a: float, b: float) -> Tensor:
"""Cut & paste from PyTorch official master until it's in a few official
releases - RW Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
Ar... | 064fce46591c490999c6495999554700f478878b | 3,659,026 |
def inverse_update(C, m, return_drop=False):
"""
Compute the inverse of a matrix with the m-th row and column dropped given knowledge of the inverse of the original
matrix.
C = inv(A)
B = drop_col(drop_row(A, m),m)
computes inv(B) given only C
Args:
C: inverse of full m... | 0f368d30d0459fe3d07d6fc1fa19dedc449e23e9 | 3,659,027 |
def loss_calc(settings, all_batch, market_batch):
""" Calculates nn's NEGATIVE loss.
Args:
settings: contains the neural net
all_batch: the inputs to neural net
market_batch: [open close high low] used to calculate loss
Returns:
cost: loss - l1 penalty
"""
loss = set... | fdca1bb0fa86d1972c2a0f8b1fab10183e98fb4e | 3,659,028 |
def fits_downloaded_correctly(fits_loc):
"""
Is there a readable fits image at fits_loc?
Does NOT check for bad pixels
Args:
fits_loc (str): location of fits file to open
Returns:
(bool) True if file at fits_loc is readable, else False
"""
try:
img, _ = fits.getdat... | 8df470b4b2895fb7d77cbccefbd2eae7f22c649b | 3,659,029 |
def union_of_rects(rects):
"""
Calculates union of two rectangular boxes
Assumes both rects of form N x [xmin, ymin, xmax, ymax]
"""
xA = np.min(rects[:, 0])
yA = np.min(rects[:, 1])
xB = np.max(rects[:, 2])
yB = np.max(rects[:, 3])
return np.array([xA, yA, xB, yB], dtype=np.int32) | 904cb58f593bedfbf0e28136a446b4f877955e49 | 3,659,030 |
from typing import List
from typing import Dict
def configure_services(config: List[Dict]) -> Dict[str, GcpServiceQuery]:
"""
Generate GcpServiceQuery list from config
:param config: list with GcpServieQuery's configuration
:return: mapping of service name to GcpServiceQuery objects
"""
if not... | 3c9b9472de4d319446ec4da1d990ecc1750bd248 | 3,659,031 |
def tags_get():
"""
Get endpoint /api/tag
args:
optional company_filter(int) - id of a company, will only return tag relation to said company
optional crowd(int) - 0 - 2 specifing crowd sourcing option. Key:
0 - all tags
1 - Only crowd sourced tags
2 - Only non crowd... | c009c0b84bbc825383dffb1141361dd1732b7b19 | 3,659,032 |
def get_accept_languages(accept):
"""Returns a list of languages, by order of preference, based on an
HTTP Accept-Language string.See W3C RFC 2616
(http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) for specification.
"""
langs = parse_http_accept_header(accept)
for index, lang in enumerate... | ad329605cd0101e61c2c21aa42f2c81a84db771b | 3,659,034 |
def get_princ_axes_xyz(tensor):
"""
Gets the principal stress axes from a stress tensor.
Modified from beachball.py from ObsPy, written by Robert Barsch.
That code is modified from Generic Mapping Tools (gmt.soest.hawaii.edu)
Returns 'PrincipalAxis' classes, which have attributes val, trend, p... | e9285464e17eb987ebfd21c8e066ff745a856dc1 | 3,659,035 |
def extractYoushoku(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if 'The Other World Dining Hall' in item['tags'] and (chp or vol):
return buildReleaseMessageWithType(item, 'The Other World Dining Hall', vol, chp, frag=frag, postfix=postfix)
return False | 686daef4d594e0e53779be48d7c49a525cabe4ee | 3,659,036 |
def _perform_Miecalculations(diam, wavelength, n, noOfAngles=100.):
"""
Performs Mie calculations
Parameters
----------
diam: NumPy array of floats
Array of diameters over which to perform Mie calculations; units are um
wavelength: float
Wavelength of light... | 4ce8fa518477c3eb38816d8f441207716b3a90df | 3,659,037 |
from typing import Tuple
def load_config_dict(pipette_id: str) -> Tuple[
'PipetteFusedSpec', 'PipetteModel']:
""" Give updated config with overrides for a pipette. This will add
the default value for a mutable config before returning the modified
config value.
"""
override = load_overrides... | 485db2aad493eda30e6dad07b3d6c9413bc5c3c8 | 3,659,038 |
def ErrorAddEncKey(builder, encKey):
"""This method is deprecated. Please switch to AddEncKey."""
return AddEncKey(builder, encKey) | c39bb36b3923ca1a0e508b23ef84a6de130700a3 | 3,659,039 |
def _read_txs_from_file(f):
"""
Validate headers and read buy/sell transactions from the open file-like object 'f'.
Note: we use the seek method on f.
"""
ans = []
f.seek(0)
workbook = openpyxl.load_workbook(f)
sheet = workbook.active
all_contents = list(sheet.rows)
_validate_he... | 0c62c647a2ff1a797fb5e8593279bbf64bc0d495 | 3,659,040 |
from typing import Union
def get_generator_regulation_lower_term_4(data, trader_id, intervention) -> Union[float, None]:
"""Get L5RE term 4 in FCAS availability calculation"""
# Term parameters
enablement_min = get_effective_enablement_min(data, trader_id, 'L5RE')
energy_target = lookup.get_trader_so... | 626ab26f92feefea25777046c1fc37c4115f7be8 | 3,659,041 |
def count_parameters(model):
"""count model parameters"""
return sum(p.numel() for p in model.parameters() if p.requires_grad) | 5edcb3ee03794cb66f5986670c4825efab93a1d8 | 3,659,042 |
def string_rule_variable(label=None, params=None, options=None, public=True):
"""
Decorator to make a function into a string rule variable.
NOTE: add **kwargs argument to receive Rule as parameters
:param label: Label for Variable
:param params: Parameters expected by the Variable function
:pa... | 3bd35ac2e27c58ee35f7e13bb359cb8240f8efda | 3,659,043 |
def detect_horizon_lines(image_thre, row, busbar, cell_size, thre=0.6, split=50, peak_interval=None, margin=None):
""" Detect horizontal edges by segmenting image into vertical splits
Parameters
---------
image_thre: array
Adaptive threshold of raw images
row: int
Number of rows of solar m... | e8365b29829d6e1a71c4c9caefff221d9357b0a3 | 3,659,044 |
def countRoem(cards, trumpSuit=None):
"""Counts the amount of roem (additional points) in a list of cards
Args:
Returns:
Integer value how many points of roem are in the cards in total
"""
roem = 0
# Stuk
# Without a trumpSuit, stuk is impossible
if trumpSuit is not None:
... | 31e2dbf346801fa81e5a5905a480f6d5b8e9ce1a | 3,659,045 |
from typing import Optional
def batch_to_space(
data: NodeInput,
block_shape: NodeInput,
crops_begin: NodeInput,
crops_end: NodeInput,
name: Optional[str] = None,
) -> Node:
"""Perform BatchToSpace operation on the input tensor.
BatchToSpace permutes data from the batch dimension of the d... | fe7004243e7c4a6dfd78b1f39df22ba7290c9244 | 3,659,046 |
def url_in(url):
""" Send a URL and I'll post it to Hive """
custom_json = {'url': url}
trx_id , success = send_notification(custom_json)
return trx_id, success | ecfcb02cdbd9050a5a305f38d9673d64b9b1d307 | 3,659,047 |
def login():
"""
Display a basic login form in order to log in a user
"""
if request.method == 'GET':
return render_template('login.html')
else:
try:
usr = User.query.get(request.form['user_id'])
if bcrypt.checkpw(request.form['user_password'].encode('utf-... | 37702dc290d627544d5714ed21d8804eaa00f354 | 3,659,048 |
def hflip(stream):
"""Flip the input video horizontally.
Official documentation: `hflip <https://ffmpeg.org/ffmpeg-filters.html#hflip>`__
"""
return FilterNode(stream, hflip.__name__).stream() | 140f7d4ceecee09e5f0ba7db9a68cee15e536ffa | 3,659,049 |
def get_diagonal_ripple_rainbows_2():
"""
Returns 11 diagonal ripple rainbows
Programs that use this function:
- Diagonal Ripple 3
- Diagonal Ripple 4
"""
rainbow01 = [
[C1, C2, C3, C4, C5, C6, C7, C8],
[C1, C2, C3, C4, C5, C6, C7, C8],
[C1, C2, C3, C4, C5, ... | ce917a063de580b2fcacfe2b59991585aefe30a4 | 3,659,050 |
def matrix_prod(A, B, display = False):
"""
Computes the matrix product of two matrices using array slicing and vector operations.
"""
if A.shape[1] != B.shape[0]:
raise ValueError("Dimensions not compatible.")
# Not allowed!?
#matrix = A.dot(B)
# Dotproduct of each A.row*B.clm
... | c38c3c3c9b1d2cc3edf6efb1997fe94a15c870ec | 3,659,051 |
def remove_quat_discontinuities(rotations):
"""
Removing quat discontinuities on the time dimension (removing flips)
:param rotations: Array of quaternions of shape (T, J, 4)
:return: The processed array without quaternion inversion.
"""
rots_inv = -rotations
for i in range(1, rotations.sha... | 7d3874f5c56f82f3a8951daef48ac115f7f8943a | 3,659,052 |
import glob
def compute_profile_from_frames(frames_str, ax, bt, box, N_bins=100, \
shift=None, verbose=False):
"""
Compute a density profile from a batch of xyz frames.
Input
=====
- frames_str: a regex containing frames in xyz format
- ax: axis along which to compute the profile
... | 70702dbcf73f2a7e9894899ca20f81eadc3046fe | 3,659,053 |
import urllib
import requests
import json
def wikipedia_search(query, lang="en", max_result=1):
"""
https://www.mediawiki.org/wiki/API:Opensearch
"""
query = any2unicode(query)
params = {
"action":"opensearch",
"search": query,
"format":"json",
#"formatversion":... | e88b50c11d78989e086417d15e91515d24151586 | 3,659,054 |
def group_result(result, func):
"""
:param result: A list of rows from the database: e.g. [(key, data1), (key, data2)]
:param func: the function to reduce the data e.g. func=median
:return: the data that is reduced. e.g. [(key, (data1+data2)/2)]
"""
data = {}
for key, value in result:
... | 7687521c216210badcda5ee54bd59a3bc6a234bd | 3,659,055 |
import torch
def prep_image(img, inp_dim):
"""
Prepare image for inputting to the neural network.
Returns a Variable
"""
orig_im = img
dim = orig_im.shape[1], orig_im.shape[0]
img = cv2.resize(orig_im, (inp_dim, inp_dim))
# img_ = img[:,:,::-1].transpose((2,0,1)).copy()
img_... | 65159c8ce3a2df3cb09a6f1f318bb3374943e314 | 3,659,056 |
import uuid
def extractLogData(context):
"""
helper function to extract all important data from the web context.
:param context: the web.py context object
:return: a dictionary with all information for the logging.
"""
logData = {}
logData['ip'] = context.ip
logData['account'] = cont... | 5fb68d4f19dae0b7175a089dd1366cab0407152b | 3,659,057 |
def Backbone(backbone_type='ResNet50', use_pretrain=True):
"""Backbone Model"""
weights = None
if use_pretrain:
weights = 'imagenet'
def backbone(x_in):
if backbone_type == 'ResNet50':
return ResNet50(input_shape=x_in.shape[1:], include_top=False,
... | 23bc493e8306d5dc5dba33cd2f67de231cbb3e02 | 3,659,058 |
def start(ctx, vca_client, **kwargs):
"""
power on server and wait network connection availability for host
"""
# combine properties
obj = combine_properties(
ctx, kwargs=kwargs, names=['server'],
properties=[VCLOUD_VAPP_NAME, 'management_network'])
# get external
if obj.get(... | 6e3e3a94095ef200e586f7dfdc7e117ae3ee375f | 3,659,059 |
def softplus(z):
"""Numerically stable version of log(1 + exp(z))."""
# see stabilizing softplus: http://sachinashanbhag.blogspot.com/2014/05/numerically-approximation-of-log-1-expy.html # noqa
mu = z.copy()
mu[z > 35] = z[z > 35]
mu[z < -10] = np.exp(z[z < -10])
mu[(z >= -10) & (z <= 35)] = log... | f683c1f2240d053c4ee2c24f64ff5576c0d9d32d | 3,659,060 |
from typing import Mapping
from typing import Hashable
from typing import Union
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import OrderedDict
from typing import Any
def merge_indexes(
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]],
variables: Mappi... | b893d118312697d1995a0a42bbff8354b73ca642 | 3,659,061 |
def least_squares(m, n):
""" Create a least squares problem with m datapoints and n dimensions """
A = np.random.randn(m, n)
_x = np.random.randn(n)
b = A.dot(_x)
x = cp.Variable(n)
return (x, cp.Problem(cp.Minimize(cp.sum_squares(A * x - b) + cp.norm(x, 2)))) | 21b3b4577ec232f6e74d1f096946d0923f867cf7 | 3,659,062 |
def expand_amn(a, kpoints, idx, Rvectors, nproj_atom=None):
"""
Expand the projections matrix by translations of the orbitals
Parameters
----------
a : ndarray, shape (nkpts, nbnds, nproj)
kpoints : ndarray, shape (nkpts, 3)
idx : ndarray
indices of translated orbitals
Rvectors:... | d68a7cd4cb019b2d516305d0b6a2b45f6a422ba8 | 3,659,065 |
def combine_basis_vectors(weights, vectors, default_value=None, node_num=None):
"""
Combine basis vectors using ``weights`` as the Manning's n value for each
basis vector. If a ``default_value`` is set then all nodes with out data
are set to the ``default_value``.
:type weights: :class:`numpy.... | 50a0cc5ba8ad88a480fc589f6fbe184548700485 | 3,659,066 |
from typing import List
from typing import Tuple
from typing import Any
def _prepare_data_for_node_classification(
graph: nx.Graph, seed_node: int
) -> List[Tuple[Any, Any]]:
"""
Position seed node as the first node in the data.
TensorFlow GNN has a convention whereby the node to be classified, the "... | 3ed718e583d9e96b2c5bd28e5640c36e5e009065 | 3,659,067 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.