content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import time
def runtime():
"""Gibt die Zeit in Seknden zurück, die das
Script bereits läuft."""
return time.time() - START_TIME | db31d5a6efb17c0f07007e9d1aae7d55b95feac1 | 66,335 |
async def set_bot_stats_api(request: Request, bt: BackgroundTasks, bot_id: int, api: BotStats, Authorization: str = Header("INVALID_API_TOKEN")):
"""
This endpoint allows you to set the guild + shard counts for your bot
"""
id = await db.fetchrow("SELECT bot_id, shard_count, shards, user_count FROM bots... | 5bb1287f81a06cfe5a98daf2f8ccae45ac91a388 | 66,336 |
def rate_limit(task_name, rate_limit, destination=None, **kwargs):
"""Set rate limit for task by type.
:param task_name: Type of task to change rate limit for.
:param rate_limit: The rate limit as tasks per second, or a rate limit
string (``"100/m"``, etc. see :attr:`celery.task.base.Task.rate_limit`... | 5a1d1595bc39bcf59ee4c6884ad63980ff21e6dd | 66,337 |
def allsensors():
"""Page for viewing all sensors."""
data = Sensor.query.all()
# data = Sensor.query.filter_by(name='*').all()
script_root()
if data:
return render_template('public/allsensors.html', data=data, request=request)
else:
return render_template('404.html') | e9ef29012fbebf114bc124a1bc8cd5abf33efbef | 66,338 |
def _Py_ISUPPER(ch):
"""
Equivalent to the CPython macro `Py_ISUPPER()`
"""
return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.UPPER | 803ffb2d495fa002d2b3a3afbfffa5541709eaaa | 66,339 |
def get_h_inv(z_val, OM=0.27, OL=0.73):
"""Integrand for calculating comoving distance.
Inputs:
z_val -- redshift value integrand is evaluated at.
OM -- matter density parameter. Defaults to 0.27.
OL -- dark energy density parameter. Defaults to 0.73.
"""
OK = 1.0 - OM - OL
H = np.sq... | 550086c79ad295382d614f29d659b028cd50d2a2 | 66,340 |
def get_configured_interfaces(xml_filter):
"""
Main method that retrieves the interfaces from config via NETCONF.
"""
with manager.connect(host=HOST, port=PORT, username=USER,
password=PASS, hostkey_verify=False,
device_params={'name': 'default'},
... | 87d114dabca85c00142bc5eb129157dbf636a326 | 66,342 |
import logging
def getInitLogger(module: str, **kwargs) -> logging.Logger:
"""Configure and initialize logging, then return a Logger for ``module``.
Parameters are passed to `logger_config`.
:param module: Name of module to be logged
"""
pywikibot.bot.init_handlers()
logging.config.dictConfig... | fcacc1c411e84ed91feb641742f160251811e1a9 | 66,343 |
from datetime import datetime
def is_date(value):
"""
Check if `value` is a date object.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a date object.
Example:
>>> import datetime
>>> is_date(datetime.date.today())
True
>>... | 3815928c9d57bb96ab107b5f74892837cea3123e | 66,344 |
import torch
def get_img_array(imgtensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
"""imgtensor: ([C,H,W],device=cuda)"""
denormimg = (
imgtensor.cpu()
.permute(1, 2, 0)
.mul_(torch.tensor(std))
.add_(torch.tensor(mean))
)
imgarray = denormimg.numpy()
... | ddc3e77c19f22bd928bee45c6d6b699d962f2aa8 | 66,345 |
def snake_bottom_middle_short():
"""
|===========|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|·····ox····|
|===========|
"""
return Snake.from_dict(
*... | 11a52b88f5e8501c80dc6e416ec3f3d569e993e1 | 66,346 |
def reachable_form(xsys):
"""Convert a system into reachable canonical form
Parameters
----------
xsys : StateSpace object
System to be transformed, with state `x`
Returns
-------
zsys : StateSpace object
System in reachable canonical form, with state `z`
T : (M, M) rea... | 7eaaa82254bcce1703de7567e49b622647e3467b | 66,347 |
def email_to_tag(text: pd.Series) -> pd.Series:
"""Convert email to <EMAIL> tag.
Parameters
----------
text : pd.Series
Series of text data
Returns
-------
prepro_text : pd.Series
Text with encoded an email adress
"""
prepro_text = text.replace(regex=r'[\w\.-]+@[... | 60002b7b934f98f0f308f2e6f7aebe6f041bbf9e | 66,349 |
def get_source_position(source):
"""Return max x, y value of a SourceCatalog or catalog row"""
if isinstance(source, SourceCatalog):
x, y = source.maxval_xindex, source.maxval_yindex
else:
x, y = source['maxval_xindex'], source['maxval_yindex']
return x, y | 217c0be6bd8934a9a99e3ddb5ec3f5b2168f7b1b | 66,350 |
def raw_func():
"""
foo bar
baz
"""
return 12345 | 471716eed6860b8abd6a0e9129fe20e7eaadbdb4 | 66,351 |
def bilstm_net(data,
seq_len,
label,
dict_dim,
emb_dim=128,
hid_dim=128,
hid_dim2=96,
class_dim=2,
emb_lr=30.0,
is_prediction=False):
"""
Bi-Lstm net
"""
# embedding lay... | d4f7f9be04b762a8514afb18834a1919c45eec88 | 66,352 |
def conv2d(x, weight, bias=None, stride=1, pad=0,
dilation=1, groups=1, padding_mode='zeros'):
"""Convolution 2D."""
# pylint: disable=unused-argument
validator.check_value_type('stride', stride, (int, tuple), None)
if isinstance(stride, int):
stride = (stride, stride)
elif len(st... | e50f21818f3bbb670e46494ad244e12110fea29d | 66,353 |
def green(room, message, *args):
"""Send a green message."""
return _color(room, message % args, 'green') | 8349b67580ed329969cf69ad8aca0f3dce37d93b | 66,354 |
def pca_3d_loadings(pca, xvars, select_components=None, cmap=None,
text_settings=None):
"""Show contributions to three principal components.
Parameters
----------
pca : object like :class:`sklearn.decomposition._pca.PCA`
The results from a PCA analysis.
xvars : list of s... | f4aabd1f0093e3729721fe7465e0a0a61d6efb05 | 66,355 |
def is_hex_str(value, chars=40):
# type: (str, int) -> bool
"""Check if a string is a hex-only string of exactly :param:`chars` characters length.
This is useful to verify that a string contains a valid SHA, MD5 or UUID-like value.
>>> is_hex_str('0f1128046248f83dc9b9ab187e16fad0ff596128f1524d05a9a77c... | f9438238b55a8b8bbe4f29f81046eb39c09423c5 | 66,357 |
import random
def generate_token(length=64):
"""Generate a random token.
Args:
length (int): Number of characters in the token.
Returns:
Random character sequence.
"""
_allowed = 'abcdefghijklmnoprstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-_$'
token = ''.join(random.System... | b1cc37216ed43e8d1d3c86e9817e87ab9833bfdd | 66,358 |
from scipy.optimize import fsolve
from math import log
from typing import Iterable
def tsat(p, bounds = False):
"""Saturation temperature (deg C) as a function of pressure (Pa).
If bounds is True, return None if the pressure is out of range."""
if bounds:
ok = (sat(0.01) <= p <= Pc1)
else: ok ... | ae6864547263fe05c165295eef9d317acb62ba73 | 66,359 |
from datetime import datetime
def calc_max_uptime(reboots):
"""Parse the passed in reboots output,
extracting the datetimes.
Calculate the highest uptime between reboots =
highest diff between extracted reboot datetimes.
Return a tuple of this max uptime in days (int) and the
... | 6f7d02bc17c16d4185e566646a70abe840934af3 | 66,360 |
import string
def get_number(s, cast=int):
"""
Try to get a number out of a string, and cast it.
"""
d = "".join(x for x in str(s) if x in string.digits)
return cast(d) if d else s | f788bfd13cc7234ca5f290ed047ec9b8bf8acc9b | 66,362 |
import hmac
def get_auth_hmac_from_key(auth_key):
""" Default instanciation of HMAC
:param bytes auth_key: secret key for signing data
:rtype: hmac.HMAC
"""
return hmac.HMAC(auth_key, hashes.SHA512(), backend=default_backend()) | c0b1539242d071768dfc897fa13a55ea2d2d7141 | 66,363 |
def maybe_fail_slow(executable, promise, plan, fail_slow=False):
"""Executes executable respecting fail-slow semantics if requested.
:param executable: The callable to execute.
:type executable: A no-argument callable.
:param promise: The promise the executable's product satisfies.
:type promise: :cl... | e593b31023dd4b56759fca2b96f7e54f63ec876d | 66,364 |
def get_errors():
"""
"""
errors_dict = {
'ReadCsvError': _('Inputed csv file not valid.'),
'ReadDatasetFromFileError': _('File not valid'),
'AddInDB': _('Failed to add object in database.'),
'UpdateInDB': _('Failed to Update object in database.'),
'DeleteInDB': _('Fa... | dffa307ecbc37f12c7b718c027c4ca135c22f4bd | 66,365 |
import uuid
def file_generator(size=2048):
""" Create a bogus file and returns it's name.
:param size: size in bytes
:returns: The name of the generated file.
"""
fn = '/tmp/rucio_testfile_' + uuid()
execute('dd if=/dev/urandom of={0} count={1} bs=1'.format(fn, size))
return fn | b64413f5902df6293d0b414e4cbb480a7be9254c | 66,366 |
def clean_up_dl_objects(data):
"""
Because dl objects need to be parsed out of any dict into json format
before they can be rendered in the browser, yet we cannot just do
json dumps because then they'll be strings...but they need
to be objects to be rendered properly.
"""
if isinstance(data,... | 992388559bbb2953d7e6640a61e6f113f3001db1 | 66,367 |
def spatialccd(jdata: list) -> list:
"""
We can't really guarantee what order (pixel wise) the CCD data is in. This aligns it
in a way that makes sense spatially, which is good for output to rasters.
Args:
jdata: initial JSON deserialization of change results for a chip
Returns:
n... | b21603fabed3fd0b1a69cefae0c72ab715d3341e | 66,368 |
def OpenDocumentText():
"""
Creates a text document
@return an OpenDocument instance with text mimetype
"""
doc = OpenDocument(u'application/vnd.oasis.opendocument.text')
doc.text = Text()
doc.body.addElement(doc.text)
return doc | 9240a85dd8efe3f1ece8210dd116a8be4485ca41 | 66,369 |
import numpy
def get_spherical_coordinates(xyz):
"""Compute spherical coordinates (r, theta, phi) for X,Y,Z point.
:param array xyz: column vector (3 row x 1 column numpy array)
:return: tuple of r, theta, phi for input coordinate
"""
r = numpy.linalg.norm(xyz)
if 0 == r:
return numpy... | 894fe52e46b55b37e9db6b447d6061bc1167518c | 66,371 |
def csr_scale_columns(*args):
"""
csr_scale_columns(int n_row, int n_col, int Ap, int Aj, signed char Ax,
signed char Xx)
csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned char Ax,
unsigned char Xx)
csr_scale_columns(int n_row, int n_col, int Ap, int Aj, short Ax, short Xx... | b9221dc01a99466deae29cbd5d3144c2f2d2402f | 66,372 |
import torch
def norm_spherical(cartesian):
"""
@params cartesian coordinate
@return normalize spherical coordinate in [-1,1]
"""
cartesian_len = torch.norm(cartesian, dim=-1)[...,None]
if len(cartesian.shape) == 2:
cartesian_len = cartesian_len.expand(-1, 3)
elif len(cartesian.sh... | bdc95e66b035229cd6d1e07627545545170f92e2 | 66,373 |
import sympy as sp
def MaxCut(nqubits, dense=True):
"""Max Cut Hamiltonian.
.. math::
H = - \\sum _{i,j=0}^N \\frac{1 - Z_i Z_j}{2}.
Args:
nqubits (int): number of quantum bits.
dense (bool): If ``True`` it creates the Hamiltonian as a
:class:`qibo.core.hamiltonians.... | a8c641e3d30e172dc7628ac7ef68c6fc61e7e4f3 | 66,377 |
import socket
def reverseNameFromIPv6Address(address):
"""
Return a reverse domain name for the given IPv6 address.
"""
# Expand addresses that are in compressed format eg ::1
fullHex = "".join(
"%02x" % (ord(c),) for c in socket.inet_pton(socket.AF_INET6, address)
)
tokens = list(... | 86991385c0585d6978e8f65de2c6b3b7209ab1f0 | 66,379 |
import re
def validate_duration(duration: str) -> str:
"""Validates time input for job duration."""
pat = re.compile(r"^([0-9]+([dDhHmMsS]?))?$")
if not pat.match(duration):
logger.error(f'Invalid time value given: {duration}')
raise ArgumentTypeError(f'Invalid time value given: {duration... | 804adbf0f2ba9186e5f2d27a0b821bf210a2a593 | 66,380 |
def get_xml_version(version):
"""Determines which XML schema to use based on the client API version.
Args:
version: string which is converted to an int. The version string is in
the form 'Major.Minor.x.y.z' and only the major version number
is considered. If None is provided... | b70a20afe440638472bc946242f7bc2c094a0526 | 66,381 |
import json
import re
def sd_datatype_mapping(XNAT, project):
"""
Method to get the Datatype mapping from Project level
:param XNAT: XNAT interface
:param project: XNAT Project ID
:return: Dictonary with scan_type/series_description and datatype mapping
"""
sd_dict = {}
if XNAT.select... | b8a4c4e15408b2d6c83a467dac1d7dfc21f9059f | 66,382 |
def power(lhs, rhs):
"""Power with auto-broadcasting
Parameters
----------
lhs : tvm.Tensor or Expr
The left operand
rhs : tvm.Tensor or Expr
The right operand
Returns
-------
ret : tvm.Tensor or Expr
Returns Expr if both operands are Expr.
Otherwise ret... | e6b3c465f3906eeb931f6d28d83ea7e146178507 | 66,383 |
def export_all_games_pgn(database, filename):
"""Export all database games in PGN export format."""
if filename is None:
return True
rr = chessrecord.ChessDBrecordGame()
rr.set_database(database)
all_games_output = None
no_games_output = True
games_for_date = []
prev_date = None
... | 30838512e22dd66747ad5ff46c9b4845ca31a776 | 66,384 |
def get_provider():
"""
Returns the singleton AuthorizationFilter instance
:rtype:
:class:`vmware.vapi.security.authorization_filter.AuthorizationFilter`
:return: AuthorizationFilter instance
"""
return _authz_filter | 4ea67bdc73cfab28f9aee9c0dfdc84de5b33753c | 66,385 |
def get_list_parsers_url(args):
"""Returns list parsers endpoint URL for corresponding region and env."""
url = f'{get_connecting_url(args)}/tools/cbnParsers'
print(f'Connecting to: {url}')
return url | 976da93d007d482d573a8204fbac9b0c71b596e5 | 66,386 |
def remove_whitespace(tokens):
"""Remove any top-level whitespace in a token list.
Whitespace tokens inside recursive :class:`~.token_data.ContainerToken`
are preserved.
:param tokens:
A list of :class:`~.token_data.Token` or
:class:`~.token_data.ContainerToken`.
:return:
A... | 05a0c2d745544e1e60e86539f38e84e8c03d7c0c | 66,387 |
def create_avg_stoplines_df(stoplines_df_name):
"""Create an aggregated stoplines_avg_df with the average stopline X, Y for each link and number of lanes"""
stopline_avg_df = stoplines_df_name.groupby('Link_ID')['stopline_X'].mean().reset_index(name='mean_X')
stopline_avg_df['mean_Y'] = stoplines_df_name.gr... | 284d22d121cb495b95e61da4c45c107b9cfd7a24 | 66,388 |
def wsl_host_docker_path(path):
"""
Returns the windows path with forward slashes. This is the format docker
wants in the -v switch.
"""
winpath = windows_drive_path(path)
return f"/{winpath[0].lower()}{winpath[2:]}" | 9a08c68709ae0b778ef248bdfb8b6c79fe66c330 | 66,389 |
def wrap(value):
"""
Wraps the given value in a Document or DocumentList as applicable.
"""
if isinstance(value, Document) or isinstance(value, DocumentList):
return value
elif isinstance(value, dict):
return Document(value)
elif isinstance(value, list):
return DocumentLi... | 839e29802413061d4b2e48d771346ad98e6e7495 | 66,390 |
def validate_gt(value_name, value, low_lim):
"""Raise error if value not greater than lower limit or wrong type.
Parameters
---------
value_name : str
Name of value being tested
value : int, float, numpy.ndarray, pint.Quantity
Value to be tested
low_lim : type(value)
``v... | 11e3f215daf77cf86842dc5a7d86ef9550dc709e | 66,391 |
def create_grid(dataset: list) -> str:
"""
Create a table grid of the github users
Args:
dataset (list): The dataset to create the table from, in this case, the list of github users.
Returns (str): table grid of github users
"""
row_length = 7
html_card = ''
for i in range(0, l... | 8cd9efaa01ece44ae06400e1e14456f80b2137fa | 66,392 |
import tqdm
import itertools
def get_annotated_phase_df(conflict_score_cost=0.1, unknown_score_cost=0.2):
"""
:return: Pandas DataFrame with the following columns:
site_id, journal_oid, journal_index, is_annotated, conflict_status, phases, {phase_name}_score, journal_text
"""
phase_annotatio... | aca08472e6e0167ba4d6d2d3e125fd452d4a2fbf | 66,394 |
import json
def update_resource(request):
""" View used to update a resource (file). """
post = json.loads(request.body.decode())
path = post.get("path")
if path is None:
return HttpResponseBadRequest(missing_parameter('path'))
try:
with open(join_fb_root(path), 'w') as f... | 4b9feae432b43f957f32185c9e0eb58b815ff60c | 66,395 |
def get_rs(key, ps, hps, imax):
"""
查 P + Pa~R 关系曲线,获取径流深 R
:param key: int 曲线代码
:param ps: list 各设计频率
:param hps: list 各设计频率下的24小时历时设计雨量
:param imax: float 最大初损值
:return: len(hps)D vector
"""
hps = np.array(hps)
pas = get_pas(ps, imax)
return np.array([get_relationship_val... | b0e6d5eb965540ab6f1db2d5a2fc16c28545e3b4 | 66,397 |
def caesar_1(char_in: str) -> str:
"""Character offset by 1 position.
Parameters:
char_in : function
Character of the source text.
Returns:
char_out : str
Character of the encrypted text.
"""
num = ord(char_in[0])
if (97 <= num <= 121) or (65 <= num <=... | 0a77b94ea2f2b1bf75334d633da0a8299f8c7960 | 66,398 |
import re
def _GetPlatformSpecificChromeDriverCompatibleVersionUrl(
google_chrome_version: str) -> str:
"""Returns the platform specific `chromedriver` version URL that is
compatible with the `Google Chrome` version given as `google_chrome_version`.
This function takes out the `major` version from the `goo... | 5757c6f233ed95f3f4a919791a49ab7bef261ee0 | 66,399 |
import ast
def tok_to_number(m: ast.Module, tok: Token) -> ast.Number:
"""Converts a numerical token into a number AST node."""
if tok.kind == TokenKind.CHARACTER:
number_kind = ast.NumberKind.CHARACTER
value = tok.value
elif tok.kind == TokenKind.KEYWORD:
assert tok.value in (Keyword.TRUE, Keyword.... | 553d231f9287046ff96d9877e1e0fdfa1ab52ffe | 66,400 |
from typing import Dict
import tqdm
def build_embeddings(embedding_size_y: int, word_indexes: Dict[str, int]) -> np.array:
"""
build embeddings to be used with basic models
"""
logger.info('build glove embeddings')
embeddings_indexes: Dict[str, np.array] = {}
# open glove 840 file
with op... | 42aeb1bd0ea652f96b9768d70d28f70291fff400 | 66,401 |
def dx_filter_coe(ver=0):
"""
差分算子discrete filter
用于correlate而非convolve
"""
##ver-1
if ver == 1:
l = sqrt(2)-1
a = zeros([3,3])
a[1,0] = -l/2
a[1,2] = l/2
a[[0,2],0] = -(1-l)/4
a[[0,2],2] = (1-l)/4
elif ver == 2:
a = zeros([3,3])
... | 6587e295c7124601c0a1364038f0d0f8eaf21141 | 66,402 |
async def api_count():
""" Aggregate api count at third minute of every hour """
task_result = await api_count_task()
return task_result | 350eab2124f0021d9478a1e58692d92c1a4b6dfe | 66,403 |
from typing import Set
def list_all_programs() -> Set[str]:
"""
List all programs registered by QCEngine.
"""
return set(programs.keys()) | 938bc95aa548d2fd722ad0f3298a15ab2accfb9c | 66,404 |
def get_runtime(job):
"""Returns the runtime in milliseconds or None if job is still running"""
if job.metadata.get("finished_time") is not None:
finished_time = job.metadata.get("finished_time")
else:
return None
start_time = job.metadata.get("scrapystats")["start_time"]
return floa... | 710d9d135ae7097bb85b0c3e8ea88d142da593e2 | 66,405 |
def apply(input):
"""
Calculates the dot product of two matricies using keras, with a tensorflow-gpu backend.
Returns the product as the output.
"""
input = InputObject(input)
z = K.dot(input.A, input.B)
# Here you need to use K.eval() instead of z.eval() because this uses the backend sessi... | 60f72e9afa59bebbfd590c5d965eadd4e0180fb4 | 66,406 |
def get_repos():
"""
Gets a list of repositories on the strands account
Return list of dictionaries
"""
return get_list('https://api.github.com/orgs/strands-project/repos')
# r = requests.get('https://api.github.com/orgs/strands-project/repos',auth=auth)
# if(r.ok):
# repos = json.lo... | 547fa9742cf986bfe103eac8cb7235a6c58247cc | 66,408 |
def get_video_duration(video_file):
"""Get video duration in seconds"""
return float(FFProbe(video_file).video[0].duration) | 75d5ac2a2f3b73880317c52f2f26cf797f832ce6 | 66,409 |
def classStatus(classes):
"""Determines the class status of the student based on credits.
:param dict classes:
The class information. Format:
classes = {className: {"grade": grade, "credits",
numCredits}}
:return:
The status of the student.
:rtype: str
"""
... | e629701553780665820c5532bd42797332c52ed0 | 66,410 |
def IsCorrectFuzzyNumberValue(value):
"""
All operations in fuzzy logic are executed with numbers in interval [0, 1].
"""
if IsNumber(value):
return (0. <= value) and (value <= 1.)
else:
print('{} not a real number in [0, 1], type = {}'.format(str(value), type(value)))
retur... | 40d39b5884daef46eafe2136d1a4b1ebbd38099e | 66,411 |
import requests
import regex
def get_available_airspaces():
"""
Gets and returns all available airspaces and their sizes from openaip
"""
try:
directory = requests.get(_airspace_url, timeout=5)
if directory.status_code == 404:
return _airspace_cache
airspaces = rege... | f464e853c47ed617c2f64b41b4a9f60a100b24b2 | 66,412 |
import torch
def bmtm(mat1, mat2):
"""batch matrix transpose matrix product"""
return torch.einsum("bji, bjk -> bik", mat1, mat2) | 9c00e371f4180da67b09be8e2cf35c3bab0785e3 | 66,413 |
def getdatasetnames():
""" retrieve the shortnames of all the datasets """
qset = Datasets.objects.all().values_list('datasetname', flat=True).order_by('id')
lst = list(qset)
return lst | 44359deff375c2c4525c3898ff7140c92bdfc4cc | 66,414 |
def get_residue_ranges(numbers):
"""Given a list of integers, creates a list of ranges with the consecutive numbers found in the list.
Parameters
----------
numbers: list
A list of integers
Returns
------
list
A list with the ranges of consecutive numbers found in the list
... | 0f263ee265574e64bec655ec2b5f35fdef2cf8af | 66,415 |
import re
def get_geometry_from_file_pdb(file_name, read_multiple=False):
"""
Reads a Conquest formatted file and the geometry of all structures in it
:param file_name: file name
:param read_multiple: read multiple files if available
:return: list of Geometry objects
"""
file_txt = open(f... | 61866d353e6d43a7f78e1a72316d916b258b4a8e | 66,416 |
import locale
import logging
def run():
"""Run atomic-reactor."""
locale.setlocale(locale.LC_ALL, '')
logging.captureWarnings(True)
setup_introspection_signal_handler()
args = parser.parse_args()
task = args.pop("func")
task_args = _process_global_args(args)
return task(task_args) | ad75d3cdf2e26d435c0768914130e01a7fcf1fed | 66,417 |
def instance_get_host(instance):
"""
Retrieve the host the instance is located on
"""
return instance['OS-EXT-SRV-ATTR:host'] | 0fef8cdf9e2ba7ac26e8a1ef2b2a1786cbe73d9d | 66,418 |
def get_ozone_conc(lat, lon, timestamp):
"""
Returns the ozone contents in matm-cm for the given latitude/longitude
and timestamp (provided as either a datetime object or a string in any
sensible format - I strongly recommend using an ISO 8601 format of
yyyy-mm-dd) according to van Heuklon's Ozone m... | 014b858fa7a8e4e594a10c44a004d46c6b7f575f | 66,419 |
def wavedecn(data, wavelet, mode='symmetric', level=None, axes=None):
"""
Multilevel nD Discrete Wavelet Transform.
Parameters
----------
data : ndarray
nD input data
wavelet : Wavelet object or name string, or tuple of wavelets
Wavelet to use. This can also be a tuple containi... | 88a77363c19839453aea7aae8402de18dfff7ea4 | 66,420 |
def instance_type_purge(context, name):
""" Removes specific instance_type from DB
Usually instance_type_destroy should be used
"""
session = get_session()
instance_type_ref = session.query(models.InstanceTypes).\
filter_by(name=name)
records = instance_... | 124d630b43b484d19532863e6ea786fc35a7c5e9 | 66,421 |
from datetime import datetime
def get_bbox_and_stat(scan_lst,
labels_lst,
obstacle_lst,
pipeline,
write_path=None,
OBB=False,
write_seg_id=False,
detailed=False,
... | 3823ebb670711ecd4f9194e400ef8a1d69f2269c | 66,422 |
from typing import Optional
def ceiling(node: NodeInput, name: Optional[str] = None) -> Node:
"""Return node which applies ceiling to the input node element-wise.
@param node: The node providing data to ceiling operation.
@param name: Optional name for output node.
@return The node performing element... | 0f258acc15fa47c053ed120c4502474540ca9d89 | 66,423 |
import random
def random_combination_with_replacement(iterable, r):
"""Random selection from itertools.combination_with_replacement(iterable, r)."""
pool = tuple(iterable)
n = len(pool)
indices = sorted(random.choices(range(n), k=r))
return tuple(pool[i] for i in indices) | ead7962804e63edaed82b39d10ee276022cd131f | 66,424 |
import csv
def loadcsv(filename):
"""
Reads an input CSV file.
Args:
filename (str): input file path.
Returns:
List containing all rows from the CSV file without headers.
"""
with open(filename, "r", encoding="utf-8") as f:
return list(filter(None, list(csv.reader(f)... | 442d0fdf7bcc160e98c83d7c848ec9477cf757fe | 66,426 |
from typing import Dict
import re
def apply_list_replace(input_str: str, replacements: Dict[str, str]) -> str:
"""
Apply a series of replacement on the input.
:param input_str: the string to be modified
:param replacements: a Dict regex -> replacement. Each item will be passed to re.sub()
:re... | 287e1a7763e7f56719adf566358c62156bcf668c | 66,427 |
def get_subject_name_from_ics_event_category(full_subject_name: str) -> str:
"""This function gets subject name from the categories in ics event
Args:
full_subject_name (str): Full subject name with format XXX_YYY_ZZZ
Return:
subject_name (str): Subject name
"""
full_subject_name_l... | 89af99b51d3cbe5193b5d22576963f27e43837e5 | 66,428 |
def line_search_wolfe2(f, myfprime, xk, pk, gfk=None, old_fval=None,
old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=None,
extra_condition=None, maxiter=10):
"""Find alpha that satisfies strong Wolfe conditions.
Parameters
----------
f : callable f(x,*arg... | 581484562c476ef096c753af449c6d0d338b5cda | 66,429 |
def rgb(duration=250, brightness=100, sleep=3000):
"""
Color changes from red to green to blue.
:param int duration: The duration to fade to next color, in milliseconds.
:param int brightness: The brightness of the transition.
:param int sleep: The time to sleep between colors, in milliseconds
... | 6392ade61c59ca1c41ae3b53c0e4516ef9c1d57b | 66,430 |
def overlappingDates(date_set1, date_set2):
"""
date_set1: (tuple) a tuple with the start date and end date
date_set2: (tuple) a tuple with the start date and end date
"""
# find recent date
if date_set1[0] > date_set2[0]:
start_date = date_set1[0]
else:
start_date = date_set... | 01e0a6f28b8e8780a1d347f5a8864887965d4a56 | 66,431 |
def use_middleware_script(container_type):
"""
Should the pilot use a script for the stage-in/out?
Check the container_type (from queuedata) if 'middleware' is set to 'container' or 'bash'.
:param container_type: container type (string).
:return: Boolean (True if middleware should be containerised)... | 74f93a0952bdd81e8b3c604e17082f86bb3ff93b | 66,432 |
def remove_events(all_time,
all_flux,
events,
width_factor=1.0,
include_empty_segments=True):
"""Removes events from a light curve.
This function accepts either a single-segment or piecewise-defined light
curve (e.g. one that is split by qua... | 9b2900d70cab8e68c4cf394ccbfb69cd8b44c526 | 66,435 |
def convolutional_model(input_shape):
"""
Implements the forward propagation for the model:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> DENSE
Note that for simplicity and grading purposes, you'll hard-code some values
such as the stride and kernel (filter) sizes.
N... | b904087a6645309247f19fcc45ba67402f3affd6 | 66,436 |
def softmax_column(Z):
"""Softmax function."""
exp_values = np.exp(Z)
return exp_values / np.sum(exp_values, axis=0, keepdims=True) | ed7aba6a94da589f9cd9aa32541fa6522e2f41ba | 66,437 |
def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ("y", "ye... | f6fbce54f7fe4bea906cc51d398d95cf2dd699e8 | 66,439 |
import warnings
def is_domain_malicious(subject: str, **kwargs) -> bool:
"""
Checks if the given domain is malicious.
.. warning::
This method may be removed in the future.
It is still available for convenience.
Please consider the following alternative example:
::
... | a525e881b00c61d4896ef07b6a8bb1a17ea023a5 | 66,440 |
from typing import Union
def serialize_attribute_value(value: Union[str, int, float, bool, None]):
"""
Serialize a value to be stored in a Magento attribute.
"""
if isinstance(value, bool):
return "1" if value else "0"
elif value is None:
return ""
return str(value) | a9d5b4f6d507672b594eb1c88d4d86c9bfc6bc11 | 66,441 |
def _str_decode(my_string):
"""Parse the string for objects and indexes and return a list.
Args:
my_string: A string object
Returns:
List of strings with strings resresenting mrsimulator objects and indexes.
Example:
>>> string = 'sys_0_site_0_isotropic_chemical_shift'
... | ea06f61a1f8b4b013a1e00f25e9de72721977e5b | 66,442 |
import torch
def get_activation(activation):
"""Given a string returns a `torch.nn.modules.activation`."""
if not isinstance(activation, str):
return activation
mapper = {
"leaky_relu": nn.LeakyReLU(),
"relu": nn.ReLU(),
"selu": nn.SELU(),
"tanh": nn.Tanh(),
... | b96544a56ff73d1ad03944f97e24859069ea000b | 66,443 |
def hidden_value(context=None, id='', value=''):
"""Generates a hidden input with the given id and value."""
return _return_or_write(context, '<input type="hidden" id="' + id + '" value="' + value + '">') | 8c5f96e8cc2c17d90ad55f673c0ccc654faafd86 | 66,444 |
def xcache_activation_command(jobid):
"""
Return the xcache service activation command.
:param jobid: PanDA job id to guarantee that xcache process is unique (int).
:return: xcache command (string).
"""
# a successful startup will set ALRB_XCACHE_PROXY and ALRB_XCACHE_PROXY_REMOTE
# so any... | 86050072785185cdcc7adcf59eafe930a6d30105 | 66,445 |
from operator import index
def times_householder_vector(A, H, j):
"""
Computes A * v_j where v_j is the j'th Householder vector in H.
Parameters
----------
A: k x M matrix to multiply by v_j.
H: M x k matrix of Householder reflectors.
j: The column of H from which to extract v_j.
Ret... | a649317b3252badfca61563bfd605804d1216b71 | 66,446 |
def mk_uni_port_num(intf_id, onu_id):
"""
Create a unique virtual UNI port number based up on PON and ONU ID
:param intf_id:
:param onu_id: (int) ONU ID (0..max)
:return: (int) UNI Port number
"""
return intf_id << 11 | onu_id << 4 | 3d348b9d6dc40f54d6f3667a8a5310a3d52b3d5d | 66,447 |
def CalculateNormalizedMoreauBrotoAutoAvFlexibility(ProteinSequence):
"""
####################################################################################
Calculte the NormalizedMoreauBorto Autocorrelation descriptors based on
AvFlexibility.
Usage:
result=CalculateNormalizedMoreauBrotoAutoAvFlexibility... | b32d741c01839feed9f76f3aca75c7c794a415fb | 66,448 |
import pickle
import pprint
def litmus_main(args):
"""
Prepare predictive model
"""
assert(args.load_state or args.scores_file)
if args.load_state:
# Load trained model + metadata
with open(args.load_state, "rb") as pkl_f:
model, featurizer, langs_list, langs_pivot... | c1bd857b71d4d2bedfa1049da5f15c236bd109db | 66,449 |
def token_to_eth_output(token_amount_to_sell: int) -> "Wei":
""" Constant Price Model implementation with fee. """
input_amount_with_fee = token_amount_to_sell * FEE_MODIFIER
numerator = input_amount_with_fee * ETH_RESERVE
denominator = TOKEN_RESERVE * 1000 + input_amount_with_fee
return Wei(numerat... | e3b88df5165282cf0e608d62864ce5122236fc1a | 66,450 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.