content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from bs4 import BeautifulSoup
def read_html(input_str: str) -> BeautifulSoup:
"""Takes str, does cleaning as input and returns BeautifulSoup object"""
f = utils.clean_input(input_str)
soup = BeautifulSoup(f, "lxml")
# removes all anchor elements/links and contents thereof
[a.decompose() for a in s... | f4320cda4b0e88c3a5709cb8646ab08c03d93d97 | 62,300 |
import pkg_resources
import os
import pickle
def load_RF():
""" Load random forest classifier and regressors from zendo.org.
Two regressors will be laoded, one with 1 estimator and one with 100 estimators. 1 estimator minimizes
bias (systematic offset) with the cost of high varience (scattering) and... | 0fadd2865ced98621ace6e0afb9eb986128f32f4 | 62,301 |
from unittest.mock import patch
async def setup_script(hass, notify_q, now, source):
"""Initialize and load the given pyscript."""
scripts = [
"/some/config/dir/pyscripts/hello.py",
]
with patch("custom_components.pyscript.os.path.isdir", return_value=True), patch(
"custom_components.... | 2c1b612801bda9cee797c63ea644684ab9b77a3a | 62,302 |
def compute_mu_for_co_component(graph, component_index, source_index,
root, vertices_in_component):
"""
Compute the mu value for co-component
INPUT:
- ``graph`` -- Graph whose MD tree needs to be computed
- ``component_index`` -- index of the co-component
- ``... | f8277bf8f37635e9c3696d733df7eba7420ae1e0 | 62,303 |
def append_filename(filename, impute_dates, moving_average):
"""! Creates consistent file names for all output.
"""
if moving_average > 0:
filename = filename + '_ma' + str(moving_average)
elif impute_dates:
filename = filename + '_all_dates'
return filename | 3d4137ac023ed1470e20a78626803b29e9c14a0f | 62,304 |
def _merge_css_list(*args):
"""Transform arguments into a single list of string values."""
css_list = []
for arg in args:
css_list += _merge_css_item(arg)
return css_list | dd0af268386aed7c8dc8245986e6edaf55f0277c | 62,305 |
def step_functions_execution_arn(state_machine_name_template: str, execution_name: str) -> str:
"""
The ARN of a state machine execution, with name derived from `state_machine_name_template`, with string formatting
to replace {stage} with the dss deployment stage.
"""
sfn_name = state_machine_name_... | a40a89c34fefb3f405bb0d86228c26a950454665 | 62,306 |
def crawled_url() -> list:
""" Get crawled url"""
# 0
crawled_url = db.uk_181125.find({}, {'_id':0, 'url':1})
crawled_url = list(map(lambda one_url : one_url['url'], crawled_url))
return crawled_url | e51c59bba080716605e8655e4e508f9fd05a92d3 | 62,307 |
def encode_data(data_structure):
"""
Encode an arbitrary python data structure in a format that is suitable
for encryption (encrypt() expects bytes).
The data structure can only contain basic python types, those supported
by json.dumps (including longs, but no arbitrary objects).
Performs the fo... | 7b3a11d7ee5a4014ccdb5499d0f4d589043b4b3b | 62,308 |
from typing import Optional
from typing import Union
from typing import List
from typing import OrderedDict
def get_model_layers(
model: nn.Module,
getLayerRepr: Optional[bool] = False,
dependencies: Optional[bool] = True,
excludeNorms: Optional[bool] = True,
excludeActs: Optional[bool] = True,
... | 6c9cc0a9f743d998250c5c9e9396c025d6cf1783 | 62,309 |
import urllib.request
def get_url(url):
""" pulls down a url and returns string of content """
LOG.debug(f'getting url {url} ..')
req = urllib.request.Request(url)
return urllib.request.urlopen(req).read().decode() | 0b9de321c6a6f965b270ac62691e046025d0be18 | 62,310 |
def block_layer(
inputs, filters, block_fn, blocks, strides, is_training, name, data_format
):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, channels] depending on data_format.
filters: T... | 6a87bf15c74812a55680d1350d1dd8667bce484f | 62,311 |
def set_meta (mimetype) :
""" Factory function for Attribute_Access to set all interesting
meta-data
"""
set_attr = []
for attr in meta_counts :
a = OOo_Tag ('meta', attr, mimetype)
t = OOo_Tag ('meta', 'document-statistic', mimetype)
set_attr.append (Set_Attribute (t, a,... | 6a7ac7ae6a2fcf8bfded921254443ef1db4e7ee7 | 62,312 |
def get_two_gaussians(N=0.5, mu=(1, 3), b=(100, 100), r=(1, 1)):
"""
Returns the two Gaussians spectral density defined in Sec. 4.2 of the thesis
"""
mu1 = mu[0]
mu2 = mu[1]
b1 = b[0]
b2 = b[1]
r1 = r[0]
r2 = r[1]
alpha = N / (r1 * np.sqrt(np.pi / b1) + r2 * np.sqrt(np.pi / b... | ec00839d74dfe3635467ba7b878c854410856b06 | 62,313 |
import html
def render_select_cells(data):
"""Render the collapse for selecting cells for differential expression"""
return html.Div(
[
html.P(),
dbc.Button(
"differential expression",
id="select_cells_button",
className="text-lef... | e1c23c329dae8eb5e8712d860e21d65a39610281 | 62,314 |
import requests
def get_sites():
"""
Get list of sites (using GOCDB instead of site configuration)
:return: list of site IDs
"""
query = {"method": "get_site_list", "certification_status": "Certified"}
url = "?".join([GOCDB_PUBLICURL, parse.urlencode(query)])
request = requests.get(url)
... | 0ef0c1203b5de58df8105e5c82e9d6d6d8f91459 | 62,315 |
def get_secret_envs(config: dict):
"""
>>> get_secret_envs({"environment": {"abc": "aws:kms:kmsencval", "def": "unencval"}})
frozenset({'abc'})
>>> get_secret_envs({"environment": {"abc": False, "def" : "aws:kms:secrev"}})
frozenset({'def'})
>>> get_secret_envs({"environment": None})
froze... | fe18e5b608b589acdb1189778279b818d1bea44b | 62,316 |
def tf_get_model_lmks(tf_model, f, lmk_face_idx, lmk_b_coords):
"""Get a differentiable landmark embedding in the FLAME surface"""
faces = f[lmk_face_idx].astype(np.int32)
return tf.einsum('ijk,ij->ik', tf.gather(tf_model, faces), tf.convert_to_tensor(lmk_b_coords)) | f4c79d4c0bc78135dc42ca250adca665b86837fb | 62,317 |
def word_tokens2string_sentences(list_of_lists_of_tokens):
"""
Return a list containing a single string of text (OUTPUT) for each word-tokenised sentence (INPUT).
E.g.,
[['I', 'think', '.'], ['Therefore', ',', 'I', 'am', '.']] => ['I think .', 'Therefore , I am .']
Parameters
-------... | daff6f1ac63c9da9882f8acf6737cf575f26a5a7 | 62,318 |
def is_valid_int_param(param, required=True):
"""Checks if the parameter is a valid integer value.
@param param: Value to be validated.
@return True if the parameter has a valid integer value, or False otherwise.
"""
if param is None and not required:
return True
elif param is None:
... | 928b61deaf2c7167f01ec596bf741c0b8f828dad | 62,319 |
from typing import List
def estimated_schedule(records: List[Transaction], record: Transaction) -> Schedule:
""" Return a forecasted dividend schedule. """
# todo: we should clean this up- don't filter out by period, caller can do that
sample_records = trailing(
by_ticker(records, record.ticker),
... | bcc37b910e3a7bf5d73aaf905c514a4ab2bdba0d | 62,320 |
def ta(tex, tbg, tau_):
"""
Eq. (18) Goldsmith et al. (2012)
"""
gbg_ = gbg(tbg)
return tstar*(1./(np.exp(tstar/tex) - 1.) - gbg_)*(1. - np.exp(-tau_)) | f6ea7908353e5fa823bd53694876e426cea277d2 | 62,321 |
def has_key(title, key):
""" Check if route dict has a specific key | str, str --> bool """
route_dict = get_route_dict(title)
return key in route_dict | 90af98f070b1bad2b3185d91a5828de5561c2335 | 62,322 |
from functools import reduce
def lcm(*integer_nums: int) -> int:
"""
Private function for calculating LCM [least common multiple] of N integers
Args:
*integer_nums: integer arguments
Returns:
Least common multiple of N positive integers.
Examples:
>>> lcm(16, 20)
... | d4afb601db6fcd0a8b5797cd1f9dea1a090bf5aa | 62,323 |
def invert_transform(T_in):
"""return inverse transform of T_in, assuming T_in is affine 4x4 transformation"""
T_out = np.eye(4)
C_out_inv = T_in[:3, :3].T # exploiting that C^T = C^-1 for rotations
T_out[:3, :3] = C_out_inv
T_out[:3, 3] = -C_out_inv.dot(T_in[:3, 3])
return T_out | e8a5ec8b4d0e2dc8a2e791d4cd60bf5dcd7aaa35 | 62,324 |
def exercise(xml):
"""Find the target element, add the new item, and return the modified XML
string.
"""
ns = {"t": "http://martin.hoppenheit.info/code/generic-tree-xml",
"e": "http://purl.org/dc/elements/1.1/"}
root = ET.fromstring(xml)
for n in root.iter("{%s}node" % ns["t"]):
... | 18079fd9bbd121f532b0e148249c36144521af90 | 62,325 |
import os
def add_or_replace_bitstreams(file_list, added_item):
"""
Generic function to add bitstreams to a DSpace item. If a file of the same name already exists in DSpace, the
checksum is compared and the file is then skipped or the contents replaced.
:param file_list: list of dicts with basic metad... | af8038995fcf676869968eb631fefc78c902c21d | 62,326 |
def auth_user(
request: Request,
db: Session = Depends(get_db),
) -> UserBase:
"""
## Dependency
Authenticates a user by verifying their access token
and returns the authenticated user info
Returns
--------
user_id : UUID
email : EmailStr
master_pwd : str
"""... | 3d61b897408a296774d9837a1779a070dd4bef33 | 62,327 |
def print_deps(i):
"""
Input: {
data_uoa - data UOA of the repo
or
repo_deps - dict with dependencies on other shared repos
(out_prefix) - output prefix befor each string
}
Output: {
... | fe72bd971b15f0ff9524d887829b60ea7b82051b | 62,328 |
def _get_mask(id_to_node, node_to_id, num_nodes, masked_nodes, additional_mask_rate):
"""
Returns the train and test mask arrays
:param id_to_node: dictionary mapping node names(id) to dgl node idx
:param node_to_id: dictionary mapping dgl node idx to node names(id)
:param num_nodes: number of user/... | 8280d7f6962ee9e0fbc7fca940c64eb72d58ba4a | 62,329 |
def Delete(taxonomy_id, annotation_id):
"""Makes an API call to delete an annotation.
Args:
taxonomy_id: Id of a taxonomy.
annotation_id: Id of the annotation.
Returns:
An Operation message which can be used to check on the progress of the
project creation.
"""
return _GetService().Delete(
... | ca9aaf23ca4df44b50a5ba7192b23bd3b4a5ab8a | 62,330 |
def unique(id, ids):
""" Ensure id is unique in set of ids. Append '_1', '_2'... if not """
while id in ids or not id:
m = IDCOUNT_RE.match(id)
if m:
id = '%s_%d' % (m.group(1), int(m.group(2))+1)
else:
id = '%s_%d' % (id, 1)
ids.add(id)
return id | 05f633aa3db40324e424fa7f889e6b434c0a0bb9 | 62,331 |
def find_or_create_active_call_for_campaign_and_caller(call_campaign, caller):
"""
Find or Create active Call for Call Campaign and Caller
For new Calls, exclude Opt Outs or Contacts called recently for any
Campaign. Assume Caller has permission to make Call.
Parameters
----------
call_cam... | 2b9d47233f3f24aac9a21b95bd2889964b214159 | 62,332 |
def questions_for_written_answer_answered_in_range(start, end):
"""Returns a list of all Questions for Written Answer, and respective
Answers, answered in date range.
"""
try:
_start = start.isoformat()
except AttributeError:
return []
try:
_end = end.isoformat()
exce... | 7cd5341ed5f1fb54c1c230356994bb9c2650c0e1 | 62,333 |
def weight_variable(shape):
"""weight_variable generates a weight variable of a given shape."""
# initial = tf.truncated_normal(shape, stddev=0.1)
initial = tf.constant(0.01, shape=shape)
return tf.Variable(initial) | 49ee5b4b9708c3780f10b7980150a6b5f3a2265f | 62,334 |
def init_proof(prop):
"""Initialize proof for proposition."""
vars = prop.get_vars()
assms, concl = prop.strip_implies()
assms.append(concl.arg if concl.is_not() else Not(concl))
return ProofState(vars, assms) | ab2ad2d4e78f4c013c6d445bde142d16ffc6f952 | 62,335 |
def get_vaccine_admin():
"""Returns DataFrame on COVID-19 vaccine administration in Italy.
Parameters
----------
None
Raises
-------
ItaCovidLibConnectionError
Raised when there are issues with Internet connection.
Returns
-------
pandas.core.frame.DataFram... | 5f2a0236f142fbdfcc9f172cf720026dfd428023 | 62,336 |
def delete_category(request, category_id):
""" Delete a category from the database """
# if not request.user.is_superuser:
# messages.error(request, 'Sorry, only site owners can do that.')
# return redirect(reverse('home'))
try:
category = get_object_or_404(Category, pk=category_id)... | 2a023ff146e1d044f895968f3339ed2057eff37a | 62,337 |
async def set_epoch_and_fallback_properties(config: ComponentConfig, current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Set properties (epoch and fallback) in the bot pipeline and policies configurations
"""
mongo_processor.save_component_properties(config.dict(), current_user.g... | 707294b906253681addb1152171b8fd45ce48371 | 62,338 |
def escape_ipv6(address):
"""Escape an IP address in square brackets if IPv6
:param address: address to optionaly escape
:type address: string
:returns: string
.. versionadded:: 3.29.0
"""
if is_valid_ipv6(address):
return "[%s]" % address
return address | c8a2afe222a9fd29e6add1da39666dbef160bb50 | 62,339 |
def fc(inputs, is_training=True, num_classes=7, hidden_layer_size=[128, 128], dropout_keep_prob=0.8, reuse=None,
scope='FC'):
"""Creates a fully connected neural net.
Args:
inputs: a 4-D tensor of size [batch_size, height, width, 3].
num_classes: number of predicted classes.
is_training... | 24b7fba8441cc74b3a342496dffe36131ceb95d7 | 62,340 |
from operator import and_
from datetime import datetime
def delete_old_traceroutes(target_name: str, days: int, keep: int):
"""
Deletes old traceroute data if days have passed, but always keep at least limit entries
:param target_name: (str) target name
:param days: (int) number of days after which a... | 5f17a073b1efcee28538f8a48629af862197489e | 62,341 |
def rad2hz(w0, fs=96000):
"""Calculate a normalised rotational frequency so that w0=2*pi --> f0=fs
w0
f0 = fs * ------
2*pi
"""
return fs*np.array(w0)/(2*np.pi) | e178dd58d01c0ca6ffbcd1f032e8d76d436a8501 | 62,342 |
from unittest.mock import patch
async def test_post_method_result_contains_is_new_setup_as_bool(
setup_course_environ, test_quart_client, jupyterhub_api_environ
):
"""
Does the POST endpoint return a boolean value to indicate if new setup was occured?
"""
async def return_async_value():
r... | 0c466dd6f968b15a5e3f3ead0f5a5ea71f1b5582 | 62,343 |
from typing import Optional
from typing import Union
from typing import Dict
def fix_level_type(
level_type: Optional[Union[str, Dict]],
engine: str = "eccodes",
) -> Optional[Union[str, Dict]]:
"""
Convert level type into dict of GRIB keys.
Notes
-----
``typeOfFirstFixedSurface``... | e9a5a608554fa09d6445b03abc790cb787d06f27 | 62,344 |
import platform, psutil
def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if you need a simple wiki simply replace the two lines below with:
return auth.wiki()
"""
host=dict(machine=platform.machi... | 4584b4687d9dbf8e6a76d3308d618a1e2b9e41d1 | 62,345 |
def cal_hel(logits, gts, eps=1e-6, reduction="mean"):
"""
https://github.com/lartpang/HDFNet/blob/master/loss/HEL.py
::
@inproceedings{HDFNet-ECCV2020,
author = {Youwei Pang and Lihe Zhang and Xiaoqi Zhao and Huchuan Lu},
title = {Hierarchical Dynamic Filtering Network for ... | c67fe4a925b9af41cff6940e6072df467d2f9c83 | 62,346 |
import requests
def _send_photo_bytes(telegram_token, chat_id, bytes_io):
"""Send photo in open() or io.BytesIO form.
"""
url = "https://api.telegram.org/bot{}/sendPhoto".format(telegram_token);
files = {'photo': bytes_io}
data = {'chat_id' : chat_id}
r= requests.post(url, files=files, data=da... | 5b72e0baa552ff03a9838119ac2d4f64ffcfa49b | 62,347 |
import io
def _GenerateMtlsDisallowedServices():
"""Generates a table for services which do NOT support client certificate."""
disallowlist = []
for service, versions in apis_map.MAP.items():
for version, api_def in versions.items():
if not api_def.enable_mtls:
disallowlist.append((service, ve... | 2a13748a6619b54604f223930f71793f9a1ba229 | 62,348 |
def clean_up_whitespace_in_template_output(text):
"""Remove some excess whitespace from using Django templates for YAML."""
ret = []
for line in text.split("\n"):
# Truly empty lines are likely intentional, so keep them
if not line:
ret.append("")
continue
#... | 8428e5575f0a731d79ae796d3f20408e33a344e6 | 62,349 |
def _validate_spotlight_mode(the_sicd):
"""
Validate the spotlight mode situation.
Parameters
----------
the_sicd : sarpy.io.complex.sicd_elements.SICD.SICDType
Returns
-------
bool
"""
if the_sicd.CollectionInfo is None or the_sicd.CollectionInfo.RadarMode is None \
... | 3b72e99e7f6e1bae17fbdced72cfaf741a4d1974 | 62,350 |
def mixed_radix_to_base_10(x, b):
"""Convert the `mixed radix`_ integer with digits `x` and bases `b` to base 10.
Args:
x (list): a list of digits ordered by increasing place values
b (list): a list of bases corresponding to the digits
Examples:
Generally, the base 10 representatio... | a821ca5ee4a720a9c445c98b2bcd2905bd6d87cb | 62,351 |
def calculate_face_normals(hull, eps=10e-6, normalize=False):
"""Calculate outwards pointing normal for each simplex."""
face_normals = np.zeros((len(hull.simplices), 3))
barycenter = np.mean(hull.points, axis=0)
for face_i, face in enumerate(hull.simplices):
# extract vertices face
v = ... | 91d450e4b11d6f0805655e94649ad4144a29db43 | 62,352 |
def test():
"""
前向和后向传播
"""
x, d = lstm_math.data_set()
l = lstm_math.LstmLayer(3, 2, 1e-3)
l.forward(x[0])
l.forward(x[1])
l.backward(x[1], d, IdentityActivator())
return l | ad0cd138c8242b4fa76d5449bcc67716d8e33336 | 62,353 |
def _pprint_dict(seq, _nest_lvl=0):
"""
internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly.
"""
fmt = u"{%s}"
pairs = []
pfmt = u"%s: %s"
for k, v in seq.items():
pairs.append(pfmt % (repr(k), repr(v)))
return fmt % ", ... | 8d48fde0030785139c29b9739a4e056e2ffd176e | 62,354 |
import os
from sys import path
import sys
def collect_name_to_dirpath(directory, prefix, suffix, exclude=None):
"""Return a mapping from filename to path rooted at directory, ignoring files
that don't match suffix, and subtrees with names in exclude. Report when a
filename appears in more than one subdir; the ... | 0c6e1502217896847fcc0628deb8a0e19a3a439a | 62,355 |
import warnings
def invert_function_interpolation(
d, initial, f_min, f_max, model_function, derivative_function=None, tol=1e-8, dx=1e-2
):
"""This function inverts a function using interpolation. For models where this is required, this is the most time
consuming step. Specifying a sensible f_max for this... | 02e47926bb3e91a8c9c223c2585f5db471ecdf57 | 62,356 |
import string
def validate_username(username: str) -> bool:
"""
Check if username if valid and return boolean.
Introduces following requirements:
- 4 < username length < 30
- username not empty
- all characters are ASCII or digits
Args:
username (str): username to chec... | d708377680e769944cb3a3a9a187f6eef72649bc | 62,357 |
import os
def get_model_test_files():
"""Get the model test files."""
_ignore_files = [
"test_modeling_common",
"test_modeling_encoder_decoder",
"test_modeling_flax_encoder_decoder",
"test_modeling_marian",
"test_modeling_tf_common",
"test_modeling_tf_encoder_de... | 3672eecd928148e51a81c9a3381da2b0f0f40a7b | 62,358 |
def asarray(a, dtype=None):
"""
Converts the input to tensor.
This function converts tensors from an array-like object.
Args:
a (Union[int, float, bool, list, tuple, numpy.ndarray]): Input data, in
any form that can be converted to a tensor. This includes lists, lists of
tuples... | 041733fca2744d786ffa65960bf1189d02b646a2 | 62,359 |
def apply_mask_v2(mask: str, address: str) -> str:
"""
DOCTEST
>>> apply_mask_v2(mask='000000000000000000000000000000X1001X', address='000000000000000000000000000000101010')
'000000000000000000000000000000X1101X'
"""
output = "".join([address[i] if mask[i] == "0" else mask[i] for i, _ in enumer... | 1865b59317ed394bea4ea658f1acfd4277521b59 | 62,360 |
def gauss_weight(patch_shape, patch_sigma=3):
"""
Gaussian patch weight
"""
patch_x, patch_y = np.meshgrid( np.arange(-(patch_shape[1]//2),patch_shape[1]//2+1), np.arange(-(patch_shape[0]//2),patch_shape[0]//2+1), sparse=False, indexing='xy')
patch_weight = np.exp(-(patch_x**2+patch_y**2)/(patch_sigma**2),dtype=_d... | ca4a70b10e13b46ff92b6dd4fc0fb84110b13e43 | 62,361 |
import os
def add_certificate(cluster_name, data):
""" Add a certificate to a cluster that can be choose to be the active
cluster in the Asperathos section in execution time.
Raises:
ex.BadRequestException -- Missing cluster and
authentication fields in request
ex.UnauthorizedExcep... | 926031d0732418850968f8208fb95d98b3ab5d24 | 62,362 |
def grab(key, dictionary):
"""This is just a wrapper around the find function, getting a single item as opposed to the iterator."""
return [i for i in find(key, dictionary)][0] | 763560908d640fa933e0096144ada0f3772ed9b8 | 62,363 |
def eeg_rereference(eeg, reference="average", robust=False, **kwargs):
"""EEG Rereferencing
This function can be used for arrays as well as MNE objects.
EEG recordings measure differences in electrical potentials between two points, which means the
signal displayed at any channel is in fact the differ... | e0f98644808e9ce50e5b5acda31a2829e96b5544 | 62,364 |
import numpy
def extract_slits(slits, spline_x, im, order=2, padding=0):
"""
this function extracts the individual spectra from the MOS image using the
slit positions determined by get_slits. the slit positions are fitted using
a spline, padded with a zero mask and then extracted.
"""
y_dim, x... | 932ed0a79ada8c66a2500dce1b82ca86581fad3f | 62,365 |
from datetime import datetime
import logging
def jwt_auth(login: str, token: str, conf: dict) -> bool:
"""authenticate login against the given jwt token
The token must be valid.
Auth can be validated against 2 secrets: the current one and the old-one
This enable the possibility to change secrets more... | 3e01036f0df7db611fb4195d8810da19983c1331 | 62,366 |
from sys import path
def siteConfigFile():
""":return: The name of the site configuration File"""
if pyFoamSiteVar in environ:
return path.join(siteDirectory(),_pyFoamConfigName)
else:
return None | 80aa740551508238200f02f7b5df69634acd2e86 | 62,367 |
from cp_banner import Banner
from cp_planoaquisanual import Planoaquisanual
from cp_procedimento import Procedimento
def main():
"""Funçao index"""
print('Init do main_route')
#window_id = str(get_window_id())
print('1')
#set_base_context(window_id)
print('2')
#ctx_dict = get_context(windo... | 850469e976deae46a4509a717640b0c8b469096c | 62,368 |
def _first_true_index(bools):
"""
Given a pandas Series of bools, returns the index of the first occurrence
of `True`. **Index-based, NOT location-based**
I.e., say x = pd.Series({0: False, 2: False, 4: True}), then
_first_true_index(x) will return index 4, not the positional index 2.
If no val... | 4d0cc2d2d3f53f5c73653aeafce7b6128a99d204 | 62,369 |
from datetime import datetime
def valid():
"""Проверить, валиден ли токен"""
json = request.get_json()
if "token" not in json:
return errors.wrong_payload("token")
token = json["token"]
actual_token = Token.get_or_none(
(Token.token == token) & (Token.token_type == "access")
... | 35ff542ebb226224b78d27fbfbd60257ccbc587e | 62,370 |
from typing import OrderedDict
def gather_sim_results(m, scenario, input_params_dict, is_dynamic_rcr=False):
"""
Gather dataframes and dictionaries into master results dictionary.
:param m:
:param scenario:
:param input_params_dict:
:param is_dynamic_rcr:
:return: Dictionary containing d... | 29ed909832d4b70136ad4e50ad51950ecae2b059 | 62,371 |
from networkx.algorithms.components import connected_components
from networkx import connected_component_subgraphs
def connect_components(graph, pos_attr, length_attr=None):
""" connects all components by iteratively inserting edges between
components that have minimal distance.
`graph` is a networkx... | 1f480044f999238af001a815e33b16324deb1d36 | 62,372 |
import warnings
def set_showlib(name):
"""Set library for live video view"""
out = CDDMConfig.showlib
if name not in ("matplotlib", "cv2", "pyqtgraph"):
raise ValueError("Unsupported library")
if name == "cv2" and not CV2_INSTALLED:
warnings.warn("cv2 is not installed so it can n... | a076465bcc8e69bc27a6957df9fd604909adcb39 | 62,373 |
import math
import zipfile
import os
def draw_region(region, plate, output_dir):
"""
Pull a TileRegion from the region_queue.
Render the TileRegion to KML and write it to disk.
Create a libkml NetworkLink object for the file and put it on the netlink_queue.
"""
goverlays = []
tiles = sea... | 1793d827c826d6cf8efdba17796e960e87450fd4 | 62,374 |
def repr(x):
""" Return the string representation of 'x'.
"""
if hasattr(x, '__repr__'):
if callable(x):
return x.__repr__(x)
return x.__repr__()
JS("""
if (x === null)
return "null";
if (x === undefined)
return "undefined";
var t ... | ea99baf8e122c17cd4227abed04386f90c18bd6e | 62,375 |
def combineBoundingBoxes(a, b):
""" Retrun wxRect as a combination of source bounding boxes """
x1 = min(a.GetX(), b.GetX())
y1 = min(a.GetY(), b.GetY())
x2 = max(a.GetX() + a.GetWidth(), b.GetX() + b.GetWidth())
y2 = max(a.GetY() + a.GetHeight(), b.GetY() + b.GetHeight())
# Beware that we canno... | 03a05881550790e6fef1f1da265aef34cbc05f32 | 62,376 |
import tqdm
def UCB(bandits, horizon, eps=0.1):
"""
requires :
Bandit - List with Bandit objects as elements already
initiated with respective probability values.
returns :
reg - Expected cumulative Regret
Simulates the Upper Confidence Bound algorithm
- at time t define
U... | ce7e0d6c9991971dcaff820e12c9a10a606cc960 | 62,377 |
def separate_graph(edges):
""" Split graph into disconnected components.
Args:
edges (:class:`numpy.ndarray`): edges of the graph.
Returns:
An array of indices indicating the component each edge belongs to.
"""
separator = MeshSeparator(edges);
separator.set_connectivity_type(M... | 7229d61498bbc10aa9c388fd70a2a01d28d10898 | 62,378 |
def get_init_time(run_time, fetch_metadata):
"""Determine the most recent init time for which all forecast data is
available."""
run_finish = (pd.Timedelta(fetch_metadata['delay_to_first_forecast']) +
pd.Timedelta(fetch_metadata['avg_max_run_length']))
freq = fetch_metadata['update_fre... | b409c49ea41eee91421a0229539cc62e00d5960b | 62,379 |
def sum_fibs(limit):
"""Sums even Fibonacci numbers upto `limit`
Args:
limit (int) : The limit the sum will be calculated to
Returns:
int : The sum of even Fibonacci numbers upto `limit`
"""
previous = 0
current = 1
future = 1
result = 0
while True:
future ... | 7e515e46880240f670bfd47fb54ac72768aac841 | 62,380 |
from typing import Dict
def associations_to_all_features(
table: str,
cohort_id: str,
obj: AllFeaturesAssociation = Body(
...,
example=ASSOCIATIONS_TO_ALL_FEATURES_EXAMPLE,
),
conn=Depends(get_db),
api_key: APIKey = Depends(get_api_key),
) -> Dic... | fa241a642d1eaa76192006c1493ca3c57466a600 | 62,381 |
def Tc(grav):
"""Function to Calculate Gas Critical Temperature in °R"""
#grav gas specific gravity
return 169.2 + 349.5 * grav - 74 * grav ** 2 | 3ad5f19b9868b05b77482db31080107723c3b303 | 62,382 |
def get_laram_details():
"""
"""
return render_template("alarmdetails.html") | cb66dff10542cff31a3f2f036450e9ab481228f9 | 62,383 |
def _combine_dict(train_dict, eval_dict, train_idx, eval_idx):
"""Recursive helper function that combines dict of tensors from two splits
into one tensor using provided indices
Parameters
----------
train_dict : dict
Dict containing tensors from `train_split`. Format
expected to ma... | 8f1969efafd04297df762df7b898c6a6b23f3ffb | 62,384 |
def get_training_datasets_dir() -> str:
"""
Get the training datasets directory of the project.
"""
return f"{get_data_dir()}/training_datasets" | 5e31b381c7380bffe9fb47c595e848e98b433492 | 62,385 |
def _Backward3a_T_Ps(P, s):
"""Backward equation for region 3a, T=f(P,s)
>>> "%.7f" % _Backward3a_T_Ps(20,3.8)
'628.2959869'
>>> "%.7f" % _Backward3a_T_Ps(100,4)
'705.6880237'
"""
I=[-12, -12, -10, -10, -10, -10, -8, -8, -8, -8, -6, -6, -6, -5, -5, -5, -4, -4, -4, -2, -2, -1, -1, 0, 0, ... | 90e87dd41a590e4c138165d07e67416706c04aef | 62,386 |
def sample_normalize(masked_counts, settings):
"""Normalize a UMI count table sample-wise."""
filter_level = settings["copyStableLevel"]
filter_values = settings["copyStableValues"]
col = masked_counts.columns
all_values = col.get_level_values(filter_level)
if filter_values == "none":
fi... | 8d09bebe40327a6ef492a3ead4624de254b88eeb | 62,387 |
def collect_nested_symbols(normalized_symbol):
"""
from a symbol object, collect nested symbols
:param normalized_symbol: used to collect nested symbols
:return: iterable of nested symbols
"""
dict_values = collect_nested_symbols_in_object_dict(normalized_symbol)
nested_code_objects = collec... | ac35ceb7b4c4d693e7e4698a8faa77ab6fa9616a | 62,388 |
def ptp_header16():
"""
This method returns the ptp header definition
"""
return read_template('template/headers/ptp16.txt') | 022a66a5502b5bf0819bc9bf069b7362cb6e153b | 62,389 |
def update_graph(ctg_value, num_value, chart_choice):
"""
This function will update the plot base on the radio button and the selection from two dropdown bar
param ctg_value: this is the category value selection from the dropdown bar
param num_value: this is the numerical value selection from the dropd... | c346d1e0d324066cf3b40c323a9cfcc5f922095e | 62,390 |
def parse_expression(src):
"""Returns the AST of given identifier.
Args:
src: A piece of code that represents a single Python expression
Returns:
A gast.AST object.
Raises:
ValueError: if src does not consist of a single Expression.
"""
node = parse_str(src)
assert isinstance(node, gast.Modul... | 477efdfb9c4c19ba652928d73316f127f750cd4e | 62,391 |
def constrain_rgb(rgb, inplace=False):
"""
If the requested RGB shade contains a negative weight for
one of the primaries, it lies outside the colour gamut
accessible from the given triple of primaries. Desaturate
it by adding white, equal quantities of R, G, and B, enough
to make RGB all posit... | 64291cea625d6ef495e2203fbc77cfec3d14a896 | 62,392 |
def changeFrom12To24(aString):
"""
Changes the format from am/pm to 24h system.
:param aString: String representing an hour value.
:return:
"""
if aString == "1":
aString = "13"
if aString == "2":
aString = "14"
if aString == "3":
aString = "15"
if aString == ... | 3a5432a4d1dc6672445b0df9ccb09edd335dacce | 62,393 |
def is_git_repo(repo_path):
"""Checks if a given path is a git repo
Args:
repo_path (os.path): path to the dir that needs to be tested to see if the dir is a git repo
Returns:
bool: True if path is a git repo.
"""
try:
_ = git.Repo(repo_path).git_dir
return True
... | 11d40690f8973b3307a340094596cbaf161a7490 | 62,394 |
from typing import Tuple
def _get_planar_roi_reference_item(
group_item: ContainerContentItem,
) -> Tuple[Code, ContentItem]:
"""Get the content item representing a planar measurement group's ROI.
Parameters
----------
group_item: highdicom.sr.ContainerContentItem
SR Content Item represen... | 618595341bdaf32d747488855df8d1e982b532e4 | 62,395 |
def _parse_to_last_comment(comments):
"""Unpack to get the last comment (hence the -1) or give '' when there is none"""
return [(c[-1]['comment'] if hasattr(c, '__len__') else '') for c in comments] | ecde5f3d6df3278c5ac1e600241c1afd2f553a1b | 62,396 |
def softmax_cross_entropy_with_logits(labels, logits, name=None):
"""Compute the softmax cross entropy with contiguous labels.
Examples:
```python
labels = tf.constant([[0., 1., ], [1., 0.]], dtype=tf.float32)
logits = tf.constant([[0.5, 0.5], [0.3, 0.7]], dtype=tf.float32)
print(tf.nn.softmax... | d297ec996ff97b7db79290529a3c2585ac15dc0b | 62,397 |
import torch
def lengths_to_encoder_padding_mask(lengths, batch_first=False):
"""
convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor
Args:
lengths: a (B, )-shaped tensor
Return:
max_length: maximum length of B sequences
encoder_padding_mask: a (max_length, B) binary... | a86b2f1d79a364d5d6ddc8d4fd78eed911056021 | 62,398 |
def parse_since(since_str):
"""A utility function to help parse a since string."""
if since_str == 'all':
since_date = None
else:
try:
since_date = parse_date_relative(since_str)
except TypeError:
since_date = None
return since_date | 03b40e1e17571967361c2b487c762b6de2913f96 | 62,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.