content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_convert_label_fn(odgt):
"""
A function that converts labels to expected range [-1, num_classes-1] where -1 is ignored.
When using custom dataset, you might want to add your own function.
"""
def convert_ade_label(segm):
"Convert ADE labels to range [-1, 149]"
return segm - 1... | dd87a1cc889faf5874eaec45db51804b20fb46ff | 41,200 |
def _get_span(s, pattern):
"""Return the span of the first group that matches the pattern."""
i, j = -1, -1
match = pattern.match(s)
if not match:
return i, j
for group_name in pattern.groupindex:
i, j = match.span(group_name)
if (i, j) != (-1, -1):
return i, j
... | 8feec723d5a09e70f000c6fcdf58269dd6ea9330 | 41,201 |
import os
def GrabLocalPackageIndex(package_path):
"""Read a local packages file from disk into a PackageIndex() object.
Args:
package_path: Directory containing Packages file.
Returns:
A PackageIndex object.
"""
with open(os.path.join(package_path, 'Packages')) as f:
pkgindex = PackageIndex()... | 4e07507ad57d490e1286cd8e6e5f0887490f23a5 | 41,202 |
from typing import Callable
from typing import Dict
def random_prop(true_prop : np.ndarray,
niter : int = 1000,
loss_function : Callable = _rmse,
) -> Dict[str,float]:
"""Random Proportion performance
Samples proportion values from a
Z-dimensional (Z is numb... | f23be6ceb7ddc88afc35f8dc7a9e4987da30d403 | 41,203 |
from pathlib import Path
def guess_format(path):
"""Guess file format identifier from it's suffix. Default to DICOM."""
path = Path(path)
if path.is_file():
suffixes = [x.lower() for x in path.suffixes]
if suffixes[-1] in ['.h5', '.txt', '.zip']:
return suffixes[-1][1:]
... | 70f463ef28adc2c65346ec8b5b87294494a9ee0f | 41,204 |
import numpy
def cartesian_to_polar(u, v):
"""
Transforms U,V into r,theta, with theta being relative to north (instead of east, a.k.a. the x-axis).
Mainly for wind U,V to wind speed,direction transformations.
"""
c = u + v*1j
r = numpy.abs(c)
theta = numpy.angle(c, deg=True)
# Convert... | ee35ca5d5201b10e31b6f0eea0471b0b97ada5fb | 41,205 |
def gkern(kernlen=3, nsig=3):
"""Returns a 2D Gaussian kernel."""
x = np.linspace(-nsig, nsig, kernlen + 1)
kern1d = np.diff(st.norm.cdf(x))
kern2d = np.outer(kern1d, kern1d)
return kern2d / kern2d.sum() | 454692c2a88b9a9ca3dc4e6ad1d5cf53a3194705 | 41,206 |
import copy
def remove_duplicate_column_names(list_of_dict_of_header_info):
"""
No two columns of the table can have the same data
:param plot_options:
:return:
"""
list_of_column_names = []
list_of_dict_of_header_info_copy = copy.deepcopy(list_of_dict_of_header_info)
for index, dict_o... | a0560b8f462363539ef11bce540e4625671957e5 | 41,207 |
def option(*param_decls, **attrs):
"""Attaches an option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`, all keyword
arguments are forwarded unchanged. This is equivalent to creating an
:class:`Option` instance manually and attaching it to the
:att... | 673c7d49e69d0cdd7d0a299c397577bb8810fd16 | 41,208 |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
new_line = [x for x in line if x !=0]
while len(new_line) < len(line):
new_line.append(0)
for ind in range(len(new_line)-1):
if new_line[ind] == new_line[ind+1]:
new_line[ind] *= 2
... | 0d05fa02101ddc9cd4dd670317f71abb016a25c5 | 41,209 |
def axesvalues(roi, parameters):
"""
Args:
roi(list): y0,x0,ny,nx
parameters(dict)
Returns:
tuple(np.ndarray)
"""
x0 = roi[1]
y0 = roi[0]
nx = roi[3]
ny = roi[2]
# Sub region
if parameters["roi"] is not None:
ax = parameters["roi"][1][0]
b... | 0d0e88971ea52bb431e03c77ff94d75fea4c6369 | 41,210 |
from urllib.parse import urljoin
import urlparse
from urlparse import urljoin
def _urljoin(base, url):
"""
urljoin shim helper for Python2\3
"""
if (hasattr(urllib, 'parse')):
else:
return urljoin(base, url) | b00b8ae61eaed1741ca16ed5b17053bd286783f2 | 41,211 |
import urllib
from bs4 import BeautifulSoup
def scrape_profile(url):
"""
Scrape the user's profile to get user location and id.
"""
r = urllib.request.urlopen(url).read()
soup = BeautifulSoup(r, "lxml")
user_country = get_user_country(soup)
user_id = get_user_id(soup)
return user_count... | c109ce603819b75c286c41f192bed20023b20460 | 41,212 |
import uuid
def make_new_aileenbox(options: dict) -> AileenBox:
""" make a new aileen_box """
aileen_box = None
if options["id"] is None:
options["id"] = uuid.uuid4()
try:
coordinates = [float(l) for l in options["location"].split(",")]
except Exception as e:
raise Exceptio... | a94d2ee2697c1ec1cd18d183306e5851c4bb100e | 41,213 |
def get_samples(profileDict):
"""
Returns the samples only for the metrics (i.e. does not return any
information from the activity timeline)
"""
return profileDict["samples"]["metrics"] | 06b273e7499e9cb64e38b91374117de6bd3f6c3e | 41,214 |
def dobro(n):
"""
Dobrar número
:param n: número a ser dobrado
:return: resultado
"""
n = float(n)
n += n
return n | fe17270b7a3373545986568657cf6755dc88638f | 41,215 |
def add_user(username, password, first_name, last_name, email, session):
"""
Creates and saves a new user to the database
:param session:
:param username:
:param password:
:param first_name:
:param last_name:
:param email:
:return: id of the new user
"""
new_user = User(us... | b1b2ca8cc73d2481c3b85861162042a7d7b2eed3 | 41,216 |
def aoi_from_experiment_to_cairo(aoi):
"""Transform aoi from exp coordinates to cairo coordinates."""
width = round(aoi[1]-aoi[0], 2)
height = round(aoi[3]-aoi[2], 2)
return([aoi[0], aoi[2], width, height]) | 40986aeaf5bb1e5d8295289ce310b4c7cf7f4241 | 41,217 |
def nonzero_colmeans(array):
"""don't consider zeros when calculating mean
"""
value_sums = np.sum(array, axis=0)
presence_sums = np.sum(array!=0, axis=0)
distr = np.true_divide(
value_sums, presence_sums, where=presence_sums!=0)
return distr | cbdb69b23a17e70af339e456023833b549215155 | 41,218 |
import requests
def admin_remove_flag():
"""
In GET request
- Deletes the flag for the respective video ID.
"""
if request.method == 'GET':
if 'user' in session:
is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8... | 9c10c9feaaf25b1f492f43102d1f155859cd25b3 | 41,219 |
def rec_dfs_edges(graph):
""" recursive way for above
Note: a-b and b-a are different in this case..
"""
nodes = graph.nodes # type: dict
visited = set()
start = list(nodes.keys())[0]
edges = []
def _rec_dfs(graph, _start, _nodes):
for _node in nodes:
if _node in vi... | c4801cb45d09602cef65f20d5612d8c0e0fc8a49 | 41,220 |
from typing import Any
def _getitem(iterable_query: Query[Any], item: Any) -> Any:
"""calculate __getitem__ in terms of an iterable query object
that also has a slice() method.
"""
def _no_negative_indexes():
raise IndexError(
"negative indexes are not accepted by SQL "
... | 55ec17372300aa9cce80bba89919514ac68ca147 | 41,221 |
def density_matrix(
N, z, l, dims=(32, 32, 32), sigma=0.5, dist=euclidean, label_frac=1.0, eps_frac=0.25
):
""" Compute density maps and species matrices """
a = l[0]
b = l[1]
c = l[2]
dx = (a + (2 * a * eps_frac)) / dims[0]
dy = (b + (2 * b * eps_frac)) / dims[1]
dz = (c + (2 * c * eps_... | ed2f443a5c70383f3287cf61c961857c94ab82a2 | 41,222 |
import time
def train(model, train_loader, optimizer):
"""Train for one epoch."""
print('running train')
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
model.train()
end = time.time()
for i, (input, tar... | 9550f78ffb40f8b99422368989d2e007f6d57725 | 41,223 |
def awl_data(word: str)->int:
"""returns all available awl data"""
result = 0
for pos in range(awl.nrows):
if (word == awl.cell(pos,0).value):
result = awl.cell(pos,1).value #AWL rating
break
pos += 1
return result | 8862bd539c722768b1c64ee1863f55e00d3d5a29 | 41,224 |
def _js_compile_action(ctx, rule_kind, module_name, friend_paths=depset(), src_jars=[]):
"""Setup a kotlin js compile action.
Args:
ctx: The rule context.
Returns:
A JavaInfo struct for the output js file that this macro will build.
"""
# The main output js file
output_js = ctx.... | f2394953246d50fb7560bbcf949ff663ba3841ce | 41,225 |
from typing import Callable
from typing import Optional
from typing import Dict
def get_response(method: Callable,
url: str,
auth: AuthBase,
json: Optional[Dict]=frozenset()):
"""
Sends a request and checks the response for errors, and retries unless it's
... | 177fcc617bddfdd86c7a8a637f88ab0337622035 | 41,226 |
def _points_in_convex_polygon_3d_jit(points, polygon_surfaces, normal_vec, d, num_surfaces=None):
"""
check points is in 3d convex polygons.
:param points: input points
:param polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array.
all surfaces' normal vector mu... | 3556b0320fd67ab2d4285dd31858c63e4a5d2500 | 41,227 |
def psar_up(high, low, close, step=0.02, max_step=0.20):
"""Parabolic Stop and Reverse (Parabolic SAR)
Returns the PSAR series with non-N/A values for upward trends
https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar
Args:
high(pandas.Series): dataset 'High' column.
... | 4cc59f8e9b6bbacc4b0127bb3fc5522575df9e54 | 41,228 |
def acons(x,v,seq):
"""Creates a fresh cons, the cdr of which is alist and the car of which is
another fresh cons, the car of which is key and the cdr of which is
datum. """
return lisptype.lispCons(lisptype.lispCons(x,v),seq) | 99eb6d87211f44b08c145be4ffa224a518e520e8 | 41,229 |
def side_regress_loss(predict_side_deltas, tgt_deltas, tgt_cls_ids, anchor_indices_sampled):
"""侧边改善回归损失
Parameter:
predict_deltas: 预测的dx回归目标,[batch_num, anchors_num, 2]
tgt_deltas: 真实的回归目标,[batch_num, ctpn_train_anchor_num, (dy,dh,dx,padding_flag)]
tgt_cls_ids: 真实的类别目标,[batch_num, ctpn_... | b01c1df4062d101e3e440c177b973e474a10b5a8 | 41,230 |
def palindromic(d):
"""Gets a palindromic number made from a product of two d-digit numbers"""
# Get the upper limit of d digits, e.g 3 digits is 999
a = 10 ** d - 1
b = a
# Get the lower limit of d digits, e.g. 3 digits is 100
limit = 10 ** (d - 1)
for x in range(a, limit - 1, -1):
... | d4324d6c2de3dff46e14b754627bb551e03e957f | 41,231 |
def get_app_details() -> pd.DataFrame:
"""Loads a table with app information:
# load app details
# Note that...
# 1. only apps of interest are retained
# 2. the cluster for each app is added
# 3. `score` and `minInstalls` are converted to float and int, respetively
# 4. `score` is rounded t... | 2e27d2eb3caba4465f1d3ddc21b6fa69dd6474a3 | 41,232 |
def update_fw_nat_rule(fw_ip, elb_ip):
"""
Call our trivial playbook in order to upgrade firewall rules
:param fw_ip:
:param elb_ip:
:return bool, String success state and the corresponding message:
"""
if CFG.DEBUG:
return True, 'DUMMY Works!'
extra_vars = {
'host': fw... | 05348cc68622c57b9e2014a0f3bd455a159d6782 | 41,233 |
def image_reproject_to_healpix_to_file(array, target_image_hdu_header, coordsys='galactic', filepath=None):
"""reproject image array to healpix image and write file
:param array: image data
:param target_image_hdu_header: the HDU object of
:param coordsys: target coordi... | f69a8a8ffbaffc47a4e0e478963217ef414105ae | 41,234 |
import subprocess
def get_warnings(env=None):
"""
Returns list of warning flags by using diagtool.
"""
diagtool_bin = get_diagtool_bin()
if not diagtool_bin:
return []
try:
result = subprocess.check_output(
[diagtool_bin, 'tree'],
env=env,
... | 5e5be44eca109dab8af1c7eb5833e1ef896e2aa5 | 41,235 |
def list_objects(kind):
"""
Endpoint to fetch all objects of given type from MS graph API
:request_argument since - delta token returned from last request (if exist)
:return: JSON array with fetched groups
"""
if r.args.get('auth') and r.args.get('auth') == 'user':
init_dao_on_behalf_on(... | de03b0ecc6505ce955f102f97f350bce6f026133 | 41,236 |
import wget
import os
def dataset_donwload(url, path_target):
"""Donwload on disk the tar.gz file
Args:
url:
path_target:
Returns:
"""
log(f"Donwloading mnist dataset in {path_target}")
os.makedirs(path_target, exist_ok=True)
wget.download(url, path_target)
tar_name = ... | f5494f04371493e5eb79277e9b5d1e07ce464d5f | 41,237 |
import sys
def get_client():
"""Utility function to retrieve an authenticated client object"""
try:
client = ContainerPlatformClient.create_from_config_file(
config_file=HPECP_CONFIG_FILE, profile=PROFILE
)
client.create_session()
return client
except APIExcepti... | 110232845d9436d73654f6c6bef58acb78fb449b | 41,238 |
def run_menu(file_path, sim_names, sim_var, loop_names, loop_var):
"""
Prints out an interactable menu allowing user to assign values and run the simulation
Parameters:
(I) file_path: path to the hologram file
(I) sim_names: names of the simulation parameters
(I) ... | c3ab9811a490fa8043695159d3ecaa8af0631c94 | 41,239 |
def resolve_presets(annotations):
"""Resolve annotation presets into actual annotations."""
result = []
for annotation in annotations:
if annotation in presets:
result.extend(resolve_presets(presets[annotation]))
else:
result.append(annotation)
return result | f0604097cc7e22fd87e77a1d2d52db6dddc7a284 | 41,240 |
import sys
def trace(fout=None, format=None, byteorder=sys.byteorder, nanosecond=False): # pylint: disable=redefined-builtin
"""Trace TCP flows.
Arguments:
fout (str): output path
format (Optional[str]): output format
byteorder (str): output file byte order
nanosecond (bool):... | 71e1d7078c5f2056dae9e4231ab70e90c6a0c214 | 41,241 |
def elementwise_grad(fun, argnum=0):
"""Like `jacobian`, but produces a function which computes just the diagonal
of the Jacobian, and does the computation in one pass rather than in a loop.
Note: this is only valid if the Jacobian is diagonal. Only arrays are
currently supported. Can be used for broadc... | fff1d4e2b42c7916312c3f830ea7a042ea188fa8 | 41,242 |
from typing import Optional
from typing import Callable
def _max(comparer: Optional[Comparer] = None) -> Callable[[Observable], Observable]:
"""Returns the maximum value in an observable sequence according to
the specified comparer.
Examples:
>>> op = max()
>>> op = max(lambda x, y: x.va... | 7e4141221893e15eacf86a2fb25dd1fcc0fc65a0 | 41,243 |
def assign_column_names_types(df: pd, metadata: dict = None) -> pd:
"""
Change column names to the names defined in metadata->data_descriptor block
Args:
df (pandas): pandas dataframe
metadata (dict): metadata of the data
Returns:
pandas dataframe
"""
metadata_columns =... | f01d704af459dcfaa698911002675e373df6fdca | 41,244 |
import collections
def batch_for_variantcall(samples):
"""Prepare a set of samples for parallel variant calling.
CWL input target that groups samples into batches and variant callers
for parallel processing.
If doing joint calling, with `tools_on: [gvcf]`, split the sample into
individuals inste... | cac24812480a58f2afccfe8c43d0dcd5d2bb559e | 41,245 |
def transform_grams(references, sentence, n):
"""
transforms all references and sentence according n-gram
:param references: list of reference translations
:param sentence: list containing the model proposed sentence
:param n: size of the n-gram to use for evaluation
:return: new_ref, new_senten... | fe175cf5e589eb7e89cd46f7144b822186ead693 | 41,246 |
def geomag2geog(phi, theta) -> tuple:
"""convert from geomagnetic to geographic
Parameters
----------
phi: float or ndarray
geomagnetic longitude in radians
theta: float or ndarray
geomagnetic latitude in radians
Results
-------
glon: float or ndarray
geograph... | ade10e77f0cc8ac00b075394358425cac9164c89 | 41,247 |
import math
def poly_coeff(points):
"""
# 1. calc s=Q(t) for given 4 control points in 3rd order Bezier curve. Calc (s,t) pair for 1000 t values.
# 2. polynormial fit (t,s) pairs to get t = L(s) coeff
# 3. return poly fit coeff, s = Q(t=1)
"""
xpoints = [p[0] for p in points]
ypoints =... | 93beae635670feb3e998b81325baea25b3529b17 | 41,248 |
def prepare_attention_input(encoder_activations: fastmath_numpy.array,
decoder_activations: fastmath_numpy.array,
inputs: fastmath_numpy.array) -> tuple:
"""Prepare queries, keys, values and mask for attention.
Args:
encoder_activations fastnp... | c826111057fc545a6160ac48d6f867c7a238076e | 41,249 |
def TStrUtil_GetCleanWrdStr(*args):
"""
TStrUtil_GetCleanWrdStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanWrdStr(*args) | d623234156d261522bda7204e550f811f260f517 | 41,250 |
def unregisterExtModuleTopLevel(name, URI):
"""Unregisters an extension module top-level element"""
ret = libxsltmod.xsltUnregisterExtModuleTopLevel(name, URI)
return ret | 1a2267713eedcea5e1f7bf0d3eda551339005a8b | 41,251 |
from datetime import datetime
def _convert_to_utc(date_string):
""" (private method) Expected input: YYYY-MM-DD-HH:MM:SS.
Conversion of standard date format to UTC.
:param date_string: string of date in format: YYYY-MM-DD-HH:MM:SS
:type date_string: string
"""
big_time_tmp = date_string.split(... | 5d8306a57a201e62c688d88db80325c423148323 | 41,252 |
def FGP_Module(V, W, check=True):
"""
INPUT:
- ``V`` -- a free R-module
- ``W`` -- a free R-submodule of ``V``
- ``check`` -- bool (default: ``True``); if ``True``, more checks
on correctness are performed; in particular, we check the data
types of ``V`` and ``W``, and that ``W`` is a... | 95ac41de7534f7420cc0b7e60f3cc24bf92e6f1d | 41,253 |
import glob
import os
import subprocess
import atexit
def run(leave_running_atexit=False):
"""Ensure an API server is running, and ARVADOS_API_* env vars have
admin credentials for it.
If ARVADOS_TEST_API_HOST is set, a parent process has started a
test server for us to use: we just need to reset() i... | 4413c7150e169a1cd347bbd7ac5897a229e9a8f5 | 41,254 |
from sys import stderr
def fromMorse(message: str) -> str:
"""decodes morse code into a message"""
morseToChar = {v: k for k,v in charToMorse.items()}
morseToChar['/'] = ' '
res = ''
for c in message.split():
res += morseToChar.get(c,'_')
if res[-1] == '_':
print("... | ee7be3f3779043ef6691945f884b2aeff8ca5ac9 | 41,255 |
def ensure_column_exists(df, col_name, col_alt = False, raise_error = True):
"""Checks if a particular name is among the column names of a dataframe. Alternative names can be given, which when
found will be changed to the desired name. The DataFrame will be changed in place. If no matching name is found an
... | d6d234e3d6117a4af6b1cb30f983c2f0688cbab0 | 41,256 |
import time
def _wait_for_ifc_up(ifname, timespan=10):
""" Waits up to timespan seconds for the specified interface to be up.
Prints a message if the interface is not up in 2 seconds.
Args:
ifname (str) : Name of the interface
timespan (int) : length of time to wait in seconds
Returns:... | 0d74d113cd9b20a646409fffff8e8a1d7f07b446 | 41,257 |
def search_by_keyword(keyword="", uuid=""):
"""
Uses the `/search` endpoint.
takes a user uuid and a keyword.
If you specify no `uuid`, the search will not show private streams?
If the keyword is empty, it will return all the streams from the app.
e.g. uuid="e9c3d27e-406b-4f4a-9b87-6d3460c60ca6... | 948c17052e113923b9559bb647c4b717dc5c859f | 41,258 |
import sys
def getArguments():
"""
Get argumments from command-line
If pass only dataframe path, pop and gen will be default
"""
dfPath = sys.argv[1]
if(len(sys.argv) == 4):
pop = int(sys.argv[2])
gen = int(sys.argv[3])
else:
pop = 10
gen = 2
return dfPa... | cc1248746a82bed597c2cc5564b35a9a241f9360 | 41,259 |
import requests
def get_feedback(post_id):
""" Get the list of feedback on post. """
# Returns: [(uid, feedback)]
route = '{}/api/v2.0/feedbacks/post/' +\
'{}?key={}&filter=JJLFGJOFIOMFLGHJLHNIFMGJILKJKHOLMHIFGGOLFNIHF'
response = requests.get(route.format(ms_config["ms_host"], post_id, m... | 9dc2579d8e533550da1e4aee5ac2a1124fe80bb6 | 41,260 |
def projected_co(verts, matrix):
""" converts coordinates of points from OCS to WCS->ScreenCS
needs matrix: a projection matrix
needs verts: a list of vectors[x,y,z]
returns a list of [x,y,z]
"""
#print 'deb:projected_co() verts=', verts #---------
temp_verts = [Mathutils.Vector(v)*matrix for v in verts]
#prin... | b5aa8a142dcb7aa7957c0d21ddf1bf809be39145 | 41,261 |
def cost2_sabx(p,x,y):
"""
Sum of squared deviations of obs and square root of general 1/x function: sqrt(a + b/x)
Parameters
----------
p : iterable of floats
parameters (`len(p)=2`)
`p[0]` a
`p[1]` b
x : float or array_like of floats
independent variable
... | 3bfb390a281cf6990af80dc595fd94f787d98ebc | 41,262 |
def set_matrix_world(obj, matrix_world):
"""
Seems only set pose by obj.location and obj.rotation_euler
"""
if len(matrix_world) == 3:
matrix_world = homo_coord(matrix_world)
obj.location, quaternion, obj.scale = mathutils.Matrix(matrix_world).decompose()
obj.rotation_euler = quaternion... | aa65ac2ccfc24a697823af2ee69e92db7b8a3887 | 41,263 |
def build_img_fda_head(cfg, input_shape):
"""
Build a image-level feature distribution alignment head
defined by `cfg.MODEL.IMG_FDA_HEAD.NAME`.
"""
head_name = cfg.MODEL.IMG_FDA_HEAD.NAME
return IMG_FDA_HEAD_REGISTRY.get(head_name)(cfg, input_shape) | fec3f2ad233ea14ae20db0cbfd147580101c0a99 | 41,264 |
import requests
import os
import tarfile
def status(jobid, results_dir_path=None, extract=False, silent=False,
host="http://www.compbio.dundee.ac.uk/jpred4/cgi-bin/rest",
jpred4="http://www.compbio.dundee.ac.uk/jpred4"):
"""Check status of the submitted job.
:param str jobid: Job id.
... | 98931b8af31cea66c602fa5c6a48a58c2f5a42e0 | 41,265 |
def underline_filter(text):
"""Jinja2 filter adding =-underline to row of text
>>> underline_filter("headline")
"headline\\n========"
"""
return text + "\n" + "=" * len(text) | 1a24982d13cd240fba0a263c5772b0fe452c0e66 | 41,266 |
def select_training_set_labels_from_database(
label_columns,
filter_args=None,
filter_func=None,
limit=None,
**kwargs
):
"""
Construct a set of training labels from a query to the SDSS-V database.
:param label_columns:
A tuple of database column... | 08a581b67a2a9ef22aa4fcd0ed62c20938539897 | 41,267 |
def pa_to_mbar(x):
"""Pa to mbar.
Parameters
----------
x : float or array of floats
Air pressure (in Pa)
Returns
-------
output : float or array of floats
Air pressure (in mbar)
"""
return x / 100. | da15ed53130437d567c2cfb347022dd92dd4f896 | 41,268 |
import logging
import os
def myLogger(Folder, LogFileName):
"""
Since logging in a loop does always write to the first instaniated file,
we make a little wrapper around the logger function to write to a defined
log file.
Based on http://stackoverflow.com/a/2754216/323100
"""
logger = logg... | 69906188cc6ae334684a645afe157ffff5724735 | 41,269 |
def vicare_login(hass, entry_data):
"""Login via PyVicare API."""
vicare_api = PyViCare()
vicare_api.setCacheDuration(entry_data[CONF_SCAN_INTERVAL])
vicare_api.initWithCredentials(
entry_data[CONF_USERNAME],
entry_data[CONF_PASSWORD],
entry_data[CONF_CLIENT_ID],
hass.con... | 9c33aaa9e842b7a0ef00c9ee7a4778de7874df94 | 41,270 |
def markup(pre, string):
"""
By Adam O'Hern for Mechanical Color
Returns a formatting string for modo treeview objects.
Requires a prefix (usually "c" or "f" for colors and fonts respectively),
followed by a string.
Colors are done with "\03(c:color)", where "color" is a string representing a
... | 7ef910aa3b057e82c777b06f73faf554d9c4e269 | 41,271 |
def get_height(tracker: TrackerComponent):
"""Returns the height of the tracker, assuming relative to the floor."""
if tracker.is_hardware:
torso_state = tracker.get_state('torso')
return torso_state.pos[2]
return 0 | a3d0d663d2727359c0d7867a60d94499f1fa304f | 41,272 |
from typing import Callable
def compute_pairs(a: Array, op: Callable[[Array, Array], Array]) -> Array:
"""Computes pairs based on values of `a` and the given pairwise `op`.
Args:
a: The array used to form pairs. The last axis is used to form pairs.
op: The binary op to map a pair of values to a single va... | f4466d5f7c4440c180be49f50488104a1c24ab8c | 41,273 |
def polyfit(dates, levels, p):
"""given the water level time history (dates, levels) for a station computes a least-squares fit of a polynomial of
degree p to water level data. return a tuple of the polynomial object and any shift of the time (date) axis"""
days = matplotlib.dates.date2num(dates)
if d... | 2f1d7261893b8f9fd09400fad4d8994ec4c8540e | 41,274 |
import gc
def _release_chain_resources(chain: Chain):
"""
Remove all 'heavy' parts from the chain
:param chain: fitted chain
:return: chain without fitted models and data
"""
chain.unfit()
gc.collect()
return chain | 8faa04045bf4049a6bfede50ea12b5eae15dbba5 | 41,275 |
def ricker_wavelet(v, sigma):
""" Returns the ricker wavelet, or mexican hat wavelet, like this:
https://en.wikipedia.org/wiki/Mexican_hat_wavelet
"""
sigma_cast = tf.cast(sigma, tf.float32)
sigmasquared = tf.pow(sigma_cast, 2.0)
f = 3.0 * np.power(np.pi, 0.25)
p1 = 2.0 / (tf.sqrt(sigma_cas... | 7dde1764984ceac8b0fdf900436ff4e4f8e6317e | 41,276 |
def solve_efield_from_potential_periodic(phi_N, delta_x_N):
"""Given potential field, solves for e-field in 1D"""
# Perform calculation
E_N = -(np.roll(phi_N, -1) - np.roll(phi_N, 1))/(2*delta_x_N)
# Return E-field
return(E_N) | b698a01db14142f64fba0cc2cace9a9bce0d8713 | 41,277 |
def add_header16(header_type_name, field_dec):
"""
This method returns a header definition with its fields description
:param header_type_name: the type name of the header
:type header_type_name: str
:param field_dec: the field description of the header
:type field_dec: str
:returns: str -... | 03729ada74453a87209b946e1c1ccfa2da3133e4 | 41,278 |
def response2dict(response):
"""
This converts the response from urllib2's call into a dict
:param response:
:return:
"""
split_newlines = response.split('\r\n')
split_tabs = [s.split('\t') for s in split_newlines if s !='']
return split_tabs | d0bcfaca4ed00c74a1a10838881dac8e80f5d479 | 41,279 |
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_bandwidth_profile_get(uuid, node_uuid, node_rule_group_uuid): # noqa: E501
"""data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_bandwidth... | abb512f2ccb6270a6a9029b46b61d0833c495aa9 | 41,280 |
import copy
def _enforce_names_consistency(specs):
"""Enforces that either all specs have names or none do."""
def _has_name(spec):
return hasattr(spec, 'name') and spec.name is not None
def _clear_name(spec):
spec = copy.deepcopy(spec)
if hasattr(spec, 'name'):
spec._name = None # pylint:d... | e332aaac8b3d503fdece41810225b7c9a60930c6 | 41,281 |
def get_job_status(ibs, jobid):
"""
Web call that returns the status of a job
CommandLine:
# Run Everything together
python -m ibeis.web.job_engine --exec-get_job_status
# Start job queue in its own process
python -m ibeis.web.job_engine test_job_engine --bg
# Start... | 0dee2b90aa5758ea750a6e35104720233ce21cfd | 41,282 |
def int2D(igrad_x, igrad_y, idx, idy, const_at_edge=False):
"""
Sparse matrix integration to solve grad(a) = b for a
Requires integration constant (= reference value at position [1,1] = iconst)
Assumes uniform spacing
Based on:
https://math.stackexchange.com/questions/1340719/numerically-find-a... | c1de420f8f484a39668c8965676396fa10553e9a | 41,283 |
def _gr0_sorted_ ( graph , reverse = False ) :
"""Make sorted graph
>>> graph = ...
>>> s = graph.sorted()
"""
oitems = ( i for i in graph.iteritems() )
sitems = sorted ( oitems , key = lambda s :s[1] , reverse = reverse )
new_graph = ROOT.TGraph ( len( graph ) )
c... | 22c0462cf8b5f082d5c7b14491d2236dced74e15 | 41,284 |
def create_big_number(title, large_number, render_func, pacing='--'):
"""
title = description of big number
large_number = whatever number you want to highlight
render_func = plotly rendering function like iplot
"""
pacing_font_color = utilities.warning_color_font(pacing)
background_color = ... | e39ac1baebc14572f3eea410ec6453e0f0705507 | 41,285 |
def affine_forward(
backbone: tf.keras.Model,
moving_image: tf.Tensor,
fixed_image: tf.Tensor,
moving_label: (tf.Tensor, None),
moving_image_size: tuple,
fixed_image_size: tuple,
):
"""
Perform the network forward pass.
:param backbone: model architecture object, e.g. model.backbone... | 12c70b16e01396c5011eed548c7ac003e9877785 | 41,286 |
def im_click(im, color_mapper=None, plot_height=400, plot_width=None,
length_units='pixels', interpixel_distance=1.0,
x_range=None, y_range=None,
no_ticks=False, x_axis_label=None, y_axis_label=None,
title=None, flip=True):
"""
"""
def display_event(div,... | 687766e7beee2a905fbad0f1a53b8bcbc52ba715 | 41,287 |
def is_param_comment(token, next_token, comment_syntax):
"""
SQLエンジンのパラメータコメント判定
"""
return get_comment_type(token, comment_syntax) == EngineComment.param \
and (is_literal(next_token) or is_wildcard(next_token) or is_parenthesis(next_token)) | 8309391d81a0532e422cf32411c735d6f327d4e5 | 41,288 |
import os
import subprocess
import glob
import time
from datetime import datetime
import json
import sys
def train(**kwargs):
"""
Train model
Load the whole train data in memory for faster operations
args: **kwargs (dict) keyword arguments that specify the model hyperparameters
"""
# Roll o... | 3e2469c52f1799accc1cb5ebeeaed2282ff0ebae | 41,289 |
from typing import Sequence
def multi_ts_support(func):
"""
This decorator further adapts the metrics that took as input two univariate/multivariate `TimeSeries` instances,
adding support for equally-sized sequences of `TimeSeries` instances. The decorator computes the pairwise metric for
`TimeSeries`... | aab3d87db99c40c65aa8355c085ab9764d117797 | 41,290 |
def course_search_index_handler(request, course_key_string):
"""
The restful handler for course indexing.
GET
html: return status of indexing task
json: return status of indexing task
"""
# Only global staff (PMs) are able to index courses
if not GlobalStaff().has_user(request.us... | 139d73b28a935c57cd940ae2922a65cdfc3e8b2b | 41,291 |
async def data(ctx: lightbulb.Context) -> None:
"""Load or read data from the node.
If just `data` is ran, it will show the current data, but if `data <key> <value>` is ran, it
will insert that data to the node and display it."""
node = await plugin.bot.d.lavalink.get_guild_node(ctx.guild_id)
if n... | 2a9deca654411038415ced2e53f4550564fd5a44 | 41,292 |
import pickle
def cheat_interest_points(eval_file, scale_factor):
"""
This function is provided for development and debugging but cannot be used in
the final handin. It 'cheats' by generating interest points from known
correspondences. It will only work for the 3 image pairs with known
corresponde... | 77bac3cd4d2946ccf8fd975f8cf7ad175d4e1f8f | 41,293 |
from bs4 import BeautifulSoup
def get_person_speech_pair(file_name):
"""
XML parser to get the person_ids from given XML file
Args:
file_name(str): file name
Returns:
person_id_speech_pair(dict): Dict[person_id(int) -> speech(str)]
"""
person_id_speech_dict = dict()
with op... | 0751ed8d46c39027c0503dcd94d8c324c700c1a5 | 41,294 |
def decode_jpeg(image_string: tf.Tensor, channels: int = 0) -> tf.Tensor:
"""Decodes JPEG raw bytes string into a RGB uint8 Tensor.
Args:
image_string: A `tf.Tensor` of type strings with the raw JPEG bytes where
the first dimension is timesteps.
channels: Number of channels of the JPEG image. Allowed... | ef541017e75a083935c6de177374edc50a0e781c | 41,295 |
import pandas
def get_df(a: int) -> pandas.DataFrame:
"""
Generate a sample dataframe
"""
return pandas.DataFrame(data={"col1": [a, 2], "col2": [a, 4]}) | 56008e78d68110e8f12463b37368d0be7f3e4c9a | 41,296 |
def log_softmax(x):
"""Perform log softmax activation on the data
Parameters
----------
data : tvm.te.Tensor
2-D input data
Returns
-------
output : tvm.te.Tensor
2-D output with same shape
"""
assert len(x.shape) == 2, "only support 2-dim log softmax"
m, n = x... | 49dbd1aaf0c4d89324db8c37ac014a9b1a503c3a | 41,297 |
def hours(datetime: dt.datetime) -> int:
"""
Returns the hours component for the given datetime value, in local time.
"""
return datetime.hour | 5846c5af86c2e121c3c28fe9507a6fd0cfd83a0b | 41,298 |
import ast
def Call_setattr(t, x):
"""Translate ``setattr(foo, bar, value)`` to ``foo[bar] = value``."""
if (isinstance(x.func, ast.Name) and x.func.id == 'setattr') and \
len(x.args) == 3:
return JSExpressionStatement(
JSAssignmentExpression(
JSSubscript(x.args[0], ... | d58a26d591611d68245d16e9abc0e42337f8a263 | 41,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.