content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
import requests
def get_cultural_hotspots(url: str, params: Dict) -> pd.DataFrame:
"""Get cultural hotspots within city boundaries."""
package = requests.get(url, params=params).json()
ch_locations = package["result"]["resources"][0]["url"]
ch_locs_dir_path = "data/raw/cultural... | 1a073998c51eca3f6a714462b864fa7d6c142e76 | 3,634,245 |
import optparse
def setopts():
""" Setup all possible command line options....
"""
usage = 'USAGE: %s [options]' % (NAME)
version = NAME + " " + __version__
parser = optparse.OptionParser(usage=usage, version=version)
parser.add_option("-v",
"--voicefile",
... | af8efe810da81af1a20747b4fcc9aa8f244ed1fc | 3,634,246 |
def f_test(df, ann):
"""Pre-select features without difference between types of dataset
Parameters
----------
df : pandas.DataFrame
A pandas DataFrame whose rows represent samples
and columns represent features.
ann : pandas.DataFrame
DataFrame with annotation of samples. Th... | 77b60abe9c09ff674f0af687552bacd75e8b75c4 | 3,634,247 |
from typing import Union
def _is_group(cli_obj: Union[Group, Command, MultiCommand]) -> bool:
"""Detects if cli obj is a Group or not"""
return isinstance(cli_obj, Group) and hasattr(cli_obj, "commands") | d262824ea8aabdd0e24740c2cbd0a9e0e4209ba1 | 3,634,248 |
import codecs
import json
def _get_input_json(input_path):
"""
A really basic helper function to dump the JSON data. This is probably a
leftover from when I was iterating on different reduce() functions.
"""
# Read in the input file.
input_file = codecs.open(input_path, encoding="utf-8", mode=... | 5c91e77b2224435dbf17fcfc2351c574c173c6aa | 3,634,249 |
import re
import urllib
def urn_from_member_name(member, base_urn):
"""Returns a URN object from a zip file's member name."""
member = utils.SmartUnicode(member)
# Remove %xx escapes.
member = re.sub(
"%(..)", lambda x: chr(int("0x" + x.group(1), 0)),
member)
# This is an absolut... | f87a5f13aa3ae1fe840caa9d28c375295a730c82 | 3,634,250 |
def create_data_set():
"""
创建数据集
:return:
"""
data_set_ = [
[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
[0, 1, 'no'],
[0, 1, 'no']
]
labels_ = ['no surfacing', 'flippers']
return np.array(data_set_), np.array(labels_) | e4c7cf3200d3acec618529a35196ec2f080d071b | 3,634,251 |
from typing import Dict
from typing import Any
def get_text(xml: bytes, context: Dict[str, Any]) -> TablesList:
"""Xml as a string to a list of cell strings.
:param xml: an xml bytes object which might contain text
:param context: dictionary of document attributes generated in get_docx_text
:returns:... | c6d1197b07cc1e07e0cb299b455d243c9ee023d0 | 3,634,252 |
from typing import Any
def day(query: int, field_name: str, object: Any) -> bool:
"""
Checks if value of object is equal to query
"""
return query == getattr(object, field_name).day | b24fc0de6c01b355633dfbd240a760c1f51bfa6f | 3,634,253 |
import glob
import tqdm
def glob_read(path, read_fun, stop_i=None, show_bar=False):
"""read all files in path by glob
Args:
path (str): absolute path
read_fun ([type]): different read function based on file type
stop_i (int, optional): stop read at file i. Defaults to None.
s... | 6932cda5ae27c72cf9db1a5360c1c130b5cea6ed | 3,634,254 |
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
return list(name_or_flags), kwargs | 7f1ba4d4005168f3c634840ddd20d6fbb73182f5 | 3,634,255 |
import math
def conv_float2negexp(val):
"""Returns the least restrictive negative exponent of the power 10
that would achieve the floating point convergence criterium *val*.
"""
return -1 * int(math.floor(math.log(val, 10))) | 562ccf7d34f8034a25cabfb471e7fc2ab9c0feb6 | 3,634,256 |
def pick_wm_class_2(tissue_class_files):
"""Returns the white matter tissue class file from the list of segmented tissue class files
Parameters
----------
tissue_class_files : list (string)
List of tissue class files
Returns
-------
file : string
Path to segment_seg_2.nii... | a30809d94a57d12084fb1747cf1854163361c50d | 3,634,257 |
def collect_datasets(data_type, varnames, list_of_ds, labels, **kwargs):
"""
Concatonate several different xarray datasets across a new
"collection" dimension, which can be accessed with the specified
labels. Stores them in an xarray dataset which can be passed to
the ldcpy plot functions (Call thi... | bd5c67d61571f9a3ab41eafb88bfe6367462e052 | 3,634,258 |
def split_tiles(image, tile_size):
"""Splits the image into tiles of size `tile_size`."""
# The copy is necessary due to the use of the memory layout.
if image.ndim == 2:
image = image[..., None]
image = np.array(image)
image = make_divisible(image, tile_size).copy()
height = width = tile_size
nrows, ... | be3d48e4fd926d0a8d2226990dac01315dc0437a | 3,634,259 |
from bs4 import BeautifulSoup
import requests
def get_insider_activity(ticker: str) -> pd.DataFrame:
"""Get insider activity. [Source: Business Insider]
Parameters
----------
ticker : str
Ticker to get insider activity data from
Returns
-------
df_insider : pd.DataFrame
G... | 97beab7bfc2ef90f74204777f0ef90c455fa0293 | 3,634,260 |
def resolve_dependencies(dependencies):
"""Resolve a set of dependencies to a specific versions or Unspecified.
You can find more for the syntax of Debian dependencies relationships
here https://www.debian.org/doc/debian-policy/ch-relationships.html
Args:
dependencies (str): string with depend... | bbc5335eaf93de0c72c7dde6272f39f75c941b71 | 3,634,261 |
def sampler(img_target, pose, intrinsics, rng, options):
"""
Given a single image, samples rays
"""
pose_target = pose[:3, :4]
ray_origins, ray_directions = get_ray_bundle(
intrinsics.height, intrinsics.width, intrinsics.focal_length, pose_target
)
coords = jnp.stack(
jnp.m... | e02907dbdef7f532ee6f843ff8fc367dc7a3ff56 | 3,634,262 |
from typing import List
def sanitize_gpu_ids(gpus: List[int]) -> List[int]:
"""
Checks that each of the GPUs in the list is actually available.
Raises a MisconfigurationException if any of the GPUs is not available.
Args:
gpus: list of ints corresponding to GPU indices
Returns:
u... | b6f3f7da19fc7f26c6229ffb80fbed3ed6dfe363 | 3,634,263 |
from typing import Type
def gauge(name: str, documentation: str, labels: tuple = ()) -> Type[Gauge]:
"""Builds a gauge with configured namespace / subsystem."""
return Gauge(
name,
documentation,
labelnames=labels,
namespace=s.PROMETHEUS_NAMESPACE,
subsystem=s.PROMETHE... | 8267cfcbbd7bdef9e3d7b6dbe8db759c2f148f40 | 3,634,264 |
def uniform_scaling(weights, prune_ratio, prec_layers, succ_layers):
"""Better prune method
Arguments:
weights (OrderedDict): unpruned model weights
prec_layers (dict): mapping from BN names to preceding convs/linears
succ_layers (dict): mapping from BN names to succeeding convs/linears... | 5a50dfd64bf9733ffbef957b184c3f88279338b1 | 3,634,265 |
def find_port(master_class_name, masters, output, opts):
"""Finds a triplet of free ports appropriate for the given master."""
try:
master_class = getattr(Master, master_class_name)
except AttributeError:
raise ValueError('Master class %s does not exist' % master_class_name)
used_ports = set()
for m ... | a5616fdefac44e450a9135d0d11563b88a84a9dc | 3,634,266 |
def find_match(good_message, bad_message):
""" Makes the hash of the bad message match that of the good one.
Args:
good_message: The good message we want to match.
bad_message: The bad message we want to make match.
Returns:
Variations of the good and bad messages that have the same hash. """
# Gene... | 723683de6b24d651bc2ebab43b7ccd758de1c4de | 3,634,267 |
import logging
def query_by_date_after(**kwargs):
"""
根据发布的时间查询,之后的记录: 2020-06-03之后,即2020-06-03, 2020-06-04, ......
:param kwargs: {'date': date}
:return:
"""
session = None
try:
date = kwargs['date'].strip() + config.BEGIN_DAY_TIME
session = get_session()
ret = ses... | 867faba9e835a8bbb539349ad316f5a594a6ead0 | 3,634,268 |
def split_data(im_in, dim, squeeze_data=True):
"""
"""
# backwards compat
return split_img_data(src_img=im_in, dim=dim, squeeze_data=squeeze_data) | e45e32e3654198e63597b0e813f3e929af11fc60 | 3,634,269 |
def user_groups(username, htgroup_fn, strict=True):
"""
Returns a list of group names for the given user
"""
groups = []
for group_name, users in read_groups(htgroup_fn, strict=strict).items():
if username in users:
groups.append(group_name)
return groups | adc452c60c25e672829d3efa99a0c4bf41213e64 | 3,634,271 |
def uffangle(i,j,k,boij,bojk,theta):
"""
Return the UFF parameters for an angle interaction in Gromacs units (degrees, kJ mol^-1 rad^-2).
Not used for the nebterpolator but I decided to keep this code.
i = Element symbol (string)
j = Element symbol for the middle atom (string)
k = Element s... | f57527c0adbff255d64304c11623cb706b3dc784 | 3,634,272 |
import random
def img_get_random_patch(img,w,h):
"""Get a random patch of a specific width and height from an image"""
# Note that for this function it is the user's responsibility to ensure
# the image size is big enough. We'll do an asertion to help but...
# Figure out the maximum starting point w... | 41ce199eb5ab8eb136f740eb2e1b495226510690 | 3,634,273 |
def list_to_dict(items):
"""Create dictionary from a parenthesized list of attribute/value pairs
:param items: list
:return: dict
"""
if not items:
items = []
# minimal
# dict(zip(items[0::2], items[1::2])
def recursive(item):
"""Check value of parenthesized list and i... | a58ed6efe88592f0fa9af1c2daf9a132272e633f | 3,634,274 |
def AVERAGEIF(avg_list, condition_list, condition):
"""Find the average of a list based on a specfic condition in another list.
Parameters
----------
avg_list : list or array
list or array that you will take the average of. Length must match condition_list.
condition_list : list or array
... | 1f34d34612626d500e534512eb493086ec19bce0 | 3,634,275 |
def fresnel_ts(n0, n1, theta0, theta1):
"""Compute the "t sub s" fresnel coefficient.
This is associated with transmission of the s-polarized electric field.
Parameters
----------
n0 : `float`
refractive index of the "left" material
n1 : `float`
refractive index of the "right" ... | faf68134372ad5df8c31107e7ff8b006ee7a1f66 | 3,634,276 |
def get_client_id_from_access_token(aws_region, aws_user_pool, token):
""" Pulls the client ID out of an Access Token
"""
claims = get_claims(aws_region, aws_user_pool, token)
if claims.get('token_use') != 'access':
raise ValueError('Not an access token')
return claims.get('client_id') | 6ce2d5771b863e4bf8da367284486f5618d09473 | 3,634,277 |
def bgloop(tag, *iterables, runner=None):
"""Run a loop in a background thread."""
if runner is None:
runner = run_thread
def decorator(func):
if tag in bg_instances and bg_instances[tag].running:
raise RuntimeError("Already running loop")
bg_instances[tag] = Object()
... | 553e650ecc0b640e0cea3ad4c714cb3d66d327b4 | 3,634,278 |
from typing import AnyStr
from typing import List
from typing import Dict
def get_metrics_rating(start: AnyStr,
end: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
Get the rating for metrics.
:start (AnyStr) A t... | 852ce6a21f03b02691748d6d9a654edf10b7ed54 | 3,634,279 |
from typing import List
def calculate_previous_risk_score_weightings() -> List[float]:
"""
Creates a risk score weighting distribution of size MAX_PREVIOUS_INCIDENTS such that the distribution
is a decreasing linear series that sums to 1. For example, with MAX_PREVIOUS_INCIDENTS == 3,
this function re... | 6064c345973335026c49522aada829eec67a5ba6 | 3,634,280 |
import torch
def warp(x, flo, device):
"""
warp an image/tensor (im2) back to im1, according to the optical flow
x: [B, C, H, W] (im2)
flo: [B, 2, H, W] flow
"""
B, C, H, W = x.size()
# mesh grid
xx = torch.arange(0, W).view(1, -1).repeat(H, 1)
yy = torch.arange(0, H).view(-1, 1).r... | d009beeab36a84ba2659d87d22dc98ad0b20bf52 | 3,634,281 |
def FindVolumeClose(hSearch):
"""Close a search handle opened by FindFirstVolume, typically
after the last volume has been returned.
"""
if kernel32.FindVolumeClose(hSearch) == 0:
return error(x_kernel32, "FindVolumeClose") | 48a8c4629d9bc10b4a8befa33f399ed1a3727347 | 3,634,283 |
def authenticated(method):
"""
Decorate methods with this to require that the Authorization
header is filled.
On failure, raises a 401 or 403 error.
Raises:
:py:class:`tornado.web.HTTPError`
"""
@wraps(method)
async def wrapper(self, *args, **kwargs):
if not self.current_... | bf64966f14d76b0f755f1d17672540a361c99c35 | 3,634,285 |
def _calculate_f1(conf_matrix):
"""
Calculate classification macro F1 score.
Parameters
----------
conf_matrix : pandas.DataFrame
DataFrame of confusion matrix.
Returns
-------
f1_total : float
Total classification macro F1 score including detection FP and FN.
f1_ta... | 9dded3affbc164487020898cb46765e5c1dc8553 | 3,634,286 |
def prepare_wiki_content(content, indented=True):
"""
Set wiki page content
"""
if indented:
lines = content.split("\n")
content = " ".join(i + "\n" for i in lines)
return content | 14daea5cdb509b333c2aead6dcb453a82e73ce8d | 3,634,287 |
def get_user_args():
""" **get_user_args** fetches user arguments from arguments"""
display_name = request.args.get('display_name')
email = request.args.get('email')
email_verified = request.args.get('email_verified')
uid = request.args.get('uid')
cell = request.args.get('cell')
provider_dat... | 679836f40c441a6b61ef05bf9f96ef328c4751a4 | 3,634,288 |
def calculate_camera_center(P: np.ndarray,
K: np.ndarray,
R_T: np.ndarray) -> np.ndarray:
"""
Returns the camera center matrix for a given projection matrix.
Args:
- P: A numpy array of shape (3, 4) representing the projection matrix
Retur... | 6bec2422af375cd1b0c6570a38f6afe60c7f927e | 3,634,289 |
def __need_local_verify(ins:VerifyTokenLocal=None):
"""
ins 是否存在,是否 VerifyTokenLocal 对象
:param ins:
:return:
"""
if ins is None:
return False # 为 None, 不需要本地验证
if not isinstance(ins, VerifyTokenLocal): # 有值,但是不是 VerifyTokenLocal 实体,抛出异常
raise WrongLocalVerifyTokenInsErr... | b418cedc53e49dfdc93d25e822b6b8803e080d17 | 3,634,290 |
def average_spectra(spec_data, t_avg, h_avg, **kwargs):
"""
Function to time-height average Doppler spectra
:param spec_data: list of xarray data sets containing spectra (linear units)
:param t_avg: integer
:param h_avg: integer
:param kwargs: 'verbosity'
:return: list of xarray data sets co... | 071fca747555fdfaebc717a3e1caf98e326c89d6 | 3,634,292 |
def get_db_dot_fmt_strings(db_list, config, query_extension="fasta"):
"""
Return a list of strings that are "{db}.{format}". Where db is the name of the database and format is the extension generated by the search (eg lastx, or tbl). There is a special case for fragmented HMM dbs where we need to add ".dbatch" ... | d5ef3640f131189917966149bbcc50e530b1727c | 3,634,294 |
import numpy
def colormap(exps, colorby, definedinEM, annotation=None):
"""Generate the self.colors in the format which compatible with matplotlib"""
if definedinEM:
if colorby == "reads":
color_res = []
for i in exps.get_readsnames():
c = exps.get_type(i, "colo... | d777fb19b52b097b569fff0f315d63115c8e2231 | 3,634,295 |
def wfs_25d_point(omega, x0, n0, xs, xref=[0, 0, 0], c=None, omalias=None):
"""Point source by 2.5-dimensional WFS.
::
____________ (x0-xs) n0
D(x0,k) = \|j k |xref-x0| ------------- e^(-j k |x0-xs|)
|x0-xs|^(3/2)
"""
x0 = util.asarray_o... | 87fbf4dc467e0c0b7a9259d80f69125326dbf86d | 3,634,296 |
def load_labels(fn, delimiter=',', id_col=0, label_col=1):
"""
Load ID list with label IDs
e.g. use to load segment label, or synapse label
"""
d = np.genfromtxt(fn, delimiter=delimiter, dtype=int)
label_to_id = {}
id_to_label = {}
for i in range(d.shape[0]):
push_dict(label_to_i... | 001dc4c3da6b9614e8c87471b86697fabad3299e | 3,634,297 |
def flatten_with_joined_string_paths(structure, separator='/'):
"""Replacement for deprecated tf.nest.flatten_with_joined_string_paths."""
return [(separator.join(map(str, path)), item)
for path, item in tree.flatten_with_path(structure)] | 36b814752f5879996fb135904bb619a909ab302b | 3,634,299 |
def make_non_pad_mask(lengths, xs=None, length_dim=-1):
"""Make mask tensor containing indices of non-padded part.
Args:
lengths (LongTensor or List): Batch of lengths (B,).
xs (Tensor, optional): The reference tensor. If set, masks will be the same shape as this tensor.
length_dim (int... | 45c60ed4119958448960db38702e7a31724bce77 | 3,634,300 |
import logging
def get_time_cols(X: pd.DataFrame, labels: bool = False) -> pd.Series:
"""Get time columns."""
X = pd.DataFrame(X)
logger = logging.getLogger(__name__)
is_time = X.dtypes.apply(lambda x: issubclass(x.type, np.datetime64))
n_features = np.sum(is_time)
logger.info("The number of ... | c8d350a9ecd5c89fe9d44d31feef5851bd36639e | 3,634,301 |
def default_browser():
"""
Return the name of the default Browser for this system.
"""
return 'firefox' | a5df3959983bcc11fb59b0aea44a0e6ed42cc579 | 3,634,303 |
def dmp_ground(c, u):
"""
Return a multivariate constant.
Examples
========
>>> from sympy.polys.densebasic import dmp_ground
>>> dmp_ground(3, 5)
[[[[[[3]]]]]]
>>> dmp_ground(1, -1)
1
"""
if not c:
return dmp_zero(u)
for i in range(u + 1):
c = [c]
... | de3a5743aa4ded69ee0df6aa6d4664919264ccbd | 3,634,304 |
import torch
def bkb(gp_model, inducing_points, q_bar=1):
"""Update the GP model using BKB algorithm.
Parameters
----------
gp_model: ExactGP
model to update
inducing_points: torch.Tensor
Tensor of dimension [N x d_x]
q_bar: float
float with algorithm parameter.
""... | 7ac7e4f273dcd3014868bab802da162ca4e01dec | 3,634,305 |
def splinter_remote_url(request):
"""Remote webdriver url.
:return: URL of remote webdriver.
"""
return request.config.option.splinter_remote_url | 17bf9bf3ebd7296a2305fe9edeb7168fbca7db10 | 3,634,307 |
import shlex
import traceback
def run(*args, **kwargs):
"""Run the external command. See ``subprocess.check_output``."""
# normalize args
if len(args) == 1:
if isinstance(args[0], str):
args = shlex.split(args[0], posix=IS_POSIX)
else:
args = args[0]
if args[0]... | d546ec949ec97b418f43319a6da90ef019bba52c | 3,634,308 |
def tfresize_image(image, size=(cfg.IMG_W, cfg.IMG_H)):
""" Resize image. """
return tf.image.resize(image, size) | e18fbe2b2ad467e459a0615e088e52279d54d8fc | 3,634,309 |
def history():
"""Show history of transactions"""
# Get information about stocks that the transactions
transactions = db.execute(
"SELECT symbol, shares, price_per_share, price, time FROM transactions WHERE user_id = ?",
session["user_id"],
)
return render_template("history.html", ... | 53aee51f5a77e6f00b55915b0d1c8d2f611bf9d5 | 3,634,310 |
def serve_static_file(request, filename, root=MEDIA_ROOT, force_content_type=None):
"""
Basic handler for serving up static media files.
Accepts an optional ``root`` (filepath string, defaults to ``MEDIA_ROOT``) parameter.
Accepts an optional ``force_content_type`` (string, guesses if ``None``) par... | b7fcb058e381ba8045ea4a14122510ddb2af3ca7 | 3,634,311 |
import numpy
def crystal_fh2(input_dictionary,phot_in,theta=None,forceratio=0):
"""
:param input_dictionary: as resulting from bragg_calc()
:param phot_in: photon energy in eV
:param theta: incident angle (half of scattering angle) in rad
:return: a dictionary with structure factor
"""
#... | 438f1491b4458358f58b9212a094dcc2f499369e | 3,634,312 |
import re
def split_list_item_by_taking_words_in_parentheses(item):
"""This function goes through items in a list and creates a new item with only the words inside the parentheses."""
species_pop_name = item.split('(')[0].split(',')
if len(species_pop_name) > 1:
species_pop_name = species_pop_name... | 2d8543611007e799d089c77b79ae7263cba36a30 | 3,634,313 |
import re
def _set_arxiv_info(paper):
"""
Retrieve paper information from the html.
:param paper: SubmittedPaper object to scrape html information.
:type paper: SubmittedPaper
:return: SubmittedPaper object with html information retrieved.
:rtype: SubmittedPaper
"""
# Remove all the m... | b37103d1ae3aa0175c49884ed2133b28ab69c327 | 3,634,314 |
def fetch_accountTransactions(accountNum):
"""
Function to return all the transaction related to an account number provided as a parameter. This
function assumes that the user has been previously authenticated and that the request is for an
account they own.
Args:
accountNum (int): User's a... | dfce7891a38817775fb6aee198e39bf9f985cf47 | 3,634,315 |
def main(items=None, printmd=None, printcal=None,
found=False, filename_template='${collection}/${date}/${id}',
save=None, download=None, requester_pays=False, headers=None, **kwargs):
""" Main function for performing a search """
if items is None:
## if there are no items then pe... | 62b562a9c450f966a6ed6fc3f9a8e37865d900f3 | 3,634,317 |
def get_utility_flow(heat_utilities, agent):
"""Return the total utility duty of heat utilities for given agent in GJ/hr"""
if isinstance(agent, str): agent = HeatUtility.get_agent(agent)
return sum([i.flow * i.agent.MW for i in heat_utilities if i.agent is agent]) / 1e3 | c4fa194d321c4db2bd9b423bc9a1c76a7274f212 | 3,634,318 |
from unittest.mock import patch
async def test_flux_with_custom_start_stop_times(hass, legacy_patchable_time):
"""Test the flux with custom start and stop times."""
platform = getattr(hass.components, "test.light")
platform.init()
assert await async_setup_component(
hass, light.DOMAIN, {light.... | 0e6b4cb257d93524fa596150cc197d94eb83e908 | 3,634,319 |
def pad(value, digits, to_right=False):
"""Only use for positive binary numbers given as strings.
Pads to the left by default, or to the right using to_right flag.
Inputs: value -- string of bits
digits -- number of bits in representation
to_right -- Boolean, direction of padding
... | 98476653ccafeba0a9d81b9193de0687dbf9d85c | 3,634,320 |
def abort(state: State) -> Process:
"""End of aborted workflow."""
return Abort(state) | a67e51351a948db0670f7695123cb9dfea28d7e2 | 3,634,321 |
def build_network(cfg):
""" Build the network based on the cfg
Args:
cfg (dict): a dict of configuration
Returns:
network (nn.Module)
"""
network = None
pretrained = cfg['model']['pretrained']
kwargs = {
'num_classes': cfg['model']['num_classes'],
}
if cfg['m... | 0fe83885846a5b12b580487ff59eb9c07d35035e | 3,634,324 |
def check_band_below_faint_limits(bands, mags):
"""
Check if a star's magnitude for a certain band is below the the
faint limit for that band.
Parameters
----------
bands : str or list
Band(s) to check (e.g. ['SDSSgMag', 'SDSSiMag'].
mags : float or list
Magnitude(s) of the ... | 9e26fcef5bf79b4480e93a5fe9acd7416337cf09 | 3,634,325 |
def findNmin_ballot_comparison_rates(alpha, gamma, r1, s1, r2, s2,
reported_margin, N, null_lambda=1):
"""
Compute the smallest sample size for which a ballot comparison
audit, using Kaplan-Markov, with the given statistics could stop
Parameters
----------
... | a3d1f33cdcbbfb10bd0a4f2fff343b752056a37b | 3,634,326 |
from typing import List
import json
def patch_item(news_id, patches):
"""Apply the patches to the given news ID. If the categories change, they will be updated
in the related NewsCategoriesMapping. Returns the modified JSON presentation."""
news = News.query.filter_by(NewsID=news_id).first()
result = ... | 6292641585b8d8e11d3440ee517e93bbe5b239f9 | 3,634,327 |
def get_sample_prediction(session, regression):
"""Generate and return a sample prediction formatted specifically for table creation.
Args:
session: A SQLalchemy session object
regression: A regression object from four_factor_regression.py
Returns:
A DataOperator object initialized... | f2e32aa2b3e892158a47479f21b11893ab553821 | 3,634,328 |
def log_variables(y_dataset, variables_to_log):
"""
take the log of given variables
:param variables_to_log: [list of str] variables to take the log of
:param y_dataset: [xr dataset] the y data
:return: [xr dataset] the data logged
"""
for v in variables_to_log:
y_dataset[v].load()
... | 442455781ea52734f12336d7ceca4016987cee9e | 3,634,329 |
def find_place_num(n, m):
"""
"""
if n==1 or m==1:
return 1
else:
return find_place_num(n-1, m) + find_place_num(n, m-1) | 632e06db2eb2e2eebdb1c5b34bea36124843a960 | 3,634,330 |
def AddWorkerpoolUpdateArgs(parser, release_track):
"""Set up all the argparse flags for updating a workerpool.
Args:
parser: An argparse.ArgumentParser-like object.
release_track: A base.ReleaseTrack-like object.
Returns:
The parser argument with workerpool flags added in.
"""
return AddWorkerp... | 51028000d8059e660d6a97a0d8ac3e82f4bca9fb | 3,634,331 |
def check_vibes(x0, y0, z0, x1, y1, z1, deadzone=750):
"""
Return boolean if the accelerometer senses vibration.
This module has a range of 1500 while resting.
The default dead zone is 750 because 1500 is quite rare.
Values for this can be measured with min-max.py before coded here.
"""
tot... | a1bae213f6fa1166cb2f69b52cb22700b0b83811 | 3,634,332 |
def voiced_seg(sig,fs,f0,stepTime):
"""
Voiced segments
sig: Speech signal
fs: Sampling frequency
f0: Pitch contour
stepTime: Step size (in seconds) used to computed the f0 contour.
"""
yp = f0.copy()
yp[yp!=0] = 1
#In case the starting point is F0 and not 0
if yp[0] == 1:
... | 354383c23e1019a9d68de41bb2a62c575001e0ee | 3,634,333 |
def scale_min_max(x, min_in, max_in, min_out, max_out):
"""Scales linearly"""
return np.clip((((max_out - min_out) * (x - min_in)) / (max_in - min_in)) + min_out, min_out, max_out) | 7e77d541e5ae329393adb1a0461a8c2081fb48e1 | 3,634,334 |
def ast_to_z3(inspected_function: dict):
"""
Get the inspected object from the ast visit
and call each mapper from extracted object to its generated Z3 conditions
then, concatenate their results in a single string.
:param inspected_function generated from the AST Visit
:return:
"""
local_variables = [x['declar... | ba94a2265673c98e5cbd5691c88c9fdadf0aa2f4 | 3,634,335 |
def freight_june_2014():
"""Find the number of freight of the month"""
for i in fetch_data_2013():
if i[1] == "Freight" and i[4] == "June":
num_0 = i[6]
return int(num_0) | 571d8e819d6abdf8786c114284de8b5542552be9 | 3,634,336 |
def add_license_creation_fields(license_mapping):
"""
Return an updated ``license_mapping`` of license data adding license status
fields needed for license creation.
"""
license_mapping.update(
is_active=False,
reviewed=False,
license_status="NotReviewed",
)
return li... | 3856c434a672150c09af4b5e4c7fd9fa55014d5c | 3,634,337 |
def filegroup(space, fname):
""" filegroup - Gets file group """
return _filegroup(space, fname) | a5b361d048c37e176e78ac2d6ffbebb3604a79cd | 3,634,338 |
import numpy as np
def make_reference_bands_inline(wannier_bands, vasp_bands, efermi=None):
"""
Compare bandstructure results from wannier and vasp.
Takes two input array.bands nodes, stores them if they're not already
stored. Takes the relevant bands from the vasp bandstructure and stores and output... | 5369bbd8accf640a79b7ccfaa1971441b93a148d | 3,634,340 |
from typing import Optional
import contextlib
def check_reorgs_task(self) -> Optional[int]:
"""
:return: Number of oldest block with reorg detected. `None` if not reorg found
"""
with contextlib.suppress(LockError):
with only_one_running_task(self):
logger.info("Start checking of r... | 58a4d97b9176ae304ad86038b578d5864821191f | 3,634,342 |
def is_all_gathered():
""" Determines if all languages have had their download goals
accomplished
"""
for lang in gathered:
if len(gathered[lang]) < NUM_TO_GATHER:
return False
return True | ad35ce939f2ca847310c6de27541fa48e64142ef | 3,634,344 |
def greedy_eval_Q(Q: QTable, this_environment, nevaluations: int = 1):
"""
Evaluate Q function greediely with epsilon=0
:returns average cumulative reward, the expected reward after resetting the environment, episode length
"""
cumuls = []
for _ in range(nevaluations):
evaluation_state ... | 296cf19b0090d488ef6ca717585114da7d8fc143 | 3,634,345 |
def lowercase(obj):
""" Make dictionary lowercase """
if isinstance(obj, dict):
return {k.lower(): lowercase(v) for k, v in obj.items()}
elif isinstance(obj, (list, set, tuple)):
t = type(obj)
return t(lowercase(o) for o in obj)
elif isinstance(obj, str):
return obj.lower... | 08b0addd87ef7ba5c016ebee50790e8d5e31042b | 3,634,346 |
def _workaround_for_datetime(obj):
"""Workaround for numpy#4983: buffer protocol doesn't support
datetime64 or timedelta64.
"""
if _is_datetime_dtype(obj):
obj = obj.view(np.int64)
return obj | 8091d264a175e9ecf8ba6bb9621bb10f5940919d | 3,634,348 |
def sql_dynamic_row_count_redshift(schemas: list) -> str:
"""Generates an SQL statement that counts the number of rows in
every table in a specific schema(s) in a Redshift database"""
sql_schemas = ', '.join(f"'{schema}'" for schema in schemas)
return f"""
WITH table_list AS (
SELECT schema... | a98fdc11a82144cf7cce152ed7cc6c2e071cd596 | 3,634,350 |
from datetime import datetime
def eow(date: datetime.date, offset: int = 0, weekday: str = "SUN") -> datetime.date:
"""
Returns the end of the week, i.e. the first date on or after the given date
whose weekday is equal to the the :code:`weekday` argument, and
offset by a given number of weeks.
... | 3020faaf9edce3912d3627878136d52151699e9b | 3,634,351 |
def dequote(s):
"""
from: http://stackoverflow.com/questions/3085382/python-how-can-i-strip-first-and-last-double-quotes
If a string has single or double quotes around it, remove them.
Make sure the pair of quotes match.
If a matching pair of quotes is not found, return the string unchanged.
"""... | 41c5e5fed901d70472dd6eef1ada7d53d395002c | 3,634,352 |
def has_issue_tracker(function):
"""
Decorator that checks if the current pagure project has the
issue tracker active
If not active returns a 404 page
"""
@wraps(function)
def check_issue_tracker(*args, **kwargs):
repo = flask.g.repo
if not flask.g.issues_enabled or not repo... | f2efa5755ffd013175456ca7fa6cea8ea386569e | 3,634,353 |
from typing import List
def find_deprecated_usages(
schema: GraphQLSchema, ast: DocumentNode
) -> List[GraphQLError]:
"""Get a list of GraphQLError instances describing each deprecated use."""
type_info = TypeInfo(schema)
visitor = FindDeprecatedUsages(type_info)
visit(ast, TypeInfoVisitor(type_i... | 6dd7673d76885de4d66f7e479382108be7ed88de | 3,634,354 |
import torch
def construct_embedding_mask(V):
"""
Construct a mask for a batch of embeddings given node sizes.
Parameters
----------
V: (batch_size) actual number of nodes per set (tensor)
Returns
-------
mask: (batch_size) x (n_nodes) binary mask (tensor)
"""
batch_size = le... | e149691bfac855911cd3074009eb6b97b2d723a0 | 3,634,355 |
def url_form(url):
"""Takes the SLWA photo url and returns the photo url. Note this
function is heavily influenced by the format of the catalogue and could be
easily broken if the Library switches to a different url structure.
"""
if url[-4:] != '.png' and url[-4:] != '.jpg':
url = url + '... | 7469850ffb6877ca116a28251d204024e15bc407 | 3,634,356 |
from datetime import datetime
def timedelta_from_now(delta):
"""
Add a timedelta to now, plus a fudge factor of a few seconds.
Most useful for chaining with Django's builtin filter "timeuntil",
for producing a humanized timedelta.
"""
return datetime.datetime.utcnow() + delta + datetime.timede... | 769739e3ca5304dfe0cd9a82c3c39be338cd5d03 | 3,634,357 |
def multivariate_gaussian(pos, mu, sigma):
"""
Calculate the multivariate Gaussian distribution on array pos.
Source: https://scipython.com/blog/visualizing-the-bivariate-gaussian-distribution/
:param pos: numpy array, constructed by packing the meshed arrays of variables
x1, x2, .. xk i... | b8a2e2851f27737332ffcba8deab6c02a455979d | 3,634,360 |
def Rpivot(p, q, Mb):
"""
Given an augmented matrix Mb, Mb = M|b, this gives the output of the
pivot entry [i, j] in or below row p, and in or to the right of column q.
"""
# n is the number of columns of M, which is one less than that of Mb.
m = len(Mb)
n = len(Mb[0]) - 1
# Initialize ... | 155be98d8560bf42cea928e8b1da6e14e3e7762d | 3,634,362 |
def create3d_vector(name=None, source='default'):
"""%s
:param name: The name of the created object
:type name: `str`_
:param source: The object to inherit from.
Can be a 3d_vector, or a string name of a 3d_vector.
:type source: `str`_ or :class:`vcs.dv3d.Gf3Dvector`
:returns: A 3d_ve... | bfbc821de05c6817d7980d6b0fdb27341aa12911 | 3,634,363 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.