content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_text(root: ET.Element, tag: str):
"""Get the text attribute if it exists."""
elem = root.find(tag)
if elem is not None:
return elem.text
return None | 9644f636a043d0c79561f49e101e7b4286a4d3dc | 3,605,600 |
def star(fn):
"""Wrap function to expand input to arguments"""
return lambda args: fn(*args) | 4ec8eb075fda1b091cb780ef6af5f42284de96dd | 3,605,601 |
def modulo(x, m):
"""
Implements Vensim's MODULO function.
Parameters
----------
x: float or xarray.DataArray
Input value.
m: float or xarray.DataArray
Modulo to compute.
Returns
-------
Returns x modulo m, if x is smaller than 0 the result is given in
the range... | 62d4cc1e3e8eab62d1a4e0504905532a6b3f668f | 3,605,602 |
def dump(ret, output, outerr, parse_param_list, logger):
"""
parses result from method of same name in lo.Volume
"""
obj = parse_param_list["args"][0]
if ret:
raise VolServerLLAError("ret=%s, output=%s, outerr=%s" % (ret, output, outerr))
return True | 857114653c5dd8fa0de3183a456ba0beffc34cff | 3,605,603 |
def check_path(path,
unix_mode,
limited_doc_files,
error_trace,
closurized_namespaces,
ignored_extra_namespaces,
custom_jsdoc_tags,
dot_on_next_line,
check_trailing_comma,
debug_indenta... | fc8afd0297cef250f1bc07ee73d4bee41b7808e6 | 3,605,604 |
def load_dict(vocab):
"""
Load dict from vocab
"""
word_dict = dict()
with open(vocab, "r") as fin:
for line in fin:
cols = line.strip("\r\n").decode("gb18030").split("\t")
word_dict[cols[0]] = int(cols[1])
return word_dict | 9f19fd51713ed2ff51f1423a9aed12caeb01165d | 3,605,605 |
import re
def decode_header(fname):
"""Returns strings of bytes up to pad sequence that precedes sync pattern (0xAA995566)"""
with open(fname, 'rb') as FH:
# Header
hl = int(hexfromba((FH.read(2))), 16)
h = hexfromba(FH.read(hl))
if h != '0ff00ff00ff00ff000':
print... | 5ad4a8eb65a16c1fad5fe01233c9dfb21c420b48 | 3,605,606 |
import argparse
def _comma_separated_strings(string):
"""Parses an input consisting of comma-separated strings."""
error_msg = 'Argument should be a comma-separated list of strings: {}'
values = string.split(',')
if not values:
raise argparse.ArgumentTypeError(error_msg.format(string))
return values | cb552351fc40eb59fe7a60cd4064d25e040f0a7b | 3,605,607 |
import os
def get_orgs(cid):
"""Fetch the clubs and orgs from informix."""
orgs = []
phile = os.path.join(settings.BASE_DIR, 'sql/clubsorgs_student.sql')
with open(phile) as incantation:
sql = '{0} {1}'.format(incantation.read(), cid)
connection = get_connection()
with connection:
... | 1766f3713b41aa58985058f52381de9e6d410274 | 3,605,608 |
def idct2(block):
"""Compute a 2D inverse discrete cosine transform."""
return idct(idct(block.T, norm='ortho').T, norm='ortho') | 69fe99f28df96d914f4df5dd5145d97eeb329cdc | 3,605,609 |
def add_interval(x, y):
"""Return an interval that contains the sum of any value in interval x and
any value in interval y."""
lower = lower_bound(x) + lower_bound(y)
upper = upper_bound(x) + upper_bound(y)
return interval(lower, upper) | f2b3771cefcd482d067056f754407857a9054262 | 3,605,610 |
def _giant_component(network):
"""Returns the giant component of a network
Parameters
----------
network : networkx.Graph
the networkx graph on which giant component extraction is applied
"""
network_components = sorted(nx.connected_components(network), key=len, reverse=True)
return n... | 48b67e5d78e535d7b2faa724cf82a25629ac4655 | 3,605,611 |
def hubbard_sparse(j1, j2, dimension):
"""The Hubbard operator :math:`|j1\\rangle>\\langle j2|` is returned as a matrix of linear size dimension.
Parameters
----------
dimension: int
j1, j2: int
indices of the two states labeling the Hubbard operator
Returns
-------
sparse.csc_... | 5117a05d6ab4d3201f64d216735e25ab6b882107 | 3,605,612 |
def boost_conservation(x):
"""Returns an x=1 distribution for ejected nucleons"""
dist = np.zeros_like(x)
# dist[(x == np.max(x)) & (x > 0.9)] = 1.*20.
dist[x == 1.] = 1. / 0.115
return dist | cdf02dcf76eab88ad2a4b33498565ff28c9292b0 | 3,605,613 |
def build_conda_cfg_env(env=None, **kwargs):
"""
Configure conda for a specific environment
TODO build_venv_config
Args:
env (Env dict): :py:class:`dotfiles.venv.venv_ipyconfig.Env`
Returns:
env (Env dict): :py:class:`dotfiles.venv.venv_ipyconfig.Env`
"""
if env is None:
... | 46ee420037ea06753f842843bcbc29d5e29e5fee | 3,605,614 |
def convert2numeral(item, cls=int, default=None):
"""
Convert an argument to a new type unless it is `None`.
"""
try:
num = cls(item)
except (ValueError, TypeError):
num = default
return num | 4c2e741eb0d7bcf6d6450db7c49f14895e0f1b15 | 3,605,615 |
def buf_sk_oas_pcov_d0_n300(y: X_TYPE = None, s: dict = None, k=1, e=1):
""" OAS based estimator for IID observations """
# https://arxiv.org/abs/0907.4698
assert k == 1
return buf_sk_factory(cls=OAS, y=y, s=s, n_buffer=300, n_emp=10, e=e) | 04c3b899b4a72dc818897290eb46933385b7cf55 | 3,605,616 |
import os
def create_template_writer(directory_name):
"""
Factory function for TemplateWriter, ensures that the
directory exists, and creates it if necessary.
Args:
directory_name the name of the directory to place output files.
"""
if not os.path.isdir(directory_name):
os.makedirs(directory_na... | be5f0bc13a6e41f7bdcfd95a507a6cb05b555f2d | 3,605,617 |
async def parse_extra_fields(extra_buff):
"""
Parses extra buffer to the extra fields vector
:param extra_buff:
:return:
"""
extras = []
rw = MemoryReaderWriter(bytes(extra_buff))
ar2 = xmrserialize.Archive(rw, False)
while len(rw.get_buffer()) > 0:
extras.append(await ar2.va... | 7d931f3e7f0064f94c0358d6f78436d25195b6b2 | 3,605,618 |
def _bumps(x):
"""Computes the "bumps" signal.
Parameters
----------
x : ndarray
Inputs values of shape (n_samples,) with dtype float32 or float64
Returns
-------
output : ndarray
The value of the signal at given inputs with shape (n_samples,)
Notes
-----
Input... | 3544838a604c03f8125ce5987f24cdae96294084 | 3,605,619 |
import kerberos, base64
def _get_krb5_ap_req(service, server):
"""Returns the AP_REQ Kerberos 5 ticket for a given service."""
try:
status_code, context = kerberos.authGSSClientInit( 'moira@%s' % server )
kerberos.authGSSClientStep(context, "")
token_gssapi = base64.b64decode( kerbero... | b9913d66cb88c49458edda9f8b861d4133835c44 | 3,605,620 |
def config_invalid_keys(config):
# type: (Dict[str, Any]) -> List[str]
"""Returns a list of keys that exist in *config* and not in KEYS."""
return [key for key in config.keys() if key not in ConfigKeys] | 486c98d790940944148c8e692b33571a9106efb2 | 3,605,621 |
def internet_status():
"""
Get the internet connection status (Try to connect to an IP address).
Returns:
True if we have internet access, False otherwise.
"""
try:
urllib2.urlopen('http://{}'.format(test_IP), timeout=1)
return True
except:
return False | 96b1c8be5595b2bd84a7a9182a0dc1d77a3be5d0 | 3,605,622 |
def train_regression(net: Network,
dataset: pd.DataFrame,
max_epochs: int,
learning_rate: float,
batch_size: int = 1):
"""
Train net for a regression task.
The dataset consists of features and regression value (in the last c... | 9d119891df44cf49db1d6c6944736d643b135b69 | 3,605,623 |
def get_variables(problem, params={}):
"""
Create a hyperopt search space description for problem.
Parameters
----
params: dict - specifies options to manipulate how kinds of variables are encoded.
> int_conversion_mode -
> The variable type `int` is by default encoded using `quniform`, se... | 7101380de6286d978ec79730370b919d68e17dcf | 3,605,624 |
from eolearn.core import EOPatch, FeatureType
from eolearn.core import OverwritePermission
def save_raster_to_eopatch(rasterpath, dataname="raster", outpath=None):
"""
Save raster with one band to eopatch
rasterpath str
outpath str
dataname str
"""
with rasterio.open(rasterpath, ... | 05b01b24daba6a9f699709b7b784f5aa0ba8f1b4 | 3,605,625 |
async def test_access_token_verifier(monkeypatch, mocker):
"""Verify AccessTokenVerifier calls correct method of BaseJWTVerifier with correct parameters."""
class AsyncMock(mocker.MagicMock):
async def __call__(self, *args, **kwargs):
return super().__call__(self, *args, **kwargs)
mock_... | af705b98bc8583a6522dba48864b5127c56fd366 | 3,605,626 |
import os
def search_conda():
"""Search for a conda virtual environment."""
conda_prefix = os.environ.get("CONDA_PREFIX")
if conda_prefix is not None:
conda_include = join(conda_prefix, 'include')
conda_lib = join(conda_prefix, 'lib')
else:
conda_include = ""
conda_lib ... | 15b9d96ed315151281b74b88fd65b79b4eb316fe | 3,605,627 |
def py_cpu_nms(dets, thresh):
"""Pure Python NMS baseline."""
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
ke... | ac675c0598345f71679b5eeaee30f3644218b514 | 3,605,628 |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured data to conform to the schema.
"""
for entry in proc_data:
int_list = ['job... | f706c62442ac53d42c61be41a5df61664b4f7076 | 3,605,629 |
import typing
def exposures(package_name: str = None) -> typing.List[ManifestExposureNode]:
"""A list of all exposures defined in the dbt project.
Args:
package_name (str): Only return exposures from the specified dbt package.
Defaults to returning exposures from all packa... | 3851062664c2245c37908ffc1832578f0643df09 | 3,605,630 |
from typing import Concatenate
def Deeplabv3(weights='pascal_voc', input_tensor=None, input_shape=(512, 512, 3), classes=21,
alpha=1., activation=None, model_path=None):
""" Instantiates the Deeplabv3+ architecture
Optionally loads weights pre-trained
on PASCAL VOC or Cityscapes. This model... | 30ce064bae0a0a2078184cfc1f3ef662a60a4baa | 3,605,631 |
import os
def get_default_ca_certs():
"""Try to find out system path with ca certificates. This path is cached and
returned. If no path is found out, None is returned.
"""
if not hasattr(get_default_ca_certs, '_path'):
for path in (
'/etc/pki/ca-trust/extracted/openssl/ca-bundl... | 587412633b409128324c6e9ff39cddda93f00795 | 3,605,632 |
def download_urn(load=True): # pragma: no cover
"""Download scan of a burial urn.
Originally obtained from Laser Design.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
... | 78ad82c4b52b9859e14b246ad12d306374a88765 | 3,605,633 |
from typing import Counter
import sys
def compute_cnt(a_it, a_n_char=1):
"""Compute counts of classes and characters.
Args:
-----
a_it: iterator
iterator over pairs of class labels and text
a_n_char: int
length of character n-grams
Returns:
--------
(cls_cnt, char_cnt): (... | 48cf8ba32895ceed30b2cc8fe78d86f9fa687a0d | 3,605,634 |
import six
def NamespaceForURI (uri, create_if_missing=False):
"""Given a URI, provide the L{Namespace} instance corresponding to it.
This can only be used to lookup or create real namespaces. To create
absent namespaces, use L{CreateAbsentNamespace}.
@param uri: The URI that identifies the namespa... | 52024139661f2f88d116544967a417586b7b8f1e | 3,605,635 |
import os
def randomize_queries(queries):
"""
Formats the results `query.get_randomize`.
:type list
:param queries: Unformatted queries
:rtype str
:return Formatted queries
"""
if len(queries) > 0:
separator = ';' + os.linesep
return separator.join(queries) + separat... | 28b8db4ebb5ac476868808457f4f34f9d0418730 | 3,605,636 |
import re
def dna_to_re(seq):
"""
Return a compiled regular expression that will match anything described by
the input sequence. For example, a sequence that contains a 'N' matched
any base at that position.
"""
seq = seq.replace('K', '[GT]')
seq = seq.replace('M', '[AC]')
seq = se... | 86afb929b2281f0f875a1f11ca8cf36584b2f895 | 3,605,637 |
from io import StringIO
def load_data(data_file_url, window_size):
"""Loads data into preprocessed (train_X, train_y, eval_X, eval_y) dataframes.
Returns:
A tuple (train_X, train_y, eval_X, eval_y), where train_X and eval_X are
Pandas dataframes with features for training and train_y and eval_y a... | 08b7f0b5d401a861f8446dffbcf320141271d9dc | 3,605,638 |
def path_commands():
"""Gives a dictionary of all executable files in the environment's PATH
>>> import sys
>>> path_commands()['python'] == sys.executable or True
True
"""
commands = {}
for path_dir in paths():
if not path_dir.isdir():
continue
for file_path in ... | bb862197bca9ae74d9b5979e329648a4471456c3 | 3,605,639 |
import os
import urllib
def maybe_download(url, download_dir):
"""
Download and extract the data if it doesn't already exist.
Assumes the url is a tar-ball file.
:param url:
Internet URL for the tar-file to download.
Example: "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
... | 12fe38d62902a9690d68d279c58a6f7af7564a66 | 3,605,640 |
from typing import Callable
import time
def create_timer() -> Callable[[], float]:
"""Create a timer function that returns elapsed time since creation of the timer function"""
start = time.time()
def elapsed():
return time.time() - start
return elapsed | e97fbb8b6fded209d1e5659f548feac726d9cf04 | 3,605,641 |
import requests
import logging
def get_recent_posts_instagram(handle):
"""Api for basic details
Arguments:
handle {str}: username
Returns:
json -- returns basic details
"""
result = None
try:
url = "https://www.instagram.com/{}/?__a=1".format(handle)
response ... | a9e60be1d4f31e3c14831eaf64b5eb2ff43d249d | 3,605,642 |
def svn_io_start_cmd3(*args):
"""svn_io_start_cmd3(apr_proc_t * cmd_proc, char const * path, char const * cmd, char const *const * args, char const *const * env, svn_boolean_t inherit, svn_boolean_t infile_pipe, apr_file_t infile, svn_boolean_t outfile_pipe, apr_file_t outfile, svn_boolean_t errfile_pipe, apr_file_... | b675cf73d15e1019ef0923859bcaa7f0232cd11c | 3,605,643 |
def get_project(project_id):
"""
Get a project based on its ID.
Example request::
GET /projects/6890192d8b6c40e5af16f13aa036c7dc
"""
# NOTE: links{ cada experimento}
# NOTE: actions{ deleteExperiments, delte_project}
# NOTE: info{ parametros del proyecto}
api_control = current_ap... | c10fb257516a26a0ce84f7b9e65d44bef84e6a43 | 3,605,644 |
from typing import Union
def fix_nodata(
arr: np.ndarray,
nodata: Union[np.int32, np.int64, np.float32, np.float64]
) -> np.ndarray:
"""Set values close to nodata to nan.
Parameters:
arr: data array to fix
nodata: value used to represent nodata
Returns:
array with imposed... | d00826888a8d03aeabbbd6edf5f76cd93414910f | 3,605,645 |
import os
import logging
import requests
def download_file(filename, url, overwrite=False):
"""
Check if file exist and download it if necessary.
Parameters
----------
filename : str
Full filename with path.
url : str
Full URL to the file to download.
overwrite : boolean (... | 18a9458cc04eec3f713c21296358e2cc0fe497c3 | 3,605,646 |
def redis_set():
"""
# r.set('foo', 'bar')
r.set('food', 'mutton', ex=3) # ex过期时间(秒) 键food的值就变成None
r.setex("fruit2", 5, "orange") # 同上
r.set('food', 'mutton', px=3) # px - 过期时间(毫秒) 键food的值就变成None
r.psetex("fruit3", 5000, "apple") # 同上
print(r.set('fruit', 'watermelon', nx=True)) #只有n... | 9ea942001be00afeb62a78c143452efb4ae03434 | 3,605,647 |
def remove_base64(examples):
"""Remove base64-encoded string if "path" is preserved in example."""
for eg in examples:
if "audio" in eg and eg["audio"].startswith("data:") and "path" in eg:
eg["audio"] = eg["path"]
if "video" in eg and eg["video"].startswith("data:") and "path" in eg... | 44442b868ff57d57d65f63bc65b681c859a1ca52 | 3,605,648 |
from typing import Mapping
def recursive_update(old_dict, update_dict):
"""
Update one embed dictionary with another, similar to dict.update(),
But recursively update dictionary values that are dictionaries as well.
based on the answers in
https://stackoverflow.com/questions/3232943/update-value-o... | 7f0c4fdca6a58f8416e5f9c2762918fa776d8d9d | 3,605,649 |
import ast
def _convert_value(value):
"""
Parse string as python literal if possible and fallback to string.
Copied from sacred.arg_parser for performance reasons.
"""
try:
return _restore(ast.literal_eval(value))
except (ValueError, SyntaxError):
# use as string if nothing el... | d8117a733f2756ba99b4e8cb190fbc4994ada4a3 | 3,605,650 |
import copy
def merge_dicts(dict1, dict2):
"""Recursively merge two dictionaries.
Values in dict2 override values in dict1. If dict1 and dict2 contain a dictionary as a
value, this will call itself recursively to merge these dictionaries.
This does not modify the input dictionaries (creates an intern... | b3dccd6301be21a096bb3d299793b4cf1461c3d9 | 3,605,651 |
def convert_geoId(fips_code):
"""Creates geoId column"""
return 'geoId/' + str(fips_code).zfill(2) | 76c644d3f4d4da292d33b3e61e82eecfe7860434 | 3,605,652 |
def AddImplicitMethodsToTable(table):
"""Adds implicit methods to actions in table, if applicable."""
return table.row_filter(AddImplicitMethodsToRow) | 60721a1d75722a65e382fd502d404c1f8ead5b43 | 3,605,653 |
import operator
def _inline_arraycall(func_ir, cfg, visited, loop, swapped, enable_prange=False,
typed=False):
"""Look for array(list) call in the exit block of a given loop, and turn list operations into
array operations in the loop if the following conditions are met:
1. The exit... | 2f9558cb4181f535545d6245b1e904931d080515 | 3,605,654 |
def read_rmsd(fname):
"""
Reads the RMSD file at the given file name.
:param fname: The file's location.
:return: The values in the RMSD file.
"""
rmsd_values = []
with open(fname) as r_file:
row_val = None
for r_line in r_file:
try:
row_val = r_l... | 2404be832a65efc0c738ada03aa44f06b45cae1b | 3,605,655 |
import urllib
import urllib.request
import os
def download(download_url = None, filename_to_save = None):
"""function for python 2/3 compatible file download from url"""
if download_url is None or download_url == '':
np('[RPA][ERROR] - download URL missing for download()')
return False
#... | 67c0035283d69f769a88578f7ecc0caf0353d3d0 | 3,605,656 |
import re
def parse_ext(exp, exps, filters, mode, isfilter=False):
""" Parse one expression from a extended query.
Returns a dictionary of information about the search field used
Appends the search equry to exps
exp is the expression to parse
exps is a list of already pars... | 42a7ebcff26c0399ffbd47584bdd2cee1aeb6165 | 3,605,657 |
def adder_function(args):
"""Dummy function to execute returning a single float."""
loc, scale = args
return loc + scale | 7646bb1acc324f05c92268b78fefaa75283f812a | 3,605,658 |
def auto_correlation(x,
axis=-1,
max_lags=None,
center=True,
normalize=True,
name='auto_correlation'):
"""Auto correlation along one axis.
Given a `1-D` wide sense stationary (WSS) sequence `X`, the auto correl... | 6abb3715b63fc1a108d032f76986cf567e3de064 | 3,605,659 |
def get_pixel_dist(pixel, red, green, blue):
"""
Returns the color distance between pixel and mean RGB value
Input:
pixel (Pixel): pixel with RGB values to be compared
red (int): average red value across all images
green (int): average green value across all images
blue (int... | 763051e37a9f484667ea7e5afcaec9bc9c450c11 | 3,605,660 |
def offset_stress(e, s, eo = 0.2/100.0):
"""
Helper function to generate yield stress from offset stress/strain data
Parameters:
e: strain data
s: stress data
eo: strain offset
"""
iff = inter.interp1d(e, s)
E = s[1] / e[1]
eoff = opt.brentq(lambda e: iff(e) - E * (e - e... | ee4056060e6bdfe6fefd2ae5878c269ba45c8600 | 3,605,661 |
def BaselineSearchPath(all_versions=False):
"""Returns the list of directories to search for baselines/results, in
order of preference. Paths are relative to the top of the source tree.
If all_versions is True, returns the full list of search directories
for all versions instead of the current version that the... | 7df62c86813e1928708d8d190978ec3ded01a67c | 3,605,662 |
def get_event_detector_df(event: int, detector: int):
"""
Given detector and event returns corresponding df
:param event: event number
:param detector: detector number
:return: pandas dataframe
"""
df_path = get_event_detector_df_path(event, detector)
df = pd.read_parquet(df_path)
re... | c2dc91c10e3a3eaef0e2e9d42e5edea5a6aee076 | 3,605,663 |
def pad_sequences(sequences, tokenizer, sos_token='[CLS]', eos_token='[SEP]', pad_token='[PAD]', max_seq_len=512):
"""Pad a list of sequences (in text format) with the BERT tokenizer. It add a ``[CLS]`` and ``[SEP]`` tokens
at the begining and end of the truncated sentences (the sentences have ``max_seq_len`` l... | c6252def06c223b1a746dd025e22674d95fa4b49 | 3,605,664 |
def get_variants_in_gene_or_transcript(db, gene_id=None, transcript_id=None):
"""Return ExAC and gnomad variants in a gene or transcript
Args:
db: The mongo database object
gene_id, transcript_id: one and only one of these 2 arguments must be specified. This function will
query for ... | a486c12d393439c13a65bc7b904fe2d233df8a65 | 3,605,665 |
import requests
def get_api_results(url, id):
"""[summary]
Args:
url ([str]): [External API url]
id ([int]): [member id]
Returns:
[json]: [API request response]
"""
r = requests.get(url.format(id))
return r.json() | 4dc686c616f3ea9124c866b593d44bdc63e54d1d | 3,605,666 |
def get_group_pillow_old(pillow_id='GroupPillow', num_processes=1, process_num=0, **kwargs):
"""
# todo; To remove after full rollout of https://github.com/dimagi/commcare-hq/pull/21329/
This pillow adds users from xform submissions that come in to the User Index if they don't exist in HQ
"""
assert... | 80bf24b658c3e58d3813bb6d42defcb9c5e982d5 | 3,605,667 |
import codecs
def get_pagerduty_api_key(config_file):
"""Extracts PagerDuty Service Integration API Key from Splunk Config.
@param config_file: Full path to file containing Pagerduty API Credentials.
@type config_file: str
@return: PagerDuty Service Integration API Key.
@rtype: str
"""
co... | 10ad2530561c5848ca82e8d3922f57d26c00eda8 | 3,605,668 |
import json
def apply_filter(filter_mask, doc):
"""
Takes a JSON string as input and returns
JSON string as output
"""
json_doc = json.loads(doc)
list_elements = []
def root_list(k, jv):
if isinstance(jv, dict):
try:
return jv[k]
except KeyE... | bbcac9b588a8e5bbbbed9a18f3ee3180ca8f3282 | 3,605,669 |
from typing import Optional
import argparse
def report_format(arg: Optional[str]) -> str:
"""Check if report format value is valid."""
if arg not in report_formats:
raise argparse.ArgumentTypeError("Specified report format is invalid!")
return arg | bbec839e2bfc25db0407786c4e8ee62f6520f32d | 3,605,670 |
import warnings
def fminbound(func: callable,
left: float,
right: float,
method: str = 'Bounded') -> OptResutType:
"""Minimum of the function in a closed interval.
Arguments:
func {callable} -- Callable function.
left {float} -- Lower bound of the... | 1227f860502da22f9f78f9a485cb15955ddabb2f | 3,605,671 |
import pdb
def _lump_mean(ndarray, dropna=True, *args, **kwargs):
"""docstring"""
ndarray = np.array(ndarray).flatten()
if dropna:
try:
bad_indexer = np.isnan(ndarray)
good_indexer = [False if x else True for x in bad_indexer]
except:
pdb.set_trace()
... | 3b7c2586cc083d4285b523badf36db919b8fe9a9 | 3,605,672 |
def parsed_url(url):
# /static?file=zhihu.js&author=gua
"""
{
'file': 'zhihu.js',
'author': 'gua'
}
"""
index = url.find('?')
if index == -1:
return url, {}
else:
path, query_string = url.split('?')
args = query_string.split('&')
query = {}... | 4e29b96e02798f8fdcd02aeeba3cfe62a8cc64ea | 3,605,673 |
def play(game=draw_new_board(), first_player=0):
"""
Play a "Connect 4" game.
:param game: a board (by default create a new empty one); this
param is useful to continue a previous saved game.
:param first_player: player starting to play (by default it is 0,
which does not exists, so triggeri... | baccc705c19f74e9522f693ec1f205035878f048 | 3,605,674 |
def window_optical_flow(vec, window):
"""
Return pairs of images to generate the optical flow.
These pairs contains the first and the last image of the optical flow
according to the size of the window.
Parameters:
-----------
vec : array_like
sorted list containing the image ids... | dde566f6eff6845cb16a1acec95a7bdbc4609b11 | 3,605,675 |
import os
def excel_formatter(data, **kwargs):
"""Method to format data as an .xlsx table using openpyxl module."""
# get arguments
try:
table = kwargs["table"]
except KeyError:
log.critical(
"output.formatter_excel: output tag missing table definition. Exiting"
)
... | 0cb6da2658e85c9fe8e0eef58e1355db97fb5e3b | 3,605,676 |
import requests
def access_token():
"""Generate access token using the provided service account key file."""
creds = service_account.Credentials.from_service_account_file(
CREDENTIALS_FILE, scopes=[CLOUD_PLATFORM_SCOPE]
)
with requests.Session() as session:
creds.refresh(goog_auth_requ... | 50cd40a0628e60c990279f17131649746a18fc67 | 3,605,677 |
def filters(_filters: Filter) -> Decorator:
"""Sets filters on a command function."""
def filter_decorator(func: CommandFunc) -> CommandFunc:
setattr(func, "_cmd_filters", _filters)
return func
return filter_decorator | 464e0f501f05f15f14d0eb8a568cad70e38a6fe3 | 3,605,678 |
def sample_lda(key, num_docs, num_topics, vocab_size, doc_length):
"""Samples documents and parameters from LDA using default prior parameters.
Samples from LDA assuming that each element of doc_topic_alpha is 1/num_topics
and each element of topic_word_alpha is 1/vocab_size.
Args:
key: A JAX PRNG key.
... | 236203f6475e385c06cfb092fb99934290f8001f | 3,605,679 |
def text_width(text_item):
"""Returns width of Autocad `Text` or `MultiText` object
"""
bbox_min, bbox_max = text_item.GetBoundingbox()
return bbox_max[0] - bbox_min[0] | 001816ff5937d1e286f00088ede076b86590a951 | 3,605,680 |
import sqlite3
import fnmatch
def banned(address, type="ban", name=False):
"""
Check if address is banned
Checks the database and sees whether the address matches a banlist entry. Mirrors are never banned and always
whitelisted
:param address: Complete IP address to check
:param whitelisted:... | f944d9fc6f744c1d53d132b701669427486f87ec | 3,605,681 |
def get_customers():
"""
The Customer List/Create API Endpoint
GET: List all customers
POST: Create a new customer
:return: list or pk
"""
id = 9 # get_dealer(current_user.id)
if request.method == 'GET':
customers = db.session.query(Customer).filter(
Custom... | fe29fb3e168d0b0f8276cdf01fb0bd23133cd132 | 3,605,682 |
def random_sailency_criterion(w: np.array) -> np.array:
"""Pruning criterion. Purely random. For benchmarking and testing purposes.
Args:
w (numpy.array): 1-dimensional numpy array containing the weights to be pruned.
Returns:
np.array: vector of saliencies.
"""
return np.random.ra... | c8931a24b5964da4025c0860a717ebf6fa8eca0f | 3,605,683 |
def create_flavor(client, name, ram, vcpus, disk, **args):
""" Create a new flavor if one does not exist. """
flavor = _find_flavor(client, name)
if flavor:
return dict(changed=False, id=flavor.id)
flavor = client.flavors.create(name, ram, vcpus, disk, **args)
return dict(changed=True, id=f... | a4cafb66c8688f916b04346270b265f1e897f338 | 3,605,684 |
def get_years_for_valid_fwi_values(df) -> list:
""" List each year that is sorted """
ffmc_data_years = df[df['ffmc_valid']].year.unique().tolist()
bui_data_years = df[df['bui_valid']].year.unique().tolist()
isi_data_years = df[df['isi_valid']].year.unique().tolist()
# Combine them and remove duplic... | 41b3725680b322932217c5d3cd97c5922eca5105 | 3,605,685 |
def darn_simulation(p, Q, Y, n, s, z_p='uniform', param='local'):
"""
Simulate a temporal network following the :math:`DARN(p)` model.
For a temporal network described by a time series of adjacency matrices :math:`\\{A_{ij}^t\\}_{i,j=1,\\ldots, n}^{t=1,\\ldots,s}` the :math:`DARN(p)` model [1]_ describes t... | a0bc41b7379e3f601d8a6f7e8ae30141881e9195 | 3,605,686 |
import asyncio
async def _gen_future():
"""returns msg id and future"""
loop = asyncio.get_running_loop()
global _global_id
_global_id += 1
fut = loop.create_future()
_global_resp[_global_id] = fut
return (_global_id, fut) | dd1a000db5cd7c895e1c782b1d22e23d778b4b1a | 3,605,687 |
from psutil import virtual_memory
import logging
def _get_ram():
""" get the RAM of the computer
:return int: RAM value in GB
"""
try:
ram = virtual_memory().total / 1024.**3
except Exception:
logging.exception('Retrieving info about RAM memory failed.')
ram = np.nan
r... | 7ed8ae4c3c388f27550d2b5c74b9b4a1b4be44bb | 3,605,688 |
from bs4 import BeautifulSoup
def is_html(string):
"""
Check if string contains html.
If html, return true, otherwise, return false.
"""
result = bool(BeautifulSoup(string, 'html.parser').find())
return result | 404723e869608ad7949c144c2f11c0bf629b0262 | 3,605,689 |
import ctypes
def ekops() -> int:
"""
Open a scratch (temporary) E-kernel file and prepare the file
for writing.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekops_c.html
:return: Handle attached to new EK file.
"""
handle = ctypes.c_int()
libspice.ekops_c(ctypes.byref(ha... | b91978a3ef1179a18b53ece633c905fb552f78c3 | 3,605,690 |
from typing import Tuple
from typing import List
def _best_guess(
input_runs: Tuple[List[float], List[float], List[float], List[float], List[float]],
a_0: float,
a_1: float,
a_2: float,
a_3: float,
a_4: float,
a_5: float,
a_6: float,
a_7: float,
a_8: float,
a_9: float,
... | 879b034dd978e5fc15f17a7a8a5e32f0d7d88c6b | 3,605,691 |
def get_level_complete_sound() -> Sound:
"""Get the level complete sound.
:return: :class:`~pygame.mixer.Sound`
"""
return Sound(__get_game_sound_path(LEVEL_COMPLETE)) | 923d7825d9f15f8b5949ed3f19ce937a3f5d6bc7 | 3,605,692 |
import torch
import time
def cg_batch(A_bmm, B, M_bmm=None, X0=None, rtol=1e-3, atol=0., maxiter=None, verbose=False):
"""
Solves a batch of PD matrix linear systems using the preconditioned CG algorithm.
This function solves a batch of matrix linear systems of the form
A_i X_i = B_i, i=1,...,K,
... | 126578e4eee0c4ec2eb2767fb40fa21b1fa58313 | 3,605,693 |
import os
def distplot_table(table, title, columns=3, rows=None, save_to=None,
xlabel=None, ylabel=None):
"""plot distribution plot of a table and save to png
a table is defined as a dictionary with 3 or 4 levels and has the following
items
dictionary['variable name']['gr... | c9b7e3dc52947d7fe909a233c7243d409014bdc7 | 3,605,694 |
import aiohttp
async def test_enable(aresponses):
"""Test enabling AdGuard Home parental control."""
# Handle to run asserts on request in
async def response_handler(request):
data = await request.text()
assert data == "sensitivity=TEEN"
return aresponses.Response(status=200, text=... | 52e3231c2cd0490892036c41b8d0c8e6e4dd302b | 3,605,695 |
def html(**kwargs):
"""
Get HTML <div> used by Recaptcha's JS script
Arguments:
site_key:
* Required
* Your Sitekey
theme:
* The color theme of the widget.
* Optional
* One of: (dark, light)
* Default: light
... | 06d0cd9045cfc11990c801f4399926fee80df1d7 | 3,605,696 |
def load_sig_owners(sig_name):
"""
Load owners specified sig
"""
owners = []
owners_file = "sig/{}/OWNERS".format(sig_name)
try:
with open(owners_file, 'r') as file_descriptor:
lines = file_descriptor.readlines()
for line in lines:
if line.strip().... | 725cfdceea02a319121770f3ec20c192f641193c | 3,605,697 |
import codecs
def get_text(filename:str) -> str:
"""
Load and return the text of a text file, assuming latin-1 encoding as that
is what the BBC corpus uses. Use codecs.open() function not open().
"""
f = codecs.open(filename, encoding='latin-1', mode='r')
s = f.read()
f.close()
return... | 43d6036ba8c10946d704dee1cd32b1968de5c199 | 3,605,698 |
import fastapi
import typing
def get_file(
project_id: int,
image_id: str,
s3=fastapi.Depends(get_s3),
user: web.User = fastapi.Depends(get_current_user),
) -> typing.Union[fastapi.responses.FileResponse, fastapi.responses.RedirectResponse]:
"""Get an image file."""
with get_session() as sessi... | 343b681dfa196c6367e80ef5a54be1ad14777777 | 3,605,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.