content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def __get_app_package_path(package_type, app_or_model_class):
"""
:param package_type:
:return:
"""
models_path = []
found = False
if isinstance(app_or_model_class, str):
app_path_str = app_or_model_class
elif hasattr(app_or_model_class, '__module__'):
app_path_str = ap... | f08685ef47af65c3e74a76de1f64eb509ecc17b9 | 3,658,900 |
import base64
def dict_from_payload(base64_input: str, fport: int = None):
""" Decodes a base64-encoded binary payload into JSON.
Parameters
----------
base64_input : str
Base64-encoded binary payload
fport: int
FPort as provided in ... | 05fe484eef6c4376f0b6bafbde81c7cc4476b83e | 3,658,901 |
def handle(req):
"""POST"""
im = Image.open(BytesIO(req.files[list(req.files.keys())[0]].body))
w, h = im.size
im2 = ImageOps.mirror(im.crop((0, 0, w / 2, h)))
im.paste(im2, (int(w / 2), 0))
io = BytesIO()
im.save(io, format='PNG')
return req.Response(
body=io.getvalue(), mime_... | d62afe253e331b4d7f037bdc56fa927bceb8bc03 | 3,658,902 |
import glob
def read_sachs_all(folder_path):
"""Reads all the sachs data specified in the folder_path.
Args:
folder_path: str specifying the folder containing the sachs data
Returns:
An np.array containing all the sachs data
"""
sachs_data = list()
# Divides the Sachs dataset into environments... | 151f1eec79251019d1a1c2b828531f6c1f01d605 | 3,658,903 |
def user_permitted_tree(user):
"""Generate a dictionary of the representing a folder tree composed of
the elements the user is allowed to acccess.
"""
# Init
user_tree = {}
# Dynamically collect permission to avoid hardcoding
# Note: Any permission to an element is the same as read permiss... | fd9b7d60da7e085e948d4def0ababc3d0cb8233f | 3,658,904 |
def extract_failure(d):
"""
Returns the failure object the given deferred was errback'ed with.
If the deferred has result, not a failure a `ValueError` is raised.
If the deferred has no result yet a :class:`NotCalledError` is raised.
"""
if not has_result(d):
raise NotCalledError()
e... | 7bc160a8ebd1c5cdeab1a91a556576c750d342f8 | 3,658,905 |
def convert_where_clause(clause: dict) -> str:
"""
Convert a dictionary of clauses to a string for use in a query
Parameters
----------
clause : dict
Dictionary of clauses
Returns
-------
str
A string representation of the clauses
"""
out = "{"
for key in c... | 8b135c799df8d16c116e6a5282679ba43a054684 | 3,658,906 |
from unittest.mock import call
def all_metadata_async():
"""Retrieves all available metadata for an instance async"""
loop = trollius.get_event_loop()
res = loop.run_until_complete(call())
return res | 9759331fbd72271820896bd2849139dc13fc9d39 | 3,658,907 |
def median_std_from_ma(data: np.ma, axis=0):
"""On the assumption that there are bit-flips in the *data*,
attempt to find a value that might represent the standard
deviation of the 'real' data. The *data* object must be a
numpy masked array.
The value of *axis* determines which way the data are ha... | 587702c52bb2000ebfe920202270610e4ed49d8c | 3,658,908 |
def __check_value_range(x: int) -> bool:
"""
Checks if integer is in valid value range to
be a coordinate for Tic-Tac-Toe.
"""
if x < 1 or x > 3:
print(__standard_error_text +
"Coordinates have to be between 1 and 3.\n")
return False
return True | 45f21b3292097baea31846b8bcc51435ae15134c | 3,658,909 |
def find_option(opt):
"""
This function checks for option defined with optcode;
it could be implemented differently - by checking entries in world.cliopts
"""
# received msg from client must not be changed - make a copy of it
tmp = world.climsg[world.clntCounter].copy()
# 0 - ether, 1 - ipv... | 23904c16f9206f9030a40e17be5f6b01cb0439cf | 3,658,910 |
from typing import Set
def generic_add_model_components(
m,
d,
reserve_zone_param,
reserve_zone_set,
reserve_generator_set,
generator_reserve_provision_variable,
total_reserve_provision_expression,
):
"""
Generic treatment of reserves. This function creates model components
rel... | 2c7eef877e0ba7744ba624205fcf590071a95b84 | 3,658,911 |
def return_all_content(content):
"""Help function to return untruncated stripped content."""
return mark_safe(str(content).replace('><', '> <')) if content else None | e24a1ee812a3a011cf6e369ba96bc2989ad7603d | 3,658,912 |
def get_trailing_returns(uid):
""" Get trailing return chart """
connection = pymysql.connect(host=DB_SRV,
user=DB_USR,
password=DB_PWD,
db=DB_NAME,
charset='utf8mb4',
... | 96e8ea67b1b91c3dfc6994b5ff56d9384aca6da5 | 3,658,913 |
def bitsNotSet(bitmask, maskbits):
"""
Given a bitmask, returns True where any of maskbits are set
and False otherwise.
Parameters
----------
bitmask : ndarray
Input bitmask.
maskbits : ndarray
Bits to check if set in the bitmask
"""
goodLocs... | 746c054310ac06c58cc32e5635d270c64481a527 | 3,658,914 |
def plot(foo, x, y):
"""x, y are tuples of 3 values: xmin, xmax, xnum"""
np_foo = np.vectorize(foo)
x_space = np.linspace(*x)
y_space = np.linspace(*y)
xx, yy = np.meshgrid(x_space, y_space)
xx = xx.flatten()
yy = yy.flatten()
zz = np_foo(xx, yy)
num_x = x[-1]
num_y = y[-1]
p... | 67bfcc70a71140efa3d08960487a69943d2acdc8 | 3,658,915 |
import struct
def _StructPackEncoder(wire_type, format):
"""Return a constructor for an encoder for a fixed-width field.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string to pass to struct.pack().
"""
value_size = struct.calcsize(format)
def SpecificEncode... | 7c58d955a903bac423799c99183066268fb7711b | 3,658,916 |
def transition_temperature(wavelength):
"""
To get temperature of the transition in K
Wavelength in micros
T = h*f / kB
"""
w = u.Quantity(wavelength, u.um)
l = w.to(u.m)
c = _si.c.to(u.m / u.s)
h = _si.h.to(u.eV * u.s)
kb = _si.k_B.to(u.eV / u.K)
f = c/l
t = h*f/kb
r... | dbec1ee2c1ad01cd257791624105ff0c4de6e708 | 3,658,917 |
def truncate_string(string: str, max_length: int) -> str:
"""
Truncate a string to a specified maximum length.
:param string: String to truncate.
:param max_length: Maximum length of the output string.
:return: Possibly shortened string.
"""
if len(string) <= max_length:
return strin... | c7d159feadacae5a692b1f4d95da47a25dd67c16 | 3,658,918 |
import requests
import json
def geoinfo_from_ip(ip: str) -> dict: # pylint: disable=invalid-name
"""Looks up the geolocation of an IP address using ipinfo.io
Example ipinfo output:
{
"ip": "1.1.1.1",
"hostname": "one.one.one.one",
"anycast": true,
"city": "Miami",
"region":... | 956a9d12b6264dc283f64ee792144946e313627b | 3,658,919 |
def mpileup2acgt(pileup, quality, depth, reference, qlimit=53,
noend=False, nostart=False):
"""
This function was written by Francesco Favero,
from: sequenza-utils pileup2acgt
URL: https://bitbucket.org/sequenza_tools/sequenza-utils
original code were protected under GPLv3 license... | bf5a0c5e147ece6e9b3be5906ba81ed54593b257 | 3,658,920 |
def normalize_missing(xs):
"""Normalize missing values to avoid string 'None' inputs.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = normalize_missing(v)
elif isinstance(xs, (list, tuple)):
xs = [normalize_missing(x) for x in xs]
elif isinstance(xs, basestri... | 5d3fef8370e6a4e993eb06d96e5010c4b57907ba | 3,658,921 |
def ini_inventory(nhosts=10):
"""Return a .INI representation of inventory"""
output = list()
inv_list = generate_inventory(nhosts)
for group in inv_list.keys():
if group == '_meta':
continue
# output host groups
output.append('[%s]' % group)
for host in inv... | 46182c727e9dbb844281842574bbb54d2530d42b | 3,658,922 |
def get_crp_constrained_partition_counts(Z, Cd):
"""Compute effective counts at each table given dependence constraints.
Z is a dictionary mapping customer to table, and Cd is a list of lists
encoding the dependence constraints.
"""
# Compute the effective partition.
counts = defaultdict(int)
... | acda347ec904a7835c63afe5ec6efda5915df405 | 3,658,923 |
import re
from re import T
def create_doc():
"""Test basic layer creation and node creation."""
# Stupid tokenizer
tokenizer = re.compile(r"[a-zA-Z]+|[0-9]+|[^\s]")
doc = Document()
main_text = doc.add_text("main", "This code was written in Lund, Sweden.")
# 01... | 36171fd68712861370b6ea1a8ae49aa7ec0c139a | 3,658,924 |
def jissue_get_chunked(jira_in, project, issue_max_count, chunks=100):
""" This method is used to get the issue list with references,
in case the number of issues is more than 1000
"""
result = []
# step and rest simple calc
step = issue_max_count / chunks
rest = issue_max_count % chunks... | 1c32859b91f139f5b56ce00f38dba38b2297109e | 3,658,925 |
def negative_height_check(height):
"""Check the height return modified if negative."""
if height > 0x7FFFFFFF:
return height - 4294967296
return height | 4d319021f9e1839a17b861c92c7319ad199dfb42 | 3,658,926 |
from .model_store import get_model_file
import os
def get_visemenet(model_name=None,
pretrained=False,
root=os.path.join("~", ".tensorflow", "models"),
**kwargs):
"""
Create VisemeNet model with specific parameters.
Parameters:
----------
mode... | 78f6ecd0136b3fae3b0b7ae9b9463e9bbf4afc6b | 3,658,927 |
def linked_gallery_view(request, obj_uuid):
"""
View For Permalinks
"""
gallery = get_object_or_404(Gallery, uuid=obj_uuid)
images = gallery.images.all().order_by(*gallery.display_sort_string)
paginator = Paginator(images, gallery.gallery_pagination_count)
page = request.GET.get('page')
... | c425c6678f2bfb3b76c039ef143d4e7cbc6ee922 | 3,658,928 |
def _gm_cluster_assign_id(gm_list, track_id, num_tracks, weight_threshold,
z_dim, max_id, max_iteration=1000):
"""The cluster algorithm that assign a new ID to the track
Args:
gm_list (:obj:`list`): List of ``GaussianComponent`` representing
current multi-target PH... | f079867333a9e66f7b48782b899f060c38694220 | 3,658,929 |
def get_bprop_scatter_nd(self):
"""Generate bprop for ScatterNd"""
op = P.GatherNd()
def bprop(indices, x, shape, out, dout):
return zeros_like(indices), op(dout, indices), zeros_like(shape)
return bprop | 3f2f5247b03ba49918e34534894c9c1761d02f07 | 3,658,930 |
from typing import Optional
import os
import hashlib
def get_md5(location: str, ignore_hidden_files: bool=True) -> Optional[str]:
"""
Gets an MD5 checksum of the file or directory at the given location.
:param location: location of file or directory
:param ignore_hidden_files: whether hidden files sho... | 4d409355c60d2561d452a45c324f5da129a2acd9 | 3,658,931 |
import requests
def delete_policy_rule(policy_key, key, access_token):
"""
Deletes a policy rule with the given key.
Returns the response JSON.
See http://localhost:8080/docs#/Policy/delete_rule_api_v1_policy__policy_key__rule__rule_key__delete
"""
return requests.delete(
f"{FIDESOPS... | b53e52b2498707b82e3ceaf89be667886c75ca3c | 3,658,932 |
def knn_search_parallel(data, K, qin=None, qout=None, tree=None, t0=None, eps=None, leafsize=None, copy_data=False):
""" find the K nearest neighbours for data points in data,
using an O(n log n) kd-tree, exploiting all logical
processors on the computer. if eps <= 0, it returns the distance to the ... | cc0dfaee8d1990f1d336e6a5e71973e1b4702e25 | 3,658,933 |
import urllib
import typing
def find_absolute_reference(
target: str,
domain: str,
remote_url: urllib.parse.ParseResult,
https_mode: _constants.HTTPSMode = _constants.DEFAULT_HTTPS_MODE,
base: typing.Optional[urllib.parse.ParseResult] = None
) -> typing.Optional[str]:
"""
... | 2c49fbe31e7490d53bb4549a73af6529fd41aa2a | 3,658,934 |
from typing import Tuple
def compute_vectors_from_coordinates(
x: np.ndarray, y: np.ndarray, fps: int = 1
) -> Tuple[Vector, Vector, Vector, Vector, np.array]:
"""
Given the X and Y position at each frame -
Compute vectors:
i. velocity vector
ii. unit tangent
... | 073262b521f3da79945674cc60ea26fee4c87529 | 3,658,935 |
import requests
def get_now(pair):
"""
Return last info for crypto currency pair
:param pair: ex: btc-ltc
:return:
"""
info = {'marketName': pair, 'tickInterval': 'oneMin'}
return requests.get('https://bittrex.com/Api/v2.0/pub/market/GetLatestTick', params=info).json() | b5db7ba5c619f8369c052a37e010229db7f78186 | 3,658,936 |
from buildchain import versions
from typing import Any
import sys
def fixture_buildchain_template_context() -> Any:
"""Emulate .in template context for buildchain."""
buildchain_path = paths.REPO_ROOT / "buildchain"
sys.path.insert(0, str(buildchain_path))
# pylint: disable=import-error,import-outside... | 365597c84659c8aa6aabaef9b0d75763e0ad9131 | 3,658,937 |
def hsv(h: float, s: float, v: float) -> int:
"""Convert HSV to RGB.
:param h: Hue (0.0 to 1.0)
:param s: Saturation (0.0 to 1.0)
:param v: Value (0.0 to 1.0)
"""
return 0xFFFF | 638c1784f54ee51a3b7439f15dab45053a8c3099 | 3,658,938 |
def make_exponential_mask(img, locations, radius, alpha, INbreast=False):
"""Creating exponential proximity function mask.
Args:
img (np.array, 2-dim): the image, only it's size is important
locations (np.array, 2-dim): array should be (n_locs x 2) in size and
each row should corres... | 14be02cee27405c3a4abece7654b7bf902a43a47 | 3,658,939 |
from typing import Tuple
def delete(client, url: str, payload: dict) -> Tuple[dict, bool]:
"""Make DELETE requests to K8s (see `k8s_request`)."""
resp, code = request(client, 'DELETE', url, payload, headers=None)
err = (code not in (200, 202))
if err:
logit.error(f"{code} - DELETE - {url} - {r... | 8ed463e063b06a48b410112f163830778f887551 | 3,658,940 |
def f(x):
"""The objective is defined as the cost + a per-demographic penalty
for each demographic not reached."""
n = len(x)
assert n == n_venues
reached = np.zeros(n_demographics, dtype=int)
cost = 0.0
for xi, ri, ci in zip(x, r, c):
if xi:
reached = reached | ri #
... | d6724595086b0facccae84fd4f3460195bc84a1f | 3,658,941 |
def clamp(minVal, val, maxVal):
"""Clamp a `val` to be no lower than `minVal`, and no higher than `maxVal`."""
return max(minVal, min(maxVal, val)) | 004b9a393e69ca30f925da4cb18a8f93f12aa4ef | 3,658,942 |
def get_closest_spot(
lat: float, lng: float, area: config.Area
) -> t.Optional[config.Spot]:
"""Return closest spot if image taken within 100 m"""
if not area.spots:
return None
distances = [
(great_circle((spot.lat, spot.lng), (lat, lng)).meters, spot)
for spot in area.spots
... | 55424c3b5148209e62d51cc7c6e5759353f5cb0a | 3,658,943 |
def drawBezier(
page: Page,
p1: point_like,
p2: point_like,
p3: point_like,
p4: point_like,
color: OptSeq = None,
fill: OptSeq = None,
dashes: OptStr = None,
width: float = 1,
morph: OptStr = None,
closePath: bool = False,
lineCap: int = 0,
lineJoin: int = 0,
over... | 7bd3c0b8e3ca8717447213c6c2ac8bc94ea0f029 | 3,658,944 |
from functools import reduce
import operator
def product(numbers):
"""Return the product of the numbers.
>>> product([1,2,3,4])
24
"""
return reduce(operator.mul, numbers, 1) | 102ac352025ffff64a862c4c5ccbdbc89bdf807e | 3,658,945 |
def load_ref_system():
""" Returns l-phenylalanine as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
N 0.7060 -1.9967 -0.0757
C 1.1211 -0.6335 -0.4814
C 0.6291 0.4897 ... | 724e0d37ae5d811da156ad09d4b48d43f3e20d6a | 3,658,946 |
import csv
def parse_dependency_file(filename):
"""Parse a data file containing dependencies.
The input file is the following csv format:
name,minerals,gas,build time,dependencies
command center,400,0,100,
orbital command,150,0,35,command center|barracks
Notice that the "depende... | 0c5194e85184e5f828354bf45a14c8d14714e8e0 | 3,658,947 |
from typing import List
def range_with_bounds(start: int, stop: int, interval: int) -> List[int]:
"""Return list"""
result = [int(val) for val in range(start, stop, interval)]
if not isclose(result[-1], stop):
result.append(stop)
return result | 1667657d75f918d9a7527048ad4207a497a20316 | 3,658,948 |
import warnings
def iou_score(box1, box2):
"""Returns the Intersection-over-Union score, defined as the area of
the intersection divided by the intersection over the union of
the two bounding boxes. This measure is symmetric.
Args:
box1: The coordinates for box 1 as a list of points
b... | 746129ac390e045887ca44095af02370abb71d81 | 3,658,949 |
def _actually_on_chip(ra, dec, obs_md):
"""
Take a numpy array of RA in degrees, a numpy array of Decin degrees
and an ObservationMetaData and return a boolean array indicating
which of the objects are actually on a chip and which are not
"""
out_arr = np.array([False]*len(ra))
d_ang = 2.11
... | 809bfb59f63a62ab236fb2a3199e28b4f0ee93fd | 3,658,950 |
from typing import Tuple
def outlier_dataset(seed=None) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Generates Outliers dataset, containing 10'000 inliers and 50 outliers
Args:
seed: random seed for generating points
Returns:
Tuple containing the inlier features, inlier l... | 1b19e66f151290047017bce76e581ae0e725626c | 3,658,951 |
def posts(request, payload={}, short_id=None):
"""
Posts endpoint of the example.com public api
Request with an id parameter:
/public_api/posts/1qkx8
POST JSON in the following format:
POST /public_api/posts/
{"ids":["1qkx8","ma6fz"]}
"""
Metrics.api_comment.record(re... | c8ec491638417fe972fe75c0cf9f26fe1cf877ae | 3,658,952 |
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 |
import sys
def dmenu_select(num_lines, prompt="Entries", inp=""):
"""Call dmenu and return the selected entry
Args: num_lines - number of lines to display
prompt - prompt to show
inp - bytes string to pass to dmenu via STDIN
Returns: sel - string
"""
cmd = dmenu_cmd(num_line... | 45a0c4add05185278d258c2c9374403cb22459fd | 3,658,960 |
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 |
from utils.loader import get_save_path
from utils.var_dim import squeezeToNumpy
from utils.loader import dataLoader_test as dataLoader
from utils.print_tool import datasize
from utils.loader import get_module
import torch
import logging
import os
import yaml
import tqdm
from pathlib import Path
def export_descriptor(... | 79f512e5c9d100d8f2001410dafd06f6cbdf79fa | 3,658,962 |
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 |
import traceback
import os
def format_exception_with_frame_info(e_type, e_value, e_traceback, shorten_filenames=False):
"""Need to suppress thonny frames to avoid confusion"""
_traceback_message = "Traceback (most recent call last):\n"
_cause_message = getattr(
traceback,
"_cause_message... | f698739f88271bc6c15554be3750bc550f5102a7 | 3,658,981 |
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 |
import subprocess
def get_volumes(fn):
"""Return number of volumes in nifti"""
return int(subprocess.check_output(['fslnvols', fn])) | 67596f0583295f837197e20dd95b1c04fe705ea4 | 3,658,983 |
import asyncio
import subprocess
async def _execSubprocess(command: str) -> tuple[int, bytes]:
"""Execute a command and check for errors.
Args:
command (str): commands as a string
Returns:
tuple[int, bytes]: tuple of return code (int) and stdout (str)
"""
async with SEM:
process = await asyncio.create_su... | f289282c45d219000d6ce8b5b4880801869d07f5 | 3,658,984 |
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 |
import sys
def redirect_std():
"""
Connect stdin/stdout to controlling terminal even if the scripts input and output
were redirected. This is useful in utilities based on termenu.
"""
stdin = sys.stdin
stdout = sys.stdout
if not sys.stdin.isatty():
sys.stdin = open_raw("/dev/tty", ... | 22321f8a0309273f409dc2876616856834f52113 | 3,658,987 |
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 |
import requests
def get(user_request, url, **kwargs):
""" A wrapper of requests.get.
This method will automatically add user's session key as the cookie to enable sso
Sends a GET request. Returns :class:`Response` object.
:param user_request: The http request contains the authentication key and is t... | 203ec28f62536dc84bfc86e6208f25af7f17212b | 3,658,990 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.