content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def _load_model(path):
"""
Load Model Implementation.
:param path: Local filesystem path to
the MLflow Model with the ``xgboost`` flavor (MLflow < 1.22.0) or
the top-level MLflow Model directory (MLflow >= 1.22.0).
"""
model_dir = os.path.dirname(... | 3fd835653f4c86b2bdd5bc5458ac428a57f55479 | 3,611,200 |
def judge(sample, w, c_1, c_2):
"""
true 属于1
false 属于2
:param sample:
:param w:
:param center_1:
:param center_2:
:return:
"""
u1 = np.mean(c_1, axis=0)
u2 = np.mean(c_2, axis=0)
center_1 = np.dot(w.T, u1)
center_2 = np.dot(w.T, u2)
pos = np.dot(w.T, sample)
r... | 49d5d65055874a2600fcc449d696de6021265a1b | 3,611,201 |
def get(myobject, query, default=None):
"""This function allows you to query a dict object to get the value
recursively through dicts and array's, returning the value found at the
end of the query chain.
Arguments:
myobject {object} -- dictionary or array of objects
query {str} -- query... | bb27d6420a392d939cbc8dd46d23f050094603b6 | 3,611,202 |
def QueueMark(*args):
"""QueueMark(qtype_t type, ea_t ea)"""
return _idaapi.QueueMark(*args) | 3dd12653a6a0a65d7c0b791e37c8c60e40b3ea29 | 3,611,203 |
import os
import re
import shutil
def generate_workflow(**inputs):
"""
generates computation graph for daic2hcp
:param t1w_file: t1w mgz file in some space
:param t2w_file: t2w mgz file aligned to t1w
:param mask_file: mask or brain mgz file aligned to t1w
:param fmri_files: list of fmri mgz f... | f79b8dc9f1890183607345b1c3ff9462bc77493e | 3,611,204 |
def maya_main_window():
"""
Get Maya main window
:return: int (maya main ptr)
"""
maya_main_ptr = omUi.MQtUtil.mainWindow()
return wrapInstance(int(maya_main_ptr), QtWidgets.QWidget) | 96ccc1f82b5ee48f048cba66c95fcc42abe7fd14 | 3,611,205 |
import click
def _cb_key_val(ctx, param, value):
"""
Click callback to validate and convert `--opt key=val --opt key2=val2` to
`{'key': 'val', 'key2': 'val2'}`.
Returns
-------
dict
"""
output = {}
for pair in value:
if '=' not in pair:
raise click.BadParamet... | b74dea54c8e57e8c6ebbd743401f45ba57bff03b | 3,611,206 |
def short_map(file, size=96, valid=True):
"""Returns a dataframe from a 'short' plate map csv file that defines each and every well from a well plate of defined size
Contains the columns 'Well ID', 'Compound', 'Protein', 'Concentration', 'Concentration Units', 'Contents', 'Type' and 'Valid'. Each defined w... | 72f614f616dbfc7759624908db37addbcd70fb69 | 3,611,207 |
import numpy
def epsfunc(x_, y_):
"""Return a matrix describing a 2d material.
:param x_: x values
:param y_: y values
:return: 2d-matrix
"""
# xx, yy = numpy.meshgrid(x_, y_)
working = geom[0][5] * numpy.ones((x_.size, y_.size))
for i in range(1, len(geom)):
ixmin = numpy.sea... | 549a27b8b1186b3bb42aaf7d9d893ffc9696c75c | 3,611,208 |
def create_referral(request):
"""Create a referral."""
email = request.POST.get("email", "missing email")
data = {"email": email, "referring_user": request.user}
form = ReferralForm(data=data)
if form.is_valid():
form.save()
messages.success(request, "We will message your friend shor... | df66efca2f2603e9987535efbcc34ae5041cca7b | 3,611,209 |
def fetch_reg(reg_dict, reg, index, data, use_init):
"""
Fetches register from state global store. Initialises it if needed.
"""
if reg in reg_dict:
d = reg_dict[reg]
if is_reg_indexed(data):
if index in d.keys():
return d[index]
#else:
... | 35ca7f40686fc8f101fee4c9ba655b23733f1fff | 3,611,210 |
def first_day_of_last_month(any_date):
"""Returns the first day of last month for any date
>>> first_day_of_last_month(datetime.date(2016, 1, 21))
datetime.date(2015, 12, 1)
"""
return first_day_of_the_month(last_day_of_last_month(any_date)) | af438cac1e67889d885952f3e07f8b8022849134 | 3,611,211 |
import hashlib
def digest_file(file_path: PathLike, hash_algo: str) -> str:
"""
Reads and digests a file according to specified hashing-algorith.
:param file_path: path to a file on disk
:param hash_algo: any algo contained in :mod:`hashlib`
:return: <hash_algo>=<hex_digest>
From http://stac... | 121fcbe81c8c690a011adff9a0502879b5a4855e | 3,611,212 |
from typing import List
def _parse_nodes(text: str) -> List[Node]:
"""
Quick and dirty implementation of a .rst parser to extract directives
"""
nodes = []
c_indent = ""
in_section = []
directive = ""
last_directive = ""
args = ""
last_args = ""
text_split = text.split("\n... | 2f0167ccf6aff4009e65d63a3a53314d354052a6 | 3,611,213 |
from typing import List
from typing import Union
from typing import Tuple
def executeColorToken(token: lexerTokens.toColorToken, inputDirection: direction, dataStack: List[int]) -> Union[Tuple[direction, List[int]], BaseException]:
"""
Executes the to color operations
:param token: input token
:param ... | fa6687b81ab18862f7dce34f1aa5fddca81d77e0 | 3,611,214 |
import re
def rfc822_parse(message):
"""Parse a message in RFC822 format.
@param message: The message in RFC822 format. Either CRLF or LF is an accepted line separator.
@return Returns a tuple of (headers, body) where headers is a list of (name, value) pairs.
The body is a CRLF-separated string.
... | a9fba803ca428c96fd98af20c3015479dae77645 | 3,611,215 |
def get_all_users(**options):
"""Returns all users.
Args:
**options: Options passed to query.
Returns:
A list of user dictionaries.
"""
cursor = _db.users.find(
{},
sort=[('create_time', pymongo.ASCENDING)],
**options)
return list(cursor) | 385dfb58c231b84adbe00d2fb0db7a50a3e987b1 | 3,611,216 |
import tempfile
import os
def create_temp_dirs(input_classes: {}, num_classes) -> (str, str, str):
"""
Creates temporary directories and symlinks them with the training path and the validation path.
:param input_classes: The input classes.
:param num_classes: The number of classes to train.
:rtype... | 201b758885bad9d688e45c3b3d01f738c3eb1360 | 3,611,217 |
def handle_exception(e):
"""
To keep all responses consistently JSON.
Return JSON instead of HTML for HTTP errors.
"""
return (
jsonify(
{
"code": e.code,
"name": e.name,
"description": e.description,
}
),
... | 5bd5cd8877878ec5c591ce8a553d1a9f652ee1d2 | 3,611,218 |
import requests
def _create_download_failed_message(exception, url):
""" Creates message describing why download has failed
:param exception: Exception raised during download
:type exception: Exception
:param url: An URL from where download was attempted
:type url: str
:return: Error message
... | 2ff2493cc1167246083ef703bdff8c76cb36a733 | 3,611,219 |
import json
def read_mongo(db, collection, query={}, projection='', limit=1000, host='localhost', port=27017, username=None, password=None, no_id=False):
""" Read from Mongo and Store into DataFrame """
# Connect to MongoDB
db = _connect_mongo(host=host, port=port, username=username, password=password, d... | 9b49f40de1eb49eece981d01d2fb5d41788ff029 | 3,611,220 |
def buffer_with_count(this, count):
"""
"""
if count < 0:
raise FatalError
q = [ [] ]
num_seen = [0]
def on_next(self, x):
num_seen[0] += 1
q[0].append(x)
if num_seen[0] == count:
self._dispatch_next(q[0])
num_seen[0] = 0
q[0]... | 2d2760b9a9223db04fe33da6442c380f6d6a23b3 | 3,611,221 |
def _apply_hadamard_to_all_qubits(s, optype, qubit_labels):
"""
Applies Hadamard gates to all qubits
Parameters
----------
s : np.array
A (2n,2n) matrix over [0,1].
optype : 'row' or 'column'
If 'row', we use row-operation Hadamard gates.
If 'column', we use column-oper... | 5a62d48dc115d903fd6580c1052d44771649ddae | 3,611,222 |
def create_empty_dataset(shape, h5_group, name='nDIM_Data'):
"""
returns a h5py.Dataset filled with zeros according to required shape list.
Parameters
----------
shape: list
List of integers denoting the shape of the main dataset
h5_group: h5py.Group
HDF5 group into which the da... | ccd773b91b0144be8be1f0040d4a4e206b489b50 | 3,611,223 |
def smooth_l1(weight=1.0, sigma=3.0):
""" Create a smooth L1 loss functor.
Args
sigma: This argument defines the point where the loss changes from L2 to L1.
Returns
A functor for computing the smooth L1 loss given target data and predicted data.
"""
sigma_squared = sigma ** 2
... | af5c09eba3f7139cead43b1e1f23e2ee253dd82c | 3,611,224 |
import re
def encode_laTex(text):
"""
:param text:
:return:
"""
if (len(text) > 1):
# if any greek letter macro map it here
# convert something like \\Sigma\\ to \textbackslash{}Sigma\textbackslash{}
# however needs to go through utf8tolatex so add placeholder to be replac... | 093be21fe9cbdd62cfc7396a78632492f9212d0f | 3,611,225 |
def LF_DG_BICLUSTER_PROGRESSION(c):
"""
This label function uses the bicluster data located in the
A global network of biomedical relationships
"""
sen_pos = c.get_parent().position
pubmed_id = c.get_parent().document.name
query = bicluster_dep_df.query("pubmed_id==@pubmed_id&sentence_num==... | 1b0847001d888b5954385759ab513e5cedb6341f | 3,611,226 |
def gap2d():
"""Helper for building a global average pooling layer."""
return nn.AdaptiveAvgPool2d((1, 1)) | f8bde4a603e36361ffb4541caeaadf7b95428bc7 | 3,611,227 |
def find_(a,n=None,d=None,nargout=1):
"""
function which returns a column vector or a tuple of column vectors (depending on the value of
nargout) containing indices where a[indices] are true in the vector/matrix 'a'
Argument 'n' tells us how many of those indices we want
"""
if d:
r... | 7c9a844d454a1a1392b8e170b6b7ec9032c3cabf | 3,611,228 |
def __covid_brief() -> str:
"""
Generates a brief message about the latest covid19 data.
"""
try:
(
is_latest_covid_data_available,
_,
new_cases,
cumulative_cases,
new_deaths,
cumulative_deaths,
) = fetch_covid_data... | 4500dced365697617d13ec24afbd835845a5f9b2 | 3,611,229 |
def correct_for_absorption(flux, ebv, band):
"""Corrects for MW dust absorption.
Keyword arguments:
flux -- Python list containing fluxes.
ebv -- float, MW E(B-V).
band -- photometric band in which correction has to be applied.
Returns:
Python list containing values of flux corrected by ab... | b6833eaa4211a319dfffe3fde26122437ce48ed0 | 3,611,230 |
def flag_bad_words(transcriptions):
"""
:params transcriptions:transcriptions is the dictionary
containing the text file that has been converted into an array
:return: updated transcriptions dictionary
This function checks to see if any words have been added to the flagged_list. """
if any(flag... | bd167612055ec872dcc67810ae3823c25b6f686b | 3,611,231 |
from typing import Dict
def update(id_: int, type_: str, object_: Dict[str,str], session: scoped_session, api_name:str) -> int:
"""Update an object properties based on the given object [PUT]."""
# Keep the object as fail safe
instance = get(id_=id_, type_=type_, session=session, api_name=api_name)
ins... | 7ace29574136b20932b0ed9196a7e68ef9c6323a | 3,611,232 |
def method_resolve_vessel(cookie, in_stimuli):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("MethodResolveVessel")
method.cookie = cookie
method.in_stimuli = in_stimuli
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
return xml_request | a5b64728fdac06e7b4653cb4d8f466d32f73be51 | 3,611,233 |
def get_month():
"""Fetch the value of month entered by user"""
# Creating a single item list for appending to global list of months
all_filter = ['all']
while True:
# Get user input for month (all, january, february, ... , june)
month = str(input('\nSelect the month - january, febr... | e08913007642803c5fd2b6b4f4ca3332bffdedd2 | 3,611,234 |
def ZA( particle ) :
"""
Uses ZAInfo to compute the particle ZA. See ZAInfo for more detail
"""
return( ZAInfo( particle )[2] ) | a96be9a671fee5b9d50b1d8477c66fbbbc230f0e | 3,611,235 |
def get_category(category_id: TicketCategoryID) -> TicketCategory:
"""Return the category with that ID, or raise an exception not found."""
category = find_category(category_id)
if category is None:
raise ValueError(f'Unknown ticket category ID "{category_id}"')
return category | f5c1462cd353c8c5112e59509096f2f7617642cc | 3,611,236 |
import os
def yarn_check(file_list):
"""
Checks if package.json was modified WITHOUT a corresponding change in the Yarn
lockfile. This can happen if a user manually edited package.json without running Yarn.
This is a user prompt right now because there ARE cases where you can touch package.json
w... | f9b1ef003733a41cde07050b45d8513428328e7f | 3,611,237 |
from typing import Optional
from typing import Dict
def abbreviated_interface_name(
interface: str,
addl_name_map: Optional[Dict[str, str]] = None,
addl_reverse_map: Optional[Dict[str, str]] = None,
) -> str:
"""Function to return an abbreviated representation of the interface name.
:param interf... | f711d4dfef1e4e435e172dd535366c61ede99735 | 3,611,238 |
def edits1(word):
"""
Produces a list of all possible edits of a given word that can be produced
by applying a single character modification.
From Peter Norvig, see http://norvig.com/spell-correct.html.
"""
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for ... | 9ccab14554fe1d945d5da848376bd18bcbf25ed2 | 3,611,239 |
def highway(input_, size, num_layers=1,scope='Highway'):
"""Highway Network (cf. http://arxiv.org/abs/1505.00387).
t = sigmoid(Wy + b)
z = t * g(Wy + b) + (1 - t) * y
where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.
"""
# return linear(input_, size)
with tf.variabl... | 597c3d3f569882992f027fa69ebf76c4ad19eb07 | 3,611,240 |
def lst_mp_equality(lst1, lst2):
"""Wrapper function to check if two lists are identical when the
lists contain MeasurementProcess objects."""
assert len(lst1) == len(lst2)
lsts_same = True
for index in range(len(lst1)):
if not isinstance(lst1[index], type(lst2[index])): # if they are diff... | 747262632f6981f47a32bc2f0ad6fcd99d763cc7 | 3,611,241 |
def asv_uncertain(unc, apf, fm):
"""Load Maribot Vane performance data."""
perf = np.genfromtxt(pyroute_path+"analysis/asv_transat/maribot_vane.csv",
delimiter=",")
tws = np.array([0, 4, 8, 12, 16, 20])
twa = np.array([0, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160])
return ... | a197ee2808e55767145ea6f396165e305d2bb71f | 3,611,242 |
def flow_resize(flow, out_size, is_scale=True, method=0):
"""
method: 0 mean bilinear, 1 means nearest, 2 bicubic and 3 area
See: https://www.tensorflow.org/api_docs/python/tf/image/ResizeMethod
"""
flow_size = tf.to_float(tf.shape(flow)[-3:-1])
flow = tf.image.resize_images(flow, out_si... | c720aacfe926a8897e0a87c14fae71581017791c | 3,611,243 |
def center_crop(img, dim):
"""Returns center cropped image
Args:Image Scaling
img: image to be center cropped
dim: dimensions (width, height) to be cropped from center
"""
width, height = img.shape[1], img.shape[0]
# process crop width and height for max available dimension
crop_width =... | b5e54550d9774f999a3b94dabde95fd12b2aaa8f | 3,611,244 |
import math
def ae_latent_softmax(latents_pred, latents_discrete, hparams):
"""Latent prediction and loss."""
vocab_size = hparams.v_size
if hparams.bottleneck_kind == "semhash":
vocab_size = 2**hparams.z_size
if hparams.num_decode_blocks < 2:
latents_logits = tf.layers.dense(latents_pred, vocab_size,... | b43512063ed58d214e3c4637288d079a64e26235 | 3,611,245 |
def ellipse_axis_length( a ):
"""
Parameters
----------
a : fitted_ellipse_obj
Returns
----------
ellipse radii
"""
b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g)
down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
... | 550a873fe4a7b9f036c0c877299d798d4a136327 | 3,611,246 |
import argparse
def percentage_float(x):
"""
Chech whether the float is a percentage.
:param x: The value to check
:return: The float reprentation of the argument.
:raise: argparse.ArgumentTypeError if the argument is not in [0, 100].
"""
x = float(x)
if x < 0 or x > 100:
rais... | 6a15c73d9469c066d94e22bf7af119ba68a20156 | 3,611,247 |
async def convSingleLottieTransparentFrames(
lottieFile: LottieFile,
frameSkip: int = 0,
scale: float = 1,
) -> dict[str, LottieFrames]:
"""Convert a single lottie file to a dictionary of LottieFile.path to
LottieFrames (LottieFile.data and a list of PIL.Image.Image frames) with
transparency.
Args:
lottieFile... | 6b9cbd68d529f609d6681240b071367baf6b8db9 | 3,611,248 |
def _unit_variance_scale(f: np.ndarray) -> np.ndarray:
"""Rescales a feature to have a unit variance."""
f_nan_max = np.nanmax(f)
f_nan_min = np.nanmin(f)
if np.isnan(f_nan_max) or np.isnan(f_nan_min):
raise ValueError('Continuous feature all missing.')
if f_nan_max == f_nan_min:
ret = np.full_like(f,... | 02a3ea26936e385910eff0d39926cc6370e17966 | 3,611,249 |
def get_champions_name(_id):
"""
this functions takes an _id and returns the associate champions name
:param _id: any integer from 1 to 555. if there is a champion, it will return the name.
:return: champions name
"""
all_champion_id = {
1: "Annie",
2: "Olaf",
3: "Galio",... | 4e062bca3636a261df1d17d77417fc19f5d89305 | 3,611,250 |
def get_resources_grouped_by_domain(tech):
"""
Given a tech slug, this function will return
all the resources for that tech grouped by domains
i/p: 'python'
"""
return_data = {}
all_resources = Resources.objects.filter(technology__slug=tech)
for resource in all_resources:
domains... | eb57410ccf99d414811863577cdc7427893aa702 | 3,611,251 |
def babel_fish_dispenser(matrix1, matrix2=None, step_size=None, axis=2):
"""Adds an input corresponding to the running average over a set number of time steps. This helps the neural network to ignore high frequency noise by passing in a uniform 1-D filter and stacking the arrays.
Parameters
----------
... | 8afe5425a9a0bde13dd874359e20ffd2faeaa21b | 3,611,252 |
def isAVersionableResource(obj):
""" True if an object is versionable.
To qualify, the object must be persistent (have its own db record), and
must not have an true attribute named '__non_versionable__'."""
if getattr(obj, '__non_versionable__', 0):
return 0
return hasattr(obj, '_p_oid') | 42dcd02b1f4e1c9f9ff555ec597d8011cfe64893 | 3,611,253 |
def fix_variable(problem, pivot, value):
"""
Return a new problem that is a copy of the one provided with
the pivot variable set to value
This function is used for branching, and prints the selection
made.
"""
new_problem = problem.copy()
new_problem['variables'] = problem['variables'].... | 40e7d358eff405c481aedd9d2b1505664fcd4d6e | 3,611,254 |
def test_progress(arg1, arg2, kwd1, kwd2, progress):
"""Simple test target for submit_progress."""
return arg1, arg2, kwd1, kwd2 | 1d761c572b15c41e1a04aafbb53ca825792df8fe | 3,611,255 |
import asyncio
async def stick_maker_static_phlogo(
text: str, image_file: Image.Image, font_path: str, image_wight: int, image_height: int) -> Image.Image:
"""
ph表情包模板
"""
def __handle() -> Image.Image:
# 处理文本主体
test_sentences = text.strip().split(maxsplit=1)
white_tex... | eff35b2eccf15f6a381c99fcaf1437bf550d017f | 3,611,256 |
def transform_dict_to_kv_list(options):
"""
{"key": None, "key2": None} becomes 'key, key2'
{"key": "\"\"", "key2": "3.5in", tocbibind: None} becomes 'key="", key2=3.5in, tocbibind'
"""
assert isinstance(options, dict)
return ", ".join(["{}={}".format(k,v) if v is not None else k for k,v in opti... | 571b3d5724b7aa0ff53698349a3255b14517bd78 | 3,611,257 |
import numpy
def Mat(m,n):
"""
Build an m x n matrix (using numpy)
For example:
>>> Mat(2,3)
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
"""
return numpy.zeros((m,n),'d') | e36164cd29ed0070a01b87ca32e6f130271dbb95 | 3,611,258 |
def create_recycled_content_datasets(data):
"""Create new datasets that consume the recyclable content from recycling or waste treatment activities in the cutoff system model.
In the cutoff system model, no credit is given for the production of recyclable materials. Rather, consumers get these materials with n... | 535aff1c5b484dd7a92daafae5ceb38f04a3c25a | 3,611,259 |
import os
import shutil
def retrieve_observation(obsid, suffix=['FLC'], archive=False,clobber=False):
"""Simple interface for retrieving an observation from the MAST archive
If the input obsid is for an association, it will request all members with
the specified suffixes.
Parameters
-----------
... | ad2b3d3025c4edafa7d01d5fde2d55b7ceeac4ec | 3,611,260 |
def get_or_abort(model, object_id, code=404):
"""Get an object with his given id
or an abort error (404 is the default)"""
result = model.query.get(object_id)
return result or abort(code) | 3c5fdea2ca367472879ea51033bc861084083c1d | 3,611,261 |
def _get_shape_name(array_name, shape_name = None):
"""Either get shape name or create from array_name."""
return shape_name if shape_name else f'{array_name}/shape' | fe0065faa3e917bb6faef5189ec7ea85ed152c99 | 3,611,262 |
def process_author(author):
"""Clean the author tag"""
# Remove tabs and ensure a maximum length.
new_author = strip_html( author[:MAX_AUTHOR_LEN] )
return new_author.replace('\t', ' ') | 4b052b527026f4d70541166539ac62deee9b4ee6 | 3,611,263 |
import json
def corpora_get_props_from_anndata(adata):
"""
Get Corpora dataset properties from an AnnData
"""
versions = corpora_get_versions_from_anndata(adata)
if versions is None:
return None
[corpora_schema_version, corpora_encoding_version] = versions
version_is_supported = co... | eb6d454fc3face05e14e868a515610faf82a1b93 | 3,611,264 |
def svn_repos_fs_revision_proplist(*args):
"""svn_repos_fs_revision_proplist(svn_repos_t * repos, svn_revnum_t rev, svn_repos_authz_func_t authz_read_func, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_fs_revision_proplist(*args) | aa515fef5570d7bd21a816370bc2640fac4a8d31 | 3,611,265 |
import scipy
import itertools
def _PD_hamming(alignA, alignB, subst, bySite, withinA, ignoreGaps=True):
"""Computation for pairwise diversity using a vector optimized hamming distance.
Optionally ignoreGaps treats gap comparisons as Nan"""
L = len(alignA.iloc[0])
gapCode = AA2CODE['-']
"""Convert... | 48cefcc6ccddbe27cbb585e5f307b32aef7d8ecc | 3,611,266 |
def convert_to_number(roman_numerals: str) -> int:
"""
Convert Roman numerals to a number
Roman numerals are written from left to right,
and from highest to lowest (in terms of individual numeral value)
:param roman_numerals: Roman numeral to convert
:type roman_numerals: str
:return: numb... | 9936816565eddbf0707d9b66941e16771e1e343d | 3,611,267 |
def ensure_loaded_agent(app: Sanic, require_core_is_ready=False):
"""Wraps a request handler ensuring there is a loaded and usable agent.
Require the agent to have a loaded Core model if `require_core_is_ready` is
`True`.
"""
def decorator(f):
@wraps(f)
def decorated(*args, **kwarg... | 5c5b163211eca2c5cc0d86eb2f72cb52ed30e336 | 3,611,268 |
from typing import Type
def _insert_temporary_wires(
context: DefinitionContext,
value: ValueLike,
inline_wire_prefix: str):
"""
Insert a temporary Wire instance so the signal isn't inlined out.
We have to do this for DefnRef because the coreir inline.cpp logic
sometimes inser... | 29461e87930cbed6afa0d55cb68229b4aea5da84 | 3,611,269 |
def getMinUnvisited(unvisited, dist):
"""
return the minimum distance vertex from
the set of vertices not yet processed.
Parameters:
unvisited (set): the set containing all the vertex not yet processed
dist (dict): a dictionary with vertex as ... | 5ccd7ab9e7e7b70c9aedecb56049332ae1f7b530 | 3,611,270 |
def update_signature_source(service, name, **_):
"""
Update a signature source by name for a given service
Variables:
service => Service to which we want to update the source
name => Name of the source you want update
Arguments:
None
Data Block:
{
... | 33c9b048d5773ebce9af576f8b35ab9556ebacac | 3,611,271 |
import os
def read_sentiment_data() -> pd.DataFrame:
"""Convert the sentiment file into a DataFrame object
Returns a DataFrame of predicted_sentiment_all_processed.csv'
Returns None if paths are not valid
"""
try:
return pd.read_csv(os.path.join(PARENT_PATH,
os.... | d523b3c8593528c35eefd0fdcc21e6e5684828fe | 3,611,272 |
import os
def load_MSTfit_eq(shot, frame):
"""
Load a reconstruction from my home directory.
"""
fname = os.path.join(mstfit_dir, 's{0:10d}/MST_s{0:10d}_f{1:02d}.csv'.format(shot, frame))
df = pd.read_csv(fname)
eq = {}
eq['x'] = df['R (m)'].to_numpy() - R0
eq['y'] = df['Z (m)'].to_nu... | 4f70b4a1d873443b08b2fe48fab7fdbe6e9dc135 | 3,611,273 |
def check_geo_granularity_DS_Cons1():
"""
checks if DS_Cons1_Map has geographic granularity finer than balancing area
"""
DS_Cons1_Map = loaders.get_parameter("DS_Cons1_Map")
cond = True
g_values = tuple(constant.GEO_COLUMNS.keys())
for row in DS_Cons1_Map:
DS, GGRAN, TGRAN = row[:3... | 8c4001e3764a1fdcbf9295990be070e26fa4a82b | 3,611,274 |
def get_delay_map(connectivity, default_delay=0, block_delay_func=lambda b:b.delay):
"""
Build map between the external output ports of `connectivity` and its input ports
mapping the delay along each path between those ports. Checks that all paths have
matching delays.
connectivity: `Connectivity` object describ... | b762783581be67f85fff3aaef88cd1fdab17004d | 3,611,275 |
def nonlin_matter_power(cosmo, k, a):
"""The nonlinear matter power spectrum; Mpc^3.
Args:
cosmo (:obj:`Cosmology`): Cosmological parameters.
k (float or array_like): Wavenumber; Mpc^-1.
a (float): Scale factor.
Returns:
float or array_like: Nonlinear matter power spectrum;... | 1bd0d72e48659c5da7511f3cb5f93e40a19eb011 | 3,611,276 |
def generate_proposed_regions(img,limit_of_proposals= 2000):
"""
Generate proposed regions using selective search and limits number of rectangles returned
"""
selective_search = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()
selective_search.setBaseImage(img)
selective_search.... | b2cfc0c630fb0e076e8c29f105fe3c86339e7b84 | 3,611,277 |
import sys
def xiHelper(x, q, E):
"""Helper function to the rotationally-invariant, optimal shrinkage
estimator of the true correlation matrix (implemented via function
optimalShrinkage of the present module).
Parameters
----------
x: type derived from numbers.Real
... | 6491a1d643905295fc9e7e8f7e7420f64dc24033 | 3,611,278 |
def get_ckpt_old_to_new(target_dir):
"""Returns ckpt names from newest to oldest. Returns [] if nothing exists"""
prev_ckpt_state = tf.train.get_checkpoint_state(target_dir)
all_ckpts = []
if prev_ckpt_state:
all_ckpts = sorted(prev_ckpt_state.all_model_checkpoint_paths, key=natural_keys, revers... | ecf94c5cb64e54c2d4dd575666194affdbd33cb2 | 3,611,279 |
def bootstrap_curation(new_df, reference):
"""
Take in an uncurated list of prescriptions and bootstrap
"""
candidate_generic = []
candidate_category = []
for values in new_df["possible_generic"]:
best_match = find_best_match(values, curated)
candidate_generic.append(best_match[0... | 0d34a2d2f5fbf9c4418eb896b14055b4d34ea1dd | 3,611,280 |
def ListBuildChannels():
"""Lists all build channels.
Returns:
a list of ndb_models.BuildChannelConfig objects.
"""
return [
BuildChannel(config)
for config in ndb_models.BuildChannelConfig.query().fetch()
] | 33b7a04f1c7f971c356bb1d6aceff0c1b3c59556 | 3,611,281 |
import os
import pytz
import sys
import subprocess
import re
def _get_localzone(_root='/'):
"""Tries to find the local timezone configuration.
This method prefers finding the timezone name and passing that to pytz,
over passing in the localtime file, as in the later case the zoneinfo
name is unknown.
... | 59a21dc76963294994ce33fe72076154803ff028 | 3,611,282 |
from typing import Dict
from typing import Counter
import tqdm
def get_char_counts(corpus_reader: CorpusReader) -> Dict[str, int]:
"""
Get a frequency distribution of characters in a corpus.
:param corpus_reader:
:return:
"""
char_counter = Counter() # type: Dict[str, int]
files = corpus_... | 7b70ed2dbaa584310b96c3f323b98367ddcf4f54 | 3,611,283 |
import string
def str2size(str):
"""Accepts a string defining a size:
1337 - 1337 bytes
150K - 150 kilobytes
2M - 2 megabytes
Returns a tuple (size,unit), where size is an integer and unit is
'B' (bytes) or 'T' (threads)."""
if str[-1] in string.digits: #TODO: de-uglify
return (int... | b7daa3a9bbc3f353c9a45edb9f8f7de279e5c5fd | 3,611,284 |
import dateutil
def ParseAutoservDate(timestamp):
"""Autoserv log format timestamp to datetime parser.
Args:
timestamp: a string.
Returns:
a datetime.
"""
year = str(Now().year)
naive_dt = dateutil.parser.parse(year + '/' + timestamp)
dt = naive_dt.replace(tzinfo=naive_dt.tzinfo or
... | 5eb2fba05399b98b47dfa4e6623a37b45f3073fa | 3,611,285 |
import math
def heading_from_to(p1: Vector, p2: Vector) -> float:
"""
Returns the heading in degrees from point 1 to point 2
"""
x1 = p1[0]
y1 = p1[1]
x2 = p2[0]
y2 = p2[1]
angle = math.atan2(y2-y1, x2-x1) * (180/math.pi)
angle = (-angle) % 360
return abs(angle) | 97f15fc3ff2f75daec7e1ad12d549570dcc18dfd | 3,611,286 |
from typing import Dict
from typing import List
def _compute_power_transforms(
Ys: Dict[str, List[float]]
) -> Dict[str, PowerTransformer]:
"""Compute power transforms."""
power_transforms = {}
for k, ys in Ys.items():
y = np.array(ys)[:, None] # Need to unsqueeze the last dimension
p... | 8ac8d0dcc39eaad4a6feddb1677ae9c0d9536703 | 3,611,287 |
import os
from datetime import datetime
def cni_scan():
"""
Scan a French National Identity Card
---
summary: scan a French National Identity Card
tags:
- cni
consumes:
- multipart/form-data
parameters:
- in: formData
name: image
type: file
require... | 886856ead70cd7baa00e8f4dea03d409e0342fbd | 3,611,288 |
def _alloc_key(name):
"""Constructs allocation key based on app name/pattern."""
if '@' in name:
key = name[name.find('@') + 1:name.find('.')]
else:
key = name[0:name.find('.')]
return key | ca3182f52d780f94a6a18c51ad0b7d841ead20d1 | 3,611,289 |
def collect_ranged_items(lm, dies):
"""Collect items that have start/end ranges."""
results = []
# Ranges refs (stored as decimal offset)
rlrefs = defaultdict(list)
for off, lines in dies.items():
_, tag, attrs = expand_die(lines)
# Does it have a PC range?
lodec, hidec = get_pc_range(attrs)
... | 627682dd8d4a563b5b220b54b0f1a5bd492f98db | 3,611,290 |
def gen_cluster(cid):
"""Generate contents of ECS Cluster page"""
data = awscli('ecs', 'describe-clusters', '--clusters', cid)
data = data['clusters'][0]
srvs = awscli('ecs', 'list-services', '--cluster', cid)
srvs = srvs['serviceArns']
cnts = awscli('ecs', 'list-container-instances', '--cluster... | 25c12c19bc0deedd0a42098dcfe9b493eb9ca315 | 3,611,291 |
import pdb
import sys
def get_all_edl_modules():
"""Get name and relative path of the modules in edl project
"""
res = {}
for k, v in sys.modules.items():
if hasattr(v, '__file__'):
if v is not None:
try:
if v.__file__ and 'site-packages' in geta... | 149a396ad4a5b33af130847bb63edfb25547651a | 3,611,292 |
def _get_prog_string(output_string):
""" obtains the string containing the version name and number
"""
pattern = app.capturing(
('Psi4' + app.SPACE +
app.one_or_more(app.NONNEWLINE) + app.SPACE +
'release'))
prog_string = apf.first_capture(pattern, out... | e30b660b4e99b986e22d6d43bd3d9831863a7c65 | 3,611,293 |
import hashlib
import zipfile
import stat
import os
import time
def download(i):
"""
Input: {
components - pre-loaded components from bootstrapping
or
cid [str] - CK CID of format (repo UOA:)module UOA:data UOA
(can use wildcards)
... | 3c1a132b63c2738c003d870e2995055026a6f40c | 3,611,294 |
def mergeH(rects):
"""Return `rects` with horizontally adjacent rectangles with the same Y coordinates merged
"""
byY = defaultdict(list)
for r in rects:
byY[r.Y0].append(r)
merged = []
for y in sorted(byY):
yrects = byY[y]
r0 = yrects[0]
for r in yrects[1:]:
... | 96a624f275d7d66acd919c1cb5016f608529e7ab | 3,611,295 |
def new_ff_l2addr_status(dp_id, addrs):
"""
Create FFL2AddrStatus message
"""
return pb.FFL2AddrStatus(
dp_id=dp_id,
addrs=addrs,
) | 41734bb259938a3ffcf9a90519b94717dc2bf567 | 3,611,296 |
import copy
def get_gts_based_on_difficulty(dataset, img_idx):
"""Returns lists of ground-truth based on difficulty.
"""
# Get all ground truth labels
all_gt_objs = obj_utils.read_labels(dataset.label_dir, img_idx)
# Filter to dataset classes
gt_objs = dataset.kitti_utils.filter_labels(all_gt... | 7d9f9ef39d91753811b43bad1a94357542d5f955 | 3,611,297 |
def get_batch_centroid_id(batch_centroid):
"""Returns a batchcentroid/id.
"""
return get_resource(BATCH_CENTROID_RE, batch_centroid) | a39610a590021eda48aa9fa1c2cf62d8944d8eed | 3,611,298 |
def get_optional_interfaces():
"""Return the optional interfaces that should be checked if the relavent
relations have appeared.
:returns: {general_interface: [specific_int1, specific_int2, ...], ...}
"""
optional_interfaces = {}
if relation_ids('ha'):
optional_interfaces['ha'] = ['clust... | 2000eede047827013f26cda14c83e77efbdf6b73 | 3,611,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.