content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def status_to_dict(status_str):
"""
Helper that converts the semicolon delimited status values to
a dict
"""
status = {}
params = [param.strip() for param in status_str.split(";") if param.strip()]
for param in params:
(key, val) = param.split(":")
status[key] = val
return status
|
b74b68c74a5eb1ffac3164355537be23b9197309
| 180,337 |
def convert_mat_value(val):
"""Convert values specified in materials elements_vars."""
return {
'values': [float(x) for x in val['values']],
'min_value': float(val['min_value']) if val['min_value'] is not None else None,
'max_value': float(val['max_value']) if val['max_value'] is not None else None,
}
|
e664d3803f7ae418e48831990ab9caab0b574217
| 486,661 |
def _compute_preferred_numer_of_labels(
available_space: int, vertical_direction: bool
) -> int:
"""
Compute an estimate for the preferred number of labels.
"""
# For horizontal direction (x axis)
preferred_number_of_labels = int(available_space / 15)
if vertical_direction:
# for y axis
preferred_number_of_labels = int(available_space / 5)
return max(2, min(20, preferred_number_of_labels))
|
4209498eda4fe8b35535ec05ad6d368ea6dba736
| 50,302 |
def convert_words_to_index(words, dictionary):
""" Replace each word in the dataset with its index in the dictionary """
return [dictionary[word] if word in dictionary else 0 for word in words]
|
4d1e46b90ecbe855e36617565551d8332f38d29d
| 514,264 |
from typing import Counter
def add_dict(dicts):
"""Add dictionaries.
This will add the two dictionaries
`A = {'a':1, 'b':2, 'c':3}`
`B = {'b':3, 'c':4, 'd':5}`
into
`A + B {'a':1, 'b':5, 'c':7, 'd':5}`
but works for an arbitrary number of dictionaries."""
# start with the first dict
res = Counter(dicts[0])
# successively add all other dicts
for d in dicts[1:]: res.update(Counter(d))
return res
|
a2e0a20735e597c5e6856a3755e14dd7153f418a
| 356,179 |
import uuid
import base64
def _try_b32_decode(v):
"""
Attempt to decode a b32-encoded username which is sometimes generated by
internal Globus components.
The expectation is that the string is a valid ID, username, or b32-encoded
name. Therefore, we can do some simple checking on it.
If it does not appear to be formatted correctly, return None.
"""
# should start with "u_"
if not v.startswith("u_"):
return None
# usernames have @ , we want to allow `[email protected]`
# b32 names never have @
if "@" in v:
return None
# trim "u_"
v = v[2:]
# wrong length
if len(v) != 26:
return None
# append padding and uppercase so that b32decode will work
v = v.upper() + (6 * "=")
# try to decode
try:
return str(uuid.UUID(bytes=base64.b32decode(v)))
# if it fails, I guess it's a username? Not much left to do
except ValueError:
return None
|
299a6ae8e2fa11788da0aa7a4ff36e24db614ec1
| 453,339 |
def string_to_list(s):
"""Splits the input string by whitespace, returning a list of non-whitespace components
Parameters
----------
s : string
String to split
Returns
-------
list
Non-whitespace string chunks
"""
return list(filter(lambda x: x, s.strip().split(' ')))
|
a88cb4359bd955e13dc6f3f86941e67c5c88c3f6
| 543,738 |
def pf(basic):
""" pf Is 12% Of Basic Salary"""
pf = basic*12/100
return pf
|
a16bda8b7102c7725b01f7bdbbe613b7f34d9409
| 363,778 |
def int_to_little_endian_bytes(integer):
"""Converts a two-bytes integer into a pair of one-byte integers using
the little-endian notation (i.e. the less significant byte first).
The `integer` input must be a 2 bytes integer, i.e. `integer` must be
greater or equal to 0 and less or equal to 65535 (0xffff in hexadecimal
notation).
For instance, with the input decimal value ``integer=700`` (0x02bc in
hexadecimal notation) this function will return the tuple ``(0xbc, 0x02)``.
:param int integer: the 2 bytes integer to be converted. It must be in
range (0, 0xffff).
"""
# Check argument type to make exception messages more explicit
if not isinstance(integer, int):
msg = "An integer in range(0x00, 0xffff) is required (got {})."
raise TypeError(msg.format(type(integer)))
# Check the argument value
if not (0 <= integer <= 0xffff):
msg = "An integer in range(0x00, 0xffff) is required (got {})."
raise ValueError(msg.format(integer))
hex_string = '%04x' % integer
hex_tuple = (int(hex_string[2:4], 16), int(hex_string[0:2], 16))
return hex_tuple
|
86325aa8dd9a0e6d36ff6b95bc7daac6f0360294
| 447,839 |
def gen_function_reset(function_name):
"""Writes a reset function for stateful models
Reset function is used to clear internal state of the model
Args:
function_name (str): name of main function
Returns:
signature (str): delcaration of the reset function
function (str): definition of the reset function
"""
reset_sig = 'func ' + function_name + '_reset_states()'
reset_fun = reset_sig
reset_fun += ' { \n\n'
reset_fun += 'memset(&' + function_name + \
'_states,0,sizeof(' + function_name + '_states)); \n'
reset_fun += "} \n\n"
return reset_sig, reset_fun
|
b35c767a341ff559e0340bf73888badac900b4ba
| 389,688 |
def get_character_dictionary_from_text(filename, name_position, dialogue_position, scenario_position):
"""
This function converts a text file inot a character dictionary.
Parameters:
filename: string: The path of the file to read
name_position: int: Number of spaces before the name
dialogue_position: int: Number of spaces before the dialogues
scenario_position: int: Number of spaces before the scenarios
Returns:
character_dialogues: dict: A dictionary with every character's dialogues,
: The sample format is "Name": list of dialogues
scenarios: dict: A list of scenarios, with the key "scenarios". It is kept
as a dict because we can further classify it into different
kinds of scenarios if we want
"""
# Filtering the empty lines
lines = list(filter(lambda x: x!='', open(filename).read().split('\n')))
character_dialogues = {}
scenarios = {'scenarios': []}
dialogue = ""
dialogue_ready = False
for line in lines: # for every line
line_arr = line.split(":")
if len(line_arr) == 1:
scenarios['scenarios'].append(line_arr[0])
elif len(line_arr) == 2:
character = line_arr[0]
dialogue = line_arr[1]
# If some random line is classified as a dialogue, skip it;
if len(character) >= 30:
continue
if not character_dialogues.get(character):
character_dialogues[character] = []
character_dialogues[character].append(dialogue)
return character_dialogues, scenarios
|
2c4b9aa6288da8ae2539ea48647e3f903b3a2e90
| 459,639 |
def GetCheckoutPath(api):
"""Path to checkout the flutter/engine repo."""
return api.path['cleanup'].join('builder', 'src')
|
cedbf61e47ff04e8769275c3197f18a02795b768
| 453,350 |
def open_file(path, mode):
"""
Attempts to open file at path.
Tried up to max_attempts times because of intermittent permission errors on windows
"""
max_attempts = 100
f = None
for _ in range(max_attempts): # pragma: no branch
try:
f = open(path, mode)
except PermissionError: # pragma: no cover
continue
break
return f
|
ae58eb8f6eb41cfb15cdbfc9c9d574148b060b73
| 221,659 |
def clean_column_name(df, index, name):
"""Check that the column has the expected name (case insensitive)
as a sanity check that the user provided the right data,
and return a new dataframe with the column renamed to the preferred casing.
"""
df_name = str(df.columns[index])
if df_name.lower() != name:
raise ValueError('Column {} in the dataframe must be called "{}"'.format(index + 1, name))
return df.rename(columns={ df_name: name })
|
e522a3f15f9fe416a4afb6dc635720e05c8ed740
| 505,392 |
def _check_slice(sli, dim):
"""
Check if the current slice needs to be treated with pbc or if we can
simply pass it to ndarray __getitem__.
Slice is special in the following cases:
if sli.start < 0 or > dim # roll (and possibly pad)
if sli.stop > dim or < 0 # roll (and possibly pad)
if abs(sli.stop - sli.start) > 0 # pad
"""
_roll = 0
_pad = 0
step = sli.step or 1
start = (0 if step > 0 else dim) if sli.start is None else sli.start
stop = (dim if step > 0 else 0) if sli.stop is None else sli.stop
span = (stop - start if step > 0 else start - stop)
if span <= 0:
return _roll, _pad, sli.start, sli.stop, sli.step
lower = min(start, stop)
upper = max(start, stop)
_start = 0 if step > 0 else span
_stop = span if step > 0 else 0
if span > dim:
_pad = span - dim
_roll = -lower % dim
elif lower < 0 or upper > dim:
_roll = -lower % dim
else:
_start = sli.start
_stop = sli.stop
return _roll, _pad, _start, _stop, step
|
70c49ab8932702f310f053588b7a07f8a6ea522d
| 445,899 |
def reverse_words(string: str) -> str:
"""Sort words in reverse order.
Examples:
>>> assert reverse_words('hello world!') == 'world! hello'
"""
return ' '.join(string.split()[::-1])
|
ec5ad7fa50c70543693d69856db7fe21fa85d632
| 69,984 |
def indentblock(text, spaces=0):
"""Indent multiple lines of text to the same level"""
text = text.splitlines() if hasattr(text, 'splitlines') else []
return '\n'.join([' ' * spaces + line for line in text])
|
aba0b00b1943d6662a1ccfcb1afbfce225ad698d
| 377,865 |
def get_class_name(obj: object) -> str:
"""
Get the full class name of an object.
:param obj: A Python object.
:return: A qualified class name.
"""
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__
return module + "." + obj.__class__.__name__
|
cbb80bfe03c62604ab5a1ecf9df35094f3f7e145
| 77,848 |
def _pickup_dt(sys1, sys2):
"""
Determine the sampling time of the new system.
:param sys1: the first system
:type sys1: TransferFunction
:param sys2: the second system
:type sys2: TransferFunction
:return: sampling time
:rtype: int | float
"""
if sys1.dt is None and sys2.dt is not None:
return sys2.dt
elif sys1.dt is not None and sys2.dt is None or sys1.dt == sys2.dt:
return sys1.dt
else:
msg = f'Expected the same sampling time. got sys1:{sys1.dt} sys2:{sys2.dt}'
raise ValueError(msg)
|
4106e5d375da70fe5b2fbaf9a8b3b293751c6820
| 292,665 |
def total_sleep_minutes(guard):
"""Calculate total minutes slept by guard."""
_, shifts = guard
return sum(
wakes - sleeps
for sleeps, wakes in shifts
)
|
4b510c8be5a47aba87b0b513f98026d0b62c636c
| 555,075 |
import re
def is_a_number(x):
"""This function determines if its argument, x, is in the
format of a number. It can be number can be in integer, floating
point, scientific, or engineering format. The function returns True if the
argument is formattted like a number, and False otherwise."""
num_re = re.compile(r'^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?$')
mo = num_re.match(str(x))
if mo:
return True
else:
return False
|
f74e8de1e865793ce1e57e85ed09c8846b9203cd
| 590,883 |
from typing import Optional
def get_hash_type(hash_value: str) -> Optional[str]:
"""Get the hash type."""
if len(hash_value) == 32:
return "md5"
elif len(hash_value) == 40:
return "sha1"
elif len(hash_value) == 64:
return "sha256"
else:
return None
|
a2dbdbeb64f8b5e340bad174c763a3302ff8318c
| 399,080 |
def round_up(x:int, up_to:int):
""" Round up to the nearest specified value"""
return x if x % up_to == 0 else x + up_to - x % up_to
|
e1b7c23d3bbe6e9e22dbb20748ce4b46b4300654
| 564,685 |
def strategy_expensive(cookies, cps, history, time_left, build_info):
"""
Always buy the most expensive item you can afford in the time left.
"""
info_object = build_info.clone()
items_list = info_object.build_items()
item_to_buy = None
max_cost = float("-inf")
for item in items_list:
item_cost = info_object.get_cost(item)
if (item_cost - cookies) / cps > time_left:
continue
elif item_cost > max_cost:
max_cost = item_cost
item_to_buy = item
return item_to_buy
|
7427332b523d08ea947cd74f00b5e4cfd9fcb3d5
| 291,051 |
def extract_patches(features, size, stride):
"""
Arguments:
features: a float tensor with shape [c, h, w].
size: an integer, size of the patch.
stride: an integer.
Returns:
a float tensor with shape [N, c * size * size],
where N = n * m, n = 1 + floor((h - size)/stride),
and m = 1 + floor((w - size)/stride).
"""
c, h, w = features.size()
patches = features.unfold(1, size, stride).unfold(2, size, stride)
# it has shape [c, n, m, size, size]
# get the number of patches
n, m = patches.size()[1:3]
N = n * m
patches = patches.permute(1, 2, 0, 3, 4).contiguous()
patches = patches.view(N, c * size * size)
return patches
|
903a7c550d1e044b087e81b2024786f416f4527d
| 498,545 |
def perform_data_split(X, y, training_idxs, test_idxs, val_idxs):
"""
Split X and y into train/test/val sets
Parameters:
-----------
X : eg, use img_bow_hist
y : corresponding labels for X
training_idxs : list/array of integers used as indicies for training rows
test_idxs : same
val_idxs : same
Returns:
--------
X_train, X_test, X_val, y_train, y_test, y_val
"""
X_train = X[training_idxs]
X_test = X[test_idxs]
X_val = X[val_idxs]
y_train = y[training_idxs]
y_test = y[test_idxs]
y_val = y[val_idxs]
return X_train, X_test, X_val, y_train, y_test, y_val
|
388737dea103086cb5a37489011e47a81735d53c
| 307,800 |
def critical_speed(_x):
"""Critical speed of rolling disc.
_x is an array/list in the following order:
g: Gravitational constant
r: Radius of disc
"""
# Unpack function arguments
g, r = _x
# Calculate return values
cs = -3**(1/2)*(g/r)**(1/2)/3
# Return calculated values
return [cs]
|
909259c8c9039b87c2c8f5fe4ae22b0236568030
| 257,797 |
def create_error(request, status, code='', title='', detail=''):
"""creates a JSON API error - http://jsonapi.org/format/#errors
"status" - The HTTP status code applicable to this problem,
expressed as a string value.
"code" - An application-specific error code, expressed as a
string value.
"title" - A short, human-readable summary of the problem. It
SHOULD NOT change from occurrence to occurrence of
the problem, except for purposes of localization.
"detail" - A human-readable explanation specific to this
occurrence of the problem.
"""
id = ''
if request:
id = request.META.get('HTTP_REQUEST_ID', '')
return {
'id': id,
'status': str(status),
'code': code,
'title': title,
'detail': detail,
}
|
4a98b4b6a746c31926940cb07854e8363b1a97c1
| 113,238 |
def pubsub_messages(request):
"""Create a list of pubsub messages."""
with open('tests/data/pubsub_messages.txt') as f:
messages = [line for line in f]
return messages
|
8fea5217e6486454cc966f7e886e749c7cf5d9ab
| 539,785 |
def return_geojson(lat,lng,increment):
"""returns geojson box around lat and lng"""
geojson_geometry = { # (lng,lat)
"type": "Polygon",
"coordinates": [
[
[
lng+increment,
lat+increment
],
[
lng+increment,
lat-increment
],
[
lng-increment,
lat-increment
],
[
lng-increment,
lat+increment
],
[
lng+increment,
lat+increment
]
]
]
}
return geojson_geometry
|
aa0d09fef600d0d76f8ae6597e8d8f6171abaf96
| 604,672 |
def find_number_to_keep(count_of_0, count_of_1, criteria) -> str:
"""
Compare numbers according to a criteria ('most' or 'least').
Criteria 'most' returns the number of which count is bigger.
Criteria 'least' returns the number of which count is lesser.
When counts are equal, criteria 'most' returns '1', and 'least' returns '0'
Args:
count_of_0 (int): count of numbers '0'
count_of_1 (int): count of numbers '1'
criteria (str): criteria for comparison
Returns:
str: resulting number (values '0' or '1')
"""
if criteria == 'most':
if count_of_0 == count_of_1:
return '1'
else:
return '0' if count_of_0 > count_of_1 else '1'
else:
if count_of_0 == count_of_1:
return '0'
else:
return '0' if count_of_0 < count_of_1 else '1'
|
743ddb403a52795cd0348ac880ad6b9011afbe25
| 249,362 |
def _make_nested_padding(pad_shape, pad_token):
"""Create nested lists of pad_token of shape pad_shape."""
result = [pad_token]
for dimension in reversed(pad_shape):
result = [result * dimension]
return result[0]
|
5be7f0dc387369a4d00c35b538854316848d049b
| 543,875 |
def iter_to_string(it, format_spec, separator=", "):
"""Represents an iterable (list, tuple, etc.) as a formatted string.
Parameters
----------
it : Iterable
An iterable with numeric elements.
format_spec : str
Format specifier according to
https://docs.python.org/3/library/string.html#format-specification-mini-language
separator : str
String between items of the iterator.
Returns
-------
str
The iterable as formatted string.
"""
return separator.join([f"{format(elem, format_spec)}" for elem in it])
|
730a8ea44785c9bb995ffae0a1b302fa25b37029
| 283,210 |
def get_jaccard_sim(str1, str2):
"""
Jaccard similarity:
Also called intersection over union is defined as size of intersection
divided by size of union of two sets.
"""
a = set(str1.split())
b = set(str2.split())
c = a.intersection(b)
return float(len(c)) / (len(a) + len(b) - len(c))
|
be39079c7a5b04add59f7e303eb1bcecbae52053
| 446,662 |
def get_meta(txt):
"""Parse meta information from text if available and return as dict.
meta information is a block imbedded in "---\n" lines having the format:
key: value
both are treated as strings the value starts after the ": " end ends with
the newline.
"""
SEP = '---\n'
meta = dict()
if txt.count(SEP) > 1 and txt.startswith(SEP):
stuff = txt[len(SEP):txt.find(SEP, 1)]
txt = txt[txt.find((SEP), 1)+len(SEP):]
for i in stuff.splitlines():
if i.count(':') > 0:
key, value = i.split(':', 1)
value = value.strip()
meta[key] = value
return meta, txt
|
c9d6f88b4771693790c371e96eada2198c73b989
| 561,881 |
def char_collect_all(s, c):
"""
Find all appearances of char in string
:param s: haystack
:param c: needle
:return: list of indices
"""
start = 0
res = []
clen = len(c)
while True:
start = s.find(c, start)
if start == -1: break
res.append(start)
start += clen
return res
|
93147386203cb3c275f7227e91e3ce20dd63820c
| 412,192 |
def func_node(node):
"""Get the function AST node from the source."""
return node.body[0]
|
9e295c7cd1dccd323e9a3544afd5e377cfa4e86c
| 237,394 |
def format_label_outputs(label: dict = {}) -> dict:
"""Take GitHub API label data and format to expected context outputs
Args:
label (dict): label data returned from GitHub API
Returns:
(dict): label object formatted to expected context outputs
"""
ec_object = {
'ID': label.get('id'),
'NodeID': label.get('node_id'),
'Name': label.get('name'),
'Description': label.get('description'),
'Color': label.get('Color'),
'Default': label.get('default')
}
return ec_object
|
bd7b7dccdceb989a5cd55e85b9dc875c4269ef40
| 602,790 |
def find_pos(mydict, n, keys):
"""
Find the bag and local position of the overall nth element in one set of a
dictionary.
Parameters
----------
mydict : dictionary
Dictionary with array_like values. Each such array_like must have the
same shape except for the first dimension.
n : int
The global position of the wanted instance.
keys : list
keys for each bag used for the ordering to look for instance n.
Returns
----------
key : key
Dictionary with array_like values corresponding to the given keys.
l : int
"""
n_ = -1
for k, key in enumerate(keys):
n_ += len(mydict[key])
if n_ == n:
return (key, len(mydict[key]) - 1)
elif n_ > n:
return (key, n - n_ + len(mydict[key]) - 1)
else:
continue
|
b51d16b934198511e60c17b6ee74ff2d9d2701e7
| 325,781 |
def original_choice(door):
"""
Return True if this door was picked originally by the contestant """
return door.guessed_originally is True
|
5d2c11e32ef4181b653642fb18a995427a3bae9b
| 682,158 |
def is_commit_verified(commit: dict) -> bool:
"""`True` if a Github commit is verified, `False` otherwise."""
return commit["commit"]["verification"]["verified"]
|
0d3e7ab1157a01f83588e47d7fe8f1e260453dff
| 285,404 |
def validate_window_size(candidate_window_size: int) -> int:
"""Return validated window size candidate, raising a meaningful error otherwise.
Parameters
-----------------
candidate_window size: int,
The candidate window size value to validate.
Raises
-----------------
ValueError,
If the provided window size parameter is not within
the allowed set of values.
Returns
-----------------
The validated value.
"""
if not isinstance(candidate_window_size, int):
raise ValueError(
(
"The window size parameter must be an integer.\n"
"You have provided `{}`, which is of type `{}`."
).format(
candidate_window_size,
type(candidate_window_size)
)
)
if candidate_window_size < 1:
raise ValueError(
(
"The window size parameter must a strictly positive "
"integer value. You have provided `{}`."
).format(
candidate_window_size
)
)
return candidate_window_size
|
6459fea1322ea791485356d4e25899aa2493fe28
| 106,758 |
import re
def get_image_name_from_recipe(recipe_file_name: str) -> str:
""" Returns the image name contained in a recipe file name. """
return re.sub(r'(^.*?)\..*$', r'\1', recipe_file_name)
|
51463799d9739082f007bca1b032d45f4590b401
| 161,000 |
def tmpdir_repoparent(tmpdir_factory, scope='function'):
"""Return temporary directory for repository checkout guaranteed unique."""
fn = tmpdir_factory.mktemp("repo")
return fn
|
90ab3cc6d5484da6cfb9c47de0caf128fa0d6a6a
| 651,358 |
import configparser
def load_config(feed_file):
"""Load configs into dict."""
config_dict = {}
config = configparser.RawConfigParser()
# load the feed config
config.read(feed_file)
config_dict = {}
for key in config:
config_dict[key] = config[key]
return config_dict
|
d1cecdf1a979d85970accdff9ad717ff733840b0
| 210,175 |
import re
import string
def clean(text):
"""
Remove tickers, special characters, links and numerical strings
Parameters
text : str
User given input
Returns
-------
str
cleaned text
Examples
--------
>>>text="RT $USD @Amila #Test\nTom\'s newly listed Co. & Mary\'s unlisted Group to supply tech for
nlTK.\nh.. $TSLA $AAPL https:// t.co/x34afsfQsh'"
>>> clean(text)
'RT Amila TestTom s newly listed Co amp Mary s unlisted Group to supply tech for nlTK h '
"""
# remove tickers
remove_tickers=re.sub(r'\$\w*','',text)
# remove new line symbol
remove_newline=re.sub(r'\n','',remove_tickers)
# remove links
remove_links=re.sub(r'https?:\/\/.*\/\w*','',remove_newline)
# remove special characters
remove_punctuation=re.sub(r'['+string.punctuation+']+', ' ', remove_links)
# remove numerical strings
remove_numeric_words=re.sub(r'\b[0-9]+\b\s*', '',remove_punctuation)
clean_text=remove_numeric_words
return clean_text
|
051cfb0c3acbe092f390b5a7040025a6b172e0de
| 332,661 |
def equilibrium_capital(alpha, delta, g, n, rho, theta, **params):
"""Steady state value for capital stock (per unit effective labor)."""
return (alpha / (delta + rho + theta * g))**(1 / (1 - alpha))
|
f8dc11767621a8b2869bf2c5346d07a3f945e125
| 353,747 |
def average_precision_at_k(targets, ranked_predictions, k=None):
"""Computes AP@k given targets and ranked predictions."""
if k:
ranked_predictions = ranked_predictions[:k]
score = 0.0
hits = 0.0
for i, pred in enumerate(ranked_predictions):
if pred in targets and pred not in ranked_predictions[:i]:
hits += 1.0
score += hits / (i + 1.0)
divisor = min(len(targets), k) if k else len(targets)
return score / divisor
|
57e21a1ca8b8f7fccc0b5c59dbfc799d8618fc93
| 7,095 |
import itertools
def _n_enr_states(dimensions, n_excitations):
"""
Calculate the total number of distinct ENR states for a given set of
subspaces. This method is not intended to be fast or efficient, it's
intended to be obviously correct for testing purposes.
"""
count = 0
for excitations in itertools.product(*map(range, dimensions)):
count += int(sum(excitations) <= n_excitations)
return count
|
ab974f8e0028928f1671c51537c9b4166c337958
| 85,874 |
def AppendPatternsToFilter(test_filter, positive_patterns=None,
negative_patterns=None):
"""Returns a test-filter string with additional patterns.
Args:
test_filter: test filter string
positive_patterns: list of positive patterns to add to string
negative_patterns: list of negative patterns to add to string
"""
positives = []
negatives = []
positive = ''
negative = ''
split_filter = test_filter.split('-', 1)
if len(split_filter) == 1:
positive = split_filter[0]
else:
positive, negative = split_filter
positives += [f for f in positive.split(':') if f]
negatives += [f for f in negative.split(':') if f]
positives += positive_patterns if positive_patterns else []
negatives += negative_patterns if negative_patterns else []
final_filter = ':'.join([p.replace('#', '.') for p in positives])
if negatives:
final_filter += '-' + ':'.join([n.replace('#', '.') for n in negatives])
return final_filter
|
1719010bd037ea96d6d11300579e6d503ae13df4
| 451,078 |
def dms_to_decimal(degrees, minutes, seconds, sign=' '):
"""Convert degrees, minutes, seconds into decimal degrees.
>>> dms_to_decimal(10, 10, 10)
10.169444444444444
>>> dms_to_decimal(8, 9, 10, 'S')
-8.152777777777779
"""
return (-1 if sign[0] in 'SWsw' else 1) * (
float(degrees) +
float(minutes) / 60 +
float(seconds) / 3600
)
|
c18bd8c094c650acbb4c374b9793fe2cc01879b5
| 427,133 |
def get_value_csr(data, indices, index):
"""get one value from a sparse vector"""
for i in range(len(indices)):
if indices[i] == index:
return data[i]
return 0.0
|
918b84e8d2cadd4d802b688729ea7dcc4135f55b
| 221,581 |
def LoadSiteList(path):
"""Loads a list of URLs from |path|.
Expects the URLs to be separated by newlines, with no leading or trailing
whitespace.
Args:
path: The path to a file containing a list of new-line separated URLs.
Returns:
A list of strings, each one a URL.
"""
f = open(path)
urls = f.readlines()
f.close()
return urls
|
c81533b5b28cc1ed66fe3c699cc66fced807a972
| 288,424 |
def get_end_activities_from_log(trace_log, activity_key="concept:name"):
"""
Get the end attributes of the log along with their count
Parameters
----------
trace_log
Trace log
activity_key
Activity key (must be specified if different from concept:name)
Returns
----------
end_activities
Dictionary of end attributes associated with their count
"""
end_activities = {}
for trace in trace_log:
if len(trace) > 0:
activity_last_event = trace[-1][activity_key]
if not activity_last_event in end_activities:
end_activities[activity_last_event] = 0
end_activities[activity_last_event] = end_activities[activity_last_event] + 1
return end_activities
|
70179252dac0d5c102f7522f909b6539dd1376ee
| 458,883 |
def largest_prime_factor_even_optimized(number):
"""
We know that, excluding 2, there are no even prime numbers.
So we can increase factor by 2 per iteration after having found the
"""
factors = []
factor = 2
if number % factor == 0:
number = number // factor
factors.append(factor)
while number % factor == 0:
number = number // factor
factor = 3
while number > 1:
if number % factor == 0:
factors.append(factor)
number = number // factor # Remainder guarenteed to be zero
while number % factor == 0:
number = number // factor # Remainder guarenteed to be zero
factor += 2
return factors
|
36269bc3fc68af504d85adae6069fb98469be9d3
| 76,348 |
import gzip
def get_open_func(filename):
"""
Gets the open function to use to open the given filename.
:param filename: The file to open.
:return: The open function, and the read-mode flag to use.
"""
# Select the open function based on the filename
if filename.endswith('.gz'):
return gzip.open, 'rt'
else:
return open, 'r'
|
d59e29bf53b80535fa81080dceb78a8712de546e
| 499,897 |
from typing import Any
def find_by_key(data: dict, target: str) -> Any:
"""
Find a value by key in a dictionary.
.. code-block:: python
>>> dct = {
>>> "A": "T",
>>> "R": 3,
>>> "B": {
>>> "C": {
>>> "D": "value"
>>> }
>>> }
>>> }
>>> find_by_key(dct, "D")
"value"
Args:
data (dict): Dict to walk through
target (str): target key
Returns:
Any: Value data[...][target]
"""
val = None
for key, value in data.items():
if isinstance(value, dict):
val = find_by_key(value, target)
if val:
break
elif key == target:
val = value
return val
|
41f3fef0c49f596e7998b32f99419cff624f5568
| 507,851 |
def find_English_definition(content: str):
"""
Find the English Definition from the content
:param content: The contents of the website
:return Eng_def: The found English definition
:return content: The contents that cut the English definition part
"""
if '释义' not in content:
Eng_def = ''
else:
START = content.find('释义')
END = content.find('</i>')
Eng_def = content[START+len('释义:<span><i>'):END]
content = content[END+len('</i></span></div>'):]
return Eng_def, content
|
9c4e748aca047fd8c381a894993f3dc2a08586ff
| 503,584 |
def format_null(string: str) -> str:
"""Remove the quotes from the null values."""
return string.replace("\"null\"", "null")
|
cfcda3e1775dbe122b7bec89a56e93aeb16c8a50
| 223,817 |
import random
def sample(p):
"""Given an array of probabilities, which sum to 1.0, randomly choose a 'bin',
e.g. if p = [0.25, 0.75], sample returns 1 75% of the time, and 0 25%;
NOTE: p in this program represents a row in the pssm, so its length is 4"""
r = random.random()
i = 0
while r > p[i]:
r -= p[i]
i += 1
return i
|
886da94e2c9e35bd07ceba606de92d2126197b99
| 25,173 |
import torch
def symmetric_mse_loss(input1, input2):
"""Like F.mse_loss but sends gradients to both directions
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to both input1 and input2.
"""
assert input1.size() == input2.size()
num_classes = input1.size()[1]
return torch.sum((input1 - input2)**2) / num_classes
|
64e01abd6b90f2874aa58cd6306709d22535f38c
| 586,631 |
def guess_mean_kind(unit, control_var):
"""
Guess which kind of mean should be used to summarize results in the given
unit.
:returns: ``'arithmetic'`` if an arithmetic mean should be used, or
``'harmonic'``. Geometric mean uses cannot be inferred by this
function.
:param unit: Unit of the values, e.g. ``'km/h'``.
:type unit: str
:param control_var: Control variable, i.e. variable that is fixed during
the experiment. For example, in a car speed experiment, the control
variable could be the distance (fixed distance), or the time. In that case,
we would have ``unit='km/h'`` and ``control_var='h'`` if the time was
fixed, or ``control_var='km'`` if the distance was fixed.
:type control_var: str
"""
if unit is None or control_var is None:
kind = 'arithmetic'
else:
if '(' in unit or ')' in unit:
raise ValueError('Units containing parenthesis are not allowed')
split_unit = unit.split('/')
if len(split_unit) == 1:
kind = 'arithmetic'
else:
try:
pos = split_unit.index(control_var)
except ValueError:
# Default to arithmetic
kind = 'arithmetic'
else:
is_divisor = bool(pos % 2)
if is_divisor:
kind = 'arithmetic'
else:
kind = 'harmonic'
return kind
|
9007d9d05d93240b1b9abdee7f06a4c6883771b8
| 346,606 |
def score_illegals(illegals):
""" Take a list of illegal closing characters and return a score per the question's criteria
"""
sum = illegals.count(')') * 3
sum += illegals.count(']') * 57
sum += illegals.count('}') * 1197
sum += illegals.count('>') * 25137
return sum
|
9e3e6e2556cf252d51ce7199a660514c3442fc1c
| 239,994 |
import re
def latexify(txt):
"""
Take some text and replace the logical vocabulary that ttg understands with LaTeX equivalents
"""
# Use LaTeX symbols as in Forallx (roughly)
substitutions = {
"not": "\\lnot",
"-": "\\lnot",
"~": "\\lnot",
"or": "\\lor",
"nor": "\\downarrow",
"xor": "\\veebar",
"!=": "\\veebar",
"and": "\\land",
"nand": "\\uparrow",
"implies": "\\rightarrow",
"=>": "\\rightarrow",
"=": "\\leftrightarrow",
}
regex = re.compile("(%s)" % "|".join(map(re.escape, substitutions.keys())))
return regex.sub(lambda mo: substitutions[mo.string[mo.start() : mo.end()]], txt)
|
6dc8f65e1c57db7dc729b7e4792b080b2836475b
| 347,065 |
def isiter(x):
"""
Returns `True` if the given value implements an valid iterable
interface.
Arguments:
x (mixed): value to check if it is an iterable.
Returns:
bool
"""
return hasattr(x, '__iter__') and not isinstance(x, (str, bytes))
|
6b2e5a6e4d676cf6c749fbac6f1e3ba64057f8e9
| 633,321 |
import re
def clean_url(url: str) -> str:
"""Remove zero width spaces, leading/trailing whitespaces, trailing slashes,
and URL prefixes from a URL
Args:
url (str): URL
Returns:
str: URL without zero width spaces, leading/trailing whitespaces, trailing slashes,
and URL prefixes
"""
removed_zero_width_spaces = re.sub(r"[\u200B-\u200D\uFEFF]", "", url)
removed_leading_and_trailing_whitespaces = removed_zero_width_spaces.strip()
removed_trailing_slashes = removed_leading_and_trailing_whitespaces.rstrip("/")
removed_https = re.sub(r"^[Hh][Tt][Tt][Pp][Ss]:\/\/", "", removed_trailing_slashes)
removed_http = re.sub(r"^[Hh][Tt][Tt][Pp]:\/\/", "", removed_https)
return removed_http
|
fb25b77524b03b5f34d8e65dde3e59c16b389cc4
| 159,920 |
def lerp(a, b, t):
""" blend the value from start to end based on the weight
:param a: start value
:type a: float
:param b: end value
:type b: float
:param t: the weight
:type t: float
:return: the value in between
:rtype: float
"""
return a * (1 - t) + b * t
|
127ff551f81423c299e4434841dd141d449d57d1
| 632,806 |
def get_header_string(search_category, search_string):
"""Returns personalized heading text depending on the passed search category."""
header_string = ""
csv_title_index = 0; csv_year_index = 1; csv_author_index = 2
if search_category == csv_title_index:
header_string = "\n\nResults books with titles containing: "
elif search_category == csv_year_index:
header_string = "\n\nResults for books published in the years: "
elif search_category == csv_author_index:
header_string = "\n\nResults for books written by: "
return header_string + search_string
|
191291345dd893731e8a683b6907fbe058f6e67f
| 119,448 |
def constant(_):
"""
Returns a constant value for the Scheduler
:param _: ignored
:return: (float) 1
"""
return 1.
|
a44434c6ef19f93d6217984a9ac34fff323f26b3
| 288,907 |
from datetime import datetime
def to_datetime(image_time: str, image_date: str) -> datetime:
"""builds datetime object
Args:
image_time (:obj:`string`): time when the image was captured
image_date (:obj:`string`): date when the image was captured
Returns:
:obj:`datetime`: contructed datetime object
Throws:
:obj:`ValueError`: if length of date string is not 8 or length of time string is not 6
"""
if len(image_date) != 8 or len(image_time) != 6:
raise ValueError('ERROR: Invalid length of input dates.')
try:
year = int(image_date[0:4])
month = int(image_date[4:6])
day = int(image_date[6:8])
hour = int(image_time[0:2])
minute = int(image_time[2:4])
second = int(image_time[4:6])
return datetime(year, month, day, hour, minute, second)
except ValueError:
# add error logging
raise
|
d77817e2c0a57f316b5034480c8dae844cb285ee
| 342,749 |
def find_num_player_in_group(group):
"""
find the number of players in a group
:param group: A Group object
:return: number of players in the group
"""
players = group.players.all()
return (len(players))
|
3a1f470bf64fe9409237da7afe1c0692a7b68d53
| 639,808 |
def compare_list_of_committees(committees1, committees2):
"""
Check whether two lists of committees are equal.
The order of candidates and their multiplicities in these lists are ignored.
To be precise, two lists are equal if every committee in list1 is contained in list2 and
vice versa.
Committees are, as usual, of type `CandidateSet` (i.e., sets of positive integers).
.. doctest::
>>> comm1 = CandidateSet({0, 1, 3})
>>> comm2 = CandidateSet({0, 3, 1}) # the same set as `comm1`
>>> comm3 = CandidateSet({0, 1, 4})
>>> compare_list_of_committees([comm1, comm2, comm3], [comm1, comm3])
True
>>> compare_list_of_committees([comm1, comm3], [comm1])
False
Parameters
----------
committees1, committees2 : list of CandidateSet
Two lists of committees.
Returns
-------
bool
"""
for committee in committees1 + committees2:
if not isinstance(committee, set):
raise ValueError("Input has to be two lists of sets.")
return all(committee in committees1 for committee in committees2) and all(
committee in committees2 for committee in committees1
)
|
3d754496aa5fb6bf7c77fc05258ecbff2d7b3f43
| 536,332 |
import re
def add_css(str):
""" Add css span tags to text by replacing strings of form:
":red:`some text`" with "<span class=\"red\">some text</span>"
"""
css_str = re.sub(r':(\w+):`([^`]+)`', r'<span class="\1">\2</span>', str)
return css_str
|
78745398e0fed89579c7c6dd2a3199917acb4849
| 184,587 |
import itertools
def one_to_one(graph, nodes):
"""
Return True if graph contains only one to one mappings. The
directed graph should be represented as a dictionary mapping of
edges for each node. Nodes should be passed a simple list.
"""
edges = itertools.chain.from_iterable(graph.values())
return len(graph) == len(nodes) and len(set(edges)) == len(nodes)
|
d320e1b018b296dc8b6e50e191a75843ea59201e
| 73,413 |
def get_first_annotated_frame_index(filename):
""" determines the frame index of the first annotated frame.
It is based on the timestamps file provided with the annotations of
particular recording.
This timestamps file provides both the frame index and corresponding timestamp
for all images that have been manually annotated in the recording.
Note that if the file does not exists, this function considers that
the frame index of the first annotated frame is 0 at time 0
Parameters
----------
filename: str
The file with annotations timestamps.
Returns
-------
list of tuples:
List of (frame_index, timestamp) for annotated frames in the sequence.
int:
Status of the process (-1 meaning failure)
"""
status = 0
try:
f = open(filename, 'r')
first_line = f.readline().rstrip()
first_line = first_line.split(' ')
indices = (int(first_line[0]), int(first_line[1]))
f.close()
except IOError:
status = -1
indices = (0, 0)
return indices, status
|
6a3091ea9b39a97777a3f157f35b4673f45984a8
| 394,014 |
import base64
def base64_encode(bot, trigger):
"""Encodes a message into base64."""
if not trigger.group(2):
return bot.reply('I need something to encode.')
encodedBytes = base64.b64encode(trigger.group(2).encode('utf-8'))
encodedStr = str(encodedBytes, 'utf-8')
bot.say(encodedStr)
|
d9d515ee07b5cb48a28cf0196f483f5e69201fc6
| 616,061 |
import torch
def batch_quadratic_form(x: torch.Tensor, A: torch.Tensor) -> torch.Tensor:
"""
Compute the quadratic form x^T * A * x for a batched input x.
Inspired by https://stackoverflow.com/questions/18541851/calculate-vt-a-v-for-a-matrix-of-vectors-v
This is a vectorized implementation of out[i] = x[i].t() @ A @ x[i]
x shape: (B, N)
A shape: (N, N)
output shape: (B)
"""
return (torch.matmul(x, A) * x).sum(1)
|
4e639fc210e944cdc6726c2daab85e486de58134
| 24,880 |
def map_compat_fueltech(fueltech: str) -> str:
"""
Map old opennem fueltechs to new fueltechs
"""
if fueltech == "brown_coal":
return "coal_brown"
if fueltech == "black_coal":
return "coal_black"
if fueltech == "solar":
return "solar_utility"
if fueltech == "biomass":
return "bioenergy_biomass"
return fueltech
|
4f7be4496d7c29eb9e9ab8f48ff408f6f4cc7c11
| 246,473 |
def average(nums):
"""Find mean of a list of numbers."""
return sum(nums) / len(nums)
|
30b1689663d80657c1530cfcd10f6b5dcfdf2de9
| 601,588 |
def point_is_in(bbox, point):
"""
Check whether EPSG:4326 point is in bbox
"""
# bbox = normalize(bbox)[0]
return (
point[0] >= bbox[0]
and point[0] <= bbox[2]
and point[1] >= bbox[1]
and point[1] <= bbox[3]
)
|
ebec8166789aba006089bbd03092de4d9e35ae86
| 53,530 |
def confusionMatrix(predicted, actual, threshold):
"""
计算数据的混淆矩阵表数值
:param predicted: 实验数据集
:param actual: 真实数据集
:param threshold: 阀值
:return: 数值形式[tp, fn, tp, tn, rate]
"""
# 检查数据长度,避免无效输入
if len(predicted) != len(actual):
return -1
# 定义混淆矩阵的四项指标
tp = 0.0 # 真实例
fp = 0.0 # 假实例
tn = 0.0 # 真负例
fn = 0.0 # 假负率
for i in range(len(actual)):
if actual[i] > 0.5:
if predicted[i] > threshold:
tp += 1.0
else:
fn += 1.0
else:
if predicted[i] < threshold:
tn += 1.0
else:
fp += 1.0
# 误分率
rate =(fn + fp) / (tp + fn + tn + fp)
rtn = [tp, fn, fp, tn, rate]
return rtn
|
866360e041f0870b88e53ea2cc6cd2ebdd568d6d
| 54,648 |
def acoustic_reflectivity(vp, rho):
"""
The acoustic reflectivity, given Vp and RHOB logs.
Args:
vp (ndarray): The P-wave velocity.
rho (ndarray): The bulk density.
Returns:
ndarray: The reflectivity coefficient series.
"""
upper = vp[:-1] * rho[:-1]
lower = vp[1:] * rho[1:]
return (lower - upper) / (lower + upper)
|
a2c14f2d0573e386b205b23a0c3956b4bf9e0edc
| 393,771 |
def ParseList(List):
"""Parse lists (e.g. 0,1,3-8,9)"""
Res = list()
if ( str(List).isdigit() ):
Res.append(int(List))
else:
for Element in List.split(','):
if '-' in Element:
x1,x2 = Element.split('-')
Res.extend(list(range(int(x1), int(x2)+1)))
else:
Res.append(int(Element))
return Res
|
2c5c76479538dced1a452e6d1b49a0c76151ef7e
| 400,001 |
def _url_joiner(*args):
"""Helper: construct an url by joining sections with /"""
return '/'.join(s.strip('/') for s in args)
|
b94b25d0f3b5820993f4adc591e5ef257b4371da
| 664,273 |
def boldheader(title):
"""Convert the given string into bold string, prefixed and followed by
newlines."""
return "\n\n**%s**\n\n" % str(title).strip()
|
987a60ed29bc87e04a92ec003f8b67bb50277d52
| 351,235 |
def compress_str(s):
"""
Compress a string by replacing consecutive duplicate characters with a count
of the number of characters followed by the character.
"""
if not s:
return s
compressed_str = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
compressed_str.append(str(count))
compressed_str.append(s[i-1])
count = 1
compressed_str.append(str(count))
compressed_str.append(s[-1])
return ''.join(compressed_str)
|
6e7d6da2244eef331b7e4f68cc31c91138dd4801
| 454,067 |
import random
def yatzy_game(number_of_dice: int = 5):
"""
Roll the indicated number of 6 sided dice using random number generator
:param number_of_dice: integer
:return: sorted list
Using random.seed to hold randomness result
>>> random.seed(1234)
>>> yatzy_game(4)
[1, 1, 1, 4]
>>> random.seed(5)
>>> yatzy_game(5)
[3, 3, 5, 6, 6]
"""
return sorted(random.choice((1, 2, 3, 4, 5, 6))
for _ in range(number_of_dice))
|
32f990cd4a1d39877e2a951e2ec7f0cdeb4d3ff6
| 152,292 |
from datetime import datetime
def datetime_to_int_seconds(dt_obj):
"""Converts a datetime object to integer seconds"""
epoch_start = datetime(1970, 1, 1)
return int((dt_obj - epoch_start).total_seconds())
|
12d279466cdea5f2fb3a136c9443ebd08d325f67
| 317,059 |
import json
def get_json_value(value):
""" Get value as JSON. If value is not in JSON format return the given value """
try:
return json.loads(value)
except ValueError:
return value
|
672f8d79aef23ee8f639ce87860029d54bf78ca3
| 646,487 |
def step_is_chg_state(step_df, chg):
"""
Helper function to determine whether a given dataframe corresponding
to a single cycle_index/step is charging or discharging, only intended
to be used with a dataframe for single step/cycle
Args:
step_df (pandas.DataFrame): dataframe to determine whether
charging or discharging
chg (bool): Charge state; True if charging
Returns:
(bool): True if step is the charge state specified.
"""
cap = step_df[["charge_capacity", "discharge_capacity"]]
cap = cap.diff(axis=0).mean(axis=0).diff().iloc[-1]
if chg: # Charging
return cap < 0
else: # Discharging
return cap > 0
|
0c36cb62528dbea4c1d58085d3f88fba0632bec0
| 272,028 |
import hashlib
def first_half_of_sha512(*data: bytes) -> bytes:
"""Returns first 32 bytes of SHA512 hash"""
return hashlib.sha512(b''.join(data)).digest()[:32]
|
c4f9b7768b35c29d668f60319dab17455b001f7d
| 489,598 |
import torch
def calculate_blend_weights(t_values: torch.Tensor,
opacity: torch.Tensor) -> torch.Tensor:
"""Calculates blend weights for a ray.
Args:
t_values (torch.Tensor): A (num_rays,num_samples) tensor of t values
opacity (torch.Tensor): A (num_rays,num_samples) tensor of opacity
opacity values for the ray positions.
Returns:
torch.Tensor: A (num_rays,num_samples) blend weights tensor
"""
_, num_samples = t_values.shape
deltas = t_values[:, 1:] - t_values[:, :-1]
max_dist = torch.full_like(deltas[:, :1], 1e10)
deltas = torch.cat([deltas, max_dist], dim=-1)
alpha = 1 - torch.exp(-(opacity * deltas))
ones = torch.ones_like(alpha)
trans = torch.minimum(ones, 1 - alpha + 1e-10)
trans, _ = trans.split([num_samples - 1, 1], dim=-1)
trans = torch.cat([torch.ones_like(trans[:, :1]), trans], dim=-1)
trans = torch.cumprod(trans, -1)
weights = alpha * trans
return weights
|
23356725fcc805c9d3805eba9fd2dd22a43a1dc1
| 524,720 |
def post_list_mentions(db, usernick, limit=50):
"""Return a list of posts that mention usernick, ordered by date
db is a database connection (as returned by COMP249Db())
return at most limit posts (default 50)
Returns a list of tuples (id, timestamp, usernick, avatar, content)
"""
list = []
cursor = db.cursor()
sql = """select id, timestamp, usernick, avatar, content from posts,
users where posts.usernick = users.nick order by timestamp desc"""
cursor.execute(sql)
query = cursor.fetchall()
length = len(query)
for index in range(length):
if usernick in query[index][4]:
list.append(query[index])
return list
|
1b50f9199b946ff9013d86ff504aa42f01680e7b
| 48,669 |
import itertools
def all_pairs(args):
"""
Generate all pairs from the list of lists args.
(stolen from cmppy/globalconstraints.py)
"""
return list(itertools.combinations(args, 2))
|
ba19d08e7c0342b0a75126e2cfff19c50cea4c53
| 369,433 |
from typing import List
from typing import Dict
def idx(words: List[str]) -> Dict:
"""Create a mapping from words to indexes
Args:
words: List of words
Returns:
w2i: Dict mapping words from their index
Raises:
"""
w2i = {}
for i, w in enumerate(words):
if w not in w2i:
w2i[w] = i
return w2i
|
173ff21b8c56dd67d38af216ac4481bc455bf397
| 90,801 |
import struct
import binascii
def make_chunk(chunk_type, chunk_data):
"""Create a raw chunk by composing chunk type and data. It
calculates chunk length and CRC for you.
:arg str chunk_type: PNG chunk type.
:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.
:rtype: bytes
"""
out = struct.pack("!I", len(chunk_data))
chunk_data = chunk_type.encode("latin-1") + chunk_data
out += chunk_data + struct.pack("!I", binascii.crc32(chunk_data) & 0xffffffff)
return out
|
19843007bdde2b74182c80a6b03404db131735f8
| 624,834 |
def map_values(function, dictionary):
"""
Transform each value using the given function. Return a new dict with transformed values.
:param function: keys map function
:param dictionary: dictionary to mapping
:return: dict with changed values
"""
return {key: function(value) for key, value in dictionary.items()}
|
7073f63e98f3b5e2a44bf76d74a40d08293f1a1d
| 646,760 |
import requests
def _get_linecount(fpath, keyword, delimiter=',', encoding='ISO-8859-1'):
"""
Return the line number in a file where the first item is
`keyword`. If there is no such line, it will return the total
number of lines in the file.
:param fpath: A path or url for the file (if a url it must
include `http`, and if a file path it must not
contain `http`).
:type fpath: string
:param keyword: The string to look for.
:type keyword: string
:param delimiter: The delimiter between items in the file,
defaults to ','.
:type delimiter: string
:param encoding: The encoding for the file, defaults to
'ISO-8859-1'.
:type encoding: string
:return: The line number in the file where the first item is
`keyword`.
:rtype: int
"""
linecount = 0
if 'http' in fpath:
req = requests.get(fpath)
for line in req.iter_lines():
startswith = line.decode(encoding).split(delimiter)[0]
if startswith == keyword:
break
linecount += 1
else:
with open(fpath, 'r', encoding=encoding) as f:
for line in f:
startswith = line.split(delimiter)[0]
if startswith == keyword:
break
linecount += 1
return linecount
|
6935d5fd121e51ae2a3195e3f06c8afe0920477e
| 492,348 |
def resource_id(source_id: str, checksum: str, output_format: str) -> str:
"""Get the resource ID for an endpoint."""
return f"{source_id}/{checksum}/{output_format}"
|
0e14b52b7dd2d4da6a4027b639ed273ef1c35e20
| 62,180 |
def build_empty_bbox_mask(bboxes):
"""
Generate a mask, 0 means empty bbox, 1 means non-empty bbox.
:param bboxes: list[list] bboxes list
:return: flag matrix.
"""
flag = [1 for _ in range(len(bboxes))]
for i, bbox in enumerate(bboxes):
# empty bbox coord in label files
if bbox == [0,0,0,0]:
flag[i] = 0
return flag
|
d42abdc68391cb27a2306ae8ed8ff3ab09977b04
| 320,109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.