content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_point(values, pct):
"""
Pass in array values and return the point at the specified top percent
:param values: array: float
:param pct: float, top percent
:return: float
"""
assert 0 < pct < 1, "percentage should be lower than 1"
values = sorted(values)
return values[-int(len(... | 11474d804e0845284a864a5cb8de23299999a5e7 | 63,544 |
def get_data(data_args,
data_cache,
read_from_cache=True,
write_to_cache=True,
write_args_to_cache=True):
"""
Prepares the raw data, if it is not yet cached.
"""
random_state = tools.check_arg(
'random_state', data_args['random_state'], int, (0... | 5bb6143d22394888fad38a5e58f6342580ce3656 | 63,546 |
def get_xpub_fingerprint(xpub):
"""
Retuns fingerprint of the XPUB itself.
IMPORTANT! NOT parent fingerprint, but hash160(pubkey) itself!
"""
b = decode_base58(xpub)
return hash160(b[-33:])[:4] | e73c4da74eeeb47a5cfb3d519647fafc213041d5 | 63,548 |
import gettext
def order():
"""Order articles."""
storefront = _get_storefront_or_404()
shop = shop_service.get_shop(storefront.shop_id)
if storefront.closed:
flash_notice(gettext('The shop is closed.'))
return order_form()
article_compilation = (
article_service.get_arti... | 2e5e15a62f62d085ecd9bd1a930d987be3483b50 | 63,549 |
def get_necessary_conf_property(conf, name):
"""
Return configuration property value and expect it to be set.
:param conf: Dictionary.
:param name: Configuration property string.
:return: Configuration property value.
"""
check_necessary_conf_property(conf, name, None)
return conf[name] | aff866d6e1bb72b9ca5a4262d87d24e65af3eb66 | 63,550 |
def get_pixel_path(p0, p1):
"""
Return pixel path from p0 to p1
Args:
p0: tuple(float, float)
Start pixel
p1: tuple(float, float)
End pixel
Returns:
list(tuple(float, float))
Ordered list of pixels
"""
p0 = np.array(p0)
p1 = np.a... | f91ee59bc35ed3b5e694a902b438628c24b81df2 | 63,551 |
def PMR_Choquet(x, y, prefs):
"""
Si positif:
x possiblement préféré à y
Si nul:
x est possiblement autant préféré que y
Si négatif:
x est tout le temps préféré à y
"""
#Number of variables
n = x.shape[0]
xcopy=x.copy()
xcopy[::-1].sort()
listX=[np.where(x==xcopy[0])[0]]
ycopy=y.copy()
ycopy[::-1].... | 728b5057215022e2876a6d121f54a5719bfc0463 | 63,552 |
def get_handlers(requested=None):
"""
get multiple chksum handlers
:param requested: None (all handlers), or a sequence of the specific
handlers desired.
:raise MissingChksumHandler: if requested chksum type has no registered handler
:return: dict of chksum_type:chksum handler
"""
... | d6a7781761cb21dc95e5349c7243910760dce078 | 63,553 |
def code(*content, sep=" "):
"""
Make mono-width text (Markdown)
:param content:
:param sep:
:return:
"""
return markdown_decoration.code(value=html_decoration.quote(_join(*content, sep=sep))) | b9cac8bb6b73ce6f372feeb8f14694c88a0317b0 | 63,555 |
import abc
import json
def stringify(obj):
"""Convert object to string.
If the object is a dictionary-like object or list,
the objects in the dictionary or list will be converted to strings, recursively.
Returns: If the input is dictionary or list, the return value will also be a list or dictionary.
... | c7e6dca941edf1adbc49b745dfc81e0eeb15d02a | 63,556 |
import torch
def decode_predictions(predictions):
"""
CTC RNN Layer decoder.
1.
2 (or more) repeating digits are collapsed into a single instance of that digit unless
separated by blank - this compensates for the fact that the RNN performs a classification
for each stripe that re... | b49ade62b5a301c9b703608635931c4dc1029ed4 | 63,557 |
from typing import Tuple
def weird_argument(request, prior_and_prior_type_and_value: Tuple[str, str, str]):
""" Fixture that provides a weird name, along with a prior and value. """
weird_param_name = request.param
prior_str, prior_type, value = prior_and_prior_type_and_value
return WeirdArgument(
... | a4938733a7ef7b09fdcb94f1217834a750516ed9 | 63,559 |
def is_valid(number):
"""Check if the number provided is a valid NIE. This checks the length,
formatting and check digit."""
try:
return bool(validate(number))
except ValidationError:
return False | 8245d43e59f831f7e03ad4e8415acc2ce2f54fef | 63,560 |
def prepare_for_table(data, machine_id):
"""We don't want to store certain fields in the DB, e.g. the _BOOT_ID
or the __CURSOR because they don't add any value in the central
log index.
"""
defint = lambda x: 0 if x == '' else int(x)
keep_and_convert = {
'MESSAGE': str,
'PRIORI... | 54c75fac6206c0c5e6b8d44553853c0c624080fa | 63,562 |
def run_2020_02_1() -> str:
"""
Run the main function and return a single result to be printed.
Returns
-------
`str`
The result to be printed.
"""
with open("advent_2020/data/02.txt") as f_in:
# Read the text and store each line in a collection.
rules_and_data = r... | cc5b1bb08150f8a30a3237355dc2069c4dfe8063 | 63,563 |
def reverse_table(tab):
"""Function that reverse an array
Args:
tab: an array
return the array reversed
"""
if not(isinstance(tab,list)):
raise ValueError('max_value, expected a list as input')
if len(tab)==0:
raise ValueError('max_value, expected a non empty a list as in... | 8ab03236e40cb270f51dde91a0e2f2760ab90316 | 63,564 |
def check_columns(df):
"""
Checks wether dataframe contains the required columns.
:param df: the data frame with track data.
:return: whether or not df contains all the required columns.
required columns: refName, start, end, name, score (is optional)
:rtype: boolean
"""
require... | 3ddc53fc0e2caad74b3218f7f47134aed258cba9 | 63,565 |
def accuracy_inf_sol(inferred,cliques_solution):
"""
'inferred' should be a set of vertices
'cliques_solution' an iterable of all the solution cliques (as sets)
"""
assert len(cliques_solution)!=0, "No solution provided!"
max_overlap = 0
best_clique_sol = cliques_solution[0]
clique_size ... | d2d38d7f3470520058f90699dab6b7eb59cbd5cf | 63,568 |
def GetGlobalParamsFromFlags():
"""Return a StandardQueryParameters based on flags."""
result = messages.StandardQueryParameters()
if FLAGS['alt'].present:
result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt)
if FLAGS['fields'].present:
result.fields = FLAGS.fields.decode('utf8')
... | 85758c3bf6acf7bd4c1d2b7045ffb0b4704c27c9 | 63,569 |
def load_japanese_vowels(split='TRAIN', return_X_y=False):
"""
Loads the JapaneseVowels time series classification problem and returns X and y.
Parameters
----------
split: str{"ALL", "TRAIN", "TEST"}, optional (default="TRAIN")
Whether to load the train or test partitio... | 2a378ee9e6625dbcc00463dd785e2b979bcc54bc | 63,570 |
def _ziprange(alist, ix):
"""
returns zip of the list, and the one with ix added at the end and first element dropped
Example
-------
::
alist = [2,4,7]
_ziprange (alist, 10)
-->
zip([2,4,7], [4,7,10]) -> (2,4), (4,7), (7,10)
"""
blist = alist.copy()
... | e816ad20e8c193487d8483cdfd3ee27d77fef814 | 63,571 |
def sgnlog(
x,
base=np.e):
"""
Signed logarithm of x: log(abs(x) * sign(x)
Args:
x (float|ndarray): The input value(s)
Returns:
The signed logarithm
Examples:
>>> sgnlog(-100, 10)
-2.0
>>> sgnlog(-64, 2)
-6.0
>>> sgnlog(100, ... | f1ea3520e85d6dfdad28deb3653356f6e3e515cd | 63,572 |
import re
def title_output_replace(input_title_output, metadata_dict, data_dict, rel_channels_dict, is_title = False, custom_vars = None):
"""Substitute %VAR% variables with provided values and constants.
Given a title (or output path) string template, replace %VAR%
variables with the appropriate va... | 83102c1557643b67ce1c52f0c69154bcfac4ac72 | 63,574 |
def get_sf(labels):
"""Returns the shape factor for each object in a labeled image
Parameters
----------
labels : 2D numpy array
an image (usually 16bit) with the cell/object labels
Returns
-------
sf_list : 1D numpy array
shape factor for each label (order corresponds to... | 34da736eaf90e927df45563ae8002f4d5203559e | 63,575 |
def getManagementBodies(project, category):
"""Returns a sorted list of a specific category of management bodies for a given project."""
# transform QuerySet into list
bodies = list(ManagementBody.objects.filter(project=project).filter(category=category))
# sort by title
return sorted(bodi... | 12be33558e1e6094b645f9f5f86465d83affbc22 | 63,576 |
def is_reference(message_or_descriptor: MessageOrDescriptorBase) -> bool:
"""Returns true if message_or_descriptor is of a reference type.
Args:
message_or_descriptor: A protobuf Message or DescriptorBase to examine.
Returns:
A Boolean indicating whether or not message_or_descriptor is a reference.
R... | 1db6e9f1c36774a662a032b9b7e1c943ca28eed1 | 63,577 |
def format_data(data, es_index):
"""
Format data for bulk indexing into elasticsearch
"""
unit = data["unit"]
rate_unit = data["rateUnit"]
egvs = data["egvs"]
docs = []
for record in egvs:
record["unit"] = unit
record["rate_unit"] = rate_unit
record["@timestamp"]... | 094af427daaf4922371e17fca70a2b8c8539d54c | 63,578 |
from pathlib import Path
def specifier_proc(dataset, subject, ix_run, es):
"""
Like specifier, but returns the equivalent folder structure for processing.
Unlike for specifier, these folders do not need to exist a-priori. For convenience, they generally take a similar
structure to what is written for ... | 7f06fd9a0bb61b9b97e67f261609e00ebdbb9e45 | 63,579 |
def get_first_derivative_matrix(n):
"""
:param x: numpy array of x-values
:return: A matrix D such that if x.size == (n,1), D * x is the first derivative of x
:symmetric first derivative (excludes endpoints like as before)
"""
m = n - 2
F = spmatrix(list(chain(*[[-0.5, 0.0, 0.5]] * m)),
... | 0ce67edd5e0acb411a394d410c27cbb373f86d42 | 63,581 |
def song_comments(commentThreadId, limit=10, offset=0):
"""
根据commentThreadId获取歌曲评论
"""
# upl = user_playlist(uid, limit=1)
base_url = 'http://music.163.com/weapi/v1/resource/comments/%s/' % commentThreadId
# data = {'offset': offset, 'limit': limit, 'uid': uid}
for i in range(retry_times):... | 1ec01ff6458396756d4c58e2a94ee1a54ae7949c | 63,583 |
from typing import Optional
def get_description(prefix: str, use_markdown=True) -> Optional[str]:
"""Get the description for the given prefix, if available."""
entry = get_resource(prefix)
if entry is None:
return None
return entry.get_description(use_markdown=use_markdown) | 257da257e65ef8b51ca431d7b6e061f7816cb06d | 63,584 |
import requests
def chain_entry_first(chain_id=None):
""" """
res = requests.request("GET", URL + '/chains/%s/entries/first' % chain_id, headers=HEADERS)
return _decode_response(res.content) | a97fb998272e6266730a23de8a78782d94da491c | 63,585 |
def paste_filename(search):
"""
Function that will create a name for the files to be saved to using the search
"""
# Removes any spaces
cleaned_keyword = search.replace(' ', '_')
# Adds 'videos.csv' at the end
filename = cleaned_keyword + "_videos.csv"
return filename | 3279ef21e039b7a63a728a6d02714086a61f3e0e | 63,586 |
def format_date(df, columns, current_format, output_format):
"""
Parameter
---------
df : dataframe whose date column has to be modified
columns : Name date columns to be transformed.
current_format : current date string format eg: dd-MM-yyy
output_format ... | eedaab4469312f9404da5600c6739004ccda53e4 | 63,587 |
def Hindex(citationlist):
"""根据citationlist获得h因子。
citationlist是按顺序的每篇文章引用次数列表
"""
indexSet = sorted(list(set(citationlist)), reverse=True)
for index in indexSet:
clist = [i for i in citationlist if i >= index]
if index <= len(clist):
break
return index | 5ef90ebf60c04df466d92bcc0d4dbb136bd4d8ca | 63,588 |
from typing import Dict
from typing import Any
from typing import Optional
from typing import Union
async def parse(
bot: Bot,
_dict: Dict[str, Any],
guild: Optional[Guild] = None
) -> Union[Channel, ChannelGroup]:
"""
解析子频道信息字典为 `Channel` 或 `ChannelGroup` 类型。
参数:
- _dict: 将用于解析的字典
... | 381e2fb1134d55589e3f309dfc08f68fafb59276 | 63,589 |
from typing import OrderedDict
def get_global_vars_dict(scope=None):
"""Returns all variables in the session in a dictionary form"""
all_vars = get_global_vars_list(scope)
vars_dict = OrderedDict()
for var in all_vars:
vars_dict[var.name] = var
return vars_dict | 45e70fc62cbacdf1658ad283bea72f898f8ff5ca | 63,590 |
def get_parser():
"""
Get parser object for `eco_mocks_create.py` script.
Returns
-------
args:
input arguments to the script
"""
## Define parser object
description_msg = 'Downloads the necessary catalogues from the web'
parser = ArgumentParser(description=description_msg,... | 7f16ac54794625a2e74df29cbefc09744c8f2c64 | 63,591 |
import numpy
def CalculateTotalNCharge(mol):
"""
#################################################################
The total negative charge
-->Tnc
Usage:
result=CalculateTotalNCharge(mol)
Input: mol is a molecule object.
Output: result is a numeric... | 55cd6bbc164cf1fbf6c244f491104ada2658e488 | 63,592 |
def create_pr_par(chrom, par_dict):
"""
create_pr_par
=============
Method to create a pyranges object of the PAR regions on the X chromosome.
Parameters:
-----------
1) chrom: (str) The Chromosome to use. (NOTE: Should be the "X" chromosome"
2) par_dict: (dict) The genome build spe... | 3dc523cb889ac7ad18972de618a05b3797e32822 | 63,593 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the foscam component."""
hass.data.setdefault(DOMAIN, {})
return True | 2af8bd4a8f7f1c7bf201e3297cc59242fc6bb2c5 | 63,594 |
import codecs
import logging
def load_embedding(filename, embedding_size):
"""
load embedding
"""
embeddings = []
word2idx = defaultdict(list)
idx2word = defaultdict(list)
idx = 0
with codecs.open(filename, mode="r", encoding="utf-8") as rf:
try:
for line in rf.read... | 374a067c91e722c8a2f3052e38f447ce7b83bfaf | 63,595 |
def grib_keys_iterator_new(msgid, namespace=None):
"""
@brief Create a new iterator on the keys.
The keys iterator can be navigated to give all the key names which
can then be used to get or set the key values with \ref grib_get or
\ref grib_set.
The set of keys returned can be controlled with ... | 9ee9bb3304f49bd192ba0998942f514fce2d85d6 | 63,596 |
def get_eval_list(assessment, current_user):
"""Returns the list of teammates who are evaluated"""
for team in Team.objects.all():
if current_user in team.student.all() and team.course == assessment.course: # get the team
evaluated_list = [student for student in team.student.all() if student... | 25fb566f37d90f577e92005eb75fcb552c0096d0 | 63,597 |
def _run_in_background(func):
"""Run func in a new thread. The thread is expected to exit on its own."""
@wraps(func)
def wrapped(*args, **kwargs):
Thread(target=func, args=args, kwargs=kwargs).start()
return wrapped | b9af5bc8cb8e653720c5cfac812289312539df79 | 63,598 |
def input_default(default_word='', tip_words='Please input words.'):
"""return default_word while input() return blank"""
input_data = input(tip_words + '(default: ' + default_word + ')\n')
if input_data.strip() == '':
print('Blank input. Using the default value: {0}'.format(default_word))
r... | 5873fd6b29f932c8f59262fb44749827eb9bcc29 | 63,599 |
def trimylim(simdat, ylim):
"""
Remove realization experimental variogram points beyond a variogram value so they won't be
plotted.
Parameters:
simdat (pd.DataFrame):
ylim (float): Value to trim points after
"""
# Get the column containing the index
if 'Variogram Index' in s... | 7f60073810a4167bc491772ce9e4c1aa23ec8183 | 63,600 |
def encode_operation(operation, flags):
"""Encodes a flagged operation as a single-byte opcode."""
encoding = OPCODE_ENCODING[operation]
for flag in flags:
encoding |= FLAG_ENCODING[flag]
return encoding | 633a7587ab08b996cad22036ae9133b061fe0249 | 63,601 |
import time
def sparseFitFluxes(oi, firstGuess, N={}, initFlux={}, refFlux=None,
significance=4, fitOnly=None, doNotFit=None,
maxfev=5000, ftol=1e-3, epsfcn=1e-8, prior=[]):
"""
use discrete wavelets (WVL) to model spectra of different components.
firstGuess: initial multi... | 83f51b4778ec115e49e7e1e7370bb32fab1660ba | 63,602 |
def transform_action_symbol(sym):
"""Transform the action symbol to a form to be more easily tokenized by BART vocabulary.
We adopt the following rules:
- lower-case everything, so that
SHIFT -> shift, REDUCE -> reduce, MERGE -> merge
- verbalize some actions, so that the meanings are better rep... | e901689c217bf47c5127b7ebadb679c3618365c6 | 63,603 |
from typing import Dict
import PIL
def plot_detections(
detection: Dict,
data: "DetectionDataset" = None,
idx: int = None,
keypoint_meta: Dict = None,
ax: plt.axes = None,
) -> PIL.Image.Image:
""" Put mask onto image.
Args:
detection: output running model prediction.
data... | 40ac809842fc0095fa84d1c66527909eec956c37 | 63,604 |
def sfc_area_latlon_box(ds, lat_str=LAT_STR, lon_str=LON_STR,
lat_bounds_str=LAT_BOUNDS_STR,
lon_bounds_str=LON_BOUNDS_STR,
sfc_area_str=SFC_AREA_STR, radius=RAD_EARTH):
"""Calculate surface area of each grid cell in a lon-lat grid."""
lon ... | 2aef4dd42dad32c0e58ed064280cbe10088ecb23 | 63,605 |
def list_rules(repository):
"""
Returns all RepoMirrorRules associated with a Repository.
"""
rules = RepoMirrorRule.select().where(RepoMirrorRule.repository == repository).all()
return rules | cf9137f3b105c361af3d53d94da737a0b89bccf3 | 63,607 |
import torch
def repeat_column(column: torch.Tensor, times: int) -> torch.Tensor:
"""
Repeats the given column the given number of times.
:param column: the column to repeat. Size [H].
:param times: the number of repetitions = W.
:return: the given column repeated the given number of times. Size [... | dfa955fbff0c4b87a7f5cef729a454eb99c93760 | 63,609 |
from keras.utils import multi_gpu_model
def create_models(backbone_retinanet, num_classes, weights, multi_gpu=0,
freeze_backbone=False, lr=1e-5, config=None):
""" Creates three models (model, training_model, prediction_model).
Args
backbone_retinanet : A function to call to create a... | ca2e91bc0703726093929fd1f749918f1011201c | 63,610 |
def get_input_decay(name):
"""
Generates the appropriate decay function for a given variable. The decays
that can be generated are static (no decay over time), linear and
exponential.
:param name: name of the variable that will be generated
:return: decay function for the variable with appropria... | cd78a75f475be01e0927cf0725b9ff0c2bb308e4 | 63,611 |
def tide_pred(modfile,lon,lat,time,z=None,conlist=None):
"""
Performs a tidal prediction at all points in [lon,lat] at times in vector [time]
z: provide depths for the transport to velocity conversion. If None, the OTPS
model depths will be used. If 1.0, it will effectively return transport values
... | 48a4544db875ac061233d5ecdffd60c844e461db | 63,612 |
def _batchnorm_fold_grad_compute(d_batch_mean, d_batch_std, data_x, batch_mean, batch_std):
"""_batchnorm_fold_grad_compute """
shape_x = te.lang.cce.util.shape_to_list(data_x.shape)
normal_size = shape_x[0] * shape_x[2] * shape_x[3]
d_batch_mean_broad = te.lang.cce.broadcast(d_batch_mean, shape_x)
... | 3ee1d8830b73c215ae1b2d14ddb586455c486262 | 63,613 |
def plot_model(fig,ax,M,my_cmap = 'cividis',lim=None):
"""
Plot 2D model, setting zeros to nans so they are not shown
"""
sel = (~np.isnan(M))
if lim is None:
lim = [M[sel].min(),M[sel].max()]
im = ax.matshow(M,cmap=plt.get_cmap(my_cmap),vmin=lim[0],vmax=lim[1])
cbar = fig.colorb... | be5e7feb0dfe4ed5c075682376a67887cc906be5 | 63,615 |
import logging
import requests
def youtube_video_details(key, vid_ids):
"""Return details of videos for which the ids are given.
Assumes ``ids`` is a comma-separated list of video ids with
no spaces."""
base_url = ('https://www.googleapis.com/youtube/v3/videos?part='
'contentDetails,id... | b6bbe82278357536b6f0f551ea50e45497154cc5 | 63,616 |
def build_put_model_as_string_required_one_value_no_default_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Puts constants to the testserver.
Puts constants to the testserver.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into... | d787dd034a8202e9d03c6a9f9d35263c2d91e6ac | 63,617 |
import itertools
def return_output(sim, outputs, reduced_precision=True):
"""Save simulated time series in npz format under keywords corresponding to
monitor names.
Parameters
----------
sim : tvb.simulator
Instance of the simulator which produced the outputs.
outputs : list
R... | 5ab349fcfdc23c601d37dd17f513bfa292109465 | 63,618 |
from typing import Optional
from typing import Tuple
import torch
def _input_format_classification(
preds: Tensor,
target: Tensor,
threshold: float = 0.5,
top_k: Optional[int] = None,
num_classes: Optional[int] = None,
multiclass: Optional[bool] = None,
) -> Tuple[Tensor, Tensor, DataType]:
... | c265a1360fe92631baf5a9aa634ab55879486969 | 63,619 |
def recipe_detail_url(recipe_id: int) -> str:
"""Return recipe detail URL"""
return reverse("recipe:recipe-detail", args=[recipe_id]) | 93180992c2d7a9a00b06383d2296a44909d1ec2a | 63,621 |
def add_page_to_extra_context(view_func):
"""
Adds the best-match page to the extra_context keyword argument. Mainly used
to provide generic views which integrate into the page module.
"""
def inner(request, *args, **kwargs):
kwargs.setdefault('extra_context', {})
kwargs['extra_cont... | 764e1fc9046f4cdb893ace566ceccf6a9a175ec1 | 63,622 |
def _create_outer_to_inner(angle: f32['']) -> geom.Transform:
"""Constructs an "outside" box to "inside" box transform.
Consider an "outside" box of shape [-1, 1]^3. We define an "inside" box to
be a box that sits inside of the "outside" box with a rotation about the
z-axis. The inside box is defined such that... | b097a1e248cae1e40414d7b76754e8f67d460177 | 63,623 |
def where_not_all_match(labels_1: Labels, labels_2: Labels):
"""Compare clustering labels of the same input data
generated by different DBSCAN approaches.
"""
more_than_one_unique_label = []
for unique_label_1 in labels_1.unique.labels:
idx_1 = np.where(labels_1.labels == unique_label_1)[0]
... | b586754a138f94544014317da557b5507e7c98f6 | 63,624 |
def zpad(x, pd, ax):
"""Zero-pad array `x` with `pd = (leading, trailing)` zeros on axis `ax`.
Parameters
----------
x : array_like
Array to be padded
pd : tuple
Sequence of two ints (leading,trailing) specifying number of zeros
for padding
ax : int
Axis to be padded
... | 671d8ada6ffbc5b6700c7500d633c6c0449adc28 | 63,625 |
import operator
def get(ind, seq, default=no_default):
""" Get element in a sequence or dict
Provides standard indexing
>>> get(1, 'ABC') # Same as 'ABC'[1]
'B'
Pass a list to get multiple values
>>> get([1, 2], 'ABC') # ('ABC'[1], 'ABC'[2])
('B', 'C')
Works on any value th... | 61dc1a0cc02e29f9f51cc57f34aa60bf6bf8d83a | 63,626 |
def compare(hand1, hand2):
"""
Compares hand1 to hand2
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
In the foregoing description, the notation sgn(expression) designates the mathe... | 5c7a652e27effe9cd01762839f78af53b889a93c | 63,629 |
def identity():
# type: () -> Projection
"""Creates a projection that does no transformation.
Returns:
Projection[hazelcast.core.MapEntry]: A projection that does no
transformation.
"""
return _IdentityProjection() | 2dd69bb631ddf8fb0bef53b0b509a3a74d104cd1 | 63,630 |
import unicodedata
def remove_punctuation(text):
"""Replaces all Unicode punctuation except dashes (Pd) with whitespaces.
Potentially induces duplicate whitespaces.
"""
text = ''.join(
' '
if unicodedata.category(c)[0] == 'P'
and unicodedata.category(c)[1] != 'd'
else c... | 0bf4c1f9100051a09252bcd3f24a8a593dc02ce2 | 63,631 |
def remove_distant_agents(x, k, indices=None):
""" Remove the distant agents.
Args:
x (N, N, C): The state difference of N agents.
k (int): The K nearest agents to keep.
Returns:
x (N, K, C): The K nearest agents.
indices (N, K): The indices of K nearest agents of each agent.... | 292072c14f4ed42999f30ec3b4b17bc90280257f | 63,632 |
import time
def _strTogMonth(v):
"""Test gYearMonth value
@param v: the literal string
@return v
@raise ValueError: invalid value
"""
try:
time.strptime("2001-" + v + "-01", "%Y-%m-%d")
return v
except:
raise ValueError("Invalid gMonth %s" % v) | 64962552ab9ae5df06f76f07c91c549927caa0dd | 63,633 |
import torch
def calc_cam(x, label, model):
"""
function to generate a class activation map corresponding to a torch image tensor
Args:
x: the 1x3x224x224 pytorch tensor file that represents the NIH CXR
label:user-supplied label you wish to get class activation map for; must be in FINDING... | 57712b9a043808f867e447dcdcb94b077e968e05 | 63,634 |
import json
def load_data():
"""記録データを返します"""
try:
database = json.load(open(DATA_FILE, mode="r", encoding="utf-8"))
except FileNotFoundError:
database = []
return database | 3ec779d6618ed497f25ad78b140efbd551daaab7 | 63,635 |
def parse_markers(f):
"""
Parse markers from mrk file f. Each marker determines a time point
and an according class-label of the movement that was imagined.
Args:
f (String) - an mrk file
Returns:
tuple of lists of ints - one list for the markers, one for
... | 670ce43529a7aae4f4ed4341938a90eb6e714fb3 | 63,636 |
def insert_file(service, title, description, parent_id, mime_type, filename):
"""Insert new file.
Args:
service: Drive API service instance.
title: Title of the file to insert, including the extension.
description: Description of the file to insert.
parent_id: Parent folder's ID.
mime_type: MIM... | b33afc947c33bfc96ddfa0ccbb92afb19ad9e454 | 63,637 |
from openeye import oechem, oedocking
from openeye import oeomega
def dock_molecules_to_receptor(receptor_filename, molecules):
"""
Dock the specified molecules, writing out to specified file
Parameters
----------
receptor_filename : str
Receptor .oeb.gz filename
molecules : list of o... | 5e1f66f8ea768e2b6423c5151d58d0f4a06619fe | 63,638 |
def polygon_shapes_from_voronoi_lines(poly_lines, geo_shape=None, shapes_from_diff_with_min_area=None):
"""
Form shapely Polygons objects from a list of shapely LineString objects in `poly_lines` by using
[`polygonize`](http://toblerity.org/shapely/manual.html#shapely.ops.polygonize). If `geo_shape` is not ... | 75b842948f739ab0ef222bda2996712c9dbeaa6a | 63,639 |
import time
import numpy
def simulate_conway_generations_from_image(initial_image,
life_generations,
empty_space_detection_depth=6):
"""
:param initial_image: The image that is the initial state, generation 0, of the simula... | dd5a7d3686fc6fea4a537438e3d9903496960cf8 | 63,640 |
import random
def randomFlip(input_image, flip_prob = 0.5):
""" flip the single image horizontally with probability flip_prob"""
tmp = random.random()
if tmp <= flip_prob:
fliped_image = input_image[:, ::-1,:];
output_image = fliped_image
FLAG = 1
else:
output_image = i... | 93587e838439aea12ea84ba44556c8575b7e3759 | 63,641 |
def countPlayers():
"""Returns the number of players currently registered."""
conn = connect()
c = conn.cursor()
c.execute("SELECT * FROM players;")
playerList = c.rowcount
conn.close()
return playerList | f487b5a61d687e218767b8865a7d9bca3426b8e2 | 63,642 |
import requests
def fetch_mb_release(mbid, user_agent='mb2md/1.0', https=True):
"""Fetches and returns the JSON recordings info for a specific MusicBrainz
ID from the MusicBrainz API.
:param mbid: MusicBrainz release ID
:param user_agent: what user-agent header to send
:param https: whether to us... | 315a475aa4dc2fc312aff5107d03127002230b99 | 63,643 |
from typing import Any
def build_post_flattened_simple_product_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Put Flattened Simple Product with client flattening true on the parameter.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request... | 1ee8bdc207cfd3d379466a9ceaf39f22d3c218dd | 63,644 |
def capture_reward_expected_c(cap_skill=CAP_SKILL_NONE):
"""
Expected value for number of capture rewards given the specified
capture skill (none by default).
"""
if cap_skill == CAP_SKILL_NONE:
min_c = 2
max_c = 3
extend_p = 22 * 100.0 / 32
elif cap_skill == CAP_SKILL_EX... | 563f3a4ad07a6121880f0fba989331a63fd3990b | 63,645 |
from concurrent.futures import ThreadPoolExecutor
def thread_map(fn, *iterables, **tqdm_kwargs):
"""
Equivalent of `list(map(fn, *iterables))`
driven by `concurrent.futures.ThreadPoolExecutor`.
Parameters
----------
tqdm_class : optional
`tqdm` class to use for bars [default: tqdm.au... | 84e325ae66a33fd3fe3ac2f912449951c136b035 | 63,646 |
def print_file(remote_filename):
"""
Gets and returns the content of a remote file.
Do this instead of call type in order to avoid console width issues.
"""
temp_file = cStringIO.StringIO()
with hide('everything'):
get(remote_path=remote_filename,
local_path=temp_file)
te... | 0385f2201bb5d02f527825953212b661ed515b6d | 63,647 |
def get_max_cpus():
"""
Returns the maximum number of CPU cores available for us to use
"""
try:
return cpu_count()
except NotImplementedError:
# If we can't figure out how many CPU cores we have... well there's got
# to be at least 1 right?
return 1 | 467a1686bf18b1fccef9408562a088ca739d30c0 | 63,648 |
def fuzzy_vector_equal(x_vec, y_vec, tolerance=global_tolerance):
""" Same as above, but for vectors.
x_vec, y_vec are 1d numpy arrays
"""
return all(abs(el) < tolerance for el in x_vec - y_vec) | 7ffe5864396234713dc583e76418120621ead1b3 | 63,649 |
def dp_key(relations):
"""
generates a unique key for the dptable dictionary
:param relations: set of relations
:return: str
"""
return '-'.join(sorted([r.name for r in relations])) | e415778193d5a5c90ba7574bccc7e82d0d95c2e8 | 63,650 |
def interp_empty_months(ds, method='full', inplace=True):
"""
Takes a xarray dataset/array and performs linear interpolation across
each month seperatly. A concatenated xr dataset is returned. This is a
wrapper for perform_interp function. The method can be set to full
or half. Full will use the b... | b935948d3345cab8fd6f6cf6cf5b6259474cec77 | 63,651 |
import json
import requests
def submitNotebookJob(notebookPath, dockerComputeDomain=None, dockerImageName=None, userVolumes=None, dataVolumes=None, resultsFolderPath="", parameters="", jobAlias= ""):
"""
Submits a Jupyter Notebook for execution (as an asynchronous job) inside a Docker compute domain.
:p... | 98217c2ed3b29638a6b25fe98cbfe37d06f25e80 | 63,653 |
def _MergeSwarmingTestShards(shard_results):
"""Merges the shards into one.
Args:
shard_results (list): A list of dicts with individual shard results.
Returns:
A dict with the following form:
{
'all_tests':[
'AllForms/FormStructureBrowserTest.DataDrivenHeuristics/0',
'AllForms/... | 2c9161bf0b5f4e748e54c51b45742505ef685d78 | 63,654 |
def find_nonterminals(mat):
"""Find nonterminal states in a transition matrix."""
return [ix for ix, row in enumerate(mat) if row[ix] != 1] | 04a7e58d4dc94aa5d7370aadc65f06edd47459b7 | 63,655 |
def transfer_asset(txn_key,
batch_key,
identifier,
label,
sender,
amount):
"""Create an AcceptOffer txn and wrap it in a Batch and list.
Args:
txn_key (sawtooth_signing.Signer): The Txn signer key pair.
batch_k... | ac1ff5956f164dc07cb05cb12c4a08397375e3d0 | 63,656 |
import pandas
def prepare_and_plot_box_risk_groups(df: pandas.DataFrame, trait_code: str,
data_column_name: str, output_path: str, sex: str = 'both',
ancestry: str = 'All'):
"""Prepares data for plotting box plots for risk groups, creates t... | d276c6523d297260988a2c62607e77b13907158c | 63,657 |
def _set_up_parser():
"""Defines a parser object used in the API that also defines possible choices presented to the user."""
problems = ("max_cut", "stable_set", "graph_partition", "vertex_cover")
p_values = (1, 2, 3, 4)
graph_types = ("random", "caveman", "barbell", "ladder")
parser = reqparse.Re... | ee03d818cc4e28dff5507e4efe74608b2828d4ab | 63,658 |
def prepare_design_masked(D: np.ndarray, mask_bw: np.ndarray) -> np.ndarray:
"""Design matrix using only the pixels in the mask
Args
----
D: np.ndarray
The design matrix as it comes from build_Design_Matrix
mask_bw: np.ndarray (binary or boolean)
The image used as mask. Entryes ... | 47072e25178722b106ef8d7221f249408a33ae74 | 63,659 |
import html
def subview_results_container_html():
"""
The placeholder html block for results. This is updated via callback.
WANRING: for the loading animation to work correctly, it must be the direct
parent of an html block which is being updated via callback.
Args:
None
Returns:
... | acd30316cc46cfdb49f09acf97b3e235fec6db56 | 63,660 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.