content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def sor_heap_fixed_abu(A, n0, A0, shape='sqr', L=1):
"""
Computes sorensen's simiarilty index for a given SAD (n0)
and spatial grain (A) at all possible seperation distances
Scaling Biodiveristy Chp. Eq. 6.10, pg.113
shape: shape of A0 see function sep_orders()
L: the width of the rectangle or ... | 94be00772e0af8e054dd295ee628edf4d91451df | 3,597,093 |
def bilinear_interp(x0,y0,field,x,y,len_x,len_y):
"""!Do bilinear interpolation of a field. This function assumes that the grid can locally be regarded as cartesian, with everything at right angles.
x0,y0 are the points to interpolate to.
"""
# Compute indeces at location
x_index = np.searchsorted(x,x0)
i... | e0e85c582cbdfa4f9f5796f553073e090687993e | 3,597,094 |
from typing import List
from typing import Optional
from typing import Dict
from typing import Union
from typing import Any
from typing import Counter
def extract_all_ev_features_names_from_log(log: EventLog, str_ev_attr: List[str], num_ev_attr: List[str],
parameters: Option... | b596d2bcafca2acf2428b5ce6187b635196768d1 | 3,597,095 |
def remove_nan_rows(arr):
"""Remove all rows with `nan` values in `arr`."""
mask = np.isnan(arr).any(axis=1)
return arr[~mask] | 4445c19ba622dcd554675aed12186a5e0f54d61a | 3,597,096 |
def Nmfcc(x, fs, p, frameSize, inc, nfft=512, n_dct=12):
"""
计算mfcc系数
:param x: 输入信号
:param fs: 采样率
:param p: Mel滤波器组的个数
:param frameSize: 分帧的每帧长度
:param inc: 帧移
:return:
"""
# 预处理-预加重
xx = lfilter([1, -0.9375], [1], x)
# 预处理-分幀
xx = enframe(xx, frameSize, inc)
# ... | 1dbccf6ead8cb3a8784c59a0d8c72515e764ffa6 | 3,597,097 |
def meta_courseprofile(request, course_id='all'):
"""
Returns derived course profiles for a course
"""
if api.views.is_cached(request):
return api.views.api_cacherender(request)
courses = []
if course_id == 'all' or course_id == 'allcourses':
courselist = api.views.get_all_course... | bdae05518002f7635f1e3f63173f0d07a7ee1fe5 | 3,597,098 |
def provide_data(split,
batch_size,
patch_height=32,
patch_width=32,
colors=3,
num_parallel_calls=None,
shuffle=True):
"""Provides batches of CIFAR10 digits.
Args:
split: Either 'train' or 'test'.
batch_si... | 9ec21cac7bcede35ec48c89d05121bf27b414a07 | 3,597,100 |
def get_upcast_box(box, vector):
"""
Given two box-types, find the one that takes priority
"""
if box is DataFrame or isinstance(vector, DataFrame):
return DataFrame
if box is Series or isinstance(vector, Series):
return Series
if box is Index or isinstance(vector, Index):
... | 3a042121776403196cba07d15043a34d42dd89c2 | 3,597,101 |
def delete_users(client: FlaskClient, auth_token: t.Optional[str] = None) -> Response:
"""DELETE /users
Args:
client (:obj:`~flask.testing.FlaskClient`): The Client fixture.
auth_token (:obj:`str`, optional): Auth token for the Authorization header.
Defaults to None.
Returns:
... | a17b8723a8a14cd7a501361aa47375773fdd5638 | 3,597,102 |
def get_gui_data(agasc_id):
"""
Fetch guide/track history for an agasc id
:param agasc_id: AGASC id
:returns: list of dicts of uses as guide stars
"""
gui = guide_stats.get_star_stats(agasc_id)
if not len(gui):
return []
gui = Table(gui)
gui.sort('kalman_datestart')
# ma... | e61818c9bbc977d02eb3aab6b7a1eeb7c86f017f | 3,597,104 |
def build_model(learning_rate,
max_len,
num_classes,
num_vocab,
num_embed,
num_hidden,
num_lstm_cells,
l2_lambda):
"""Build a RNN with TensorFlow"""
# Placeholders.
X = tf.placeholder(tf.int32, [... | 5fc097b550cde6d8bd6b260f1f0b1cf9ab144f1d | 3,597,105 |
def raxisa(matrix):
"""raxisa(ConstSpiceDouble [3][3] matrix)"""
return _cspyce0.raxisa(matrix) | a0d5ba3018975cf6253031fe5c6c4039d42c015e | 3,597,106 |
def get_attribute_value(field, attribute):
"""Recursively traverse the tuple list for accessing an attribute's value.
"""
if tuple == type(field):
return get_attribute_value(get_attribute_value(field[0], field[1]), attribute)
return getattr(field, attribute) | 1a37194cdb171a60cf0f7fad679ba33107e2e916 | 3,597,108 |
def ESNet_x0_75(pretrained=False, use_ssld=False, **kwargs):
"""
ESNet_x0_75
Args:
pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
If str, means the path of the pretrained model.
use_ssld: bool=False. Whether using distillation pret... | 2a783482c78987bb0e851e5fa0fc6e771b5896a9 | 3,597,109 |
import math
def cell_angles(cell_coords, viewpoint):
"""Compute angles between cells and viewpoint where 0 angle is right of
viewpoint.
Inputs:
-cell_coords: coordinate tuple (rows, cols) as numpy.where()
from which to compute the angles
-viewpoint: tuple (row, col)... | f3150a48257c0b9d21540329026d1981fd12f3ab | 3,597,111 |
def ddpm_conv3x3(x, out_planes, stride=1, bias=True, dilation=1, init_scale=1.):
"""3x3 convolution with DDPM initialization."""
bias_init = jnn.initializers.zeros
output = nn.Conv(
out_planes,
kernel_size=(3, 3),
strides=(stride, stride),
padding='SAME',
use_bias=bias,
kernel_dilation=(di... | 1da4bb710f9870e027e07980c52b6f5e4e0e740d | 3,597,113 |
def returnType(rettype=None, *args):
"""Define return type for MPC coroutines.
Used in first await expression in an MPC coroutine.
"""
if rettype == None:
return _afuture(None)
if isinstance(rettype, Future):
return _afuture(Future)
def make(i):
if i == len(args):
... | b7cbfb1fd0b21295e54504a35e2e5b246158004a | 3,597,115 |
def y_minority_con_majority_211(by_grps):
"""
Examples:
PASS - [[S,S],[N,N,S,O]]
FAIL - [[S,N],[N,N,S,O]]
FAIL - [[S,S],[N,N,O,O]]
FAIL - [[S,S],[S,S,N,O]]
"""
if by_grps[0][0]!=by_grps[0][1]:
print("Failed y_minority_con_majority_211 -- small groups do not match")
r... | 598522211c70b74ae8717a0f37045b2541e99046 | 3,597,116 |
def finalMatrix(matrix):
"""Función que halla la magnitud de una matriz de imaginarios
(list 2D) -> list 2D"""
row, column = len(matrix), len(matrix[0])
for i in range(row):
nRow = []
for j in range(column):
nRow.append([(modulo(matrix[i][j]) ** 2), 0])
matrix[i] = n... | 6c51d1b867d2ba5d824dc8283c1dbb95e31c2899 | 3,597,117 |
def get_team(id_, cache_time=5):
"""
Get team by ID.
Args:
id_: team ID
cache_time: response cache lifetime in seconds, or `None` for infinite cache
"""
s = session(cache_time)
res = s.get(f'{BASE_URL}/database/team?id={id_}')
return check_network_response(res) | 346956637d100c61c8494eb69474f5896a2e2ea7 | 3,597,118 |
def get_neighbours(k,Lx,Ly,iopen = 1):
"""
return the neighbours of site k in the
hexagonal lattice, with open boundary
conditions on the y-direction for odd iopen
00 01 02 03 04
05 06 07 08 09
10 11 12 13 14
15 16 17 18 19
directions (e1 = x-versor)
y
... | 2b37f7e03005a797581b5624bfac33ce44dcce92 | 3,597,119 |
from typing import Generator
import inspect
import tokenize
from io import StringIO
def tokenize_source(obj: object) -> Generator:
"""Returns a generator for the tokens of the object's source code."""
source = inspect.getsource(obj)
token_generator = tokenize.generate_tokens(StringIO(source).readline)
... | 6e0cc8b709f4a6d5c84eb711b543925c60413877 | 3,597,121 |
from typing import Dict
from typing import Any
from typing import Callable
def pprint_dict(
d: Dict[str, Any], delim: str = "\n", func: Callable[[Any], Any] = None
) -> str:
"""Pretty printing for dictionaries"""
if func is None:
lst = [f"{k} = < {v} >" for k, v in d.items()]
else:
lst... | 60dbc9932723f708465739fad45add0a34418337 | 3,597,122 |
from typing import Optional
def compute_relative_rotation_angle(R_1: Optional[Rot3], R_2: Optional[Rot3]) -> Optional[float]:
"""Compute the angle between two rotations.
Note: the angle is the norm of the angle-axis representation.
Args:
R_1: the first rotation.
R_2: the second rotation.... | 906df9ab46221eeb11ba255a0dad9e220c5c9456 | 3,597,123 |
def matrix_W_F2(beta, n_labels):
"""W matrix for F2 measure"""
W = np.ndarray(shape=(n_labels, n_labels))
for i in np.arange(1, n_labels+1):
for j in np.arange(1,n_labels+1):
W[i-1, j-1] = 1/(i*(beta**2) + j)
return(W) | dbb0aa2160edb1df6ddc7c6e837cce32b0793e46 | 3,597,124 |
def return_expr(func):
"""Create a new function from func that returns the final expression"""
code = func.__code__
# remove POP_TOP and LOAD_CONST (None)
co_code = code.co_code[:-6] + code.co_code[-2:]
code = code_replace(code, co_code=co_code)
rv = FunctionType(
code,
func.__gl... | 8535eeb580378bbcdff1e77783a0e1153020f2e5 | 3,597,126 |
def calculate_3d_flux_weights(
true_energies, true_coszens, true_azimuths, en_splines, enpow=1, az_linear=True
):
"""Calculate flux weights for given array of energy, cos(zenith) and
azimuth.
Arrays of true energy, zenith and azimuth are expected to be for MC events,
so they are tested to be of the... | 18d54b7800148f5ffd0104fc7e5557e8be206bd8 | 3,597,128 |
import click
def format_status(status, success_green=False):
"""
Format status with color
"""
if status in SUCCESS_STATUSES:
if success_green:
return click.style(status, fg='green')
else:
return status
if status in WARNING_STATUSES:
return click.sty... | dfecd619fc5c4e52ff7fc6852c0176f6e575607e | 3,597,129 |
import torch
def test_t_1d():
"""Test of PyTorch aten::t on Glow with 1d inputs."""
def test_f(a):
b = a + a
return b.t()
x = torch.randn(7)
jitVsGlow(test_f, x, expected_fused_ops={"aten::t"}) | ee602f1a48fc6d1feac7e6179f0f0c0ed9c29cd9 | 3,597,130 |
from datetime import datetime
def format(value):
"""Format value in a way suitable for CSV export."""
if isinstance(value, unicode):
return value.encode('utf-8')
if isinstance(value, str):
return value.replace('\n', ' ')
if isinstance(value, list):
return ', '.join(value)
i... | d3080c5decea11774b6be7cccc54968fbf722563 | 3,597,131 |
def get_current_user(
exception_when_missing=True, user=None,
session=None, **kwargs
):
"""get current user."""
return _get_user(
user.id, session=session,
exception_when_missing=exception_when_missing
) | 183fd439a3c56e761f97bf144285bd6854953896 | 3,597,132 |
import hashlib
def validate_secret_string(sk_str):
"""
Validates a given public key string.
:param sk_str:
:return:
"""
val = base58.b58decode(sk_str)
if len(val) != 35:
return False
prefix = val[0]
if prefix != SECRET_PREFIX:
return False
sha256 = hashlib.sh... | f543338893067c964e84974d2a8956391089b5b2 | 3,597,133 |
import json
def print_report(assets, meta_types, brief=False, security_config=None):
"""
Print subnets
"""
# Construct Region/VPC/subnet
report = dict()
for asset in assets:
if type(asset).__name__.upper() not in meta_types:
continue
if asset.location.region is None... | 7d6a47bcad1f8d2483e24b00402ad1d0b4b45621 | 3,597,134 |
def location_variance(df):
""" Variance in locations
Defined as the log of the sum of the variances of latitude and longitude.
var(latitude) + var(longitude)
Args:
df (pandas.DataFrame): RADAR android_phone_location dataframe
Returns:
float: location variance
"""
return arr_l... | 972a4306f12591ff8d9140bdc83ee2dd5e5d7ad5 | 3,597,135 |
def getJobStatus(jobId):
"""
Gets a dictionary with the job status as an integer value, together with its semantic meaning. The integer value is a power of 2, that is, 1:PENDING, 2:QUEUED, 4:ACCEPTED, 8:STARTED, 16:FINISHED, 32:SUCCESS, 64:ERROR and 128:CANCELED
:param jobId: Id of job (integer).
:retu... | de6437e3d9f3aa804c53e8d3f9166d34f4f360bd | 3,597,137 |
import six
import collections
def _join(left, right, keys=None, join_type='inner',
uniq_col_name='{col_name}_{table_name}',
table_names=['1', '2'],
col_name_map=None):
"""
Perform a join of the left and right Tables on specified keys.
Parameters
----------
left : Table
... | c14b44c925e3dbb9c55dcc78fb228016e1749b20 | 3,597,138 |
from typing import Tuple
def is_event(item: Tuple[str, str]) -> bool:
"""Check item from labelled list of folders if it is event folder.
Args:
item: item from labelled list of folders
Returns:
True if folder in tuple is event-type
"""
i_type = item[1]
return i_type == "event" | 2307813e7777955b11a5d84c7dbc114a8a690562 | 3,597,140 |
def true_negative_rate(y_true: ArrayLike, y_pred: ArrayLike):
""" Returns the True Negative Rate (aka. Selectivity, Specificity) for the
prediction: TN/(TN+FP)
Args:
y_true, y_pred (numpy-compatible, ArrayLike): binary valued
objects holding the ground truth and predictions (respectively),
... | 97f4972e8647ad34a3f8eb0461e21bedcb91bbc7 | 3,597,141 |
def _parse_arg_line(line):
"""
pull out the arg names from a line of CLI help text introducing args
>>> _parse_arg_line(' -s, --sudo run operations with sudo (nopasswd) (deprecated, use')
['-s', '--sudo']
"""
return [
part.strip().split(' ')[0].split('=')[0]
for par... | 5d6bbddc43792ee974d0dfec4637046aff602052 | 3,597,142 |
import bisect
def edc(Mh, z, delta_t=50):
"""Effective duty cycle, see Trenti et al. 2010.
Args:
-----
Mh (float or array_like): halo mass(es) in Msun/h.
z (float): redshift.
delta_t (float): duty cycle parameter.
Returns:
--------
eps (float or array_like): duty ... | 9234762c849116be048593d6c1e23f8fd5d0b4b9 | 3,597,143 |
def pyiterator_iter(this):
"""
Returns `this.`
https://docs.python.org/3/library/stdtypes.html#typeiter says
an iterator should have an __iter__ method.
"""
return this | 5a44e38f6219f9ab0b629be817b0e2877c464149 | 3,597,144 |
from typing import List
from typing import get_origin
def get_json_lines(annotation: ResourceAnnotation, field: str, route: str,
request: bool = False) -> List:
"""Generate documentation lines for the given annotation.
This only documents schemas of type "object", or type "list" where each... | 0e6e623f8daaa6334a42e3b67cf9a337a2715715 | 3,597,145 |
def checked(request, key, val):
"""Returns "checked" if key=value appears in the request URL parameters
Use this tag to set the class, for highlighting selected filter options
"""
params = request.GET.dict()
if key in params:
values = params[key].split(',')
if val in values:
... | b89825ed276a7a99b630a92f63472c3b8ee50c97 | 3,597,146 |
def apply_ants_transform_to_image(transform, image, reference, interpolation='linear'):
"""
Apply an ANTsTransform to an ANTsImage
Arguments
---------
transform : ANTsTransform object
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_ants_data("r16")).clone('float'... | d8cecd342f64d83c0b7ab92a9b867545a67d4901 | 3,597,147 |
def LinkResourceProxy( name, resource, libraries = [], directive = ''):
"""
Links a resource proxy
param: name name of the result
param: resource key of the resource one wants to link
param: directive extra directives
"""
target = _plumbing.target( _plumbing.executable_name_path( name... | 4e5e5d50c2bac66b6d926e65db1b55615c2b7280 | 3,597,148 |
import math
def draw_arms():
"""draws arms"""
radius = constants["radius"]
arms = constants["arms"]
peon.tp(constants["center"] + Vector2(radius, 0), 90)
peon.pu()
peon.circle(radius, arms["principal"])
peon.pd()
peon.pencolor("firebrick")
peon.fillcolor("red")
peon.begin_fil... | cbe1b7253dae271c563c13522cabfa53e255a18a | 3,597,149 |
import string
def checkInput(userInput, kind_):
"""
Check user's input.
:param userInput: str
:return: bool
"""
if kind_ == 'approx_price':
for i in userInput:
if i not in string.digits and i != '.':
return False
return True
elif kind_ == 'price_... | 534d34ecb062ec32b1f2a58d30f20ecaba953e8f | 3,597,150 |
def _CK_MECHANISM_TYPE_to_enum(mechanism):
"""Convert CK_MECHANISM_TYPE to enum or be okay."""
try:
return Mechanism(mechanism)
except ValueError:
return mechanism | afbf832798516bb5949b5566c66817ad384c1bdb | 3,597,151 |
def _process_exp(exp):
"""Use the exp name to return the names of the MPRAGE
data and the bold data (in that order).
"""
if exp == "fh":
mpragename = "mprage"
boldname = "fh"
elif exp == "butterfly":
mpragename = "mprage"
boldname = "butterfly"
elif exp == ... | d7b144c59bc6b6a2ba8ea5e5ffd1c607e1e7a51d | 3,597,153 |
def hex_to_binary(hex_value: str, num_bits: int) -> str:
"""
0xabcd
"""
assert hex_value.startswith('0x')
hex_value = hex_value[2:]
bits = int_to_bits(int(hex_value, 16), num_bits)
assert len(bits) == num_bits
return bits | 41c814cc05a0c65e2e319d7a6efb2baafd06cada | 3,597,154 |
def simulate_from_gui(parameters_from_gui, progress_callback):
"""
Starts the whole simulation with the inputs from GUI
"""
simulation = InverseSimulationController()
result = run_simulation(**parameters_from_gui, simulation=simulation,
progress_callback=progress_callbac... | 6c4fad2c30d7614cbdf3f7a093874de9d7b319e7 | 3,597,155 |
def create_dropout(rate, seed):
"""Create a dropout operation."""
options = {
"dropout_rate": rate,
"seed": seed
}
return Operation(options, no_parameters, apply_dropout) | e5e1b75d710e8f3e5af9985df90666249075e769 | 3,597,156 |
def is_3dmuon(trigger_mask):
"""Returns True if the trigger mask contains the 3D muon flag.
Parameters
----------
trigger_mask : int or array(int)
A value or an array of the trigger_mask, either of an event, or a hit.
"""
return is_bit_set(trigger_mask, ktrg.JTRIGGER3DMUON) | 0cc22654adf6f7de0cb96fb6a35e6e62255c572f | 3,597,157 |
import re
def unescape(url):
"""
The url retrieved from MySQL database has extra slash('\') for all the
punctuations.
@param url: the url string to be unescaped
@type url: C{string}
"""
return re.sub(r'\\(.)', r'\1', url) | ef1d0f84a407c8d0d970a86044558066702735dd | 3,597,158 |
from typing import List
from typing import Optional
from typing import Tuple
import itertools
def _mi_for_arrays(c_arrs0: List[np.ndarray],
c_arrs1: List[np.ndarray],
d_arrs0: List[np.ndarray],
d_arrs1: List[np.ndarray],
weights: Optional[np.... | 8c266155aecae06e9314fad675051ddabd25f24e | 3,597,160 |
def calculate_binomial_coefficient(n: int, k: int) -> int:
"""Calculate the binomial coefficient (n over k)."""
if n < 0:
raise ValueError('`n` must not be negative!')
if k < 0:
raise ValueError('`k` must not be negative!')
if k > n:
return 0
binomial_coefficient = 1
for... | 31942eecaa10cb7a13e9cd38dd2daed8d0618b40 | 3,597,161 |
def cas2vec_transform(data, bins, disc_method, sequence_length):
"""
Transform diffusion event data into discrete valued sequences as described
in the cas2vec paper by using bins (slices)
:param data: Cascade data
:param bins: Bins (slices)
:param disc_method: discretization method
:param se... | df0e54ac23d8f85bc5df6b175a64144b92c4955c | 3,597,162 |
def capture_info(line, lines_iter, first_line=True):
"""
Helper method to capture the other results information
"""
in_info = list()
if first_line:
in_info.append(line)
while lines_iter.peek().startswith(' '):
in_info.append(next(lines_iter))
if not first_line:
in_inf... | 14384420b58cbc97032a4675fd0aec2b9f24db30 | 3,597,163 |
def get_reg_user(user, chat):
"""
Args:
chat (telegram.Chat)
user (telegram.User)
Returns:
RegisteredUser: Finds or creates a new registered user
"""
str_id = str(user.id)
if str_id not in registered_users:
registered_users[str_id] = RegisteredUser(chat_id=chat.i... | d8f168c9d6a79431e4707a4f130c61cd7f0e26f3 | 3,597,164 |
def vanilla_residual_unit_3d(inputs,
out_filters,
kernel_size=(3, 3, 3),
strides=(1, 1, 1),
mode=tf.estimator.ModeKeys.EVAL,
use_bias=False,
activ... | 300f89c3e7a70fc644c35b0c0247af275bfe2bdb | 3,597,165 |
def _prep_for_list(lb_list):
"""
Removes tenant id and changes the nodes list to 'nodeCount' set to the
number of node on the LB
"""
entries_to_keep = ('name', 'protocol', 'id', 'port', 'algorithm', 'status', 'timeout',
'created', 'virtualIps', 'updated', 'nodeCount')
filt... | e08b977fc00d654518e78466dc51a56d2669a655 | 3,597,166 |
def prompt_for_simplecount_input():
"""Prompt for user input for updating method for simplecount estimates."""
msg = '\nSpecify the method type for updating simplecount table data.' +\
' Choices for the method type include:' +\
'\n- 1 - Automatically update database records from select data sour... | 80e2d7a87ee4278cdee7103195d93fe77c598eff | 3,597,167 |
def get_miners_by_address():
"""
通过账户查询所属节点
:return:
"""
address = request.form.get("address")
result = MinerService.get_miners_by_address(address)
return response_json(result) | f2ce88abd7eb05446739ca49fa0e2f4e3419dcf5 | 3,597,170 |
def isAnalysisJob(trf):
""" Determine whether the job is an analysis job or not """
if (trf.startswith('https://') or trf.startswith('http://')):
analysisJob = True
else:
analysisJob = False
return analysisJob | 75ccaf711dd04dc99aca266533fee7303fad3e85 | 3,597,172 |
def main():
"""Akari solver example."""
size = 10
lattice = grilops.get_square_lattice(size)
black_cells = {
(0, 0): None,
(0, 3): None,
(0, 9): None,
(1, 7): None,
(2, 1): 3,
(2, 6): 0,
(3, 2): 2,
(3, 5): None,
(3, 9): 1,
(4, 3): 1,
(4, 4): 0,
... | 7ca104745896c82c976bbf9f03d3d9f72fae91f3 | 3,597,173 |
def remove_url_fragment(url):
"""
>>> remove_url_fragment("https://example.com/dir/thefile.tar#internal.txt")
'https://example.com/dir/thefile.tar'
:param url: A URL, possibly with a #fragment at the end
:type url: str
:return: The URL without the #fragment.
:rtype: str
"""
urlparts... | 4578f5a97865c8c19f2e946f8871c708a930fc4b | 3,597,174 |
def is_digits(src):
"""Returns True if all bytes match the production for DIGIT.
Empty strings return False"""
if src:
for b in src:
if not is_digit(b):
return False
return True
else:
return False | 478f44c9fdaa90096b285c761a72461313ed43f6 | 3,597,175 |
from typing import Tuple
from typing import Union
def get_human_length(length: int) -> Tuple[Union[int, float], str]:
"""Get the human readable length from the result
@type length: int
@param length: The length of the response body
@returns Tuple[int|float, str]: The tuple with new length
... | cba65b257c6930c3b64aba22505884df6ff3a9d0 | 3,597,176 |
def powset(S):
"""In : S (set)
Out: List of lists representing powerset.
Since sets/lists are unhashable, we convert the set
to a list,perform the powerset operations, leaving
the result as a list (can't convert back to a set).
Example:
S = {'ab', 'bc'}
... | 8d5cbc09f595d81b4a486994cfbce2a0cf97cf15 | 3,597,177 |
import numpy
def crop_image(image):
"""Crop an image to 1 pixel more that image, assuming the image background is white."""
height, width = get_shape(image)
top = height
bottom = 0
left = width
right = 0
for y_pos in range(height):
for x_pos in range(width):
if not nump... | 617cd7dc611970fa2d103f5c5f65d548e7d22059 | 3,597,179 |
def vars_in_func_used(abstract_syntax_tree):
"""Check that variables defined in a function are used later."""
errors = []
set_scopes = find_variables_in_scopes.set_in_tree(abstract_syntax_tree)
used_scopes = find_variables_in_scopes.used_in_tree(abstract_syntax_tree)
# Iterate through the set and ... | 933e378194da411f4f0970c1046faa00f0007b07 | 3,597,180 |
def get_status(site):
"""
:returns: Running status of a site
:rtype: int
:raises NoMatchingSite: If no matching site is in the database
"""
conn = _connect()
curs = conn.cursor()
curs.execute('SELECT isrunning FROM sites WHERE site = ?', (site, ))
result = curs.fetchone()
if no... | 336d86da99088c70cf7893826d48f01a2792ee76 | 3,597,181 |
def __find_realdepth_vector(s,ivec,nvec,n1,n2):
""" estimate the real depth from apparent for each element of array """
assert type(s) is np.ma.MaskedArray and type(ivec) is np.ndarray \
and type(nvec) is np.ndarray and nvec.shape == (3,) \
and type(n1) is float and type(n2) is float, 'invalid input'
... | d397fa48f07dc425127f76c90e32489e56b18b24 | 3,597,182 |
from datetime import datetime
def _escape_mapper_args(args):
"""
transfer data
"""
if isinstance(args, int):
return args
if isinstance(args, str):
return '\'' + args + '\''
if isinstance(args, bool):
return 1 if args else 0
if isinstance(args, (datetime, date)):
... | 29bed7e3d466c95d521b18353cc24b039714daa3 | 3,597,183 |
async def image_handwritten_text_recognition_S3_directory(params: ImageOcrS3Dir):
"""
Handwriting recognizer with google's vision API for
all .jpg files in a dir
### Request Body
- `s3_dir`: string
#### The s3 directory of the images that text and complexity scores are needed.
- `get_... | f6baaba0123db40ba108e70f6954724a933b027a | 3,597,184 |
def eval_model(n, filename, model, log_prob_func, caches):
"""Returns the perplexity of the model on a specified test set."""
log_prob_sum = 0
file_word_count = 0
with open(filename) as f:
for line in f:
prob, num_tokens = eval_sentence(n, line, model, log_prob_func, caches)
... | 2e1ed931d04361cb9d6042b82fd0756df01f1159 | 3,597,185 |
def parse_active_camera():
"""Parse the active camera
Raises
RuntimeError: When no active modelPanel an error is raised.
Returns:
str: Name of camera
"""
panel = capture.parse_active_panel()
camera = cmds.modelPanel(panel, query=True, camera=True)
return camera | 60fca8c6c15097b7d0f1b813745f6b07c9146415 | 3,597,186 |
def find_invader_shooter(invaders, player):
"""Find an invader shooter to take the shot."""
col = 0
# Create set of columns available
choice = randint(0, 1)
# 0 = try to shoot near player.
# 1 = shoot anywhere.
if choice == 0:
col = find_shooter_col_near_player(invaders, player)
else:
col = find_random_shoo... | 0507e30fb1713f07e351591461c1bea3a9714823 | 3,597,187 |
def slice_dict(original_dict, key_string):
"""
:param original_dict: Original (and larger) dictionary with all entrances
:param key_string: key string (desired starting string)
:return: A new dictionary with all the entrances of the original that start with key_string
"""
newdict = {}
for k... | 812b5a45115127f71cd5f2ebc02ea35c2582c81f | 3,597,188 |
def load_bigquery_table(project_id, dataset_id, table_id, filename):
""" Uploads a file to Google BigQuery.
Args:
project_id: Google Cloud Project ID for destination.
dataset_id: Name of destination dataset.
table_id: Name of destination table.
filename: Name of CSV file to be u... | 866982d180c72806311b8af159728957c9be6671 | 3,597,189 |
def get_loaders(datasets, num_tasks, nc_first_task, batch_size, num_workers, pin_memory, validation=.1):
"""Apply transformations to Datasets and create the DataLoaders for each task"""
trn_load, val_load, tst_load = [], [], []
taskcla = []
dataset_offset = 0
for idx_dataset, cur_dataset in enumera... | 9a13dd55fbff57fc76ff3609d647334b40838025 | 3,597,191 |
def nth_prime(n: int) -> int:
"""
Return the n'th prime number
The results are cached on file, so the primes are only calculated once.
"""
return get_primes(n)[n - 1] | 4fc69fbe2ec395f8c07c748189b54b5144ef25d0 | 3,597,192 |
import datasets
def data_loader(
context: StepContext,
) -> Output(data=pd.DataFrame, profile=DatasetProfile,):
"""Load the diabetes dataset."""
X, y = datasets.load_diabetes(return_X_y=True, as_frame=True)
# merge X and y together
df = pd.merge(X, y, left_index=True, right_index=True)
# lev... | e1ee491d32f000238431f01838c4c658f32b3a9d | 3,597,193 |
def noid(d):
""" Removes `id` key from a dict so we don't have to keep these things
around when trying to match
"""
if 'id' in d: del d['id']
return d | 35bc1e062e5c68e362f69c0cf079bf9d509801a9 | 3,597,194 |
import requests
def get_user_balance():
"""
取账户余额
"""
url = 'http://%s%s' % (host, balance_get_uri)
params = {
'un': un, # 账号
'pw': pw, # 密码
}
return requests.get(url, params).text | 58a0133a6a34294aedca95991108dde0794a9ee1 | 3,597,195 |
def get_ip_range(cidr_block):
"""
gets a cidr block of with cidr format '24.0.0.0/12'
returns a start and end ip address of format '24.0.0.0', '24.15.255.255'
:param cidr_block:
:return:
"""
start, bits = cidr_block.split('/')
start = start.strip()
bits = int(bits.strip())
start_int = ip_to_int(start)
end_i... | 9ebef73772dbf04898a9dfd3a3257a2f5a43750f | 3,597,196 |
def add_inputs(varname, inputs):
"""
Iterate over given inputs and create input socket value setters
"""
inputinits = ""
#valnamecount = 1
for inp in inputs:
if inp.type == 'SHADER': continue
if inp.is_linked: continue
inpname = get_socket_name(inp, inputs, True, inp... | bf64113aaaeb67a592bc939c40af6117cda98bec | 3,597,197 |
def elslib_SphereUIso(*args):
"""
* compute the U Isoparametric gp_Circ of the sphere, (the meridian is not trimmed).
:param Pos:
:type Pos: gp_Ax3
:param Radius:
:type Radius: float
:param U:
:type U: float
:rtype: gp_Circ
"""
return _ElSLib.elslib_SphereUIso(*args) | b9872796203b7e5153548756bf9883a32825a002 | 3,597,198 |
def make_element(tag, namespace_s=None, attributes=None, text=None):
""" This handler creates an empty element with the given ``tag``. The tag can
have a prefix. If ``namespace_s`` is ``None`` the namespace mapping of the
:term:`transformation root` is used as context. If given as :term:`mapping`,
... | c521e33cd8f908599d7ba8cee3caaa1702c6f8c7 | 3,597,199 |
def htmlReadFile(filename, encoding, options):
"""parse an XML file from the filesystem or the network. """
ret = libxml2mod.htmlReadFile(filename, encoding, options)
if ret is None:raise treeError('htmlReadFile() failed')
return xmlDoc(_obj=ret) | 03a5aa70257316fb5f3d48080ec5097bc8f48e5b | 3,597,200 |
import torch
def nms3d(boxes: Tensor, scores: Tensor, iou_threshold: float) -> Tensor:
"""3D NMS function GPU implementation (for BEV boxes).
Args:
boxes (torch.Tensor): Input boxes with the shape of (N, 7)
([x, y, z, dx, dy, dz, heading]).
scores (torch.Tensor): Scores of boxes w... | b2f1b9226506528b90d77eb97481479046cfa000 | 3,597,201 |
import builtins
def tp_ext_srv_cfg():
"""
:rtype : ExtSrvCfg
"""
if '__ext_srv_cfg__' not in builtins.__dict__:
builtins.__dict__['__ext_srv_cfg__'] = ExtSrvCfg()
return builtins.__dict__['__ext_srv_cfg__'] | 775ab00c2e79c3d4d31f8627ead9c99059b1a6ae | 3,597,202 |
import pandas
from functools import reduce
def save_confusion_matrix(label, predict, path="cm.pdf"):
"""
Creates confusion matrix.
:param label: list of labels [list]
:param predict: list of predictions [list]
:param path: path to file [str]
:return: none.
"""
classes = sklearn.utils.... | ebdf8e37b749e5e9f166d0da178840ece4b9c295 | 3,597,203 |
def unique_name(container, name, ext):
"""Generate unique name for container file."""
filename = '{}.{}'.format(name, ext)
i = 0
while filename in container:
i += 1
filename = '{}.{}.{}'.format(name, i, ext)
return filename | f2403611d58551fff65d996d426e458efd03ec80 | 3,597,204 |
import io
from re import I
import textwrap
def _generate_ivisitor(symbol_table: intermediate.SymbolTable) -> Stripped:
"""Generate the visitor interface."""
blocks = [] # type: List[Stripped]
for symbol in symbol_table.symbols:
if isinstance(symbol, intermediate.Enumeration):
continu... | 2d6c0d0c82bafe4b7d643036ce2f3e58cc1bc703 | 3,597,205 |
def get_compression_write_mode(compression):
"""Get the compression's default mode for openning the file buffer for
writing.
Returns
-------
write_mode_map: dict
Dictionary that maps known compression protocol names to default write
mode used to open files for
:func:`~compre... | 830cd2f3eb3e63b786be946a20e688102943efab | 3,597,206 |
def NFVALLoss(recon, data, mu, log_var, log_det):
"""
Compute the validation loss for the normalizing flows
Input :
recon = reconstructed event tensors, (minibatch_size, *)
data = actual event tensors, (minibatch_size, *)
mu = mu tensor for z_0, (minibat... | 7d3b5aed7371686b26e44a58a7e7345f2385003c | 3,597,207 |
import json
def get_select_data(checkList,model):
"""
获取要执行操作的数据
:param checkList: 选中的数据id列表(json)
:param model: 数据模型
:return:
"""
model_data_list = []
# 转化为python数据类型
checkList = json.loads(checkList)
for id in checkList:
model_data = model.objects.filter(pk=int(id))
... | 294f95dfb2ae3575c68ed0d82734b1cad97b5fcc | 3,597,209 |
import six
def _is_sequence(seq):
"""Returns true if its input is a `tuple`, `list`, or `range`.
Args:
seq: an input sequence.
Returns:
True if the sequence is a `tuple`, `list`, or `range`.
"""
return isinstance(seq, (tuple, list, six.moves.range)) | e94094c314cff5bf9bd7525453d7906ca55d7261 | 3,597,210 |
def get_medians(relAbs):
"""
Creates dictionary that will later allow us to sort phyla by how abudant/common they are across samples.
Note that for tax groups where median is zero, we will instead sort by average.
Arguments:
relAbs (dict) -- maps tax group index (determined by which co... | f2b194c1167fd492c4d3f600df6fdd96cbb9d731 | 3,597,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.