content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_path_cost(slice: np.ndarray = None, offset: int = 0, p1: float = 10, p2: float = 120) -> np.ndarray:
"""
Find the minimum costs in a D x M slice where M represents the number of pixels in the given direction.
:param slice: M x D array from cost volume
:param offset: ignore pixels at border
... | 3fb6510324d055e706aedcb8f2c3a25cf0d52d76 | 3,605,584 |
import tempfile
import json
def _get_run_command(wandb_run: wandb.apis.public.Run) -> str:
"""Return python run command for input wandb_run."""
with tempfile.TemporaryDirectory() as tmp_dirname:
wandb_file = wandb_run.file("wandb-metadata.json")
with wandb_file.download(root=tmp_dirname, repla... | e7f0f23e5f4c463043bda246e20aa2ee9b52cfa5 | 3,605,585 |
def Triangle_right (color, long, short = None, include_base = False, ** kwargs) :
"""Rule for a CSS triangle pointing right with `color`."""
if short is None :
short = long
rkw = dict \
( kwargs
, border_color = C_TRBL0 (l = color)
, border_width = TRBL (short, 0, short, l... | 208c5db32db496a8376bd496a0fe6392ef28a959 | 3,605,586 |
from datetime import datetime
def generate_header(header: str = "") -> str:
"""
Generates a file header.
Args:
header: A custom header to insert.
Returns:
str: The generated header of a file.
"""
syntax = " Warning generated file ".center(90, "-")
date = datetime.now().is... | 0821aef1f5f77dcd7b9fb1bcbcbca74749c3ed4a | 3,605,588 |
from typing import OrderedDict
def sort_precomputed(precomputed, all_pre_comp):
"""Sorts the precomputed equations in the given dictionary as per the
dependencies of the symbols and returns an ordered dict.
Note that this will not deal with finding any precomputed symbols that
are dependent on other ... | 79c24236566ea2726eb6cb228750f195fd778a11 | 3,605,589 |
def _mbits(num_bytes, duration_ms) -> float:
"""Return Mbit/s."""
mbits = (num_bytes * 8) / (1024 * 1024)
seconds = duration_ms / 1000
if seconds == 0:
return 0
return mbits / seconds | 8e4a1157ddb5f4d0361a553081aa8c6c3b0d62a6 | 3,605,590 |
def configure(**kwargs):
"""
Convenience function to merge multiple settings into the default global
config.
Example:
>>> import conjur
>>> conjur.configure(appliance_url='https://conjur.example.com/api',
... account='example',
... cert_path='/... | f200d89c76107569bd00367fb26bb10d0695412b | 3,605,591 |
def run_prb(path):
"""Execute the .prb probe file and import resulting locals return results as dict.
Args:
path: file path to probe file with layout as per klusta probe file specs.
Returns: Dictionary of channel groups with channel list, geometry and connectivity graph.
"""
if path is None... | 605bc61aa730d056ce5d8b07ad4753ea076eea89 | 3,605,592 |
def goto_definitions(script):
"""Get definitions for thing under cursor."""
return script.goto_definitions() | b614c72080b51e7c91100359cd863f9a8deae228 | 3,605,593 |
def get_main_path():
"""
Returns the working directory.
:return: A string containing the working directory path.
"""
return getcwd() | c86b233bb7fab1bbee695c551eacf468b3ed2eeb | 3,605,594 |
def hasActiveManifest(service):
"""
return the name of the active manifest under a specific __service
@param __service: name of __service
@return: existence of active manifest
"""
activePath = activeManifestPath(service)
return activePath is not None and activePath != '' | 42d908c1c8a931fd85ff8e0a332fc95c6944790e | 3,605,595 |
def constrain_mdl_obs_time(mdls, obs):
"""
This constrains all the models to the temporal range of the observations
"""
years = obs.coord('year').points
for cube in mdls:
years = np.intersect1d(years, cube.coord('year').points)
con = iris.Constraint(year=years)
out_mdls = []
fo... | 303528a3fcaf3bfe374e6486a772f5ce58833b95 | 3,605,597 |
def get_adgroup_df(ads_df, num_days=90):
"""
Adgroups - Look at the effectiveness of different ad groups in bounce and close rate.
* time windowed - look at the last 1, 7, 14, 28, and 90 days. Look for major changes in 1-7 and 7-28
"""
adgroups = ads_df.groupby('adgroup')
adgroup_df = adgroups.... | 1723064da39554cdc6ddea50d69a07ffc65c08b1 | 3,605,598 |
import torch
def pad_atomic_properties(atomic_properties, padding_values=defaultdict(lambda: 0.0, species=-1)):
"""Put a sequence of atomic properties together into single tensor.
Inputs are `[{'species': ..., ...}, {'species': ..., ...}, ...]` and the outputs
are `{'species': padded_tensor, ...}`
A... | e346a6f2111fe417d92ab702aaf7a104398654fa | 3,605,599 |
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 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 |
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 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 |
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 |
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 |
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 |
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 |
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 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 |
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 |
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 |
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 |
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 |
def adder_function(args):
"""Dummy function to execute returning a single float."""
loc, scale = args
return loc + scale | 7646bb1acc324f05c92268b78fefaa75283f812a | 3,605,658 |
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 |
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 |
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 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 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 |
import dask.dataframe as dd
def read_json(
url_path,
orient="records",
lines=None,
storage_options=None,
blocksize=None,
sample=2 ** 20,
encoding="utf-8",
errors="strict",
compression="infer",
meta=None,
engine=pd.read_json,
**kwargs
):
"""Create a dataframe from a ... | ec5b47fc10b58548c27728136989829df1ca81d8 | 3,605,700 |
import torch
def nograd_param(x):
"""
Naively make tensor from x, then wrap with nn.Parameter without gradient.
"""
return nn.Parameter(torch.tensor(x), requires_grad=False) | c483c0fc2b1db5b1d9ff4b16106784bc5de8e7d4 | 3,605,701 |
def node_attach(db, storage, registry, user):
"""
Attach to a node
"""
node_id = request.form.get('node_id')
registry.attach(node_id, request.form.get('address'), user.user_id)
broadcast('attach', {
'node_id': node_id,
'owner': user.dict()
})
return '' | 8e88acfecf5468fb2d6700d332a45853b93c47c6 | 3,605,703 |
def hingeval(x: ArrayLike, mn: float, mx: float) -> ArrayLike:
"""Computes hinge transformation values.
Args:
x: Array-like of covariate values
mn: Minimum covariate value to fit hinges to
mx: Maximum covariate value to fit hinges to
Returns:
Array of hinge features
"""... | b72c6c8aa1425bb3fabf4452ce7ba78793d87792 | 3,605,705 |
def next_token_inside_string(s, inside_string):
"""Given a code string s and an initial state inside_string, return
whether the next token will be inside a string or not."""
for token, value in PythonLexer().get_tokens(s):
if token is Token.String:
value = value.lstrip('bBrRuU')
... | 65e9e9f0fbcf49e899f45a7259b53f54ee120925 | 3,605,706 |
def summerE(n: int) -> int:
"""
Uses the arithmetic series formula.
Avoids generating the multiples, thanks to math.
"""
def sum_multiples(divisor: int, terms: int) -> int:
return divisor * (terms * (terms + 1)) // 2
fizzsum = sum_multiples( 3, (n-1) // 3)
buzzsum = sum_mu... | 6b4ee36075a5b46bd51c58c3bd44c103061c7cd1 | 3,605,707 |
import requests
def post_data(url, file):
"""
:param url: 接口url
:param file: 上传文件的路径
:return:
"""
files = {"file": open(file, "rb")}
s = requests.session()
r = s.post(url, files=files, verify=False)
r_json = r.json()
print('r', r_json)
if r_json.get('success... | 24e53797698e61789c3233cc1bf150fdbf0485fd | 3,605,708 |
from typing import Optional
from typing import Dict
from typing import Any
from pathlib import Path
import torch
import transformers
def train(
dataset: DatasetDict,
model_name: str = "trained-speakerbox",
model_base: str = DEFAULT_BASE_MODEL,
max_duration: float = 2.0,
seed: Optional[int] = None,... | 2ba74f36381eb9a7cd25b39d1036c7a0ab8a09c0 | 3,605,709 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.