content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_rgeo(coordinates):
"""Geocode specified coordinates
:argument coordinates: address coordinates
:type coordinates: tuple
:returns tuple
"""
params = {'language': GEOCODING_LANGUAGE,
'latlng': ','.join([str(crdnt) for crdnt in coordinates])}
result = get(url=GEOCODING... | ca8d07f526260d48955dee1b32d18bf14b21f9f6 | 3,643,600 |
def norm_lib_size_log(assay, counts: daskarr) -> daskarr:
"""
Performs library size normalization and then transforms the
values into log scale.
Args:
assay: An instance of the assay object
counts: A dask array with raw counts data
Returns: A dask array (delayed matrix) containing ... | 3fdcde36daa3c3c491c3b85f718d75e6276af8fa | 3,643,601 |
def compare_dicts(cloud1, cloud2):
"""
Compare the dicts containing cloud images or flavours
"""
if len(cloud1) != len(cloud2):
return False
for item in cloud1:
if item in cloud2:
if cloud1[item] != cloud2[item]:
return False
else:
ret... | 4c13ed92da2cd40b543b75fac119b5da302717e3 | 3,643,602 |
import json
def ajax_stats():
"""
获取客户统计
:return:
"""
time_based = request.args.get('time_based', 'hour')
result_customer_middleman = customer_middleman_stats(time_based)
result_customer_end_user = customer_end_user_stats(time_based)
line_chart_data = {
'labels': [label for la... | a467bd656535695333030ded34ccb299d57c8ef7 | 3,643,603 |
import string
def str2int(string_with_int):
""" Collect digits from a string """
return int("".join([char for char in string_with_int if char in string.digits]) or 0) | 86955812fa3b2e6af0b98a04a1516897ccf95c25 | 3,643,604 |
def grid_to_3d(reward: np.ndarray) -> np.ndarray:
"""Convert gridworld state-only reward R[i,j] to 3D reward R[s,a,s']."""
assert reward.ndim == 2
reward = reward.flatten()
ns = reward.shape[0]
return state_to_3d(reward, ns, 5) | f848900b3b9ba7eb94fc1539fb1b24107e3db551 | 3,643,605 |
def find_routes(paths) -> list:
"""returns routes as tuple from path as list\
like 1,2,3 --> (1,2)(2,3)"""
routes = []
for path in paths:
for i in range(len(path)):
try:
route = (path[i], path[i + 1])
if route not in routes:
r... | 67fb8eb575dd45879f5e5b465a7886f2a2387b26 | 3,643,606 |
def z_step_ncg_hess_(Z, v, Y, F, phi, C_Z, eta_Z):
"""A wrapper of the hess-vector product for ncg calls."""
return z_step_tron_hess(v, Y, F, phi, C_Z, eta_Z) | 2c6e800040e5090333cbba0924985bf7fe17c873 | 3,643,607 |
def list_servers(**kwargs) -> "list[NovaServer]":
"""List all servers under the current project.
Args:
kwargs: Keyword arguments, which will be passed to
:func:`novaclient.v2.servers.list`. For example, to filter by
instance name, provide ``search_opts={'name': 'my-instance'}``
... | 3e12a6e24687e74942cc86bc616d57ebdb5a6521 | 3,643,608 |
from typing import Optional
from typing import cast
def resolve_xref(
app: Sphinx,
env: BuildEnvironment,
node: nodes.Node,
contnode: nodes.Node,
) -> Optional[nodes.reference]:
"""
Resolve as-yet-unresolved XRefs for :rst:role:`tconf` roles.
:param app: The Sphinx application.
:param env: The Sphinx b... | d4bc46765de1e892aa6753678fab5ad2ff693f68 | 3,643,609 |
def deploy_tester_contract(
web3,
contracts_manager,
deploy_contract,
contract_deployer_address,
get_random_address,
):
"""Returns a function that can be used to deploy a named contract,
using conract manager to compile the bytecode and get the ABI"""
def f(contract_n... | ee925e9632f3bfd66a843d336bd287c92543b2ed | 3,643,610 |
def make_hashable_params(params):
"""
Checks to make sure that the parameters submitted is hashable.
Args:
params(dict):
Returns:
"""
tuple_params = []
for key, value in params.items():
if isinstance(value, dict):
dict_tuple = tuple([(key2, value2) for key2, ... | 39d5de594b8caf776d2732e0e58b1c11127e5047 | 3,643,611 |
def check_member_role(member: discord.Member, role_id: int) -> bool:
"""
Checks if the Member has the Role
"""
return any(role.id == role_id for role in member.roles) | 500c9c33dd0e25a6a4704165add3d39c05d510d2 | 3,643,612 |
import itertools
def tag_bedpe(b, beds, verbose=False):
"""
Tag each end of a BEDPE with a set of (possibly many) query BED files.
For example, given a BEDPE of interacting fragments from a Hi-C experiment,
identify the contacts between promoters and ChIP-seq peaks. In this case,
promoters and Ch... | a1b95e04abd9401a6494fad2c2b6d48ecb14d414 | 3,643,613 |
from typing import Tuple
def point(x: float, y: float, z: float) -> Tuple:
"""Create a point."""
return Tuple(x, y, z, 1.0) | 035f01d990d16634867b147b7fcb7e9d5edf7f92 | 3,643,614 |
def partial_pipeline_data(backend, user=None, *args, **kwargs): # pragma: no cover
"""
Add the session key to a signed base64 encoded signature on the email request.
"""
data = backend.strategy.request_data()
if 'signature' in data:
try:
signed_details = signing.loads(data['sign... | 54c0124b49fead91fed238ded15f6c3167f0aed4 | 3,643,615 |
def arrayinv(F, Fx):
"""
Args:
F: dx.ds function value at x
Fx: dx.dx.ds derivative of function at x
Returns:
"""
return np.array([np.linalg.solve(a, b) for a, b in zip(Fx.swapaxes(0,2), F.T)]).T | ac412bf0cb03a77d0a18295b899aeabd8bcdbfb3 | 3,643,616 |
import os
import csv
def schedule_list(req):
"""List scheduled jobs
"""
schedule = []
if os.path.exists(SCHEDULE):
with open(SCHEDULE) as f:
for n, a, t in csv.reader(f):
schedule.append({'Name': n, 'Timer': t, 'Action': a})
return {'Err': '', 'Schedule': schedu... | cdcb9eb15b2faae83bd03765aeb329fd0f4ca6ae | 3,643,617 |
def mil(val):
"""convert mil to mm"""
return float(val) * 0.0254 | 9071b0116a7062ef93d6bee56a08db2b9bec906a | 3,643,618 |
def ask_number(question, low, high):
"""Poproś o podanie liczby z określonego zakresu."""
response = None
while type(response) != int:
try:
response = int(input(question))
while response not in range(low, high):
response = int(input(question))
except V... | fdae37e6a0cd34d36b647a23f4a0f58cad46680a | 3,643,619 |
import os
def CheckGypFile(gypfile):
"""Check |gypfile| for common mistakes."""
if not os.path.exists(gypfile):
# The file has been deleted.
return
with open(gypfile) as fp:
return CheckGypData(gypfile, fp.read()) | edc9971616f0fd6e65872034f485f0156e219fae | 3,643,620 |
import numpy
from typing import Tuple
import math
def _beams_longitude_latitude(
ping_header: PingHeader, along_track: numpy.ndarray, across_track: numpy.ndarray
) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""
Calculate the longitude and latitude for each beam.
https://en.wikipedia.org/wiki/Geographic_... | c43171830206c5db878a817a03a4830aae878765 | 3,643,621 |
def true_range_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d) -> tp.Array2d:
"""Calculate true range."""
prev_close = generic_nb.fshift_nb(close, 1)
tr1 = high - low
tr2 = np.abs(high - prev_close)
tr3 = np.abs(low - prev_close)
tr = np.empty(prev_close.shape, dtype=np.float_)
for ... | 7b7594a1a5adf4e280a53af3e01d9aec5bd3b80c | 3,643,622 |
def laplacian_operator(data):
"""
apply laplacian operator on data
"""
lap = []
lap.append(0.0)
for index in range(1, len(data) - 1):
lap.append((data[index + 1] + data[index - 1]) / 2.0 - data[index])
lap.append(0.0)
return lap | 3d7755cdc52352cc445d5942e34c09f65f3e11db | 3,643,623 |
def _stringmatcher(pattern):
"""
accepts a string, possibly starting with 're:' or 'literal:' prefix.
returns the matcher name, pattern, and matcher function.
missing or unknown prefixes are treated as literal matches.
helper for tests:
>>> def test(pattern, *tests):
... kind, pattern, ... | 76a673133aaf7493b531b4f73364af2d16dd214b | 3,643,624 |
def enu_to_ecef(ref_lat_rad, ref_lon_rad, ref_alt_m, e_m, n_m, u_m):
"""Convert ENU coordinates relative to reference location to ECEF coordinates.
This converts local east-north-up (ENU) coordinates relative to a given
reference position to earth-centered, earth-fixed (ECEF) cartesian
coordinates. The... | a6a7e8e3a67a17894d68d6c62b2ac7fcef7a09ec | 3,643,625 |
import re
import requests
def is_file_url(share_url: str) -> bool:
"""判断是否为文件的分享链接"""
base_pat = r'https?://[a-zA-Z0-9-]*?\.?lanzou[a-z].com/.+' # 子域名可个性化设置或者不存在
user_pat = r'https?://[a-zA-Z0-9-]*?\.?lanzou[a-z].com/i[a-zA-Z0-9]{5,}/?' # 普通用户 URL 规则
if not re.fullmatch(base_pat, share_url):
... | d9b56a2187cedeb79cb848192b544026a5d85e29 | 3,643,626 |
def get_compton_fraction_artis(energy):
"""Gets the Compton scattering/absorption fraction
and angle following the scheme in ARTIS
Parameters
----------
energy : float
Energy of the gamma-ray
Returns
-------
float
Scattering angle
float
Compton scattering fr... | 2121712c542c967ef7008a4bdf8b88a8e2bcdb6c | 3,643,627 |
def is_argspec_compatible_with_types(argspec, *args, **kwargs):
"""Determines if functions matching 'argspec' accept given 'args'/'kwargs'.
Args:
argspec: An instance of inspect.ArgSpec to verify agains the arguments.
*args: Zero or more positional arguments, all of which must be instances of
computa... | 5103fa00737f4faeda49441f9d67388f34599d09 | 3,643,628 |
def get_span_feats_stopwords(stopwords):
"""Get a span dependency tree unary function"""
return partial(get_span_feats, stopwords=stopwords) | 86fd8c597f39f71c489665c05d164e0a3e1e69c0 | 3,643,629 |
def get_argument_parser(argparser):
"""Augments the given ArgumentParser for use with the Bonobo ETL framework."""
return bonobo.get_argument_parser(parser=argparser) | 584fc867660f85998a679d1883828ea7a8c3896f | 3,643,630 |
from pathlib import Path
def input_file_path(directory: str, file_name: str) -> Path:
"""Given the string paths to the result directory, and the input file
return the path to the file.
1. check if the input_file is an absolute path, and if so, return that.
2. if the input_file is a relative path, co... | dd866a5f8b6f776238269844d64686f7fb28347c | 3,643,631 |
def loss(S, K, n_samples=None):
"""Loss function for time-varying graphical lasso."""
if n_samples is None:
n_samples = np.ones(S.shape[0])
return sum(
-ni * logl(emp_cov, precision)
for emp_cov, precision, ni in zip(S, K, n_samples)) | 07ad436bf5aee5e8b1dc53e89b894c4c8883cedd | 3,643,632 |
def flat_dict(df):
"""
Add each key-value of a nested dictionary that is saved in a dataframe, as a new column
"""
for col in df.columns:
if type(df[col][0]) == dict:
df = pd.concat(
[df.drop([col], axis=1), df[col].apply(pd.Series)], axis=1)
# sometim... | ec817b9c7a08aab95bb29981dafbb1f1e03821eb | 3,643,633 |
from typing import List
async def run_setup_pys(
targets_with_origins: TargetsWithOrigins,
setup_py_subsystem: SetupPySubsystem,
console: Console,
python_setup: PythonSetup,
distdir: DistDir,
workspace: Workspace,
union_membership: UnionMembership,
) -> SetupPy:
"""Run setup.py command... | 713f0b7f3558e2a69dcca0a7a251f4991ee49073 | 3,643,634 |
def list_tasks():
"""
显示所有任务列表,方便管理任务
:return:
"""
try:
task_id = request.args.get("task_id")
task_status = request.args.get('status')
# 构造条件查询元组
task_info_list = list()
tasks = TaskService.get_tasks_url_num(task_id=task_id, task_status=task_status)
f... | c6d205e95bd7a1a2e76baf7f89c917310b683bc0 | 3,643,635 |
import itertools
import torch
def make_fixed_size(
protein,
shape_schema,
msa_cluster_size,
extra_msa_size,
num_res=0,
num_templates=0,
):
"""Guess at the MSA and sequence dimension to make fixed size."""
pad_size_map = {
NUM_RES: num_res,
NUM_MSA_SEQ: msa_cluster_size,... | 1125e1cdbe8f12d6613fb8dd9374afdbf1fd065a | 3,643,636 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_urlhaus package"""
reload_params = {"package": u"fn_urlhaus",
"incident_fields": [],
"action_fields": [],
"function_params": [u"urlhaus_artifact_type", u"urlhaus_artifact_val... | 1665121ab3305f517242b122e2aaae2b12fe57f0 | 3,643,637 |
def urls(page, baseurl=auto, direct=True, prev=True, next=True):
"""
Return a list of pagination URLs extracted form the page.
When baseurl is None relative URLs are returned; pass baseurl
to get absolute URLs.
``prev``, ``next`` and ``direct`` arguments control whether to return
'next page', '... | 70f0337b5ed1a1cd8c0cfd1f99f8ad67da85b23d | 3,643,638 |
def sinc_filter(audio: tf.Tensor,
cutoff_frequency: tf.Tensor,
window_size: int = 512,
sample_rate: int = None,
padding: Text = 'same') -> tf.Tensor:
"""Filter audio with sinc low-pass filter.
Args:
audio: Input audio. Tensor of shape [batch, audi... | ea13a320744bb380b20643c2a995be67fc9d1303 | 3,643,639 |
def _getDataFlows(blocks):
"""
Given a block dictonary from bifrost.proclog.load_by_pid(), return a list
of chains that give the data flow.
"""
# Find out what rings we have to work with and which blocks are sources
# or sinks
rings = []
sources, sourceRings = [], []
sinks, sinkRin... | 197cc64b5bf7ecd8e5c7d912239c93a1feffcd14 | 3,643,640 |
def find_lowest_cost_node(costs: dict, processed: list) -> dict:
"""Return the node with the lowest cost"""
lowest_cost = float("inf") # Infinity
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in ... | aeb0ef046619bc9280d3d712329c672f76e36c90 | 3,643,641 |
def scale_img(image, random_coordinate=False):
"""
对原图大小进行处理,
:param image:
:param random_coordinate:
:return:
"""
h, w, c = image.shape
if max(h, w) > 640:
f_scale = min(640./h, 640./w) # scale factor
image = cv2.resize(src=image, dsize=None, fx=f_scale, fy=f_scale, in... | 6a0b93f4564c6d83e60f6f7a250822f801e0b65b | 3,643,642 |
import math
def magnitude(v: Vector) -> float:
"""computes the magnitude (length) of a vector"""
return math.sqrt(sum_of_squares(v)) | 881f2a3e75520b3f8da7ea093765e36d78e48c57 | 3,643,643 |
import os
import requests
def pew(text):
"""PEW -- Percentage of Echomimetic (onomatopoeic) Words."""
pew = None
onomatopoeic_words_num = 0
path = '/tmp/onomatopoeic_words_en-1.0.txt'
if not os.path.exists(path):
url = 'https://raw.githubusercontent.com/korniichuk/phd/master/resources/on... | 781cb95ade2fd3b11440022e0447aef18cdde7fc | 3,643,644 |
import os
import sys
def topngbytes(name, rows, x, y, **k):
"""
Convenience function for creating a PNG file "in memory" as
a string. Creates a :class:`Writer` instance using the keyword
arguments, then passes `rows` to its :meth:`Writer.write` method.
The resulting PNG file is returned as bytes.... | 569b913211640627132f0c0af13614218bec3f46 | 3,643,645 |
import time
def supply_domes1finesk():
"""
Real Name: b'"Supply Domes-1Finesk"'
Original Eqn: b'MIN("Domes-1 Demad finesk" (Time), (outflow Finesk) )'
Units: b'MCM/Month'
Limits: (None, None)
Type: component
b''
"""
return np.minimum(domes1_demad_finesk(time()), (outflow_finesk())... | e7bbbdc49e45044179053a02c4b76c1dda798bc0 | 3,643,646 |
def poll(handle):
"""
Polls an push_pull handle to determine whether underlying
asynchronous operation has completed. After `poll()` returns `True`, `synchronize()`
will return without blocking.
Arguments:
handle: A handle returned by an push_pull asynchronous
operation.
... | e228183068517962e7886c020e662b8c1a1f2912 | 3,643,647 |
from typing import Tuple
def _increase_explicit_hydrogen_for_bond_atom(
rwmol: Chem.rdchem.RWMol,
remove_bidx: bool,
bidx: int,
remove_eidx: bool,
eidx: int,
ai_to_remove: list,
) -> Tuple[Chem.rdchem.RWMol, list]:
"""Increase number of explicit hydrogens for atom in a bond.
Args:
... | cf0276730ee0837d43098f9712f7c199ba93b268 | 3,643,648 |
import os
import tempfile
import urllib
def maybe_download(filename, work_directory, source_url):
"""Download the data from source url, unless it's already here.
Args:
filename: string, name of the file in the directory.
work_directory: string, path to working directory.
source_url: url to down... | ddf3912517ac65d9775302522c1d287cd6499b89 | 3,643,649 |
def plot_historical_actuals_forecast(e, title=None, ylabel='',
include_pred_int=False,
years_prior_include=2,
forecast_display_start=None,
e2=None):
"""Produce a plot of... | e6604fe35ce6a65ff61ee45a387167d019be867a | 3,643,650 |
import time
import threading
def f2(a, b):
"""
concurrent_num = 600 不用怕,因为这是智能线程池,如果函数耗时短,不会真开那么多线程。
这个例子是测试函数耗时是动态变化的,这样就不可能通过提前设置参数预估函数固定耗时和搞鬼了。看看能不能实现qps稳定和线程池自动扩大自动缩小
要说明的是打印的线程数量也包含了框架启动时候几个其他的线程,所以数量不是刚好和所需的线程计算一样的。
## 可以在运行控制台搜索 新启动线程 这个关键字,看看是不是何时适合扩大线程数量。
## 可以在运行控制台搜索 停止线程 这个关键字,看... | 4f555d2b684e06d171a821fde6c10d2a72596396 | 3,643,651 |
def minimize_loss_single_machine_manual(loss,
accuracy,
layer_collection,
device=None,
session_config=None):
"""Minimize loss with K-FAC on a single machine(I... | c5f53d7eddabe3ea5ac30ae4ecc050ee43ffa5e7 | 3,643,652 |
def bass_call_0(function, *args):
"""Makes a call to bass and raises an exception if it fails. Does not consider 0 an error."""
res = function(*args)
if res == -1:
code = BASS_ErrorGetCode()
raise BassError(code, get_error_description(code))
return res | 9355f12b7277914e2397c64103666be0f5b801e5 | 3,643,653 |
def port_speed(value : str | None = None) -> int | None:
"""Port speed -> Mb/s parcer"""
if value is None:
return None
elif value == "X":
return 0
elif value == "M":
return 100
elif value == "G":
return 1000
elif value == "Q":
return 2500
else:
... | 2bb41bf66211724a12bdf392ecf018c71836f42b | 3,643,654 |
def convert_flag_frame_to_strings(flag_frame, sep=', ', empty='OK'):
"""
Convert the `flag_frame` output of :py:func:`~convert_mask_into_dataframe`
into a pandas.Series of strings which are the active flag names separated
by `sep`. Any row where all columns are false will have a value of `empty`.
P... | fa7f0cc427e4b6e4c703ea2011af59f1bad090ab | 3,643,655 |
def pp_file_to_dataframe(pp_filename):
""" read a pilot point file to a pandas Dataframe
Parameters
----------
pp_filename : str
pilot point file
Returns
-------
df : pandas.DataFrame
a dataframe with pp_utils.PP_NAMES for columns
"""
df = pd.read_csv(pp_filename... | 777272db75f0e6c7bd1eee0b24d4879bf2ceb66a | 3,643,656 |
import os
def get_ps_lib_dirs():
"""
Add directory to list as required
"""
polysync_install = os.path.join('/', 'usr', 'local', 'polysync')
polysync_lib = os.path.join(polysync_install, 'lib')
polysync_vendor = os.path.join(polysync_install, 'vendor', 'lib')
return [
polysync_lib,... | ce4745ef5dcdb4c00051eff6fae6082f98c90498 | 3,643,657 |
def edit_product(request, product_id):
""" Edit a product in the store """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only store owners can do that.')
return redirect(reverse('home'))
product = get_object_or_404(Product, pk=product_id)
if request.method == 'POST':... | 0f22ca856ca71e973bd8eed85bba7f54ce3a3464 | 3,643,658 |
def _resolve_target(target, target_frame='icrs'):
"""Return an `astropy.coordinates.SkyCoord` form `target` and its frame."""
if target_frame == 'icrs':
return parse_coordinates(target)
return SkyCoord(target, frame=target_frame) | b2b8132ca15b6bcfbb6d67c90abf36760be6a2d1 | 3,643,659 |
import itertools
def iter_fragments(fragiter, start_frag_id = None, stop_frag_id = None):
"""Given a fragment iterator and a start and end fragment id,
return an iterator which yields only fragments within the range.
"""
if start_frag_id and stop_frag_id:
dpred = lambda f: fragment_id_lt(f.fra... | a1ab1245a6cb450cdb363a7029147501adf913db | 3,643,660 |
from typing import Generator
import os
def evaluate_gpt_with_distgen(settings,
archive_path=None,
merit_f=None,
gpt_input_file=None,
distgen_input_file=None,
workdir=None,
use_tempdir=True,
gpt_bin='$GPT_BIN',
... | ed229084f43cc8143538d1e76ea1a5e4e4f220eb | 3,643,661 |
from bst import BST
def bst_right_imbalanced():
"""Bst that extends right."""
test_bst = BST((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
return test_bst | 4cdb45770634c389831057832b33755fe0a8db23 | 3,643,662 |
import time
def retry(exception_to_check, tries=4, delay=0.5, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
Args:
exception_to_check (Exception): the exception to check.
may be a tuple of exceptions to check
... | 8e607104abf1cd5165199b7792f6955084e674cd | 3,643,663 |
def HESSIAN_DIAG(fn):
"""Generates a function which computes per-argument partial Hessians."""
def h_fn(*args, **kwargs):
args = (args,) if not isinstance(args, (tuple, list)) else tuple(args)
ret = [
jaxm.hessian(
lambda arg: fn(*args[:i], arg, *args[i + 1 :], **kwa... | 01075519f7c3ae052a553bd3911e0447fa8da6ce | 3,643,664 |
from scipy.spatial import cKDTree
import numpy
def match_xy(x1, y1, x2, y2, neighbors=1):
"""Match x1 & y1 to x2 & y2, neighbors nearest neighbors.
Finds the neighbors nearest neighbors to each point in x2, y2 among
all x1, y1."""
vec1 = numpy.array([x1, y1]).T
vec2 = numpy.array([x2, y2]).T
... | cd360ee6fc0ec83fad565313f6cbb0e8a4292ca2 | 3,643,665 |
def make_doc():
""" Only used for sphinx documentation """
doc_app = Flask(__name__)
doc_app.register_blueprint(blueprint())
return doc_app | beff9149ceffb04f80071f6a595ef13e72ebc838 | 3,643,666 |
def logout(request):
"""Logs out the user"""
user_logout(request)
return redirect(auth_views.login) | 739ef6b3b4daded0af786f8261072e05e8bba273 | 3,643,667 |
import os
import tempfile
def to_pydot(obj):
"""Specify either of the following options: a dot string (filename or text),
a networkx graph, a pydot graph, an igraph graph, or a callable function.
The function will be called with a filename to write it's dot output to."""
if isinstance(obj, pydot.... | 26ec25b22b415ba4a4f65172bdc47bf3eb4f7bc7 | 3,643,668 |
import math
def workout_train_chunk_length(inp_len: int,
resampling_factor: int = 1,
num_encoders: int = 5,
kernel: int = 8,
stride: int = 2) -> int:
"""
Given inp_len, return the chunk ... | a7e7f42aa9670f1bda98c588e50052db0f4eb90f | 3,643,669 |
def asin(e):
"""
:rtype: Column
"""
return col(Asin(parse(e))) | 7c7fb32e84d7a9af74bc64eed2f111fd2030a499 | 3,643,670 |
import subprocess
def gs_exists(gs_url):
"""Check if gs_url points to a valid file we can access"""
# If gs_url is not accessible, the response could be one of:
# 1. "You aren't authorized to read ..."
# 2. "No URLs matched: ..."
# and it would have a non-0 status, which would be raised.
#... | bfec2639d98f9c99107951ca3e48bdfc1c6ea545 | 3,643,671 |
def ft32m3(ft3):
"""ft^3 -> m^3"""
return 0.028316847*ft3 | 74f55f722c7e90be3fa2fc1f79f506c44bc6e9bc | 3,643,672 |
def get_audience(request):
"""
Uses Django settings to format the audience.
To figure out the audience to use, it does this:
1. If settings.DEBUG is True and settings.SITE_URL is not set or
empty, then the domain on the request will be used.
This is *not* secure!
2. Otherwise, sett... | f5321a1ecb80c2aa3b7b16979429355841eee30a | 3,643,673 |
def max_shading_elevation(total_collector_geometry, tracker_distance,
relative_slope):
"""Calculate the maximum elevation angle for which shading can occur.
Parameters
----------
total_collector_geometry: :py:class:`Shapely Polygon <Polygon>`
Polygon corresponding to t... | f3e623607ae1c2576fa375146f4acc6186189d8c | 3,643,674 |
def tensor_scatter_add(input_x, indices, updates):
"""
Creates a new tensor by adding the values from the positions in `input_x` indicated by
`indices`, with values from `updates`. When multiple values are given for the same
index, the updated result will be the sum of all values. This operation is almo... | 38707efab3d2f947cbc44dacb6427281d3b652cb | 3,643,675 |
def test100():
"""
CIFAR-100 test set creator.
It returns a reader creator, each sample in the reader is image pixels in
[0, 1] and label in [0, 9].
:return: Test reader creator.
:rtype: callable
"""
return reader_creator(
paddle.v2.dataset.common.download(CIFAR100_URL, 'cifar'... | f43e27a7ce1ec40dfc50d513de5406b2683a566b | 3,643,676 |
def _calculate_target_matrix_dimension(m, kernel, paddings, strides):
"""
Calculate the target matrix dimension.
Parameters
----------
m: ndarray
2d Matrix
k: ndarray
2d Convolution kernel
paddings: tuple
Number of padding in (row, height) on one side.
If you... | 77b5cabd7101b957a27fc422d1ed1715525400a0 | 3,643,677 |
def any_email():
"""
Return random email
>>> import re
>>> result = any_email()
>>> type(result)
<type 'str'>
>>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None
True
"""
return "%s@%s.%s" % (any_string(max_length=10),
... | 8575d02d3c9a777bc2cf27f1344676cad5514d5e | 3,643,678 |
def transform_pts_base_to_stitched_im(pts):
"""Project 3D points in base frame to the stitched image
Args:
pts (np.array[3, N]): points (x, y, z)
Returns:
pts_im (np.array[2, N])
inbound_mask (np.array[N])
"""
im_size = (480, 3760)
# to image coordinate
pts_rect = ... | c6397451e458af086fe316c6933ca27641daac26 | 3,643,679 |
def get_equal_static_values(*args):
"""get_equal_static_values(FileConstHandle input, FileConstHandle out) -> bool"""
return _RMF.get_equal_static_values(*args) | 8f929f0eae16e620b5025ad34b4437d836d8d671 | 3,643,680 |
def quaternion_to_rotation_matrix(quaternion):
"""
This converts a quaternion representation of on orientation to
a rotation matrix. The input is a 4-component numpy array in
the order [w, x, y, z], and the output is a 3x3 matrix stored
as a 2D numpy array. We follow the approach in
"3D Math P... | 95a8dd9d0a9510710e7b6ed676a5f03e26b2da96 | 3,643,681 |
def load_subject(filename: str,
mask_niimg):
"""
Load a subject saved in .mat format with
the version 7.3 flag. Return the subject
niimg, using a mask niimg as a template
for nifti headers.
Args:
filename <str> the .mat filename for the subject... | e3cdb751cebd7407b694555adfb21e7a6a224c50 | 3,643,682 |
import os
import glob
def get_data_monash(directory):
"""
Get the monash data in a dictionary
"""
# Generate the wildcard for the models
wildcard = os.path.join(directory, "*")
model_files = glob.glob(wildcard)
all_models = {}
for model_file in model_files:
# First extract the... | c427d49a925cdd97ddaf6731e799c90192b5ea33 | 3,643,683 |
def pretty_duration(seconds):
"""Return a human-readable string for the specified duration"""
if seconds < 2:
return '%d second' % seconds
elif seconds < 120:
return '%d seconds' % seconds
elif seconds < 7200:
return '%d minutes' % (seconds // 60)
elif seconds < 48 * 360... | 8e34addedeeb98e1e028fa9374fcc8c4f134a9f7 | 3,643,684 |
def plot_ecdf(tidy_data, cats, val, title, width=550, conf_int=False):
"""
Plots an ECDF of tidy data.
tidy_data: Set of tidy data.
cats: Categories to plot
val: The value to plot
title: Title of plot
width: width of plot
conf_int: Whether or not to bootstrap a CI.
"""
p = bokeh... | 11ef82111ad300826f47f6ce91ea588911a790c8 | 3,643,685 |
from operator import concat
def upsert(left, right, inclusion=None, exclusion=None):
"""Upserts the specified left collection with the specified right collection by overriding the
left values with the right values that have the same indices and concatenating the right values
to the left values that have different ... | b4754c01ff521b892107afd8dd12b015bd4e293a | 3,643,686 |
from typing import Counter
def train(training_data):
"""Trains the model on a given data set.
Parameters
----------
training_data
Returns
-------
"""
counts = Counter(training_data)
model = {}
# sort counts by lowest occurrences, up to most frequent.
# this allows higher... | 328901b090392097d22b21a948691787e0128d48 | 3,643,687 |
from datetime import datetime
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['cache'] = 86400
desc['description'] = """This chart totals the number of distinct calendar
days per month that a given present weather conditio... | 0927644a801a2829a97fbc6e78ef70fff1e8edfe | 3,643,688 |
import logging
from datetime import datetime
import time
def check_cortex(ioc, ioc_type, object_id, is_mail=False, cortex_expiration_days=30):
"""Run all available analyzer for ioc.
arguments:
- ioc: value/path of item we need to check on cortex
- ioc_type: type of the ioc (generic_relation and corte... | c647ab09bd97dda75dc4073634ac4a68cbf8613a | 3,643,689 |
def _env_corr_same(wxy, Xa, Ya, sign=-1, log=True, x_ind=None, y_ind=None):
"""
The cSPoC objective function with same filters for both data sets:
the correlation of amplitude envelopes
Additionally, it returns the gradients of the objective function
with respect to each of the filter coefficients.... | 2004e3ab1f9c81466e8dc946b04baf5a692b169d | 3,643,690 |
def create_resource():
"""Hosts resource factory method"""
deserializer = HostDeserializer()
serializer = HostSerializer()
return wsgi.Resource(Controller(), deserializer, serializer) | ed49ae9fecce67fcd3c4fa1a2eac469eb97e239b | 3,643,691 |
def get_ref_kmer(ref_seq, ref_name, k_len):
""" Load reference kmers. """
ref_mer = []
ref_set = set()
for i in range(len(ref_seq) - k_len + 1):
kmer = ref_seq[i:(i + k_len)]
if kmer in ref_set:
raise ValueError(
"%s found multiple times in reference %s, at p... | 72b75dccfba122a986d50e144dea62bfafe0fb50 | 3,643,692 |
def get_distutils_build_or_install_option(option):
""" Returns the value of the given distutils build or install option.
Parameters
----------
option : str
The name of the option
Returns
-------
val : str or None
The value of the given distutils build or install option. If ... | 7f0d72e1c30c752761eb8c7f8f0ffeb875183d4d | 3,643,693 |
def CMDset_close(parser, args):
"""Closes the issue."""
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error('Unrecognized args: %s' % ' '.join(args))
cl = Changelist(auth_config=auth_config)
# Ensure t... | 6711ba947e9d839217a96568a0c07d1103646030 | 3,643,694 |
def gchip(k_k, b_b, c_c):
"""gchip(k_k, b_b, c_c)"""
yout = b_b*c_c*nu_f(1, b_b, k_k)**((c_c+1)/2)*\
cos((c_c+1)*atan(b_b*k_k))
return yout | 81fa674a2fb03875e39f2968986104da06a5ea44 | 3,643,695 |
def create_component(ctx: NVPContext):
"""Create an instance of the component"""
return ProcessUtils(ctx) | ec9d4539583dbdeaf1c4f5d8fce337077d249ab2 | 3,643,696 |
import ipaddress
def is_valid_ip(ip: str) -> bool:
"""
Args:
ip: IP address
Returns: True if the string represents an IPv4 or an IPv6 address, false otherwise.
"""
try:
ipaddress.IPv4Address(ip)
return True
except ValueError:
try:
ipaddress.IPv6Addre... | aa1d3b19828dd8c3dceaaa8d9d1017cc16c1f73b | 3,643,697 |
def complete_tree(leaves):
"""
Complete a tree defined by its leaves.
Parmeters:
----------
leaves : np.array(dtype=np.int64)
Returns:
--------
np.array(dtype=np.int64)
"""
tree_set = _complete_tree(leaves)
return np.fromiter(tree_set, dtype=np.int64) | 4bfc1ae01efd9595ef875613bd00d76f7c485421 | 3,643,698 |
import torch
def pick_best_batch_size_for_gpu():
"""
Tries to pick a batch size that will fit in your GPU. These sizes aren't guaranteed to work, but they should give
you a good shot.
"""
free, available = torch.cuda.mem_get_info()
availableGb = available / (1024 ** 3)
if availableGb > 14:... | 31d970697b417b40f8ef5b41fdeacc0e378543a0 | 3,643,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.