content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
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 |
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 |
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 |
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 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 |
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 |
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 |
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 |
import json
import copy
def demo():
"""The Nevermined Federated Learning demo.
This demo showcases the nevermined Federated Learning capabilities.
FLow:
1. Setup nevermined
2. Setup accounts
3. Publish compute to the data assets
4. Publish algorithm
5. Publish work... | f98ce00cc16c5d3bb96cca41640cef24e946a759 | 3,611,300 |
def cdlhangingman(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of hanging man for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string)... | 775510fdaebfdb100e37489bd03cee589d7aa341 | 3,611,301 |
def gast_to_code(gast, out_lang, lvl=0):
"""
gast router that takes generic ast and the output language
that the gast needs to be converted to and executes the
conversion recursively
out_lang correspond to the language codes defined in datastructure:
javascript: js
python: py
"""
con... | f6256ad2e2ce2b94b830fcd9eba0c1be6249c232 | 3,611,302 |
from typing import Callable
def skill(name: str) -> Callable:
"""Wrap function to transform it into Skill object."""
def wrapper(func: Callable) -> Skill:
return Skill(name, func)
return wrapper | 3e5ab800f417fa5a3108747f84c23bac2fcc6df0 | 3,611,303 |
def rotate(arr, n, p):
"""Rotates an array.
Args:
arr: The array to be rotated.
n: The size of arr.
p: The number of rotations to be performed.
Returns:
An array rotated p times.
Raises:
ValueError: If p > n.
"""
if p > n:
raise ValueError("The n... | cae9264ac44ef7864a74f00b93f0f3431525a5a5 | 3,611,304 |
def world2Pixel(geoMatrix, x, y):
"""
Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
the pixel location of a geospatial coordinate
"""
ulX = geoMatrix[0]
ulY = geoMatrix[3]
xDist = geoMatrix[1]
yDist = geoMatrix[5]
rtnX = geoMatrix[2]
rtnY = geoMatrix[4]
pixel = int((x - ulX) / xDist)... | 7f676061ae12c9a7ffeedfdf1bfb88fb84d24f8f | 3,611,305 |
def _derivative(f, a, method='central', h=0.01):
"""
Compute the difference formula for f'(a) with step size h.
copied from:
https://personal.math.ubc.ca/~pwalls/math-python/differentiation/differentiation/
Parameters
----------
f : function
Vectorized function of one variable
... | de02aaf132922c0be8aeb84bea5af5d09e850b9d | 3,611,306 |
def forbidden_request() -> dict:
"""
Returns a generic forbidden request response back.
Used when the token given is not authorized to act on resources.
"""
return return_response(403, responses[403]) | 3e1668d923cdbada58ea0661632364dce8970147 | 3,611,307 |
def recursion_constants(max_n):
"""
Calculates the values useful for performing the scalar potential algorithm
"""
k = _gen_2d_array(max_n, max_n, 0)
for n in range(1, max_n):
for m in range(n + 1):
k[m][n] = (((n - 1) * (n - 1)) - (m ** 2)) / (
(2.0 * n - 1) * (2... | 934ae6e98314b3511fd22fdc080581e1ff3e25bf | 3,611,309 |
import platform
def return_malware():
"""Return malware list per platform"""
if platform.system() == "Windows":
return windows_malware_list
else:
return linux_malware_list | 977b7bcb107607aa649455683e805836460a95dc | 3,611,310 |
def tokenize(text) -> list:
"""
Parses input and returns valid input as typed tokens
If token starts with a:
* character -> word (this will be messed up if b' or r' is introduced
* number -> int || float
Currently does not handle special characters
"""
stack = []
tokens... | f7e08180d6e15ffabdc14e6dc3aa984a33a3a3b0 | 3,611,311 |
def encode(query, doseq=False, safe='', encoding=None,
errors=None, quote_via=quote_plus):
"""Wrapper for urllib.parse.encode"""
return urlencode(query, doseq=doseq, safe=safe,
encoding=encoding, errors=errors, quote_via=quote_via) | a02e681d01c7c9be2aba5df770ed405f241f06d4 | 3,611,312 |
def get_session(url, key, secret):
"""Get a :class:`tempoiq.client.Client` instance with the given session
information.
:param String url: Backend's base URL, in the form
"https://your-url.backend.tempoiq.com"
:param String key: API key
:param String secret: API secret
:r... | a79b2ce48ea916d70802dcf193e85104447322da | 3,611,313 |
def get_diffusion_plot_analysis_features(data):
"""Returns all the features associated with the diffusion plot analysis, that is: DTXC, DTYC, DTRC, X2, Y2, R2, DXS, DYS, DRS, HXS, HYS, HRS, DXL, DYL, DRL, HXL, HYL, HRL"""
DTXC, DTYC, DTRC, X2, Y2, R2, DXS, DYS, DRS, HXS, HYS, HRS, DXL, DYL, DRL, HXL, HYL, ... | db079212b5945ed6c4f15a511cbccfdee52783ae | 3,611,314 |
import pdb
import itertools
def make_resampled_models(lbda_obs, grid_param_list, model_grid=None,
model_reader=None, em_lines={}, em_grid=None,
dlbda_obs=None, instru_fwhm=None, instru_idx=None,
filter_reader=None, interp_nonexist=True):
... | faec105aa7181493cfaf915c3ef4d25c9f7f69d2 | 3,611,315 |
def insert_in_bst(root, node):
"""
Insert node in the binary search tree
:param root: root node of the binary search tree
:type root: TreeNode
:param node: node to insert
:type node: TreeNode
:return: root node
:rtype: TreeNode
"""
if root is None:
root = node
else:
... | 3c737d71c5793e7baa51d1ad75b6cc056abbda82 | 3,611,317 |
from typing import Tuple
from typing import Optional
from typing import Type
def _get_serializer_field_type(field: Field) -> Tuple[str, Optional[Type]]:
"""
Get typescript type from trivial serializer field.
"""
field_type: str
dependency = None
if type(field) in DRF_FIELD_MAPPING:
fie... | 3180ab5ce6f100894ee3b9ed55af6a3dd5a5b0b8 | 3,611,318 |
def format_bytes(b):
"""Format bytes as human-readable text."""
kb = 1024
mb = kb*1024
gb = mb*1024
if b < kb:
return '%s b' % b
elif b < mb:
return '{0:.2f} kb'.format(float(b) / kb)
elif b < gb:
return '{0:.2f} mb'.format(float(b) / mb)
else:
return '{0:.2f} gb'.format(float(b) / gb) | 4c41105449a8a07e3aca932d9ab3326176f6f1f6 | 3,611,319 |
def get(name):
"""
Return the :term:`doclist` of the `Page` specified by `name`
"""
page = dataent.get_doc('Page', name)
if page.is_permitted():
page.load_assets()
docs = dataent._dict(page.as_dict())
if getattr(page, '_dynamic_page', None):
docs['_dynamic_page'] = 1
return docs
else:
dataent.res... | 09373abbc03494b1cc133c9e1b2e32f767007681 | 3,611,320 |
def create_app(config_mode=None, config_file=None):
""" Creates the Flask application
Kwargs:
config_mode (str): The configuration mode. Must be a `class` in
`config.py`. One of ('Production', 'Development', 'Test',
'Docker')
config_file (str): The configuration file.
... | 7a2456e98dd55d0cd6063d324d57c864948f2de2 | 3,611,324 |
def computeBootstrap(data, pointingID):
"""Compute the 95% Bootstrap CI from a list of annotations
@param data tuple of np.array containing (accs, annotTCTs, trialTCTs)
@param pointingID the pointingID to look at
@return a tuple (acc_avg, acc_std, tct_trial_avg, tct_trial_std, tct_annot_avg, tct_annot_s... | 93e902eeec3eb6b6aeeb4ad943247eab8d49f677 | 3,611,325 |
import numpy
def from_meshio(mesh):
"""Convert a :class:`meshio.Mesh` to :class:`toughio.Mesh`.
Parameters
----------
mesh : meshio.Mesh
Input mesh.
Returns
-------
toughio.Mesh
Output mesh.
"""
if mesh.cell_data:
version = get_meshio_version()
if... | 409dd5984d393f1d13587141d3783e0dedb3bfab | 3,611,326 |
def register_decoder(name=None):
"""Register a decoder. name defaults to function name snake-cased."""
def decorator(decoder_fn, registration_name=None):
"""Register & return decoder_fn with registration_name or default name."""
decoder_name = registration_name or default_name(decoder_fn)
... | 09b29c7fde8218f7150d108545f7ca80b1f200b4 | 3,611,327 |
def _CalcPanelLocalApparentWindSph(alphas, betas, angular_rate_b,
apparent_wind_speed, panel, params):
"""Calculates local apparent wind at each sampling point on a panel.
Args:
alphas: Angle-of-attacks [rad] represented as a (...,) ndarray.
betas: Sideslip angles [rad] r... | b79ff990852a1f81338935814a12242c5e53d0c8 | 3,611,328 |
def cross_validate(model, train, test=None, k=5):
"""Calculates mean error using k-fold cross-validation."""
train = train.sample(frac=1, random_state=360) # Shuffles rows.
k = k if test is None else 1
chunks = np.array_split(train, k)
mean_rmse = 0
for i in range(0, k):
if VALIDATING:... | d53f3baf00ae7cf797e82fc476718ee702dc8236 | 3,611,329 |
def composite_difference_composite(original, other):
""" Subtract all elements that belong to other from original.
This is a tricky one, as we have to subtract one tree from another.
Good thing we can iterate over both trees in linear time and perform the entire difference operation
in linear time as w... | dd7e63924ef49191b398e3cdb90e7c4e13edd799 | 3,611,330 |
def calcular_puntos (boolean,cant_punt,difficult):
"""resta o suma segun si se equivoco o no en las coincidencias y segun la dificultad elegida"""
if boolean:
x = sumar_puntos(cant_punt,difficult)
else:
x = restar_puntos(cant_punt,difficult)
return x | b90ab5296290f12d455bb392928974192a63ce9a | 3,611,331 |
def conv2d(images, kernels, padding="SAME", strides=[1, 1]) -> core.Variable:
"""2D convolution, with same api as tf.nn.conv2d [1].
Args:
images: A `Variable` of shape [n_images, imheight, imwidth, n_channels].
kernels: A `Variable` of shape [kernheight, kernwidth, channels_in, channels_out].
... | ca04ea24e2ed645d1b9693a8596bc97287d24f9a | 3,611,332 |
def getVelocity(data):
""" Calculate velocity of a given set of values using linear regression.
Arguments:
data An iterable of numbers.
Returns:
velocity The estimates slope.
"""
sumY = sumXY = 0
for x, y in enumerate(data):
sumY, sumXY =... | d86c5e0b6f2e6024b9578486d377915649402f3a | 3,611,333 |
def freeze_layer(layer):
"""
Freeze a layer, so its weights won't be updated during training
:param layer:
:return:
"""
for param in layer.params:
layer.params[param].discard('trainable')
return layer | 2edcd24743fc62bf5e8a7cef9ce871e691d38d85 | 3,611,334 |
def serialize_example(row):
"""
Creates a tf.Example message ready to be written to a file.
"""
# Create a dictionary mapping the feature name to the tf.Example-compatible
# data type.
fp = preprocess_fp(row[0])
year = preprocess_year(row[2])
feature = {
"floorplan": _floats_ar... | 7d201a0a06087e7bf4e8dec34215b8a1a4ddfdf3 | 3,611,335 |
def parse_cached(cached_credentials):
"""Parse existing csv file
Requires first 4 columns to be TeamNum, Password, Code, Color [in hex]
"""
teamnums = []
passwords = []
codes = []
with open(cached_credentials) as f:
f.readline()
for line in f:
tokens = line[:-1].... | 95b9802011f22a66aa688947f059b29592de7487 | 3,611,337 |
def ubytes(n_spin_orbitals, i, state):
"""
Remove electron at orbital i in state.
Parameters
----------
n_spin_orbitals : int
Total number of spin-orbitals in the system.
i : int
Spin-orbital index
state : bytes
Product state.
Returns
-------
state_new :... | 157beb144221468aa6472390f39cc2ba70b25ed6 | 3,611,338 |
def tf_grad(t_scalar_func):
"""Maps a TF scalar-function to its TF gradient-function."""
def f_grad(t_pos):
tape = tf.GradientTape()
with tape:
tape.watch(t_pos)
t_val = t_scalar_func(t_pos)
grad = tape.gradient(t_val, t_pos)
assert grad is not None, '`None` gradient.'
return grad
... | 7ba0d2b9f74c6bdf4e62261e7d11cc34087a78b4 | 3,611,339 |
def parse_tpkl_depreciated(filename):
"""
A function to parse custom recarray objects.
This variation is dependent upon table.py from the Anfinrud Lab
Parameters:
filename (str): path of file to be analyzed
Returns:
Trace:custom object built to hold a single scattering curve and
... | 3c30df6f5aacd39ec4de4c87c18e71f19e09dd8a | 3,611,340 |
def time_to_string(time):
"""Converts a datetime instance to a string"""
if time is None:
return time
if time == "now":
time = datetime.now()
return mktime(time.timetuple()) | 137e1b9c434d3e034402c2f37acd136390d59530 | 3,611,341 |
def spacecraft_valid_id(request):
"""
AJAX method for checking whether a given identifier is in use or not within
the database.
:param request: The GET HTTP request.
:return: '{ isValid: "true/false", value: "$GET.value" }
"""
requested_id = request.GET['value']
if not requested_id:
... | 0fb635955e7c11148bbe7077042a106fab1551f7 | 3,611,342 |
from unittest.mock import patch
def reentrant_redis_locks():
"""Decorator/context manager to enable reentrant redis locks
This is useful for tests that do things like acquire a lock and
then, before the lock is released, fire off a celery task (which
will usually be executed synchronously due to
... | 7aa7a1cb5d2dc6dd732068f00a9ac4a81830cea4 | 3,611,344 |
def include_original(dec):
""" Meta decorator, which make the original function callable
(via f._original() )
"""
def meta_decorator(f):
decorated = dec(f)
decorated._original = f
return decorated
return meta_decorator | ba1bd643c192c1fc11df668ee4744202e1e3fd3a | 3,611,345 |
def get_related_model(model, relationname):
"""Gets the class of the model to which `model` is related by the attribute
whose name is `relationname`.
"""
if hasattr(model, relationname):
attr = getattr(model, relationname)
if hasattr(attr, 'property') \
and isinstance(at... | 6cec4b5edf148dc9a6b1197f70a203aa63fd0730 | 3,611,346 |
from typing import List
from typing import Dict
def retrieve_all(database_connection: mysql.connector.connect
) -> List[Dict]:
"""Returns a list of OrderedDicts with scorekeeper details for all
scorekeepers
Arguments:
database_connection (mysql.connector.connect)
"""
score... | 60eda30a6ebfc515d6972914d16da424a9c71a9a | 3,611,347 |
def proper_paranthetics(string):
"""
Evaluate whether open and closed parentheses match in proper order.
Return 1 if there are unclosed open parens.
Return 0 if parens are balanced.
Return -1 if there are close parens not preceded by open parens.
"""
paren_stack = Stack()
for char in st... | 6f9bb2961e1386f8887b9ea7770f8154b8d58b81 | 3,611,348 |
def sqexpcov(n: int, w: float, var: float = 1.0):
"""Construct square exponential covariance matrix
Args:
n: size of the matrix
w: scale
var: variance
Returns:
"""
# i, j = meshgrid(arange(n), arange(n))
# return var * exp(- w * (i - j) ** 2)
return var * exp(-w * ... | 8ac7230763caa9e0f9637425ae4442d35603ec55 | 3,611,349 |
def create_email_addresses_in_group(email_group_id):
"""
Create new /email_addresses in a certain email_group
---
Method: POST
@param: email_group_id int
@param: email_addresses str // if many, divided by comma
"""
request_data = request.json
# get email_group
email_group = Emai... | c2f25ad7d63c9c8af5d5def1c343b86065291e84 | 3,611,350 |
from typing import Tuple
def make_config(
src_path: str,
dst_path: str,
*,
data: OptAnyByStrDict = None,
exclude: OptStrSeq = None,
include: OptStrSeq = None,
skip_if_exists: OptStrSeq = None,
tasks: OptStrSeq = None,
envops: OptAnyByStrDict = None,
extra_paths: OptStrSeq = Non... | 1efc6ea1ad90fc5611737bb729796c6b5cce04c0 | 3,611,351 |
import re
def add_new_entry():
"""Add an entry"""
# json_data = request.get_json()
title = str(request.data.get('title', '')).strip()
description = str(request.data.get('description', ''))
# check empty title
if not title:
response = {"message": "Please input title", "status": 401}
... | d0f0a42aeaecf0af6d6b48b1cca9c0baa30ac8be | 3,611,352 |
def error_403(error):
"""
Página de erro customizada: Erro 403
Args:
error: error class
Returns:
Template renderizado: errors/403.html
"""
return render_template('errors/403.html', legend='Erro 403'), 403 | 8628a078a4c5d5155180e98e9fa678199516b6c5 | 3,611,354 |
import json
def post_sqs_message(queue, payload, delay=0):
"""
Send a new SQS message for backend processing
:param queue: Boto3 SQS Queue object
:param payload: Json Serializable Python object
:param delay: Delay in second. How much time to delay before message becomes active
:return: Nothing... | e148dcb0b115bbaf71982b1b08461034d17b6710 | 3,611,355 |
import warnings
def fill_nan(array: np.ndarray) -> np.ndarray:
"""Replace NaNs with values interpolated from their neighbors
Replace NaNs with values interpolated from their neighbors using a 2D Gaussian
kernel, see: https://docs.astropy.org/en/stable/convolution/#using-astropy-s-convolution-to-replace-b... | 78d4c0eca90bd008e65ba604176738273590cb52 | 3,611,357 |
def backup_remote():
"""Does a remote database dump and scps the file. Returns the filename."""
remote_filename = get_backup_filename(hostname=env.host_string)
print("Remote filename: " + remote_filename)
with cd('bookmarker'):
run('source env/bin/activate && ' + BACKUP_COMMAND + remote_filenam... | abd9010cf8ae93bf51505286ca266b048bd3fbf4 | 3,611,358 |
def build_signature_def_from_tensors(inputs, outputs, method_name):
"""Builds signature def with inputs, outputs, and method_name."""
return tf.saved_model.signature_def_utils.build_signature_def(
inputs={
key: tf.saved_model.utils.build_tensor_info(tensor)
for key, tensor in inputs.items(... | 8f9ee68236fdbd0ecdf6e860c50020c8c8bfefd3 | 3,611,360 |
def splice_before(base, search, splice, post_splice="_"):
"""Splice in a string before a given substring.
Args:
base: String in which to splice.
search: Splice before this substring.
splice: Splice in this string; falls back to a "." if not found.
post_splice: String to add ... | f8f5bf3c2355c38d16157836863e501cbc846d40 | 3,611,361 |
import typing
def _field_from_annotation(attr: str,
annotation,
array_type: FieldArrayType = FieldArrayType.scalar,
) -> FieldDesc:
"""
Create a SimpleField or a StruturedField, given annotation information.
Parameters
-... | 44a1ab7c67731d6e60ea7f8bb762dd1f55f32bf8 | 3,611,362 |
import csv
def average_trip_length_with_protion_of_trips_longer_than_30_min(filename):
"""
This function reads in a file with trip data and reports the number of
trips made by subscribers, customers, and total overall.
"""
with open(filename, 'r') as f_in:
# set up csv reader object
... | eda083cde82da0f8db8f2a4716674496e81a2c74 | 3,611,363 |
def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7, print_msg=False):
"""
Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n
Arguments:
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"... | 2c969bc4baf112384009a410fc4a1f98a73ffd3a | 3,611,364 |
from typing import Optional
def is_short_flag_reason(flag: str) -> Optional[str]:
"""
Checks if the given string is a valid short flag.
:param flag: The string to check.
:return: None if it is a valid short flag,
or the reason if not.
"""
# Short flags must start... | 5c95fe2266a964f91995ef4607475761f6dc96b7 | 3,611,365 |
def text_from_doc_list(doc_list):
"""
extract a text from list of html elements.
"""
return [doc.text for doc in doc_list] | 09370e07fc34c481091a5d34683e3668da12f5a4 | 3,611,366 |
def renderHTML(maxrows,sortby,search,descend):
"""generate HTML table with sorted filtered results"""
data_sorted = sorted(indexnotebooks(), key=lambda item: item[sortby])
if len(search)>0:
data_sorted = list(filter(lambda x:x['path'].lower().find(search.lower())>-1,data_sorted))
nitems = len(da... | 6394c3bbdb182c52f6f3cf6e8cbc433832ddce48 | 3,611,367 |
import librabbitmq # noqa
def supports_librabbitmq() -> bool | None:
"""Return true if :pypi:`librabbitmq` can be used."""
if _detect_environment() == 'default':
try:
except ImportError: # pragma: no cover
pass
else: # pragma: no cover
return Tr... | 20700ca975514c4a2b300a257b045bd8cb65734e | 3,611,368 |
from enum import Enum
def _create_enums(properties):
"""Returns a list of Enums to be generated"""
enums = {}
for property_ in properties:
# Only generate enums for keyword properties that do not require includes.
if property_['field_template'] in ('keyword', 'multi_keyword') and len(prope... | c9c8acf01283515909aff380ac7196c867b17edc | 3,611,369 |
def get_config_file(config=None):
"""
This method parses properties and returns the value of CONFIG_FILE.
If undefined, VACCA_CONFIG is returned as fallback.
"""
global VACCA_CONFIG,VACCA_DIR
print('-')*80
if not config:
VACCA_CONFIG = get_env_variable('VACCA_CONFIG',DB_HOST)
... | fd3ac7fd151aea924032cf7e3c55abf6804f6a71 | 3,611,370 |
def adder():
"""Adds all the numbers the user gives until "done" is typed."""
print("Type a number or 'done' when finished")
result = 0
while True:
try:
val = input("Please give input: ")
if val == "done":
break
else:
result += ... | ce68159b6f071b47b9876ce3a6a7ec18ddd0d5fb | 3,611,371 |
def fixed_start_fourier_df(pd_index, freq, k, name="ffcomp"):
"""
Generates fourier features, with a fixed starting point
"""
assert isinstance(
pd_index, pd.Index
), "Provide pd.Index subclass as the first argument"
assert pd_index.freq, "freq for input index is not defined"
assert ... | 610ac96cf84d96a94c90340ac72ada6c0638aa50 | 3,611,372 |
import re
def load_obj(filename):
"""
load from a Wavefront obj file
"""
vertices_pool = []
uvs_pool = []
normals_pool = []
indices = []
vertices = []
normals = []
uvs = []
vertices_map = {}
for line in open(filename, 'r'):
line = line.strip()
spli... | b135a767e7d3e9d173506a5087a26aeb78dee8d9 | 3,611,374 |
from datetime import datetime
def prepare_dataset():
"""
Download out.csv, cast the right datatypes and convert date
:return: Dataframe - columns = ['timestamp', 'article_id', 'click', 'date']
"""
df = pd.read_csv('./data/R6A/out.csv', usecols=['timestamp', 'article_id', 'click'], sep=' ')
df... | 4f41827940147cf87d8d10bfc5e28c04a2a02979 | 3,611,375 |
def mse(x, y, axis=None):
"""Mean squared error"""
if np.isclose(x.size, 0.0) and np.isclose(y.size, 0.0):
return 0.0
elif np.isclose(x.size, 0.0):
return np.mean(np.absolute(y))
elif np.isclose(y.size, 0.0):
return np.mean(np.absolute(x))
min_l = min(len(x), len(y))
x... | b9028704bfcda9ff821b3c7d075289e7f173a241 | 3,611,376 |
def detect(sess, net, im_file, mode='normal', cls='person', cls_ind=1):
"""Detect all objects of a single class in an image using pre-computed object proposals."""
im = cv2.imread(im_file)
if mode == 'fast':
scores, boxes = im_detect_fast(sess, net, im)
else:
scores, boxes = im_dete... | 45a5f7a0480e95eb05dd5304f8c1a584d453189d | 3,611,378 |
from typing import Tuple
def decode(
data: _ByteString,
errors: _Str = 'strict'
) -> Tuple[str, int]:
"""Convert a bytes type of escaped utf8 hexadecimal to a string.
Args:
data (bytes or bytearray or memoryview): The escaped utf8
hexadecimal bytes.
errors (str or ... | a651c318f393791c421d60d2ab9f3e50f0a12b5b | 3,611,380 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.