content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import struct
def readString(f, len_=1):
"""Read len_ bytes as a string in file f"""
read_bytes = f.read(len_)
str_fmt = '>'+str(len_)+'s'
return struct.unpack( str_fmt, read_bytes )[0] | 5ffbfdb55f0bbc2365d6d4417d50d309789079b9 | 166,148 |
def momentum(vector):
""" Computes the momentum of a vector.
Parameters:
- `vector` : :class:`list` of :class:`floats`
Moentum is computed as follow:
- momentum = 100*(new - old)/old
Returns the momentum of the vector (:class:`float`)
"""
return 100*((vector[0] - vector[-1])/... | 11159a1038588a538d4257384ac5565c90bb151b | 136,279 |
from typing import List
def get_citation_ids(article:dict,direction:str='citations')->List:
"""Get ids for papers cited / citing a paper in our corpus"""
return [c['arxivId'] for c in article[direction]] | 9eb45999e8351d03605b413e302860b8a26e5b6e | 372,857 |
import shlex
def parse_kv_pairs(key_value_string):
""" Parse string of key value pairs to dict
Example:
'key1=value1 "key 2"="value 2"' --> {'key1': value1, 'key 2': 'value 2'}
parse(s)
"""
if not key_value_string:
return {}
return dict(token.split('=') for token in shlex.... | 90740cd31b0199b3701689ebcc4d70174d235c2e | 300,213 |
def get_locations(content_div):
"""
Returns the location divs from the content block
:param: content_div - the parent div that has all the location divs
"""
# the first element which is an empty div
return content_div.findAll('div', recursive=False)[1:] | fa42998a10624151c73f811d62c8e691b9ff7409 | 344,447 |
import torch
def rect_to_polar(real, imag):
"""Converts the rectangular complex representation to polar"""
mag = torch.pow(real**2 + imag**2, 0.5)
ang = torch.atan2(imag, real)
return mag, ang | ff97f81d928a0c8aa66ee075bfd4df153029bed7 | 129,694 |
def _underlying_variable_ref(t):
"""Find the underlying variable ref.
Traverses through Identity, ReadVariableOp, and Enter ops.
Stops when op type has Variable or VarHandle in name.
Args:
t: a Tensor
Returns:
a Tensor that is a variable ref, or None on error.
"""
while t.op.type in ["Identity"... | c2d48b61e7236d1b28f0f905fd3d32429dcb1776 | 611,964 |
def generate_input_target_text(cut_word_list):
"""
生成对应的训练集X和y,这里X和y都是分词过的词语list
:param cut_word_list: 存储所有歌词,其每个元素是一个list,存储一首歌(一首歌使用的又是list of list结构,一个list是一句歌词);
:return:
input_texts: 数据集X对应的list
target_texts: 数据集y对应的list
max_seq_input: X中样本的最大长度
max_seq_target: y中样本的最大长度
input_w... | dc36f7a618aab5342b849c9e1fa51bd7cd73cb92 | 433,690 |
def merge_dfs(df_list, keys_for_merge):
"""Joins all the dataframes on the keys.
Does an outer join, does not check that all rows exist in all dataframes.
Args:
df_list: A list of pandas dataframes. Each needs to have the keys_for_merge
as columns.
keys_for_merge: A string list of column names to ... | f5b0ee9250f7d0c2a855c7b62684d12371a34ec5 | 129,422 |
import gzip
def gzip_file(file, file_name):
""" Gzip a file
:param file file:
:param str file_name:
:return: the gzipped file
:rtype: gzip file
"""
with gzip.open(file_name + '.gz', 'wb') as gzipped_file:
gzipped_file.writelines(file)
return gzipped_file | d1569b3ef8ebed46eb7a3fd128479d3999fb228c | 31,282 |
def __calculate_waterfootprint(wf_ing, quantity):
"""
Calculate the right water footprint of a ingredient from its
(l/kg) water footprint and the quantity provided (in gr).
:param wf_ing: the water footprint of the ingredient.
:param quantity: the quantity of the ingredient.
:return: the water ... | eb675f718dfdf619cf874c8a1fb2cca2f55ed0a5 | 683,249 |
import uuid
def fromMsg(msg):
"""Create UUID object from UniqueID message.
:param msg: `uuid_msgs/UniqueID`_ message.
:returns: :class:`uuid.UUID` object.
"""
return uuid.UUID(bytes = msg.uuid) | 1be5562203b895ad434ea44300617437c1e478af | 133,492 |
def cast_map_to_str_dict(map):
"""
Helper function to cast Unreal Map object to plain old python
dict. This will also cast values and keys to str. Useful for
metadata dicts.
"""
return {str(key): str(value) for (key, value) in map.items()} | cbe640af4a23fc6a348a08aaeb963fa06ced1446 | 259,049 |
def filter_str(check_str):
"""
过滤无用字符
:param str check_str:待过滤的字符串
:return str temp:过滤后的字符串
"""
temp = ''
for i in check_str:
if i != '\n' and i != '\x00':
temp = temp + i
return temp | 2787d1455beb491b85ce3db17232503565b76693 | 636,149 |
def construct_rss_url(root_url, rss_feed_path):
"""
Construct URL for the RSS feed.
Args
root_url: Blog's root URL.
rss_feed_path: String or Path object describing the path to the RSS feed
under the blog's root directory.
Returns
The RSS feed URL as a string.
... | 96fa2573ec2051511a6d1fa13fd269dea10d3ec0 | 476,682 |
import hashlib
def get_md5(str_):
"""
hash function --md5
:param str_:origin str
:return:hex digest
"""
md5 = hashlib.md5()
md5.update(str_.encode('utf-8'))
return md5.hexdigest() | fb905d673ac7407fcaa3f70a822620dd38dbb5e6 | 18,495 |
def find(x):
"""
Find the representative of a node
"""
if x.instance is None:
return x
else:
# collapse the path and return the root
x.instance = find(x.instance)
return x.instance | 5143e9d282fb1988d22273996dae36ed587bd9d2 | 2,062 |
from typing import Union
def product(*args : Union[float,int]) -> Union[float,int]:
"""Returns the product of float or ints
product(3,4,5) -> 60
product(*[3,4,5]) -> 60
"""
prod = 1
for num in args:
prod*=num
return prod | 555453bce30c01a28f5f299cc4b5787bf3cd63fa | 440,134 |
def sanitize_string(string):
"""Sanitizes a string for it to be between U+0000 and U+FFFF"""
if string:
return ''.join(c for c in string if ord(c) <= 0xFFFF).strip() | 4f01448b06180403dedbb787aaa0e072315ebb54 | 576,613 |
def cast_operator_matrix_dtype(matrix, dtype):
"""
Changes the dtype of a matrix, without changing the structural type of the object.
This makes sure that if you pass sparse arrays to a LocalOperator, they remain
sparse even if you change the dtype
"""
# must copy
# return np.asarray(matrix... | d3f7f3277c540fc9f949f5e41021633abaab74a2 | 132,466 |
def get_jsonpath(obj: dict, jsonpath):
"""
Gets a value from a dictionary based on a jsonpath. It will only return
one result, and if a key does not exist it will return an empty string as
template tags should not raise errors.
:param obj: The dictionary to query
:param jsonpath: The path to th... | 0ddead3d3cc5cfdd3d6557921bfac5d98169f540 | 137,517 |
from typing import List
def join_items_with_and(items: List[str]) -> str:
"""Join the list with commas and "and"."""
if len(items) <= 2:
return " and ".join(items)
return "{} and {}".format(", ".join(items[:-1]), items[-1]) | 4f495f07bc7e421c5be0e9c58785cc53984403a3 | 592,443 |
def calc_check_digit(number):
"""Calculate the check digit."""
s = sum((2 - i) * int(n) for i, n in enumerate(number[:12])) % 11
return str((1 - s) % 10) | f19a256218e924a96fb4c490b44029613f6a7b97 | 312,624 |
def correct_protein_name_list(lst):
""" Correct a list of protein names with incorrect separators involving '[Cleaved into: ...]'
Args:
lst (:obj:`str`): list of protein names with incorrect separators
Returns:
:obj:`str`: corrected list of protein names
"""
if lst:
lst = l... | c612d7af7408a8df9ac07ea183c57d43f33ec200 | 538,388 |
from typing import List
from typing import Any
def split_list_into_consequtive_chunks(lst: List[Any], n_chunks) -> List[List[Any]]:
"""
>>> split_list_into_consequtive_chunks([1, 2, 3, 4, 5, 6, 7, 8], 3)
[[1, 2, 3], [4, 5, 6], [7, 8]]
>>> split_list_into_consequtive_chunks([1, 2, 3, 4, 5, 6, 7], 3)
... | 1762a0c5b743d8ce833c5206c5efa7f6e8c05253 | 483,198 |
def indent(text, indentation):
"""Indents a string of text with the given string of indentation.
PARAMETERS:
text -- str
indentation -- str; prefix of indentation to add to the front of
every new line.
RETURNS:
str; the newly indented string.
"""
return '\n'.j... | 9854034bea05a318a3444ac771b0ae017b7c395a | 404,677 |
from typing import List
def get_package_nvrs(built_packages: List[dict]) -> List[str]:
"""
Construct package NVRs for built packages except the SRPM.
Returns:
list of nvrs
"""
packages = []
for package in built_packages:
if package["arch"] == "src":
continue
... | a560d3dbf89fbb934fb100fdb73491df972a06de | 629,046 |
def check_if_pack_on_hand(hand):
"""
Function used to check if player have a pack of cards on hand.
:param hand: list of cards on player hand
:return: list of cards values which can be played as pack
"""
tmp = {}
for card in hand:
if card[1] in tmp.keys():
tmp[card[1]] +=... | 4302b36395cb229119af0e279f4d9180b25e9d3d | 594,535 |
def get_resource_requests_from_networktab(networktab):
"""
Parse `networktab` to extract only `ResourceSendRequest` information.
"""
events = networktab['traceEvents']
network_events = []
for event in events:
if event['name'] == 'ResourceSendRequest':
network_events.append(ev... | 97e50596fbdd057878f2febfc49f3f7d81faa9f1 | 639,569 |
def clean_population_stats(data_frame):
"""
Clean our population dataframe. Rename some columns, drop some columns etc..
:param data_frame: population dataframe
:return: pandas dataframe, cleaned
"""
df_pop = data_frame.drop(["Country Code", "Indicator Name", "Indicator Code", "Unnamed: 63"], ax... | eda1a48ec58d688b9586a938c78b0787346becba | 549,081 |
def getMostStrictType(typeA: str, typeB: str) -> str:
"""Return the most 'strict' type of license from the available types.
Args:
typeA (str): type of the first license
typeB (str): type of the second license
Returns:
str: the most 'strict' type
"""
strict = ["Public Domain", "Permissive", "Weak Copyleft",... | e8eb0ced58e3f79c827078d5abe708eb86820da6 | 406,030 |
import math
def getdistance(vector1, vector2):
"""
Accepts two vectors (track.normalizedlist arrays, containing weighted
values for each track attribute). Vectors must be the same length.
Returns the distance between the two vectors, or None if there is an
error.
"""
try:... | 5b15d7bc29b78f8e34e1b93c03c35f62ba39b179 | 149,137 |
import math
def _full_length(length: int, kernel_size: int, stride: int):
"""
Given a convolution-like operation with the given kernel size and stride,
return the length the input should have so that the last frame is full.
"""
length = max(length, kernel_size)
return stride * math.ceil((leng... | b77e13a6f7fd84f8acded525982e7abecfa4242a | 171,788 |
from typing import Any
def is_null(value: Any) -> bool:
"""
Check if value is NaN or None
"""
return value != value or value is None | 7a9d82a78b58638aa87109e0376c2095ac7d8ad8 | 185,275 |
def get_connectivity(self, elem_tag):
"""Return the connectivity for one selected element
Parameters
----------
self : Mesh
an Mesh object
elem_tag : int
an element tag
Returns
-------
connect_select: numpy.array
Selected connectivity. Return None if the tag doe... | b71e13a94bca667e3e9d643b0aa41c8e4f690b5a | 449,111 |
def grazing(vs, eaten, zooplankton):
"""Zooplankton grows by amount digested, eaten decreases by amount grazed"""
return {eaten: - vs.grazing[eaten], zooplankton: vs.grazing[eaten]} | 9e955c3cc16e00f8fffd9ef210093ecd82ac11df | 649,138 |
def add_sales_variance(bigTable):
""" Adds a new column reporting the variance
in unit_sales for each (item, store) tuple
"""
df = bigTable.groupby(['store_nbr', 'item_nbr'])['unit_sales']\
.var().reset_index()
return bigTable.merge(df.rename(columns={'unit_sales':
... | 709cd71354f89489bc1cb1e46f07a42777ad5bc4 | 506,862 |
def checkOtherPointsClicked(game, clickX, clickY):
"""
If one of the opponent's points cards has been clicked,
return the card that was clicked, else None
"""
for card in game.otherPlayer.pointsCards:
if card.imageObj.collidepoint(clickX, clickY):
return card
return None | f65b791e1048a0e27389e5e12187df175dff1041 | 578,412 |
def starts_with_wan(string):
"""Test if a string starts with Chinese \"ten thousand\"."""
return string.startswith('万') or string.startswith('万元') \
or string.startswith('(万)') or string.startswith('(万元)') \
or string.startswith('(万元)') | 5887aca9ad09e4c6178c154ea6d22e7d76653124 | 247,157 |
def getind(dataset, wid, spec):
"""
Specifies individual dataset for column 2 and 3 of table 2:
In column 2 early decisions are considered while in column 3
late decisions are considered. For col 1 and 4 all decicions
are taken into account.
Args:
dataset(Pd.DataFrame): dataset containi... | 3d32705a726d653019f94232bf5f6177fa9c6a5a | 258,632 |
def isWordGuessed(secretWord: str, lettersGuessed: list) -> bool:
"""Verify if secretWord was guessed
Args:
secretWord: the word the user is guessing
lettersGuessed: what letters have been guessed so far
Returns:
bool: True if all the letters of secretWord are in lettersGuessed,
... | 26b108324c36af5ace2ff7f0f39f39788f9cbbcd | 279,612 |
def build_all_reduce_device_prefixes(job_name, num_tasks):
"""Build list of device prefix names for all_reduce.
Args:
job_name: 'worker', 'ps' or 'localhost'.
num_tasks: number of jobs across which device names should be generated.
Returns:
A list of device name prefix strings. Each element spell... | 65383026a658af3cd192bf2302d5184e7b2219e7 | 387,137 |
import random
def shuffle(alist):
"""Return a new shuffled list.
>>> a = ["a", "b", "c", "d", "e"]
>>> b = shuffle(a)
>>> a
["a", "b", "c", "d", "e"]
>>> b
[...]
"""
blist = alist.copy()
random.shuffle(blist)
return blist | 1646c0b7f49a683c11ccb4709bbc06e5699621db | 318,758 |
def parse_config(configfile):
"""Parse the config file 'configfile' and return the parsed key-value pairs as dict"""
return {k:v for k,v in map(lambda x: x.strip().split('='), filter(lambda x: not x.strip().startswith('#'),
(line for line in open(configfile))))} | 022243368fb63588a4bffaa6dad799e1bc5c2e66 | 689,053 |
def distance(pt1, pt2):
"""
Simple 2d euclidean distances between two points.
args:
pt1: The first point.
pt2: The second point.
"""
return (pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2 | bbbb44d10be96c10ad96db0fe242d81a7facfb68 | 479,414 |
def decode(obj):
"""decode an object"""
if isinstance(obj, bytes):
obj = obj.decode()
return obj | 649fc6b46b5b9609acbb7cd99fa66180411af055 | 66,013 |
import base64
def makeDid(vk, method="dad"):
"""
Create and return Did from bytes vk.
vk is 32 byte verifier key from EdDSA (Ed25519) keypair
"""
# convert verkey to jsonable unicode string of base64 url-file safe
vk64u = base64.urlsafe_b64encode(vk).decode("utf-8")
did = "did:{}:{}".forma... | 7b09205ca0f88fefb20b55443878761a5cb3614b | 196,023 |
def set_empty(data):
"""
Tests if the set is empty.
"""
return not data | 90a7019fbfb036bc50443de82e96a0ac425bbbbd | 349,243 |
import json
def to_review_json(s):
"""
Converts the string to json
:param s: A string
:return: A json formatted string representation of the object
"""
b = {}
if s:
b.update({"reviewComment": s})
return json.dumps(b)
else:
return None | 384f8e4f8d625081fa858e184ae7a559f590a420 | 31,288 |
def structure_to_dict(structure):
"""Convert a ctypes.Structure to a dict"""
out = {}
for key, _ in structure._fields_: # pylint: disable=protected-access
out[key] = getattr(structure, key)
return out | 5a2641dbd61458b3976fe9aa587cc3d39159da49 | 344,437 |
def _MakeLocationLookup(strText):
""" Create location lookup dictionary from strPathProjectText. """
dicLocationLU = {}
with open(strText) as txt:
for line in txt.readlines()[1:]:
lst = line.strip().split(':')
k = lst[0].strip()
v = [s.strip() for s in lst[1].spli... | d47b9e5430d75c3c0002c6b9fafa1671e5ec21a8 | 278,978 |
def score_filter(predictions, min_score):
"""Remove prediction bounding boxes with probability under a threshold
Parameters
----------
predictions : dict
all predictions
min_score : int
threshold score
Returns
-------
dict
filtered predictions
"""
new_p... | 28f8c0604f3dabc76ffbda911357d0bdd5bd5331 | 10,815 |
def to_int_action(toks):
"""Convert first token to integer"""
return int(toks[0]) | 0e0d6ed3515a4170b01ed1cd05b0c82a0b01d0ae | 139,839 |
import importlib
def _load_player(modulename, package='.'):
"""
Load a Player class given the name of a module.
:param modulename: where to look for the Player class (name of a module)
:param package: where to look for the module (relative package)
:return: the Player class (a class object)
... | 7a6de7116fb3d664d01811473114eff5c29900ad | 590,963 |
from typing import List
def charge_set(ox_state: int) -> List[int]:
"""Set of defect charge states.
-1 (1) is included for positive (negative) odd number.
E.g., charge_set(3) = [-1, 0, 1, 2, 3]
charge_set(-3) = [-3, -2, -1, 0, 1]
charge_set(2) = [0, 1, 2]
charge_set(-4) = [-... | 513ecbe67eef3e4e5da83c72e34bc027080e69cc | 211,415 |
def all_served(state, goal):
"""Checks whether all passengers in goal have been served"""
for thisPassenger in state.served:
if not state.served[thisPassenger] and thisPassenger in goal.served and goal.served[thisPassenger]:
return False
return True | f4b44131ad82c0e6775e7dc2d59123494c3ff399 | 123,923 |
import yaml
def load(filename):
"""Load yaml."""
settings = {}
with open(filename, 'r') as f:
settings = yaml.load(f, Loader=yaml.FullLoader)
return settings | 580b0ab3c76fef1220da255637458ce1334a05c8 | 250,025 |
def clenshaw_curtis_rule_growth(level):
"""
The number of samples in the 1D Clenshaw-Curtis quadrature rule of a given
level.
Parameters
----------
level : integer
The level of the quadrature rule
Return
------
num_samples_1d : integer
The number of samples in the qu... | 6bc6ac5caa1c41f9a8a77b25846d6a2d572bfa82 | 552,087 |
from typing import Union
import json
def dump_json(obj: Union[dict, list, str, int, float], **kwargs) -> bytes:
"""Dump dict to json encoded bytes string"""
return json.dumps(obj, **kwargs).encode() | 22006bf037b9a60ae2316f21df82ce6f559039ca | 500,776 |
def strip_matching(from_str, char):
"""Strip a char from either side of the string if it occurs on both."""
if not char:
return from_str
clen = len(char)
if from_str.startswith(char) and from_str.endswith(char):
return from_str[clen:-clen]
return from_str | 9e5f5340e2ffde51d4fe8ed524561c99e0a22dcd | 660,430 |
def get_ndistinct_subsequences(sequence):
"""
Computes the number of distinct subsequences for a given sequence, based on original implementation by
Mohit Kumar available `here <https://www.geeksforgeeks.org/count-distinct-subsequences/>`_.
Example
--------
>>> sequence = [1,2,1,3]
>>> ps.get_ndistinct_subseq... | ba655e5d45176e77aacde895dc6928c22daad4ba | 319,789 |
def get_feature_type (f_feature_names) :
"""Get the type of features in a dict"""
dict_feature_type ={}
fi = open(f_feature_names, mode='r', encoding='utf-8')
for line in fi :
line = line.rstrip()
f_name, f_type = line.split("\t")
dict_feature_type[f_name]=f_type
fi.close()... | 205ba9e64024266c38ab3ee28c29bbe8065af546 | 125,314 |
def nth_combination(iterable, r, index):
"""Equivalent to list(combinations(iterable, r))[index]."""
pool = tuple(iterable)
n = len(pool)
if r < 0 or r > n:
raise ValueError
c = 1
k = min(r, n - r)
for i in range(1, k + 1):
c = c * (n - k + 1) // i
if index < 0:
i... | 4d36bc4d834298924c259060bf79f762a26ee5c6 | 414,545 |
def interpolate(color_a, color_b, factor):
"""
Interpolate between two colors be the given factor
:param color_a: List or tuple of three value, red, green and blue
:param color_b: List or tuple of three value, red, green and blue
:param factor: Factor for interpolating between the two colors
:re... | dbd60cd891445a6f41ee5f6c3a625d87d037532c | 327,845 |
import re
def remove_junos_group(src):
"""
Remove XML attribute junos:group from the given string.
:param str src: Source string
:returns: String with junos:group occurrences removed.
"""
return re.sub(r' junos:group="[^"]+"', '', src) | 311b335085b686e433a94da42abc22cbe959ef82 | 60,229 |
from typing import Union
from typing import Tuple
def output_name_to_outputs(name: str) -> Union[Tuple[int], Tuple[int, int]]:
"""
Finds the output path index associated with the output names specified in the
config.
For the baseband modules, these indices correspond directly to a physical output (
... | 3a159231dcab61bbeee12a33c426c678e95fc749 | 169,005 |
def _parse_data_row(row, columns, counters, **options):
"""Parse table data row.
If a cell has multiple tags within it then each will be seperated
by `sep` character.
Parameters
----------
row : BeautifulSoup Tag object
A <tr> tag from the html, with data in at least one cell.
... | 500c9634b8110575d3c7800a0a1f2616fa08ac03 | 15,234 |
def _stringify_time_unit(value: int, unit: str):
"""
Returns a string to represent a value and time unit,
ensuring that it uses the right plural form of the unit.
>>> _stringify_time_unit(1, "seconds")
"1 second"
>>> _stringify_time_unit(24, "hours")
"24 hours"
>>> _stringify_time_unit(... | 6839bc944d1afb46d34dc2d2b9ddb3eb508a5c60 | 351,120 |
def add_header(image_string):
"""
Adds the base64 encoding header for jpg images
to a base64 encoded string.
:param image_string: A base64 encoded image string
without a header
:return: A base64 encoded string with a jpg header
"""
image_string = str(image_string)[2:]
image_string_... | 522ea9d89adeedab1c11bae0c032c28df51573d9 | 338,750 |
import math
def almost_sqrt_factors(x):
"""Returns two integers that are close to each other and
multiply to a product that is close to x.
Args:
x: the integer to factor into a nd b
returns:
a, b integers
"""
y = math.sqrt(x)
a = math.floor(y)
b = math.ceil(y)
ret... | 631e7770af3fe90d3218d37ef8d567cc2cad62e6 | 226,270 |
def get_kids(dic, resource, current):
"""
Function to get iteratively all kids regarding a parent agency.
Input:
- dic: Dictionary with the hierarchy of the agencies in the form of
dic[parent_agency]=[child1, child2, ..., childN]
- resource: String, the name of the parent agen... | 6dbf752b8a523a4510d09bac95059bd35b1b67e5 | 405,752 |
def find_max(lst,start,end):
"""
找从lst[start] 到 lst[end-1]之中的最大值下标
:return: 最大值在lst中的下标
"""
max = start
for i in range(start,end):
if lst[i] > lst[max]:
max = i
return max | 7525f6e8fcf324dd7f892d8f3e3ff5a19864c76c | 136,841 |
def get_month(date):
"""
Extract month from date
"""
return int(date.split('-')[1]) | eabf8f51554f537bbf12148eb9a9151fabe1cfad | 19,704 |
def build_headers(access_token, client_id):
"""
:param access_token: Access token granted when the user links their account
:param client_id: This is the api key for your own app
:return: Dict of headers
"""
return {'Content-Type': 'application/json',
'Authorization': f'Bearer {acce... | 5cd8ae3e06f67b7a4fdb1644ae82c62cb54479cb | 709,337 |
def is_indexable_but_not_string(obj):
"""Return True if ``obj`` is indexable but isn't a string."""
return not hasattr(obj, "strip") and hasattr(obj, "__getitem__") | 40c35dd3f800a0b7f7ccee8f1164426626a48e00 | 683,197 |
def precision(tp, fp, eps: float = 1e-5) -> float:
"""
Calculates precision (a.k.a. positive predictive value) for binary
classification and segmentation.
Args:
tp: number of true positives
fp: number of false positives
eps: epsilon to use
Returns:
precision value (... | f21e01489821b3aa62fb2041a2bf4f2f7427fdce | 607,545 |
def mac_str(n):
"""
Converts MAC address integer to the hexadecimal string representation,
separated by ':'.
"""
hexstr = "%012x" % n
return ':'.join([hexstr[i:i+2] for i in range(0, len(hexstr), 2)]) | 634fe4c79772ada0ebde972140bdd28aa2bed0f3 | 499,663 |
def get_correct_query(input_query: str):
"""
Ignoring multiple whitespaces in input string
:param input_query: string
:return: same query with 1 whitespace between words
"""
correct_words = []
words = input_query.split(' ')
for w in words:
w = w.strip()
if w != '':
... | 0b49112ae8119e335a4d1ae7cecb0b59f87332d7 | 348,426 |
import _decimal
import struct
def decimal(value):
"""Encode a decimal.Decimal value.
:param decimal.Decimal value: Value to encode
:rtype: bytes
"""
if not isinstance(value, _decimal.Decimal):
raise TypeError('decimal.Decimal type required')
tmp = '%s' % value
if '.' in tmp:
... | 66ff790763c818cb59fccd8919e6b4847c63c162 | 357,787 |
def split_instr(instr):
"""
Given an instruction of the form "name arg1, arg2, ...",
returns the pair ("name", "arg1, arg2, ...").
If the instruction has no arguments, the second element of
the pair is the empty string.
"""
result = instr.split(None, 1)
if len(result) == 1:
return result[0], ""
e... | 7bbc6ecf20c478ccce963be9f37fca0a330d3d80 | 622,703 |
import re
import click
def validate_email_address(ctx, param, value):
"""Ensure that email addresses provided are valid email strings"""
# Really just check to match /^[^@]+@[^@]+\.[^@]+$/
email_re = re.compile('^[^@ ]+@[^@ ]+\.[^@ ]+$')
if not email_re.match(value):
raise click.BadParameter(
... | 4be5a86038b4f7be2fdf0f6f4c9f8d732d00454e | 600,039 |
def select_number(list_of_numbers):
"""The player select *one* number of a list of numbers"""
answer = ""
while ((not answer.isdecimal()) or int(answer) not in list_of_numbers):
answer = input("Please type selected number and press ENTER: ")
return int(answer) | af91b18508ff361b0524a551949aac7d93f9afc6 | 699,324 |
import torch
def decode_delta(delta: torch.Tensor, anchor_mesh: torch.Tensor) -> torch.Tensor:
"""Converts raw output to (x, y, w, h) format where (x, y) is the center,
w is the width, and h is the height of the bounding box.
Args:
delta (torch.Tensor): Raw output from the YOLOLayer.
anch... | cfad342c545d5b0f223488f52a445d8580f42d16 | 513,355 |
def str2int(s: str) -> int:
"""将字符串数字转为整数
:param s: 字符串数字
:return: 对应的整形数,如果不是数字返回0
"""
try:
res = int(s)
except Exception:
res = 0
return res | 6b7f77c30596b24f31cf102f89611cece1bf095e | 496,057 |
import click
def get_input_prompt(title, colour="white"):
"""Get prompt for input() function"""
return click.style(f"- {title} \u2192 ", colour) | d263484b642126cd71a68791c0737a3714938705 | 427,010 |
def letter_code(letter):
"""Determine the ISO 6346 numeric code for a letter.
Args:
letter (str): A single letter.
Returns:
An integer character code equivalent to the supplied letter.
"""
value = ord(letter.lower()) - ord("a") + 10
return value + value // 11 | 22718e2d6f83b968a1ba9dc4cfec10fbe45d78fe | 433,165 |
import string
def base26(number: int) -> str:
"""Generate a base 26 representation of `number`
Namely:
- 0 -> A
- 1 -> B
- ...
- 25 -> Z
"""
if number == 0:
return string.ascii_uppercase[0]
digits = []
while number:
digits.append(string.ascii_uppercase[numb... | 7fee5f3f8d363b862bb78f6a8d5ff52e12e4997e | 514,445 |
def get_num_train_images(hparams):
"""Returns the number of training images according to the dataset."""
num_images_map = {
'imagenet': 1281167,
'cifar10': 50000,
}
if hparams.input_data.input_fn not in num_images_map:
raise ValueError(
f'Unknown dataset size for input_fn {hparams.input_... | e75e827026b247158ca76890990b04d51cd99a6a | 23,439 |
def _iou(p1, p2):
"""Computes intersection over union of two intervals.
Args:
p1 ((int,int)): First interval as (first ts, last ts)
p2 ((int,int)): Second interval as (first ts, last ts)
Returns:
float: intersection over union of the two intervals.
"""
i_start = max(... | 2fbe75748a131ce2cfbfe7cee5a9fff300e617e1 | 59,882 |
import math
def handle_flyaway(sim_clock, capsule):
"""
The user has started flying away from the moon. Since this is a
lunar LANDING simulation, we wait until the capsule's velocity is
positive (downward) before prompting for more input.
Returns True if landed, False if simulation should continu... | 9534b1bb1979058c01094ab04ab6e2fabaedc231 | 425,072 |
import hashlib
def CryptDeriveKey(password, key_len=0x20):
"""
Emulate MS CryptDeriveKey
https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptderivekey
:param bytes password: Password to base the key off of.
:param int key_len: Length of key to be used.
:return: Seque... | 76ca203a59b98acf230b534d6d85797e21169eec | 244,062 |
import json
def read_reference_cities(reference_geojson_filename):
"""Returns list of cities as objects with fields 'id',
'properties', 'geometry' (as geojson features generated by overpass-api).
"""
with open(reference_geojson_filename) as f:
geojson = json.load(f)
return geojson['feature... | 58a96a3e1600c0d095dbf3fc317571d7cd62979d | 470,919 |
def valid_version(version):
"""Return true if the **version** has the format 'x.x.x' with integers `x`"""
try:
numbers = [int(part) for part in version.split('.')]
except ValueError:
return False
if len(numbers) == 3:
return True
else:
return False | 6639f8969579b51a307622bd35e1209a0d88cfc9 | 253,587 |
def head(*args, **kwargs):
"""Returns first n rows"""
return lambda df: df.head(*args, **kwargs) | d480e678fa5261ce1e54ba886c8735aa06dfa694 | 372,626 |
def match(results, expected):
"""Return whether or not the results match the expectation. Excludes the response object."""
for result in results:
result.pop('data')
return results == expected | 516e2ed197c161b4bccf69eca892c51042db5296 | 452,424 |
from typing import Iterable
def duplicated(lst: Iterable) -> set:
"""Find which items are duplicated in a list/set/tuple (does not keep order)
Args:
lst: Iterable with items to check
Returns:
Set: set with items repeated (unique)
Examples:
>>> a = [1, 2, 3, 1, 4, 5, 2]
... | 9cd1ebf51b291baad673091f982425202a92cf61 | 211,994 |
def _make_env(environment):
"""Change from Docker environment to Kubernetes env
Args:
environment (dict): Docker-style environment data
Returns:
list: Kubernetes-style env data
"""
env = []
for key, value in environment.items():
env.append({"name": key, "value": value})... | ba3b149dbf27ecabb6287a7d067a0f242744cb7d | 638,973 |
def _get_partition_from_id(partitions, user_partition_id):
"""
Look for a user partition with a matching id in the provided list of partitions.
Returns:
A UserPartition, or None if not found.
"""
for partition in partitions:
if partition.id == user_partition_id:
return p... | 257db9d2302395055f90af87db68ebffde65f237 | 562,514 |
import json
def output_fn(prediction_output, accept='application/json'):
"""
Converts the outputted json to bytes
"""
if accept == 'application/json':
# logger.info("Output successfully parsed.")
return json.dumps(prediction_output).encode('utf-8')
raise Exception('Requested unsupp... | ad894d9cf3f0626a1fe8ef0a48a0d3034e2fbc95 | 404,668 |
def measure_relative(S):
"""Calculate the "measure-relative" score as defined in the paper
Args:
S (List[List[int]]): accuracy counts as defined in the paper
Returns:
score (float): measure-relative score
"""
denom = S[0][0] + S[1][1] + S[0][1] + S[1][0]
if denom == 0:
... | 598330f5d8981cc19545fbe38c4579e4fa8078a9 | 509,220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.