content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def expected_win(theirs, mine):
"""Compute the expected win rate of my strategy given theirs"""
assert abs(theirs.r + theirs.p + theirs.s - 1) < 0.001
assert abs(mine.r + mine.p + mine.s - 1) < 0.001
wins = theirs.r * mine.p + theirs.p * mine.s + theirs.s * mine.r
losses = theirs.r * mine.s + theirs... | 92de2010287e0c027cb18c3dd01d95353e4653c4 | 2,144 |
def SizeArray(input_matrix):
"""
Return the size of an array
"""
nrows=input_matrix.shape[0]
ncolumns=input_matrix.shape[1]
return nrows,ncolumns | 3ac45e126c1fea5a70d9d7b35e967896c5d3be0b | 2,148 |
def preimage_func(f, x):
"""Pre-image a funcation at a set of input points.
Parameters
----------
f : typing.Callable
The function we would like to pre-image. The output type must be hashable.
x : typing.Iterable
Input points we would like to evaluate `f`. `x` must be of a type acce... | 6ca0496aff52cff1ce07e327f845df4735e3266a | 2,152 |
from typing import Dict
def load_extract(context, extract: Dict) -> str:
"""
Upload extract to Google Cloud Storage.
Return GCS file path of uploaded file.
"""
return context.resources.data_lake.upload_df(
folder_name="nwea_map",
file_name=extract["filename"],
df=extract["v... | c9d5fedf6f2adcb871abf4d9cead057b0627267a | 2,153 |
def reverse_index(alist, value):
"""Finding the index of last occurence of an element"""
return len(alist) - alist[-1::-1].index(value) -1 | 21fc4e17a91000085123ea4be42c72cb27a3482c | 2,158 |
def shingles(tokens, n):
"""
Return n-sized shingles from a list of tokens.
>>> assert list(shingles([1, 2, 3, 4], 2)) == [(1, 2), (2, 3), (3, 4)]
"""
return zip(*[tokens[i:-n + i + 1 or None] for i in range(n)]) | 93e8f3828bf4b49397e09cb46565199dcd7a68be | 2,162 |
def prefix_attrs(source, keys, prefix):
"""Rename some of the keys of a dictionary by adding a prefix.
Parameters
----------
source : dict
Source dictionary, for example data attributes.
keys : sequence
Names of keys to prefix.
prefix : str
Prefix to prepend to keys.
Retu... | e1c8102fddf51cd7af620f9158419bff4b3f0c57 | 2,165 |
def _grep_first_pair_of_parentheses(s):
"""
Return the first matching pair of parentheses in a code string.
INPUT:
A string
OUTPUT:
A substring of the input, namely the part between the first
(outmost) matching pair of parentheses (including the
parentheses).
Parentheses between... | 7441c1b8734c211b9b320e195155719452cf7407 | 2,166 |
def find_start_end(grid):
"""
Finds the source and destination block indexes from the list.
Args
grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf)
Returns
start: <int> source block index in the list
end: <int> destination block index... | d617af3d6ebf9a2c9f42250214e3fe52d2017170 | 2,169 |
from typing import Optional
import inspect
def find_method_signature(klass, method: str) -> Optional[inspect.Signature]:
"""Look through a class' ancestors and fill out the methods signature.
A class method has a signature. But it might now always be complete. When a parameter is not
annotated, we might ... | 17d3e7d554720766ca62cb4ad7a66c42f947fc1c | 2,170 |
def split_bits(word : int, amounts : list):
"""
takes in a word and a list of bit amounts and returns
the bits in the word split up. See the doctests for concrete examples
>>> [bin(x) for x in split_bits(0b1001111010000001, [16])]
['0b1001111010000001']
>>> [bin(x) for x in split_bits(... | 556a389bb673af12a8b11d8381914bf56f7e0599 | 2,173 |
def save_network_to_path(interactions, path):
"""Save dataframe to a tab-separated file at path."""
return interactions.to_csv(path, sep='\t', index=False, na_rep=str(None)) | f189c6e8f7791f1f97c32847f03e0cc2e167ae90 | 2,177 |
import re
def is_branch_or_version(string):
"""Tries to figure out if passed argument is branch or version.
Returns 'branch', 'version', or False if deduction failed.
Branch is either 'master' or something like 3.12.x;
version is something like 3.12.5,
optionally followed by letter (3.12.5b) for a... | 6a5ad7cb7af29b6ce0e39ff86171f0f230929fb3 | 2,180 |
def CONTAINS_INTS_FILTER(arg_value):
"""Only keeps int sequences or int tensors."""
return arg_value.elem_type is int or arg_value.has_int_dtypes() | c4452c5e6bbd9ead32359d8638a6bf1e49b600ba | 2,185 |
def sort_2metals(metals):
"""
Handles iterable or string of 2 metals and returns them
in alphabetical order
Args:
metals (str || iterable): two metal element names
Returns:
(tuple): element names in alphabetical order
"""
# return None's if metals is None
if metals is None:... | dab922797a6c7b94d6489d8fc4d9c1d99f3ee35c | 2,188 |
from datetime import datetime
def datetime_without_seconds(date: datetime) -> datetime:
"""
Returns given datetime with seconds and microseconds set to 0
"""
return date.replace(second=0, microsecond=0) | de30c7770d84751b555c78e045f37783030d8970 | 2,189 |
import six
def format_ratio(in_str, separator='/'):
""" Convert a string representing a rational value to a decimal value.
Args:
in_str (str): Input string.
separator (str): Separator character used to extract numerator and
denominator, if not found in ``in_str`` w... | 308ec972df6e57e87e24c26e769311d652118aee | 2,190 |
from typing import Any
def get_artist_names(res: dict[str, Any]) -> str:
"""
Retrieves all artist names for a given input to the "album" key of a response.
"""
artists = []
for artist in res["artists"]:
artists.append(artist["name"])
artists_str = ", ".join(artists)
return artist... | 2913c813e7e6097cb2cb3d3dfb84f831bbc0a6e7 | 2,195 |
from typing import Iterator
from typing import Tuple
from typing import Any
import itertools
def _nonnull_powerset(iterable) -> Iterator[Tuple[Any]]:
"""Returns powerset of iterable, minus the empty set."""
s = list(iterable)
return itertools.chain.from_iterable(
itertools.combinations(s, r) for r... | ad02ab8ac02004adb54310bc639c6e2d84f19b02 | 2,196 |
def printable_cmd(c):
"""Converts a `list` of `str`s representing a shell command to a printable
`str`."""
return " ".join(map(lambda e: '"' + str(e) + '"', c)) | b5e8a68fc535c186fdbadc8a669ed3dec0da3aee | 2,198 |
def is_compiled_release(data):
"""
Returns whether the data is a compiled release (embedded or linked).
"""
return 'tag' in data and isinstance(data['tag'], list) and 'compiled' in data['tag'] | ea8c8ae4f1ccdedbcc145bd57bde3b6040e5cab5 | 2,202 |
def divisor(baudrate):
"""Calculate the divisor for generating a given baudrate"""
CLOCK_HZ = 50e6
return round(CLOCK_HZ / baudrate) | a09eee716889ee6950f8c5bba0f31cdd2b311ada | 2,204 |
def send(socket, obj, flags=0, protocol=-1):
"""stringify an object, and then send it"""
s = str(obj)
return socket.send_string(s) | a89165565837ad4a984905d5b5fdd73e398b35fd | 2,206 |
def strip_extension(name: str) -> str:
"""
Remove a single extension from a file name, if present.
"""
last_dot = name.rfind(".")
if last_dot > -1:
return name[:last_dot]
else:
return name | 9dc1e3a3c9ad3251aba8a1b61f73de9f79f9a8be | 2,209 |
def remove_arm(frame):
"""
Removes the human arm portion from the image.
"""
##print("Removing arm...")
# Cropping 15 pixels from the bottom.
height, width = frame.shape[:2]
frame = frame[:height - 15, :]
##print("Done!")
return frame | 99b998da87f1aa2eca0a02b67fc5adc411603ee4 | 2,216 |
import re
def valid_account_id(log, account_id):
"""Validate account Id is a 12 digit string"""
if not isinstance(account_id, str):
log.error("supplied account id {} is not a string".format(account_id))
return False
id_re = re.compile(r'^\d{12}$')
if not id_re.match(account_id):
... | 30f3aa9547f83c4bea53041a4c79ba1242ae4754 | 2,218 |
def is_color_rgb(color):
"""Is a color in a valid RGB format.
Parameters
----------
color : obj
The color object.
Returns
-------
bool
True, if the color object is in RGB format.
False, otherwise.
Examples
--------
>>> color = (255, 0, 0)
>>> is_col... | 46b8241d26fa19e4372587ffebda3690972c3395 | 2,220 |
import ipaddress
import logging
def _get_ip_block(ip_block_str):
""" Convert string into ipaddress.ip_network. Support both IPv4 or IPv6
addresses.
Args:
ip_block_str(string): network address, e.g. "192.168.0.0/24".
Returns:
ip_block(ipaddress.ip_network)
"""
... | b887c615091926ed7ebbbef8870e247348e2aa27 | 2,229 |
def mul_ntt(f_ntt, g_ntt, q):
"""Multiplication of two polynomials (coefficient representation)."""
assert len(f_ntt) == len(g_ntt)
deg = len(f_ntt)
return [(f_ntt[i] * g_ntt[i]) % q for i in range(deg)] | 504838bb812792b6bb83b1d485e4fb3221dec36e | 2,230 |
from datetime import datetime
def parse_date(datestr):
""" Given a date in xport format, return Python date. """
return datetime.strptime(datestr, "%d%b%y:%H:%M:%S") | b802a528418a24300aeba3e33e9df8a268f0a27b | 2,235 |
def get_num_forces(cgmodel):
"""
Given a CGModel() class object, this function determines how many forces we are including when evaluating the energy.
:param cgmodel: CGModel() class object
:type cgmodel: class
:returns:
- total_forces (int) - Number of forces in the coarse grained model
... | 5f5b897f1b0def0b858ca82319f9eebfcf75454a | 2,236 |
def _passthrough_zotero_data(zotero_data):
"""
Address known issues with Zotero metadata.
Assumes zotero data should contain a single bibliographic record.
"""
if not isinstance(zotero_data, list):
raise ValueError('_passthrough_zotero_data: zotero_data should be a list')
if len(zotero_d... | cec2271a7a966b77e2d380686ecccc0307f78116 | 2,240 |
def ignore_ip_addresses_rule_generator(ignore_ip_addresses):
"""
generate tshark rule to ignore ip addresses
Args:
ignore_ip_addresses: list of ip addresses
Returns:
rule string
"""
rules = []
for ip_address in ignore_ip_addresses:
rules.append("-Y ip.dst != {0}".fo... | 3ac43f28a4c8610d4350d0698d93675572d6ba44 | 2,242 |
from typing import Optional
from typing import Tuple
import crypt
def get_password_hash(password: str, salt: Optional[str] = None) -> Tuple[str, str]:
"""Get user password hash."""
salt = salt or crypt.mksalt(crypt.METHOD_SHA256)
return salt, crypt.crypt(password, salt) | ea3d7e0d8c65e23e40660b8921aa872dc9e2f53c | 2,251 |
def _summary(function):
"""
Derive summary information from a function's docstring or name. The summary is the first
sentence of the docstring, ending in a period, or if no dostring is present, the
function's name capitalized.
"""
if not function.__doc__:
return f"{function.__name__.capi... | a3e3e45c3004e135c2810a5ec009aa78ef7e7a04 | 2,261 |
def remove_namespace(tag, ns):
"""Remove namespace from xml tag."""
for n in ns.values():
tag = tag.replace('{' + n + '}', '')
return tag | d4837a3d906baf8e439806ccfea76284e8fd9b87 | 2,266 |
def is_unique(x):
# A set cannot contain any duplicate, so we just check that the length of the list is the same as the length of the corresponding set
"""Check that the given list x has no duplicate
Returns:
boolean: tells if there are only unique values or not
Args:
x (list): elemen... | 12b4513a71fc1b423366de3f48dd9e21db79e73a | 2,268 |
def number_field_choices(field):
"""
Given a field, returns the number of choices.
"""
try:
return len(field.get_flat_choices())
except AttributeError:
return 0 | b8776e813e9eb7471a480df9d6e49bfeb48a0eb6 | 2,276 |
def resize_image(image, size):
"""
Resize the image to fit in the specified size.
:param image: Original image.
:param size: Tuple of (width, height).
:return: Resized image.
:rtype: :py:class: `~PIL.Image.Image`
"""
image.thumbnail(size)
return image | 67db04eac8a92d27ebd3ec46c4946b7662f9c03f | 2,277 |
def price_sensitivity(results):
"""
Calculate the price sensitivity of a strategy
results
results dataframe or any dataframe with the columns
open, high, low, close, profit
returns
the percentage of returns sensitive to open price
Note
-----
Price sensitivity is calc... | 02ab811bf689e760e011db6d091dcb7c3079f0d1 | 2,282 |
import torch
def biband_mask(n: int, kernel_size: int, device: torch.device, v=-1e9):
"""compute mask for local attention with kernel size.
Args:
n (torch.Tensor): the input length.
kernel_size (int): The local attention kernel size.
device (torch.device): transformer mask to the devi... | ab3a5f25f9fe0f83579d0492caa2913a13daa2d7 | 2,285 |
def str_cell(cell):
"""Get a nice string of given Cell statistics."""
result = f"-----Cell ({cell.x}, {cell.y})-----\n"
result += f"sugar: {cell.sugar}\n"
result += f"max sugar: {cell.capacity}\n"
result += f"height/level: {cell.level}\n"
result += f"Occupied by Agent {cell.agent.id if cell.agen... | d62801290321d5d2b8404dbe6243f2f0ae03ecef | 2,290 |
def get_reachable_nodes(node):
"""
returns a list with all the nodes from the tree with root *node*
"""
ret = []
stack = [node]
while len(stack) > 0:
cur = stack.pop()
ret.append(cur)
for c in cur.get_children():
stack.append(c)
return ret | c9ffaca113a5f85484433f214015bf93eea602d1 | 2,291 |
def f(i):
"""Add 2 to a value
Args:
i ([int]): integer value
Returns:
[int]: integer value
"""
return i + 2 | 72b5d99f3b2132054805ab56872cf2199b425b20 | 2,293 |
def estimate_label_width(labels):
"""
Given a list of labels, estimate the width in pixels
and return in a format accepted by CSS.
Necessarily an approximation, since the font is unknown
and is usually proportionally spaced.
"""
max_length = max([len(l) for l in labels])
return "{0}px".f... | 1e22ad939973373a669841dd5cc318d6927249ca | 2,299 |
def count_num_peps(filename):
"""
Count the number of peptide sequences in FASTA file.
"""
with open(filename) as f:
counter = 0
for line in f:
if line.startswith(">"):
counter += 1
return counter | c062a22cd925f29d8793ab364a74cf05cbae2a66 | 2,300 |
def _stored_data_paths(wf, name, serializer):
"""Return list of paths created when storing data"""
metadata = wf.datafile(".{}.alfred-workflow".format(name))
datapath = wf.datafile(name + "." + serializer)
return [metadata, datapath] | 5f01d804db9f1848cc13e701a56e51c06dccdb31 | 2,302 |
import re
def get_number_location(
input : str,
):
# endregion get_number_location header
# region get_number_location docs
"""
get the string indices of all numbers that occur on the string
format example: [ ( 0, 1 ), ( 4, 6 ), ( 9, 9 ) ]
both begin and end are inclusive, in contrast with t... | de035f640dd33dc96b4072bdc925efc649285121 | 2,304 |
import re
def is_valid_slug(slug):
"""Returns true iff slug is valid."""
VALID_SLUG_RE = re.compile(r"^[a-z0-9\-]+$")
return VALID_SLUG_RE.match(slug) | 439349f0689cd53fb2f7e89b2b48b90aa79dae80 | 2,305 |
def note_favorite(note):
"""
get the status of the note as a favorite
returns True if the note is marked as a favorite
False otherwise
"""
if 'favorite' in note:
return note['favorite']
return False | 503f4e3abaab9d759070c725cdf783d62d7c05d2 | 2,310 |
def get_source_fields(client, source_table):
"""
Gets column names of a table in bigquery
:param client: BigQuery client
:param source_table: fully qualified table name.
returns as a list of column names.
"""
return [f'{field.name}' for field in client.get_table(source_table).schema] | abc161f252c03647a99a6d2151c00288b176a4e7 | 2,312 |
def select_id_from_scores_dic(id1, id2, sc_dic,
get_worse=False,
rev_filter=False):
"""
Based on ID to score mapping, return better (or worse) scoring ID.
>>> id1 = "id1"
>>> id2 = "id2"
>>> id3 = "id3"
>>> sc_dic = {'id1' : 5, 'id2': ... | f2fa5f33eead47288c92715ce358581a72f18361 | 2,317 |
def add_args(parser):
"""Add arguments to the argparse.ArgumentParser
Args:
parser: argparse.ArgumentParser
Returns:
parser: a parser added with args
"""
# Training settings
parser.add_argument(
"--task",
type=str,
default="train",
metavar="T",
... | cfebbfb6e9821290efdc96aaf0f7a7470e927c70 | 2,318 |
from typing import List
from typing import Dict
from typing import Any
def assert_typing(
input_text_word_predictions: List[Dict[str, Any]]
) -> List[Dict[str, str]]:
"""
this is only to ensure correct typing, it does not actually change anything
Args:
input_text_word_predictions: e.g. [
... | 0835bad510241eeb2ee1f69ac8abeca711ebbf53 | 2,323 |
import re
def expand_parameters(host, params):
"""Expand parameters in hostname.
Examples:
* "target{N}" => "target1"
* "{host}.{domain} => "host01.example.com"
"""
pattern = r"\{(.*?)\}"
def repl(match):
param_name = match.group(1)
return params[param_name]
return ... | 04f62924fdc77b02f3a393e5cc0c5382d1d4279a | 2,332 |
import re
def _skip_comments_and_whitespace(lines, idx):
###############################################################################
"""
Starting at idx, return next valid idx of lines that contains real data
"""
if (idx == len(lines)):
return idx
comment_re = re.compile(r'^[#!]')
... | b2b794681859eaa22dfc1807211bf050423cd107 | 2,333 |
def named_payload(name, parser_fn):
"""Wraps a parser result in a dictionary under given name."""
return lambda obj: {name: parser_fn(obj)} | 259525b93d056e045b0f8d5355d4028d67bfac45 | 2,334 |
def _4_graphlet_contains_3star(adj_mat):
"""Check if a given graphlet of size 4 contains a 3-star"""
return (4 in [a.sum() for a in adj_mat]) | 307f03707d1a7032df0ccb4f7951eec0c75832fe | 2,339 |
def get_sentence_content(sentence_token):
"""Extrac sentence string from list of token in present in sentence
Args:
sentence_token (tuple): contains length of sentence and list of all the token in sentence
Returns:
str: setence string
"""
sentence_content = ''
for word in sente... | 4f6f1bb557bb508e823704fc645c2901e5f8f03f | 2,340 |
def option_not_exist_msg(option_name, existing_options):
""" Someone is referencing an option that is not available in the current package
options
"""
result = ["'options.%s' doesn't exist" % option_name]
result.append("Possible options are %s" % existing_options or "none")
return "\n".join(resu... | 7ffa0afa81483d78a1ed0d40d68831e09710b7e1 | 2,343 |
def string_unquote(value: str):
"""
Method to unquote a string
Args:
value: the value to unquote
Returns:
unquoted string
"""
if not isinstance(value, str):
return value
return value.replace('"', "").replace("'", "") | e062c012fc43f9b41a224f168de31732d885b21f | 2,347 |
import configparser
def read_section(section, fname):
"""Read the specified section of an .ini file."""
conf = configparser.ConfigParser()
conf.read(fname)
val = {}
try:
val = dict((v, k) for v, k in conf.items(section))
return val
except configparser.NoSectionError:
re... | 65d6b81b45fc7b75505dd6ee4dda19d13ebf7095 | 2,351 |
def _helper_fit_partition(self, pnum, endog, exog, fit_kwds,
init_kwds_e={}):
"""handles the model fitting for each machine. NOTE: this
is primarily handled outside of DistributedModel because
joblib cannot handle class methods.
Parameters
----------
self : Distributed... | 30b7e6d48c2f0fa3eb2d2486fee9a87dad609886 | 2,352 |
def get_users(metadata):
"""
Pull users, handles hidden user errors
Parameters:
metadata: sheet of metadata from mwclient
Returns:
the list of users
"""
users = []
for rev in metadata:
try:
users.append(rev["user"])
except (KeyError):
u... | 48dbae6a63019b0e4c2236a97e147102fe4d8758 | 2,354 |
def str_to_size(size_str):
"""
Receives a human size (i.e. 10GB) and converts to an integer size in
mebibytes.
Args:
size_str (str): human size to be converted to integer
Returns:
int: formatted size in mebibytes
Raises:
ValueError: in case size provided in invalid
... | 0051b7cf55d295a4fffcc41ed5b0d900243ef2da | 2,362 |
def decay_value(base_value, decay_rate, decay_steps, step):
""" decay base_value by decay_rate every decay_steps
:param base_value:
:param decay_rate:
:param decay_steps:
:param step:
:return: decayed value
"""
return base_value*decay_rate**(step/decay_steps) | c593f5e46d7687fbdf9760eb10be06dca3fb6f7b | 2,366 |
def crc16(data):
"""CRC-16-CCITT computation with LSB-first and inversion."""
crc = 0xffff
for byte in data:
crc ^= byte
for bits in range(8):
if crc & 1:
crc = (crc >> 1) ^ 0x8408
else:
crc >>= 1
return crc ^ 0xffff | 2560f53c1f2b597d556a0b63462ef56f0c972db2 | 2,371 |
def _read_dino_waterlvl_metadata(f, line):
"""read dino waterlevel metadata
Parameters
----------
f : text wrapper
line : str
line with meta dictionary keys
meta_dic : dict (optional)
dictionary with metadata
Returns
-------
meta : dict
dictionary with metad... | 949535f4fc677a7d0afc70a76e377ccefcc8943f | 2,372 |
def reverse(array):
"""Return `array` in reverse order.
Args:
array (list|string): Object to process.
Returns:
list|string: Reverse of object.
Example:
>>> reverse([1, 2, 3, 4])
[4, 3, 2, 1]
.. versionadded:: 2.2.0
"""
# NOTE: Using this method to reverse... | 5eb096d043d051d4456e08fae91fb52048686992 | 2,375 |
def help_text_metadata(label=None, description=None, example=None):
"""
Standard interface to help specify the required metadata fields for helptext to
work correctly for a model.
:param str label: Alternative name for the model.
:param str description: Long description of the model.
:param exa... | a1fb9c9a9419fe7ce60ed77bc6fadc97ed4523f8 | 2,376 |
def _maven_artifact(
group,
artifact,
version,
ownership_tag = None,
packaging = None,
classifier = None,
exclusions = None,
neverlink = None,
testonly = None,
tags = None,
flatten_transitive_deps = None,
aliases = None):
... | 9f97cd8cadfc3ad1365cb6d291634a9362fea4e8 | 2,378 |
from typing import List
def get_povm_object_names() -> List[str]:
"""Return the list of valid povm-related object names.
Returns
-------
List[str]
the list of valid povm-related object names.
"""
names = ["pure_state_vectors", "matrices", "vectors", "povm"]
return names | cb80899b9b3a4aca4bfa1388c6ec9c61c59978a4 | 2,383 |
def get_dotted_field(input_dict: dict, accessor_string: str) -> dict:
"""Gets data from a dictionary using a dotted accessor-string.
Parameters
----------
input_dict : dict
A nested dictionary.
accessor_string : str
The value in the nested dict.
Returns
-------
dict
... | 2c82c0512384810e77a5fb53c73f67d2055dc98e | 2,384 |
def _format_param(name, optimizer, param):
"""Return correctly formatted lr/momentum for each param group."""
if isinstance(param, (list, tuple)):
if len(param) != len(optimizer.param_groups):
raise ValueError("expected {} values for {}, got {}".format(
len(optimizer.param_gr... | 52904bdfb1cba7fe3175606bf77f5e46b3c7df80 | 2,387 |
def operating_cf(cf_df):
"""Checks if the latest reported OCF (Cashflow) is positive.
Explanation of OCF: https://www.investopedia.com/terms/o/operatingcashflow.asp
cf_df = Cashflow Statement of the specified company
"""
cf = cf_df.iloc[cf_df.index.get_loc("Total Cash From Operating Activities"... | ed6a849fa504b79cd65c656d9a1318aaaeed52bf | 2,390 |
def _is_json_mimetype(mimetype):
"""Returns 'True' if a given mimetype implies JSON data."""
return any(
[
mimetype == "application/json",
mimetype.startswith("application/") and mimetype.endswith("+json"),
]
) | 9c2580ff4a783d9f79d6f6cac41befb516c52e9f | 2,396 |
from datetime import datetime
def make_request(action, data, token):
"""Make request based on passed arguments and timestamp."""
return {
'action': action,
'time': datetime.now().timestamp(),
'data': data,
'token': token
} | 60e511f7b067595bd698421adaafe37bbf8e59e1 | 2,397 |
def get_unique_chemical_names(reagents):
"""Get the unique chemical species names in a list of reagents.
The concentrations of these species define the vector space in which we sample possible experiments
:param reagents: a list of perovskitereagent objects
:return: a list of the unique chemical names... | ae5d6b3bdd8e03c47b9c19c900760c8c2b83d0a0 | 2,399 |
def max_votes(x):
"""
Return the maximum occurrence of predicted class.
Notes
-----
If number of class 0 prediction is equal to number of class 1 predictions, NO_VOTE will be returned.
E.g.
Num_preds_0 = 25,
Num_preds_1 = 25,
Num_preds_NO_VOTE = 0,
... | 2eadafdaf9e9b4584cd81685a5c1b77a090e4f1c | 2,401 |
def _get_log_time_scale(units):
"""Retrieves the ``log10()`` of the scale factor for a given time unit.
Args:
units (str): String specifying the units
(one of ``'fs'``, ``'ps'``, ``'ns'``, ``'us'``, ``'ms'``, ``'sec'``).
Returns:
The ``log10()`` of the scale factor for the time... | 2371aab923aacce9159bce6ea1470ed49ef2c72f | 2,404 |
from typing import Dict
from typing import Any
from typing import Tuple
def verify_block_arguments(
net_part: str,
block: Dict[str, Any],
num_block: int,
) -> Tuple[int, int]:
"""Verify block arguments are valid.
Args:
net_part: Network part, either 'encoder' or 'decoder'.
block: ... | cead023afcd72d1104e02b2d67406b9c47102589 | 2,405 |
def filesystem_entry(filesystem):
"""
Filesystem tag {% filesystem_entry filesystem %} is used to display a single
filesystem.
Arguments
---------
filesystem: filesystem object
Returns
-------
A context which maps the filesystem object to filesystem.
"""
return {'fi... | 3afbd0b8ee9e72ab8841ca5c5517396650d2a898 | 2,409 |
def gather_squares_triangles(p1,p2,depth):
""" Draw Square and Right Triangle given 2 points,
Recurse on new points
args:
p1,p2 (float,float) : absolute position on base vertices
depth (int) : decrementing counter that terminates recursion
return:
squares [(float,float,float,float)...] : absolut... | de4e720eb10cb378f00086a6e8e45886746055c0 | 2,411 |
def decorate(rvecs):
"""Output range vectors into some desired string format"""
return ', '.join(['{%s}' % ','.join([str(x) for x in rvec]) for rvec in rvecs]) | 31a3d4414b0b88ffd92a5ddd8eb09aaf90ef3742 | 2,413 |
def get_color(card):
"""Returns the card's color
Args:
card (webelement): a visible card
Returns:
str: card's color
"""
color = card.find_element_by_xpath(".//div/*[name()='svg']/*[name()='use'][2]").get_attribute("stroke")
# both light and dark theme
if (color == "#ff0101... | 452266b81d70973149fed4ab2e6cbc9c93591180 | 2,414 |
def add_chr_prefix(band):
"""
Return the band string with chr prefixed
"""
return ''.join(['chr', band]) | 08a99220023f10d79bdacdb062a27efcb51086ce | 2,415 |
def disable_text_recog_aug_test(cfg, set_types=None):
"""Remove aug_test from test pipeline of text recognition.
Args:
cfg (mmcv.Config): Input config.
set_types (list[str]): Type of dataset source. Should be
None or sublist of ['test', 'val']
Returns:
cfg (mmcv.Config):... | bda3a5420d32d55062b23a6af27cee3e203b878c | 2,416 |
def delta_in_ms(delta):
"""
Convert a timedelta object to milliseconds.
"""
return delta.seconds*1000.0+delta.microseconds/1000.0 | 4ed048155daf4a4891488e28c674e905e1bbe947 | 2,418 |
def selection_sort(data):
"""Sort a list of unique numbers in ascending order using selection sort. O(n^2).
The process includes repeatedly iterating through a list, finding the smallest element, and sorting that element.
Args:
data: data to sort (list of int)
Returns:
sorted l... | 8b745be41c857669aedecb25b3006bbdc1ef04eb | 2,419 |
def player_count(conn, team_id):
"""Returns the number of players associated with a particular team"""
c = conn.cursor()
c.execute("SELECT id FROM players WHERE team_id=?", (team_id,))
return len(c.fetchall()) | cfced6da6c8927db2ccf331dca7d23bba0ce67e5 | 2,420 |
def find_process_in_list( proclist, pid ):
"""
Searches for the given 'pid' in 'proclist' (which should be the output
from get_process_list(). If not found, None is returned. Otherwise a
list
[ user, pid, ppid ]
"""
for L in proclist:
if pid == L[1]:
return L
r... | 19eab54b4d04b40a54a39a44e50ae28fbff9457c | 2,428 |
def get_dp_logs(logs):
"""Get only the list of data point logs, filter out the rest."""
filtered = []
compute_bias_for_types = [
"mouseout",
"add_to_list_via_card_click",
"add_to_list_via_scatterplot_click",
"select_from_list",
"remove_from_list",
]
for log in... | e0a7c579fa9218edbf942afdbdb8e6cf940d1a0c | 2,430 |
import random
def attack(health, power, percent_to_hit):
"""Calculates health from percent to hit and power of hit
Parameters:
health - integer defining health of attackee
power - integer defining damage of attacker
percent to hit - float defining percent chance to hit of attacker
... | 83a74908f76f389c798b28c5d3f9035d2d8aff6a | 2,436 |
import json
def load_data(path):
"""Load JSON data."""
with open(path) as inf:
return json.load(inf) | 531fc2b27a6ab9588b1f047e25758f359dc21b6d | 2,437 |
import random
def seed_story(text_dict):
"""Generate random seed for story."""
story_seed = random.choice(list(text_dict.keys()))
return story_seed | 0c0f41186f6eaab84a1d197e9335b4c28fd83785 | 2,444 |
def round_int(n, d):
"""Round a number (float/int) to the closest multiple of a divisor (int)."""
return round(n / float(d)) * d | 372c0f8845994aaa03f99ebb2f65243e6490b341 | 2,447 |
def check_hostgroup(zapi, region_name, cluster_id):
"""check hostgroup from region name if exists
:region_name: region name of hostgroup
:returns: true or false
"""
return zapi.hostgroup.exists(name="Region [%s %s]" % (region_name, cluster_id)) | b237b544ac59331ce94dd1ac471187a60d527a1b | 2,448 |
def refresh_wrapper(trynum, maxtries, *args, **kwargs):
"""A @retry argmod_func to refresh a Wrapper, which must be the first arg.
When using @retry to decorate a method which modifies a Wrapper, a common
cause of retry is etag mismatch. In this case, the retry should refresh
the wrapper before attemp... | 089b859964e89d54def0058abc9cc7536f5d8877 | 2,453 |
def get_event_details(event):
"""Extract event image and timestamp - image with no tag will be tagged as latest.
:param dict event: start container event dictionary.
:return tuple: (container image, last use timestamp).
"""
image = str(event['from'] if ":" in event['from'] else event['from'] + ":la... | c9b4ded7f343f0d9486c298b9a6f2d96dde58b8c | 2,468 |
import json
def copyJSONable(obj):
"""
Creates a copy of obj and ensures it is JSONable.
:return: copy of obj.
:raises:
TypeError: if the obj is not JSONable.
"""
return json.loads(json.dumps(obj)) | 1cc3c63893c7716a4c3a8333e725bb518b925923 | 2,469 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.