content stringlengths 42 6.51k |
|---|
def calc_check_digits(number):
"""Calculate the extra digits that should be appended to the number to make it a valid number.
Source: python-stdnum iso7064.mod_97_10.calc_check_digits
"""
number_base10 = ''.join(str(int(x, 36)) for x in number)
checksum = int(number_base10) % 97
return '%02d' % ... |
def is_transactional_goal(domain_goal: dict):
"""Checks if a domain goal is transactional. For MultiWOZ this is equivalent to the presence of a ``'book'``
field in the domain goal.
Parameters
----------
domain_goal
Domain goal containing constraints and information requests. See `compute_ig... |
def select(data: dict, index: int=0):
""" Select datum from batched dict values.
:param data: Dictionary to batched values.
:param index: Batch index.
:return: Dictionary without batch dim.
"""
selected = {}
for key, value in data.items():
selected[key] = value[index]
return s... |
def decode_fourcc(fourcc_code):
"""Decode FOURCC code into string."""
fourcc_code = int(fourcc_code)
return "".join([chr((fourcc_code >> 8 * i) & 0xFF) for i in range(4)]) |
def tryint(s):
"""Try to convert s into an integer. Otherwise return s unchanged.
>>> tryint(1)
1
>>> tryint('1')
1
>>> tryint('one')
'one'
"""
try:
return int(s)
except ValueError:
return s |
def _has_newline(line):
"""
Used by has_bad_header to check for \\r or \\n
"""
if line and ('\r' in line or '\n' in line):
return True
return False |
def sortPairReverse( a, b, lessOrEq ):
"""return a1, b1 such that a1 >= b1"""
return (b, a) if lessOrEq(a,b) else (a,b) |
def ratio2int(p, k):
"""Returns p * k if k < 1 else k
Result is cast to nearest integer in [1, p]
Parameters:
-----------
p : int
k : int or float
>>> ratio2int(10, 1)
1
>>> ratio2int(10, 1.0)
1
>>> ratio2int(10, .99)
10
... |
def compilation_db_emitter(target, source, env):
""" fix up the source/targets """
# Someone called env.CompilationDatabase('my_targetname.json')
if not target and len(source) == 1:
target = source
# Default target name is compilation_db.json
if not target:
target = ['compile_comma... |
def pad_sents(sents, pad_id=0):
"""
pad the list of sents according to max sent len
@param sents (list[list[int]]): list of word ids of sentences
@param pad_id (int): pad idx
@return sents_padded (list[list[int]]): padded sentences
"""
sents_padded = []
max_len = 0
for sent in sents... |
def _increment_name(name):
"""Returns a name similar to the inputted name
If the inputted name ends with a hyphen and then a number,
then the outputted name has that number incremented.
Otherwise, the outputted name has a hyphen and the number '1' appended to it.
"""
index = name.rf... |
def backward_no_normalization(D):
"""
:param D: dictionary of unnormalized wavelet coefficients
:return: inverse of of forward_no_normalization(D)
>>> v1 = [1, 2, 3, 4]
>>> forward1 = forward_no_normalization(v1)
>>> backward1 = backward_no_normalization(forward1)
>>> v1 == backward1
Tru... |
def _get(indexable_container, index, default):
"""like 'get' on a dict, but it works on lists, too"""
try:
return indexable_container[index]
except (IndexError, KeyError):
return default |
def splitlines(s):
"""splits the string into a list of lines, retaining the newline character.
s.split("\n") cannot be used because it removes the newline character."""
assert isinstance(s, str)
l = []
b = 0
for i,c in enumerate(s):
if c == '\n':
l.append(s[b:(i+1)])
... |
def get_label(trait):
"""Format the trait's label."""
part = trait["part"] if trait.get("part") else ""
subpart = trait["subpart"] if trait.get("subpart") else ""
trait = trait["trait"] if trait["trait"] not in ("part", "subpart") else ""
return " ".join([p for p in [part, subpart, trait] if p]) |
def as_bool(val):
"""
Convert a value to a boolean. `val` is `True` if it is a boolean that contains True, is a string
of 'true' or 't' (case-insensitive), or is a non-zero numeric (or string of non-zero numeric). False
in all other cases including if `val` is `None`.
:param val: Value to test.
... |
def fact(x):
"""Return factorial of x."""
if x == 1:
return 1 # Base case
else:
return fact(x-1) * x |
def find_end_index(start_index, lines):
"""
Given a start index and lines of data, finds the first line that
contains only ',,,,' and returns the index for that line.
"""
end_index = None
for line in lines[start_index:]:
if line == ',,,,':
end_index = lines.index(line, start_... |
def nativestr(x):
"""Return the decoded binary string, or a string, depending on type."""
return x.decode("utf-8", "replace") if isinstance(x, bytes) else x |
def dict_to_filter_params(d, prefix=""):
"""
Translate a dictionary of attributes to a nested set of parameters suitable for QuerySet filtering. For example:
{
"name": "Foo",
"rack": {
"facility_id": "R101"
}
}
Becomes:
{
... |
def row_text(rendered_row):
"""Return all text joined together from the rendered row"""
return b"".join(x[-1] for x in rendered_row) |
def get_sortable_html_footer():
"""Gets footer for sortable html page.
Check function `get_sortable_html_header()` for more details.
"""
return '</tbody>\n</table>\n\n</body>\n</html>\n' |
def full_ipv6(ip6):
"""Convert an abbreviated ipv6 address into full address."""
return ip6.replace('::', '0'.join([':'] * (9 - ip6.count(':')))) |
def first_alpha(s):
"""
Returns the length of the shortest substring of the input that
contains an alpha character.
"""
for i, c in enumerate(s):
if c.isalpha():
return i + 1
raise Exception("No alpha characters in string: {}".format(s)) |
def findMatching(device, device_arr):
"""
Check the array of devices to see if there is a matching element.
Args:
device (string): The name of the device attempting to be added.
device_arr (array): An array of the devices attached to a profile.
"""
matches = [x for x in device_arr i... |
def linsearch(array, val):
"""
Linear search.
Linear search of `val` in `array`. Returns `idx` such as `val == array[idx]`,
returns `None` otherwise.
"""
for idx in range(len(array)):
if val == array[idx]:
return idx
return None |
def find_empty_cells(board):
"""Returns the empty cells of the board."""
return [x for x in board if x in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] |
def quick_sort(collection):
"""Pure implementation of quick sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
... |
def recursive_staircase_problem(n):
"""
Parameters
----------
n : int
number of steps
Returns
-------
int
number of ways a child can run a stairs
>>> recursive_staircase_problem(4)
7
>>> recursive_staircase_problem(0)
1
"""
def staircase(m):
... |
def line_intersection(L1, L2):
"""Computes intersection of two lines.
Colinear lines are treated as if they had
no intersection.
Source: https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines
"""
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[... |
def _energy_correction(x, B, param_tm=None, param_fr=None, phi_t_psi_f=False):
"""Enables `||jtfs(x)|| = ||x||`.
**Stride**:
Unaliased subsampling by 2 divides energy by 2.
Make up for it with `coef *= sqrt(2)`.
**Unpadding**:
Suppose input length is 64, and stride is 8. Then, `l... |
def notNone(a):
"""
Returns True if array a contains at least one element that is not None. Returns False otherwise.
"""
return a.count(None) != len(a) |
def eta(t):
"""
Parameters:
====================
t -- time at which learning rate is to be evaluated
Output:
====================
step -- learning rate at time t
"""
return 1.0 / (t + 5) |
def extract_substep_response(error):
"""
Behave hides the message we want in another message, so we need to extract it:
https://github.com/behave/behave/blob/644038147a8fcb4cb9de860156d85483a77b8f72/behave/runner.py#L401
"""
error_messages = error.args[0].split('\n')
try:
error_response ... |
def _inverse_permutation_worker(permutation: list, items: list) -> int:
"""
The index of permutation in the Johnson-Trotter list of
permutations of elements in items.
"""
if len(permutation) == 1:
return 0
else:
n = len(items)
index = permutation.index(items[-1])
... |
def remove_enclosing_dirs(full_path):
""" Remove any directories in a filepath
If you pass a filename to this function, meaning it doesn't
contain the "/" string, it will simply return the input back to you.
Args:
full_path (str): a Unix-based path to a file (with extension)
Returns:
... |
def addressInNetwork(ip, net):
"""
Is an address in a network
"""
return ip & net == net |
def is_kind_of_class(obj, a_class):
"""
Return:
True if obj is an instance of class that it inherited from
"""
return isinstance(obj, a_class) |
def to_base(number, base):
"""Convert a decimal to another other base.
Convert a base 10 number to any base from 2 to 16.
Args:
number: A decimal number.
base: The base of the provided number.
Returns:
A string with the number in a requested base.
"""
# Hold a convers... |
def deep_eq(_v1, _v2):
"""
Tests for deep equality between two python data structures recursing
into sub-structures if necessary. Works with all python types including
iterators and generators. This function was dreampt up to test API responses
but could be used for anything. Be careful. With deeply nested st... |
def scilabel(value: float, precision: int = 2) -> str:
"""Build scientific notation of some value.
This is dedicated to use in labels displaying scientific values.
Args:
value: numeric value to format.
precision: number of decimal digits.
Returns:
the scientific notation of th... |
def delete_multi_async(
keys,
retries=None,
timeout=None,
deadline=None,
use_cache=None,
use_global_cache=None,
global_cache_timeout=None,
use_datastore=None,
use_memcache=None,
memcache_timeout=None,
max_memcache_items=None,
force_writes=None,
_options=None,
):
"... |
def check_1(lst):
"""
checks whether the amount of visible skyscrapers is the equal to pivot
>>> check_1(['4', '1', '2', '3', '5', '4', '*'])
True
"""
if lst[-1] == '*':
del lst[-1]
pivot = int(lst[0])
# del lst[-1]
board = []
for j in lst:
board.append(int(j))
... |
def large_num_formatter(num, pos=None):
"""
Format large numbers using appropriate sufixes for powers of 1000
Parameters:
num: (int): The tick value to be formatted
pos: (int): Position of the ticker
"""
for unit in ['', 'mil', 'Mi.', 'Bi.']:
if abs(num) < 1000.0:
... |
def format_datetime(dt):
"""Format the datetime string"""
if not dt:
return ""
fmt = "%Y-%m-%d %H:%M:%S"
return dt.strftime(fmt) |
def get_symmetric_neg_th_nb(pos_th):
"""Compute the negative return that is symmetric to a positive one."""
return pos_th / (1 + pos_th) |
def get_fixture_value_raw(request, name):
"""Set the given raw fixture value from the pytest request object.
:note: Compatibility with pytest < 3.3.2
"""
try:
return request._fixture_values.get(name)
except AttributeError:
try:
return request._funcargs.get(name)
... |
def get_word_bin(string):
"""
Given a string, returns its binary representation in 0s and 1s
"""
return ''.join(format(ord(x), 'b') for x in string) |
def bogomips_linux(cores):
"""Return sum of bogomips value for cores."""
total = 0
with open('/proc/cpuinfo') as cpuinfo:
for cpu in cpuinfo.read().split('\n\n'):
for line in cpu.splitlines():
if line.startswith('processor'):
if int(line.split(':')[1])... |
def create_checkpoint_name(pars):
""" Defines the filename of the network
:param pars: training hyper-parameters
:return: filename composed of the hyper-parameters
"""
checkpoint_name = 'net'
for key, value in pars.items():
checkpoint_name += '_' + key
if key == 'alphas':
... |
def categorize_nps(x):
"""
Takes a NPS rating and outputs whether it is a "promoter",
"passive", "detractor", or "invalid" rating. "invalid" is
returned when the rating is not between 0-10.
Args:
x: The NPS rating
Returns:
String: the NPS category or "invalid".
"""
# ... |
def hexWithoutQuotes(l):
"""
Return a string listing hex without all the single quotes.
>>> l = range(10)
>>> print(hexWithoutQuotes(l))
[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9]
"""
return str([hex(i) for i in l]).replace("'", "") |
def covariance(datapoints, num_features, mean_feature_vector_for_c):
"""
Calculates the Covariance Matrix that is needed for each cluster of data.
The covariance matrix is calculated as described by the Fisher Score PDF for the project
:param datapoints: datapoints in cluster
:param num_features: n... |
def is_palindrome(s):
"""check if a string is a palindrome"""
return s == s[::-1] |
def joinErrors(errors):
"""
Return the error from the branch that matched the most of the input.
"""
# This next statement doesn't work on python3 as None
# is not sortable with respect to int.
#errors.sort(reverse=True, key=operator.itemgetter(0))
def noneSorter(o):
r = o[0]
... |
def suitedcard_dict(cards):
""" Returns a dictionary of suits and card lists. Useful for dividing a list
of cards into all the separate suits.
"""
suits = {}
for c in cards:
suits.setdefault(c.suit, []).append(c) # Dict grouping
return suits |
def test_jpeg(h, f):
"""JPEG data in JFIF or Exif format"""
if not h.startswith(b'\xff\xd8'):#Test empty files, and incorrect start of file
return None
else:
if f:#if we test a file, test end of jpeg
f.seek(-2,2)
if f.read(2).endswith(b'\xff\xd9'):
ret... |
def valid_boolean(boolean_as_hopefully_int) -> int:
"""Use this to parse an argument as if it were boolean, and get back an int 0 or 1.
In sqlite a 'boolean' is actually an int which takes the value 1 or 0, with 1 representing True.
Raises ValueError if passed an un-parse-able value.
"""
try:
... |
def format_byte_size(value: int, unit: str = 'B', factor: int = 1024, include_unit=True) -> str:
"""
Given an integer *value*, this function formats the number which is assumed to be a size in bytes into a different
byte related unit such as kilobytes, megabytes etc.
:param int value: The actual intege... |
def monthAbbrevFormat(month: int) -> str:
"""Formats a (zero-based) month number as an abbreviated month name, according to the current locale. For example: monthAbbrevFormat(0) -> "Jan"."""
months = [
"Jan",
"Feb",
"Ma",
"Apr",
"May",
"Jun",
"Jul",
... |
def try_parse_int(value):
"""Tries to parse the value as an int"""
try:
return int(value), True
except ValueError:
return value, False |
def _dedupe_entities(alerts, ents) -> list:
"""Deduplicate incident and alert entities."""
alrt_ents = []
for alrt in alerts:
if alrt["Entities"]:
alrt_ents += [ent.__hash__() for ent in alrt["Entities"]]
for ent in ents:
if ent.__hash__() in alrt_ents:
ents.remo... |
def ExpectDict(obj):
"""Return a dictionary or raises an exception."""
if isinstance(obj, dict):
return obj
elif obj is None:
return {}
else:
raise ValueError('Expecting a dictionary.') |
def bitmap2str(b, n, on='o', off='.'):
""" Generate a length-n string representation of bitmap b """
return '' if n==0 else (on if b&1==1 else off) + bitmap2str(b>>1, n-1, on, off) |
def join_all(domain, *parts):
"""
Join all url components.
:rtype: str
:param domain: Domain parts, example: https://www.python.org
:rtype: list
:param parts: Other parts, example: "/doc", "/py27"
:rtype: str
:return: url
Example::
>>> join_all("https://www.apple.com", "... |
def flatten(deep_array):
"""Returns flatten array."""
response = []
for item in deep_array:
if isinstance(item, list):
response.extend(flatten(item))
elif isinstance(item, (str, int)):
response.append(item)
return response |
def KVAL(n, d):
"""Convert fourier order into real coordinate"""
if n<=d/2:
return n
else:
return n-d |
def to_base(amt: float, dec: int) -> int:
"""Returns value in e.g. wei (taking e.g. ETH as input)."""
return int(amt * 1 * 10 ** dec) |
def next_non_zero_index(chain, start=0):
"""Return the next index >= start of a non-zero value. -1 on failure to find"""
non_zeros = filter(lambda x: x, chain[start:])
value = next(non_zeros, None)
return chain.index(value, start) if value else -1 |
def validWorkspace(uri):
"""Function to check whether workspace is a geodatbase"""
if ".gdb" in str(uri) or ".sde" in str(uri):
return True
else:
return False |
def validate_geography(lon: float, lat: float):
"""
Verifies that latitude and longitude values are valid
:param lon: longitude value in degrees
:param lat: latitude value in degrees
:return valid: boolean for whether the lon/lat values are valid
"""
lon_valid = lon >= -180 and lon <= 180
... |
def decode_url_to_string(urlstr):
""" takes a string (which has been part of a url) that has previously been encoded, and converts it back to a normal string
:param urlstr: takes part of a urlstr that represents a string name
:return: the string without the underscores
>>> decode_url_to_string('hello_wo... |
def fragment_banner(fragment_path, side, data):
"""Generate a banner to wrap around file fragments
:param string fragment_path: A path to a module fragment
:param string side: ONE OF: "header", "footer"
:param StringIO data: A StringIO object to write the banner to
"""
side_msg = {
"header": "Begin inc... |
def user_data_from_identity(identity):
"""
Get the user details dict from the rh-identity data or error out.
"""
if 'user' not in identity:
return None
return identity['user'] |
def two_of_three(x, y, z):
"""Return a*a + b*b, where a and b are the two smallest members of the
positive numbers x, y, and z.
>>> two_of_three(1, 2, 3)
5
>>> two_of_three(5, 3, 1)
10
>>> two_of_three(10, 2, 8)
68
>>> two_of_three(5, 5, 5)
50
"""
tmp = max(x, y, z)
... |
def format_decimalized_number(number, decimal=1):
"""Format a number to display to nearest metrics unit next to it.
Do not display digits if all visible digits are null.
Do not display units higher then "Tera" because most of people don't know what
a "Yotta" is.
>>> format_decimalized_number(123_4... |
def nvl(*args):
"""
SQL like coelesce / redshift NVL, returns first non Falsey arg
"""
for arg in args:
try:
if arg:
return arg
except ValueError:
if arg is not None:
return arg
return args[-1] |
def stringtodigit(string: str):
"""
attempts to convert a unicode string to float or integer
:param str string: String to attempt conversion on
:return:
"""
try:
value = float(string) # try converting to float
except ValueError:
try:
value = int(string) # try c... |
def texi_if(ifcond, prefix='\n', suffix='\n'):
"""Format the #if condition"""
if not ifcond:
return ''
return '%s@b{If:} @code{%s}%s' % (prefix, ', '.join(ifcond), suffix) |
def is_pos_int(number: int) -> bool:
"""
Returns True if a number is a positive integer.
"""
return type(number) == int and number >= 0 |
def is_original_process_func(clsdict, bases, base_class=None):
"""Only wrap the original `process` function.
Without these (minimal) checks, the `process` function would be
wrapped at least twice (the original `process` function from the
user's DoFn, and our wrapped/decorated one), essentially causing
... |
def remove_empty_list_items(read):
"""
Removes empty list items, which Confluence will strip out anyway
"""
read = read.replace('<li></li>', '')
return read |
def choose_chain(blockchains):
"""
Expect one or several blockchains composed
of a list of blocks
return the choosen chain
"""
# /!\ you might want to do something else.. :)
choosen_chain = []
maxv = 0
for chain in blockchains:
if maxv < len(blockchains[chain]):
... |
def _check_bases(seq_string):
"""Check characters in a string (PRIVATE).
Remove digits and white space present in string. Allows any valid ambiguous
IUPAC DNA single letters codes (ABCDGHKMNRSTVWY, lower case are converted).
Other characters (e.g. symbols) trigger a TypeError.
Returns the string ... |
def title_case_loop(value):
"""Return the specified string in title case using a loop."""
result = ""
for i, word in enumerate(value):
if(i == 0 or value[i - 1] == " "):
result += word.upper()
else:
result += word
return result |
def pretty_solution(solution):
"""
Purpose: Modify the solution to that it is represented as a mostly legible
string.
Input: Solution as a list of boolean values.
Return: Solution represented as a string
"""
pretty = ""
ith_literal = 1
ten_per_line = 0
for literal in solution... |
def common_prefix_length(seq_a, seq_b):
"""
Return the length of the common prefix between two sequences.
Parameters
----------
seq_a : iter
An iterable holding the first sequence.
seq_b : iter
An iterable holding the second sequence.
Returns
-------
length: int
... |
def at_most_once_vld(string):
"""
True if string contains zero or only one instance of each VLD characters, False otherwise.
PARAMETERS:
string : str
RETURNS: bool
"""
vld = {"V": 0, "L": 0, "D": 0}
for letter in string:
if letter in vld:
# Count occurrences of... |
def parse_ingredient(line):
"""Parse line to tuple with name and dict of properties of ingredient."""
name, rest = line.split(': ')
properties = {}
for part in rest.split(', '):
property_name, value = part.split()
properties[property_name] = int(value)
return name, properties |
def grange(a,b,step=1.2):
"""
Returns a list between a and b of geometrically progressing series
"""
r = []
while(a < b):
r += [a]
a *= step
return r |
def convert_to_aws_ecr_compatible_format(string):
"""Make string compatible with AWS ECR repository naming
Arguments:
string {string} -- Desired ECR repository name
Returns:
string -- Valid ECR repository name
"""
return string.replace(" ", "-").lower() |
def sum(num1, num2):
"""Buggy logic"""
results = {
(3, 5): 8, (-2, -2): -4,
(-1, 5): 4, (3, -5): -2, (0, 5): 5}
return results.get((num1, num2)) |
def spscr(content):
"""
Get LaTeX code for displaying the given content in superscript.
Parameters
----------
content : str
Content to be displayed in superscript.
Returns
-------
str
LaTeX code for superscripted content.
"""
return "^{" + content + "}" if cont... |
def flatten(t):
"""Merge a list of lists into a single list
"""
return [item for sublist in t for item in sublist] |
def non_admin_persona(personas, posted_personas):
"""
This fixture is intended to be an arbitrary choice among persona users that is NOT a group administrator.
"""
for key, persona in personas.items():
groups = persona.get("groups", [])
if "admin" not in groups:
return posted... |
def calc_qv_delta_p_ref(n_delta_p_ref, vol_building):
"""
Calculate airflow at reference pressure according to 6.3.2 in [2]
:param n_delta_p_ref: air changes at reference pressure [1/h]
:param vol_building: building_volume [m3]
:returns: qv_delta_p_ref : air volume flow rate at reference pressure ... |
def search_list_with_dicts(container, key, value):
"""Search for dict in list with dicts
Useful for searching for milestone in the list of them.
:param container: an iterable to search in
:param key: key of dict to check
:param value: value of key to search
:returns: first acceptable dict
... |
def remove_version_connect(msgs):
"""Remove #version-connect messages from a list of messages"""
return [msg for msg in msgs if msg.name != 'version-connect'] |
def flatten(lst):
"""
flattens lists, any combination of lists within lists
will be converted into one long list
"""
return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) |
def STD(src_column):
"""
Builtin standard deviation aggregator for groupby. Synonym for tc.aggregate.STDV
Example: Get the rating standard deviation of each user.
>>> sf.groupby("user",
... {'rating_std':tc.aggregate.STD('rating')})
"""
return ("__builtin__stdv__", [src_column]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.