content stringlengths 42 6.51k |
|---|
def digits_increase(num):
"""boolean test for number whose digits increase from left to right.
Arg:
num: the number to test. expecting a six-digit number.
Returns:
boolean
"""
output = True
digits = [int(i) for i in str(num)]
for i, dig in enumerate(digits[:-1]):
if... |
def slugify_province(prov):
"""
Province name to slug i.e. lowercase, and spaces to dashes.
"""
return prov.replace(' ', '-').lower() |
def discrete_escape(trace, msg):
"""
:param trace: a partial trace
:param msg: the message at a pyro primitive site
:returns: boolean decision value
Utility function that checks if a sample site is discrete and not already in a trace.
Used by EscapePoutine to decide whether to do a nonlocal ex... |
def _dict_deep_merge(a, b, path=None):
"""
Merges dict(b) into dict(a)
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
_dict_deep_merge(a[key], b[key], path + [str(key)])
elif ... |
def get_ratings_tuple(entry):
""" Parse a line in the ratings dataset
Args:
entry (str): a line in the ratings dataset in the form of UserID::MovieID::Rating::Timestamp
Returns:
tuple: (UserID, MovieID, Rating)
"""
items = entry.split('::')
return int(items[0]), int(items[1]), fl... |
def trim_args(kwds):
"""Gets rid of args with value of None, as well as select keys."""
reject_key = ("type", "types", "configure")
reject_val = (None, ())
kwargs = {
k: v for k, v in kwds.items() if k not in reject_key and v not in reject_val
}
for k, v in kwargs.items():
if k i... |
def search_list(in_list, item):
"""Search for property in the input data
Parameters
----------
in_list : list
list of all the available properties
item : str
name of the property to search
Returns
-------
list
list of index of the searched property
"""
r... |
def has_isolated_transposition(source, image):
"""Check whether a, b exist, with a -> b and b -> a"""
f = dict(zip(source, image))
for s, i in zip(source, image):
if f[i] == s:
return True
return False |
def is_leaf(cluster_):
"""a cluster is a leaf if it has length 1"""
return len(cluster_) == 1 |
def wrap(value, wrapper='"'):
"""Jinja2 map filter to wrap list items in a string on both sides.
E.g.: ['a', 'b', 'c'] -> ['"a"', '"b"', '"c"']
"""
return wrapper + value + wrapper |
def _add_slash_suffix(meta_value):
"""Add slash as the suffix is missing"""
if meta_value and not meta_value.endswith("/"):
return "{0}/".format(meta_value)
return meta_value |
def INT_CARTINDEX(am, i, j):
"""Returns offset index for cartesian function.
#define INT_CARTINDEX(am,i,j) (((i) == (am))? 0 : (((((am) - (i) + 1)*((am) - (i)))>>1) + (am) - (i) - (j)))
"""
return 0 if (i == am) else ((((am - i + 1) * (am - i)) >> 1) + am - i - j) |
def plugin_is_valid(plugin):
"""Determine whether or not plug-in `plugin` is valid
Arguments:
plugin (Plugin): Plug-in to assess
"""
if not plugin:
return False
return True |
def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/float(n) |
def dicom_age_in_years(age_string):
"""Helper function to extract DICOM age into float
Parameters
----------
age_string : str
The age string as defined in the DICOM standard,
see http://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_6.2.html
Returns
-------
f... |
def hex_to_int(str_hex: str) -> int:
"""
Convert 0xdead1234 into integer
"""
return int(str_hex[2:], 16) |
def Percentile2(scores, percentile_rank):
"""Computes the value that corresponds to a given percentile rank.
Slightly more efficient.
"""
scores.sort()
index = percentile_rank * (len(scores)-1) // 100
return scores[index] |
def combine_from_pair(bit_765, bit_43210):
"""Store diacritics code (values 0-6) & letter code (values 1-26)
in one byte-sized code.
"""
code = (bit_765 << 5) + bit_43210
return code |
def extract_values(json_array, key):
""" Obtain all values for a key in the JSON (dict) array """
return [item[key] for item in json_array] |
def concat_numbers(n: int, m: int) -> int:
"""Concatenates two non-negative integers in base 10.
Args:
n: The non-negative integer that will be prepended to ``m``.
m: The non-negative integer that will be appended to ``n``.
Returns:
An integer containing all base-10 digits of ``n``... |
def action_from_trinary_to_env(action) -> int:
"""
Maps trinary model output to int action understandable by env
"""
assert action in (0, 1, 2), f'Wrong action: {action}'
return {
0: 0,
1: 2,
2: 5
}[action] |
def createElementXML(name,type,prefix='xsd'):
""" Function used for the creation of xml elements. """
return '<%s:element name="%s" type="%s:%s"/>'%(prefix,name,prefix,type) |
def POS(POSInt):
"""Returns 'F' if position indicator is present. The AllSportCG sends a * in a specific position to indicate which
team has posession, and this changes that character to an 'F'. Using font Mattbats, F is a football."""
POSText = ""
if POSInt == 42:
POSText = "F"
return(POSText) |
def convertBack(x, y, w, h):
#================================================================
# 2.Purpose : Converts center coordinates to rectangle coordinates
#================================================================
"""
:param:
x, y = midpoint of bbox
w, h = width, height of t... |
def to_singular(name):
"""Convert the name to singular if it is plural
This just trims a trailing 's', if found.
"""
return name[:-1] if name.endswith("s") else name |
def some_complex_restriction(N):
"""I have no clue what this does but it returns a bool"""
A = sum([1/x for x in range(int(N)) if x != 0])
return A + N**0.5 > 2*N |
def createListForComboBox(dictionary, maxLength):
"""creating list for adding dictionary to combo box"""
finished = []
for key in dictionary:
if key == '':
finished.append('')
else:
finished.append(key + ' : ' + ' ' * (maxLength - len(key)) + str(dictionary[key]))
... |
def hyphen_range(s):
""" Takes a range in form of "a-b" and generate a list of numbers between a and b inclusive.
Also accepts comma separated ranges like "a-b,c-d,f" will build a list which will include
Numbers from a to b, a to d and f"""
s="".join(s.split())#removes white space
r=set()
for x ... |
def filter_data(d_to_filt, names_to_include):
"""
Filters telemetry data
:param d_to_filt: Unfiltered telemetry data
:param names_to_include: list of names to include
:return: filter event list
"""
data = []
for t in d_to_filt:
if 'character' in t and t['character']['name'] in na... |
def get_method_attr(method, cls, attr_name, default = False):
"""Look up an attribute on a method/ function.
If the attribute isn't found there, looking it up in the
method's class, if any.
"""
Missing = object()
value = getattr(method, attr_name, Missing)
if value is Missing and cls is not... |
def vfunc(t=0, z=0, y=0, x=0):
"""A function that returns a linear combination of coordinates
"""
return 1.13*x + 2.35*y + 3.24*z - 0.65*t |
def Udrift(amp,gAbs,c,d):
"""Calculates the 2nd order Stokes drift for a linear mode
Parameters
----------
amp : float
Description: Wave amplitude
gAbs : float
Magnitude of gravitational acceleration
c : float
Wave celerity
d : float
Water depth
Return... |
def trim_lib_name(platform, lib_name):
"""
Trim the libname if it meets certain platform criteria
:param platform: The platform key to base the trim decision on
:param libname: The libname to conditionally trim
:return:
"""
if platform.startswith('win_x64'):
return lib_name
if no... |
def _to_household_ids(in_file_paths):
""" COUNTRY,YEAR,SERIALNO,PERSONS,puma_id,
HHTYPE,PERNUM,place_id,SYNTHETIC_HID,longitude,
latitude """
hid_column = 8
hids = set()
for in_file_path in in_file_paths:
with open(in_file_path, 'r') as fin:
print('reading', in_file_p... |
def intHexString(n, length, sep=4):
"""Convert an integer to a dotted hex representation.
Args:
n (int): integer to convert
length (int): number of hex bytes
sep (int): dot seperator length
Returns:
The hex string representation.
"""
hstr = ''
hlen = len... |
def get_key_by_value(dict_, value):
"""Return key by value."""
for key, val in dict_.items():
if value == val:
return key
return None |
def get_qname(uri, name):
"""
Returns a fully qualified name from URI and local part. If any argument has boolean value
`False` or if the name is already a fully qualified name, returns the *name* argument.
:param uri: namespace URI
:param name: local or qualified name
:return: string or the na... |
def permutations_without_dups(string):
""" 8.7. Permutations without Dups: Write a method to compute all
permutations of a string of unique characters.
Complexity: O(n^3)
"""
def expand_perms(y, xs):
out = []
for x in xs:
for i in range(len(x) + 1):
copy ... |
def strip_quotes(s):
"""Trim white space and, if necessary, quote characters from s."""
s = s.strip()
# Strip quotation mark characters from quoted strings.
if len(s) >= 3 and s[0] == '"' and s[-1] == '"':
s = s[1:-1]
return s |
def argpad(arg, n, default=None):
"""Pad/crop list so that its length is ``n``.
Parameters
----------
arg : scalar or iterable
Input argument(s)
n : int
Target length
default : optional
Default value to pad with. By fefault, replicate the last value
Returns
----... |
def sum_pair(numbers, sum_to):
"""
Naive approach with double for loop over unsorted numbers array
Complexity: O(n2)
"""
for n1 in numbers:
for n2 in numbers:
if n1 + n2 == sum_to:
return True
return False |
def calc_crc16(data):
"""Calc byte string CRC16"""
s = 0
if len(data) % 2 == 1:
data += chr(0)
for i in range(0, len(data), 2):
if type(data[i]) is str:
s += ord(data[i]) + (ord(data[i + 1]) << 8)
else:
s += data[i] + (data[i + 1] << 8)
s &= 0xfff... |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
# Handle non-integer inputs
try:
int(number)
except ValueError:
return None
# Handle n... |
def analyzeConnectivity(map, key):
"""
Analyze the connectivity of a given map using the key value.
Parameters
map: The map to analyze (dict)
key: The key value (variable)
Returns
list: A list of connected values to the key (list)
"""
list = []
... |
def SCALAR_LINEAR_INTERPOLATOR(t0, v0, t1, v1, tt):
"""
Good intepolator if our values can be added, subtracted, multiplied and divided
"""
return v0 + (tt - t0) * (t1 - t0) / (v1 - v0) |
def Force_Gravity(mass_ship, altitude):
"""Calculates the force of gravity acting on the ship at altitude in meters
Args:
mass_ship (float): The mass of the ship at timestep i.
altitude (float): The altitude of the rocket above Mean Sea level
Returns:
force_gravity (float): Calculate... |
def replace_last(source_string, replace_what, replace_with):
""" Function that replaces the last ocurrence of a string in a word
:param source_string: the source string
:type source_string: str
:param replace_what: the substring to be replaced
:type replace_what: str
:param ... |
def mk_range(name, startnum, endnum, chain=None, color='gray70'):
"""Generate the PyMol code to display a colorized region."""
return """
color %(color)s, %(name)s and resi %(snum)s-%(enum)s %(chain)s
""" % {
'name': name,
'snum': startnum,
'enum': endnum,
'chain': ... |
def dictkeyclean(d):
"""Convert all keys of the dict 'd' to (ascii-)strings.
:Raises: UnicodeEncodeError
"""
new_d = {}
for (k, v) in d.items():
new_d[str(k)] = v
return new_d |
def confopt_int(confstr, default=None):
"""Check and return a valid integer."""
ret = default
try:
ret = int(confstr)
except Exception:
pass
return ret |
def clean_message(message):
""" (str) -> str
Return a message that only includes uppercase alphabetical characters.
>>> clean_message('good morning')
'GOODMORNING'
>>> clean_message('1975 commercial')
'COMMERCIAL'
"""
new_message = ''
for char in message:
if char.isalpha()... |
def alpha_enumerate(message):
"""
Enumerate only alphabetical chars
"""
enumerated = []
num = 0
for c in message:
if c.isalpha():
enumerated.append((num, c))
num += 1
else:
enumerated.append((-1, c))
return enumerated |
def column(matrix, i):
"""Returns i-th column from two-dimensional list matrix
"""
return [row[i] for row in matrix] |
def lon2txt(lon, fmt='%g'):
"""
Format the longitude number with degrees.
:param lon: longitude
:param fmt:
:return:
:Examples:
>>> lon2txt(135)
'135\N{DEGREE SIGN}E'
>>> lon2txt(-30)
'30\N{DEGREE SIGN}W'
>>> lon2txt(250)
'110\N{DEGREE SIGN}W'
"""
lon = (lon ... |
def round_down(value, base):
"""
Round `value` down to the nearest multiple of `base`.
Expects `value` and `base` to be non-negative.
"""
return int(value - (value % base)) |
def line_intersection(m1, b1, m2, b2):
"""find (x, y) of point intersection of two lines"""
if m1 is None and m2 is None:
return all if abs(b1 - b2) < 0.001 else None
if m1 is None:
return b1, m2 * b1 + b2
elif m2 is None:
return b2, m1 * b2 + b1
elif abs(m1 - m2) < 0... |
def index_per_user(user, request):
"""Show this user's albums."""
return dict(
target_user=user,
) |
def compute_iou(bboxA, bboxB):
""" Computes the intersection over union between two bounding boxes.
Arguments:
bboxA, bboxB: Bounding Boxes
Returns:
iou (float): intersection over union between bboxA and bboxB
"""
# find coordinates of intersecting rectangle
xA = max(bboxA[0], ... |
def partition(xs, key):
"""Split xs by key, returning a list of matching elements and
a list of non-matching elements.
xs -- list -- items to partition
key -- f(x) -> bool -- partitioning function
returns -- (list, list) -- matches & non-matches
"""
matches, not_matches = [], []
for x... |
def p_wrap(content):
"""wrap string in a <p> tag"""
return "<p>%s</p>" % content |
def sort_by_val_return_str(d):
"""
Takes a dict, sorts it by the value, and returns the string with key:value
in reverse order by value
"""
string = ""
for u in sorted(d.items(), key=lambda x:x[1], reverse=True):
string += " {}:{}".format(u[0], u[1])
return string |
def _countNumberOfAparitions(array, number):
"""Number of aparitions of a number in an array
Parameters
----------
array : array of numbers
number : number to search for
Returns
-------
aparaitions : int
Number of aparitions of the number in the given array
"""
... |
def delete_trailing_number(line):
"""Deletes trailing number from a line.
WARNING: does not preserve internal whitespace when a number is removed!
(converts each whitespace run to a single space). Returns the original
line if it didn't end in a number.
"""
pieces = line.split()
try:
... |
def remove_common_path_at_beginning(path1, path2):
"""
Removes path that is similar on both given paths at the beginning of both of them
:param path1: str
:param path2: str
:return: str
"""
path2 = path2 or ''
value = path2.find(path1)
sub_part = None
if value > -1 and value =... |
def noamwd_decay(step, warmup_steps, model_size, rate, decay_steps, start_step=0):
"""Learning rate schedule optimized for huge batches"""
return (model_size ** (-0.5) * min(step ** (-0.5), step * warmup_steps**(-1.5)) *
rate ** (max(step - start_step + decay_steps, 0) // decay_steps)) |
def filter_out_empty_dict_entries(dict_to_filter):
"""
Filter out entries in a given dict that correspond to empty values.
At the moment this is empty lists, dicts and None
:param dict_to_filter: dict to filter
:returns: dict without empty entries
"""
EMPTY_VALUES = (None, [], {})
re... |
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (iterable of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
... |
def is_mol_end(a: str, b: str) -> bool:
"""Determine if `a` and `b` are both tokens within a molecule (Used by the `group_with` function).
Returns False whenever either `a` or `b` is a molecule delimeter (`.` or `>>`)"""
no_dot = (a != ".") and (b != ".")
no_arrow = (a != ">>") and (b != ">>")
no_p... |
def _convert_github_url_to_api(url):
"""Convert github html url to api url"""
url = url.split('/') # urls are always forward slash regardless of OS
user, repo, branch, dirpath = url[3], url[4], url[6], url[7:]
dirpath = '/'.join(dirpath)
return branch, 'https://api.github.com/repos/%s/%s/contents/%... |
def match_keyword(token, keywords):
"""
Checks if the given token represents one of the given keywords
"""
if not token:
return False
if not token.is_keyword:
return False
return token.value.upper() in keywords |
def cooking(s):
"""
Returns the HTML encoded version of the given ASCII string.
"""
htmlCodes = (
('&', '&'),
("'", '''),
('"', '"'),
('>', '>'),
('<', '<'),
(' ', ' '),
('\n', '<br>')
)
... |
def validate_list(value):
"""
Validate a list input.
Parameters:
value (any): Input value
Returns:
boolean: True if value is a list
"""
return isinstance(value, list) |
def wnid_str_to_int(str_wnid):
""" string wnid to integer wnid"""
return int(str_wnid[1:].lstrip('0')) |
def json_value_available(o, k):
"""
Check out o[k].
:param o: object
:param k: key
:return: boolean
"""
try:
o[k]
return True
except KeyError:
return False |
def get_expanse_exposure_context(data):
"""
provides custom context information from the Expanse Exposure API
"""
def exposure_to_obj(exposure):
return {
"ExposureType": exposure['exposureType'],
"BusinessUnit": exposure['businessUnit']['name'],
"Ip": exposur... |
def parse_address(address):
"""Create a tuple containing a string giving the address, and an
integer port number.
"""
base, port = address.split(':')
return (base, int(port)) |
def to_json(record, fields) -> dict:
"""Convert a record with its fields to a dictionary."""
dct = {}
for field in fields:
dct[field] = record[field]
return dct |
def _len_arg(typ):
"""Returns the length of the arguments to the given type."""
try:
return len(typ.__args__)
except AttributeError:
# For Any type, which takes no arguments.
return 0 |
def isa(value, target):
"""True if value is a target via ==, issubclass, or isinstance"""
# equality
if value == target:
return True
# instance vs type
if issubclass(type(value), type):
if issubclass(type(target), type): # pragma: no cover
return issubclass(value, targe... |
def aresubclasses(subclasses, superclasses):
"""
Takes two lists; checks if each element of the first list is
a subclass of the corresponding element in the second list.
`subclasses`: sequence of ``type``
A list of potential subclasses.
`superclasses`: sequence of ``type``
A list o... |
def lower_keys(mapping):
"""
Return a new ``mapping`` modified such that all keys are lowercased strings.
Fails with an Exception if a key is not a string-like obect.
Perform this operation recursively on nested mapping and lists.
For example::
>>> lower_keys({'baZ': 'Amd64', 'Foo': {'Bar': {'A... |
def fizzbuzz(n):
"""Return the FizzBuzz string of a number."""
if n % 15 == 0:
return 'FizzBuzz'
elif n % 3 == 0:
return 'Fizz'
elif n % 5 == 0:
return 'Buzz'
return str(n) |
def merge_dict(d1, d2):
"""
:type d1: dict
:type d2: dict
"""
merged_d = d1.copy()
merged_d.update(d2)
return merged_d |
def _scope_name_deduplication(key, scope_names, memo) -> list:
"""
Scope name deduplication.
Args:
key (str): Module name.
scope_names (list): Scope names.
memo (dict): Memo to record module name.
Returns:
list, renamed scope name.
"""
result = []
if key not... |
def polym_2(params,x):
"""params: [0]: cuaratic coeff; [1]: linear coeff. [2]: function value at x=0"""
f = params[0] * (x ** 2) + params[1] * x + params[2]
return f |
def fmt_n(large_number):
"""
Formats a large number with thousands separator, for printing and logging.
Param large_number (int) like 1_000_000_000
Returns (str) like '1,000,000,000'
"""
return f"{large_number:,.0f}" |
def is_fq_local_branch(ref):
"""Return True if a Git reference is a fully qualified local branch.
Return False otherwise.
Usage example:
>>> is_fq_local_branch("refs/heads/master")
True
>>> is_fq_local_branch("refs/remotes/origin/master")
False
>>> is_fq_local_bra... |
def is_equal(x, y, tolerance=0.000001):
"""
Checks if 2 float values are equal withing a given tolerance
:param x: float, first float value to compare
:param y: float, second float value to compare
:param tolerance: float, comparison tolerance
:return: bool
"""
return abs(x - y) < toler... |
def get_plot_dict_p_s(ch_var):
"""Returns a dictionary of key parameters for plotting based on varied component."""
d = {}
# polyelectrolyte density varied
if ch_var == 'p':
d = {'ch_var':'p', 'ch_fix':'s', 'order':[0,1], 'name_var':'Polymer'}
# salt density varied
elif ch_var == 's':
... |
def invert_map(dic):
"""
Inverts map. Raises ValueError if map is not invertible.
"""
inv = {v: k for k, v in dic.items()}
if len(inv) != len(dic):
raise ValueError("map not invertible!")
return inv |
def check_disqualified_strings(input_str, list_of_disqualified_str):
"""
Given an str input_str and a list of str list_of_disqualified_str
the function check_disqualified_strings returns true iff none of the
strings in list_of_disqualified_str is part of the input_str
"""
return_bool = True
... |
def iif(condition, true_value, false_value=None):
"""
"Inline If" : an ``if`` statement as a function.
Examples:
>>> from atelier.utils import iif
>>> print("Hello, %s world!" % iif(1+1==2, "real", "imaginary"))
Hello, real world!
>>> iif(True, "true")
'true'
>>> iif(False, "true")... |
def filesize(value):
"""
Return human-readable filesize string.
Adapted from https://djangosnippets.org/snippets/1866/
"""
if value is None:
return '-'
if value < 512000:
value = value / 1024.0
ext = 'kb'
elif value < 4194304000:
value = value / 1048576.0
... |
def countBits(n):
""" count_bits == PEP8 (forced mixedCase by CodeWars) """
return '{:b}'.format(n).count('1') |
def _ccw(a, b, c):
"""Test if the points a, b, c are in counterclockwise order."""
return (c[1] - a[1]) * (b[0] - a[0]) > (b[1] - a[1]) * (c[0] - a[0]) |
def _is_cglc(fname):
"""Check if a filename can be a CGLC raster."""
if len(fname.split("_")) != 8:
return False
if not fname.lower().endswith(".tif") or "_ProbaV_LC100_" not in fname:
return False
return True |
def merge_dicts(src: dict, dest: dict):
"""
Merge src dict into dest dict.
"""
for key, value in src.items():
if isinstance(value, dict):
# Get node or create one
node = dest.setdefault(key, {})
if node is None:
dest[key] = value
el... |
def meep_vertices(points, z):
""" Converts a list of 2D points into a meep vertices array.
"""
points_str = [
'mp.Vector3({}, {}, {})'.format(x, y, z)
for x, y in points
]
return "[" + ",".join(points_str) + "]" |
def strictly_decreasing(py_list):
"""
check if elements of a list are strictly decreasing.
"""
return all(x > y for x, y in zip(py_list, py_list[1:])) |
def _google_filter(items: list) -> list:
"""
Take list of dictionaries of items and return \
only ``title``, ``link``, ``snippet`` keys from them.
Args:
`items`: the list of dictionaries of links that has to be filtered.
Returns:
`list`: the list of dictionaries of links with \
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.