content stringlengths 42 6.51k |
|---|
def find_text_color(hex_str):
"""Return correct text color, black or white,
based on the background color.
Parameters:
hex_str (str): Hex color
Returns:
str: Output hex color for text
"""
(r, g, b) = (hex_str[1:3], hex_str[3:5], hex_str[5:])
color = "#ffffff"
if 1 - (in... |
def is_subsequence(string1, string2, m=None, n=None, case_sensitive=False):
""" Returns true if str1 is a subsequence of str2.
m is length of str1 and n is length of str2
"""
if m is None:
m = len(string1)
if n is None:
n = len(string2)
if not case_sensitive:
string1 = ... |
def cols_to_string_with_dubquotes(cols, backslash=False):
"""
Gets a string representation of a list of strings, using double quotes.
Useful for converting list of columns to a string for use in a query.
Backslashes are possible if the query will be passed as a string argument to (for instance) Shuttle... |
def str2link(s, directory, title=''):
""" Used by the --html options, this takes a string and makes it into
an html <a href...> link without a closing </a>.
"""
if directory == '':
return ''
else:
if title:
return '<a href="%s/%s" title="%s">' % (directory, s, title)
... |
def to_abs_deg_min_sec(value):
"""
return the value to the absolute value in degree, minute, seconds
"""
abs_value = abs(value)
degrees = int(abs_value)
rem = (abs_value - degrees) * 60
minutes = int(rem)
seconds = round((rem - minutes) * 60, 5)
return degrees, minutes, seconds |
def cross(p, n):
"""
Check of two lines cross from previous and new data couples.
@param p couple with the previous two values
@param n couple with the last two values
@return 0 if no cross, 1 if first cross up second, -1 for down.
"""
# return (p[0] > p[1] and n[0] < n[1]) or (p[0] < p[1]... |
def get_router_port(endpoint):
""" get the network device and port of where the endpoint is connected to.
Args:
endpoint (endpoint): endpoint
A routerport is a dict with the following keys:
router (string): name of the netork device
port (string): port on the router.... |
def relabel_negatives(clusters):
"""Place each negative label in its own class
"""
idx = -1
relabeled = []
for cluster in clusters:
relabeled_cluster = []
for class_label in cluster:
if class_label <= 0:
class_label = idx
relabeled_cluster.appe... |
def run_zip_surject_input(job, context, gam_chunk_file_ids):
"""
run_whole_surject takes input in different format than what we have above, so we shuffle the
promised lists around here to avoid a (probably-needed) refactor of the existing interface
"""
return list(zip(*gam_chunk_file_ids)) |
def parse_crc32(crc32):
"""Checks for crc32 validity and makes it an uppercase str."""
# If crc32 comes from the patch file, perform int to str conversion
if isinstance(crc32, int):
crc32 = hex(crc32).lstrip("0x")
# Make crc32 uppercase, empty it if isn't valid hex of len 8
if isinstance(c... |
def guess_n_initial_points(params): #96 (line num in coconut source)
"""Guess a good value for n_initial_points given params.""" #97 (line num in coconut source)
return max(len(params), min(len(params) * 2, 10)) |
def rest_adjust(data, adjustments):
"""
Apply a per-key 'actions' to a dictionary *if* the key is present.
When mapping between the gRPC and the REST representations of resources
(Bucket, Object, etc.) we sometimes need to change the name and/or format
of some fields.
The `adjustments` describ... |
def cleanHTML(text):
"""Remove html tags from a string"""
import re
clean = re.compile('<.*?>')
return re.sub(clean, '', text) |
def clean_list(list):
""" cleans a list of all extraneous characters """
clean_list = []
try:
for element in list:
clean_list.append(element.strip())
except Exception:
return -1
return clean_list |
def getBin(value: int):
"""Converts the given integer into string bit representation."""
brep = "{0:b}".format(value)
return brep |
def rmerge(x: dict, y: dict) -> dict:
"""Merge two dicts recursively"""
new = x.copy()
for i in y:
val = y[i]
if i in new and isinstance(new[i], dict) and isinstance(val, dict):
val = rmerge(new[i], val)
new[i] = val
return new |
def remove(*types):
"""Select a (list of) to be removed objects(s)
>>> remove("registrationid1", "registrationid2")
{'remove': ['registrationid1', 'registrationid2']}
>>> remove("tag1", "tag2")
{'remove': ['tag1', 'tag2']}
>>> remove("alias1", "alias2") ... |
def sum_of_a_range(a = 10,b = 1000):
"""
What the heck is a docstring?!?
"""
total_sum = 0
for i in range(a, b):
total_sum += i
return total_sum |
def sites_in_data(device_data):
""" helper function to list all projects in the dataset
"""
sites = []
for device in device_data:
if device['Site'] not in sites:
sites.append(device['Site'])
return sites |
def ring_origin(ring):
"""
>>> ring_origin(0)
[0, 0]
>>> ring_origin(1)
[1, 0]
>>> ring_origin(2)
[2, -1]
>>> ring_origin(3)
[3, -2]
"""
if ring == 0:
return [0, 0]
else:
return [ring, -(ring - 1)] |
def _mklist(values):
"""Convert tuple to list, and anything else to a list with just that thing.
This is a helper to fix an inconsistency with the group keys in a
pandas.groupby object. When grouping by multiple columns, the keys are
tuples of values. When grouping by a single column, even if specified... |
def without_empty_values(iterable):
"""Return a copy of ``iterable`` with all ``empty`` entries removed.
"""
try:
return {k: v for k, v in iterable.items() if (hasattr(v, "__len__") and len(v) > 0) or not hasattr(v, "__len__")}
except AttributeError:
return type(iterable)((v for v in ite... |
def bin(number, prefix="0b"):
"""
Converts a long value to its binary representation.
:param number:
Long value.
:param prefix:
The prefix to use for the bitstring. Default "0b" to mimic Python
builtin ``bin()``.
:returns:
Bit string.
"""
if number is None:
raise TypeError("'%... |
def roles_to_dict(data):
"""
roles_to_dict recupere un reponse JSON pour y extraire les roles (ID + name)
:param data: reponse JSON en dictionnaire avec les roles
:return: dictionnaire avec les roles (ID + name)
"""
data_roles = data["roles"]
result = {}
for role in data_roles:... |
def render_flags(flags, bit_list):
"""Show bit names.
"""
res = []
known = 0
for bit in bit_list:
known = known | bit[0]
if flags & bit[0]:
res.append(bit[1])
unknown = flags & ~known
n = 0
while unknown:
if unknown & 1:
res.append("UNK_%04... |
def get_icon_name(x):
"""
Returns the icon name from a CDragon path
"""
return x.split('/')[-1] |
def safe_octal(octal_value):
"""
safe_octal(octal_value) -> octal value in string
This correctly handles octal values specified as a string or as a numeric.
"""
try:
return oct(octal_value)
except TypeError:
return str(octal_value) |
def get_rect_from_selection(anno):
"""Return a rectangle from a selection annotation."""
media_frag = anno['target']['selector']['value']
regions = media_frag.split('=')[1].split(',')
return {
'x': int(round(float(regions[0]))),
'y': int(round(float(regions[1]))),
'w': int(round(... |
def noncov_btwn_sta(place1: float, place2: float,
cov1: float, cov2: float) -> float:
"""
Calculate noncoverage between place1 and place2
:param place1:
:param place2:
:param cov1:
:param cov2:
:return: Noncoverage between two placed station
"""
dist = abs(place2 ... |
def is_number(s):
"""Remove all slashes from string `s`; return True if convertable to float and False otherwise."""
try:
float(s.replace('/', ''))
return True
except ValueError:
return False |
def f(x):
"""
Defining Function
"""
return x**3 - 2*x + 2 |
def sign(number: float) -> int:
"""
This helper method returns 0, 1, or -1 based on the sign of the given number
:param number: a number
:return: 0 iff number is 0, -1 iff number is negative, and 1 iff number is positive
"""
if number == 0:
return 0
if number < 0:
return -... |
def find_and_replace_math(content):
"""Replace latex-like math formulas in content
with sphinx-like math formulas
content : a string.
"""
if content.count('$') > 1:
start = content.find('$')
end = content.find('$', start + 1)
doxy_latex = content[start: end + 1]
rst_... |
def is_list_of_lists(l):
"""
Check if l is a list of lists
"""
return all( [isinstance(el, list) for el in l] ) |
def active_css_rstate(rtype, rstate):
"""
returns dict with rstates as keys and css class value
:param rstate: string
:return: dict
"""
return {'active': '', 'expired': '', 'all': '', 'ipv4': '', 'ipv6': '', 'rtbh': '', rtype: 'active',
rstate: 'active'} |
def get_padding(shape1, shape2):
""" Return the padding needed to convert shape2 to shape1 """
assert len(shape1) == len(shape2)
h_diff, w_diff = shape1[1] - shape2[1], shape1[2] - shape2[2]
padding_left = w_diff // 2
padding_right = w_diff - padding_left
padding_top = h_diff // 2
padding_bottom = h_diff ... |
def setbox(x, y, mbox, xmax, ymax):
"""Create a box of length mbox around a position x,y. If the box will
be out of [0,len] then reset the edges of the box to be within the
boundaries
Parameters
----------
x : int
Central x-position of box
y : int
... |
def switch_block_hash(switch_block) -> str:
"""Returns hash of most next switch.
"""
return switch_block["hash"] |
def get_old_name(arg):
"""Get the old rame for a possible renamed argument
"""
idx = arg.find('@')
if idx == -1:
return arg
else:
return arg[:idx] |
def index_to_letter(idx):
"""Convert a numerical index to a char."""
if 0 <= idx < 20:
return chr(97 + idx)
else:
raise ValueError('A wrong idx value supplied.') |
def perm_or_factory(perm, *args, **kwargs):
"""Check if perm is a factory (callable) and if so, apply arguments. If not, just return the perm."""
if callable(perm):
return perm(*args, **kwargs)
return perm |
def deformat_serialized(formatted):
"""Undoes the process in format_serialized."""
lf_toks = []
in_label = False # Whether we are processing the intent/slot label
for tok in formatted.replace("]", " ]").split():
if in_label:
if tok == "=":
in_label = False
... |
def _get_tx_hash_key(key: str, org_data: dict) -> str:
"""
If key is 'txHash' and it is not in original data in dict but 'tx_hash' is in,
it returns 'tx_hash' for a new key.
:param key: key in dict
:param org_data: original data in dict
:return: new key named 'tx_hash' or original key
"""
... |
def get_typed(d, key, constructor=None, default=None):
"""
like dict.get, but if the response/default is not None, pass it to the given constructor.
Parameters
----------
d : dict
key : hashable
constructor : callable
default
Returns
-------
"""
response = d.get(key, d... |
def kebab2snake(string: str) -> str:
"""Convert a ``kebab-cased`` string to a ``snake_cased`` one.
:param string: String to be converted.
:type string: str
:returns: The given string converted to snake case.
:rtype: str
"""
return string.replace("-", "_") |
def calc_adjusted_yield(ys, pa, parf, co2f, tf, fr, system_multiplier):
"""
Adjusted Plant Yield Equation
Notes
-----
Ya = Ys x PA x parf x co2f x Tf x (1 - Fr)
Adjusted Plant Yield = Standard Yield x Plant Area x PAR factor
parf = ratio of actual PAR deli... |
def str_warp(str_):
"""Change input string."""
if isinstance(str_, str) and not (
str_.startswith('\'') and str_.endswith('\'')):
return "'{}'".format(str_)
else:
return str_ |
def expected_jk_variance(K):
"""Compute the expected value of the jackknife variance estimate
over K windows below. This expected value formula is based on the
asymptotic expansion of the trigamma function derived in
[Thompson_1994]
Paramters
---------
K : int
Number of tapers used i... |
def escape_word(text: str) -> str:
"""
Escape a word to be Alpino compatible.
"""
return text.replace("[", "\\[").replace("]", "\\]") |
def get_step_metric_dict(ml):
"""Get mapping from metric to preferred x-axis."""
nl = [m["1"] for m in ml]
md = {m["1"]: nl[m["5"] - 1] for m in ml if m.get("5")}
return md |
def parse_lib_part(self, get_name_only=False): # pylint: disable=unused-argument
"""
Create a Part using a part definition from a SKiDL library.
"""
# Parts in a SKiDL library are already parsed and ready for use,
# so just return the part.
return self |
def _format_sign(is_negative, spec):
"""Determine sign character."""
if is_negative:
return '-'
elif spec['sign'] in ' +':
return spec['sign']
else:
return '' |
def improved_sort(_list):
"""
Improved Bubble Sorting algorithm
:param _list: list of values to sort
:return: sorted values
"""
for i in range(len(_list)):
stop = True
for j in range(len(_list) - 1, i, -1):
if _list[j] < _list[j - 1]:
stop = False
... |
def cmake_cache_entry(name, value, comment=""):
"""Generate a string for a cmake cache variable"""
return 'set(%s "%s" CACHE PATH "%s")\n\n' % (name,value,comment) |
def char2binary (c):
"""Translate a character to the binary encoding of its Unicode code point.
Example: 'a' --> 1100001
Hint: recall the ord function mentioned in lecture Thursday
(see https://docs.python.org/3/library/functions.html)
Params: c (str of length 1) a character
Returns: (str) bi... |
def _split(start, end, count, min_interval_sec=120):
"""
Split section from `start` to `end` into `count` pieces,
and returns the beginning of each piece.
The `count` is adjusted so that the length of each piece
is no smaller than `min_interval`.
Returns:
--------
List of the offset... |
def unique_string(longer_string, shorter_string):
"""Find the unique character in a string"""
compare_string = longer_string[: len(shorter_string)]
for i, letter in enumerate(compare_string):
if sorted(compare_string) == sorted(shorter_string):
return longer_string[-1]
elif sho... |
def removeprefix(string, prefix):
"""Implementation of str.removeprefix() function available for Python versions lower than 3.9."""
if string.startswith(prefix):
return string[len(prefix) :]
else:
return string |
def doi_identifier(identifiers):
"""Extract DOI from sequence of identifiers."""
doi_identifier = identifiers.get("doi")
return doi_identifier['identifier'] if doi_identifier else None |
def split_strip(string, delimiter=','):
"""Splits ``string`` on ``delimiter``, stripping each resulting string
and returning a list of non-empty strings.
Ported from Jonathan Buchanan's
`django-tagging <http://django-tagging.googlecode.com/>`_"""
if not string:
return []
words = [w.str... |
def discard_scores(numlist):
"""Filter numlist: construct a new list from numlist with
the first two, and then the lowest two, scores discarded.
"""
newlist = numlist[2:]
least = [-1,-1]
for i in range(len(newlist)):
if least[0] == -1 or newlist[i] < least[0]:
least[1] = leas... |
def url_encode(src_str):
"""
It returns the URL UTF-8 encoded value of the given string.
A string with null value is considered as an empty string.
"""
if not src_str:
return ""
import urllib.parse
return urllib.parse.quote(src_str, encoding="UTF-8") |
def encode_storables_to_python_code(obj, tabs=0)->str:
"""Outputs python code needed to generate a given Storable object.
Replaces all storable instances (child classes of Storable that
have a ._stored_params attribute) in into their their name and params.
Works recursively through sub-list and sub-dict... |
def remove_invalid_chars(xmlstring):
"""
remove invalid chars from a string
Args:
xmlstring(str): input string to clean
Returns:
cleanstring(str): return string with invalid chars replaced or removed
"""
invalidchars = {'<': '<', '>': '>', '"': '"',
... |
def combine(a, b):
""" Takes 2 strings of the same length and returns a string 's' where
s[i] = a[i] if a[i] != '*' else b[i]
i.e. it removes wildcards from 'a' by replacing them with the characters
in the same position in 'b'
returns string with the above rule"""
assert len(a) == len(b... |
def has_grant_on_col(privileges, grant):
"""Check if there is a statement like SELECT (colA, colB)
in the privilege list.
Return (start index, end index).
"""
# Determine elements of privileges where
# columns are listed
start = None
end = None
for n, priv in enumerate(privileges):
... |
def uniqueIdentifierTypes_e(otype=None):
"""
unique identifier lookup function
Args:
otype: str, int
Returns: if is int then return string; otherwise, if the type is string return int
"""
uniqueIdentifierTypes_t = {
"unknown": 0,
"telemetryObject": 1,
... |
def parse_addr(data):
"""Parse the address from an LDAP response when $ is used to
separate lines."""
if data is None:
return None
addr = data.split('$')
return addr |
def assert_pure(s):
"""
raise an Exception if the given string is not :func:`ispure`.
"""
#~ assert ispure(s), "%r: not pure" % s
if s is None:
return
if isinstance(s, str):
return True
try:
s.decode('ascii')
except UnicodeDecodeError as e:
raise Exception... |
def derivative_sigmoid(y: int) -> float:
"""Calculate the derivative of the sigmoid function
Args:
y (int): the output of the sigmoid function of x
Returns:
float: the output of the derivative sigmoid function
"""
return y * (1 - y) |
def get_username_from_payload_handler( payload ):
"""
Override this function if username is formatted differently in payload
"""
return payload.get( 'username' ) |
def get_percentage(num1, num2):
"""Returns the percentage of two given numbers."""
if num1 and num2:
return int(100 * (float(num1) / float(num2)))
else:
return 0 |
def get_unique_values_and_exclude_nulls_from_list(data):
"""
:param data: a list of values
:return: a list of none empty unique values
"""
return list(
filter(None, set(data)),
) |
def bubble_sort(in_list):
"""Function to run the bubble sort algorithm."""
if not isinstance(in_list, list):
raise TypeError('Please insert a list')
swapped = True
while swapped:
swapped = False
for i in range(len(in_list) - 1):
if in_list[i] > in_list[i + 1]:
... |
def tors_reduced_sym_factor(sym_factor, rotors):
""" Decrease the overall molecular symmetry factor by the
torsional mode symmetry numbers
"""
for rotor in rotors:
for tors_name, tors_dct in rotor.items():
if 'D' in tors_name:
sym_factor /= tors_dct['sym_num']
... |
def extract_message(result): # pragma: no cover
"""Extracts the original message from a parsing result."""
return result.get('text', {}) |
def check_divider(numerators_0, denominators_0, numerators_1,
denominators_1):
"""Returns whether the first fraction divides the second fraction.
Args:
numerators_0 (tuple): Numerators of the first fraction.
denominators_0 (tuple): Denominators of the first fraction.
n... |
def coin_counter_function(change_owed, coin_list):
"""
Function that returns the optimal change in the fewest possible coins/bills.
:param change_owed: (INT) The total change owed.
:param coin_list: (LIST[INT]) The individual values of coins/bills available, in any order.
:return: {coin/bill: amount... |
def subtract_arrays(x, y):
"""
This function subtracts each element of one of the two passed lists
from the other.
Args:
x (list): The list to subtract from
y (list): The list to subtract
Returns:
list: the pairwise differences of ``x`` and ``y``.
Examples:
>>>... |
def about_me(your_name):
"""
Return the most important thing about a person.
Parameters
----------
your_name
A string indicating the name of the person.
"""
return "The wise {} loves Python.".format(your_name) |
def remove_name_ext(file_name):
"""remove file name extension"""
string = file_name[:file_name.rfind('.')]
return string |
def sec0to1(val):
"""
Converts the system security values into values between 0 and 1
"""
retval = 0.0
if val < 0:
retval = 0.0
elif val > 1:
retval = 1.0
else:
retval = round(val, 1)
return retval |
def get_deleted_keys(new_entity_list, old_entity_list):
"""Returns list of keys of entities that were removed."""
new_by_key = frozenset(x.key for x in new_entity_list)
return [old.key for old in old_entity_list if old.key not in new_by_key] |
def find_ballot(ballot_num, unique_ballot_manifest):
"""
Find ballot among all the batches
Input
-----
ballot_num : int
a ballot number that was sampled
unique_ballot_manifest : dict
ballot manifest with unique IDs across batches
Returns
-------
tuple : (original_b... |
def split_s3_obj_url(url):
""" assumes:
- that bucket name does not contain: '.amazonaws.com' or '/'
- that bucket url follows this pattern: '{bucket name}.s3.{region}.amazonaws.com' """
bucket_name = url[
:len(url[:url.find(".amazonaws.com")][::-1]) - url[:url.find(".am... |
def len_similarity_score(len1: float,
len2: float) -> float:
"""
Calculate how similar are two lengths.
:param len1: First length.
:param len2: Second length.
:return: Length relative similarity score.
"""
scale = len1 / len2
if scale <= 1:
return scale
... |
def granule_core_fields(item):
"""Extract only fields that are used to identify a record"""
record = {}
umm = item.get('umm', {})
record['GranuleUR'] = umm.get('GranuleUR')
meta = item.get('meta', {})
record['concept-id'] = meta.get('concept-id')
record['revision-id'] = meta.get('revision-i... |
def args2command(*args):
""" to convert positional arguments to string list """
try:
assert None not in args
assert "" not in args
except:
print("args:", args)
raise(ValueError("None values not allowed in args!"))
return [str(_).strip() for _ in args] |
def tomac(v):
"""Tuple to MAC Address
:param v: MAC address
:type v: tuple
:return: MAC address
:rtype: str
"""
return "%02x:%02x:%02x:%02x:%02x:%02x" % v |
def populate_set(dictionary, key, set_to_populate):
"""Functions to populate a set with key values of the given key"""
value = dictionary[key]
set_to_populate.add(value)
return set_to_populate |
def _stacktrace_beginning(stacktrace, size):
""" Gets the first `size` bytes of the stacktrace """
if len(stacktrace) <= size:
return stacktrace
return stacktrace[:size] |
def get_whizzml_options(defaults=None):
"""Adding arguments for the whizzml subcommand
"""
if defaults is None:
defaults = {}
options = {
# directory for the package
'--package-dir': {
"action": 'store',
"dest": 'package_dir',
"default": de... |
def pad_lists(lists, padding_value=None, max_length=None):
"""Pads a list of lists.
Args:
lists: A list of lists.
Returns:
A tuple with the padded collection of lists and the original length of each
list.
"""
if max_length is None:
max_length = max(len(lst) for lst in lis... |
def dictionary_delta(existing_dict, desired_dict):
""" Compute the delta between two dictionaries
:param existing_dict:
:param desired_dict:
:return:
"""
existing_keys = set(existing_dict.keys())
desired_keys = set(desired_dict.keys())
to_be_deleted = existing_keys - desired_keys
to_... |
def __is_label(string: str) -> bool:
"""
Return if a given string is a label declaration.
:param string:
:return:
"""
return string.endswith(":") and '"' not in string and "'" not in string |
def colorpicker(value, colors):
"""
Given set of colors, picks a color from comma-separated list
based on initial character of string.
Example:
{{ user.username|colorpicker:"#00ff00,#ff0000,#0000ff" }}
"""
choices = colors.split(",")
return choices[ord(value[0] if value else " ") % len... |
def convert_to_hex(val):
"""
Returns a hex representation of val.
:param val: a list containing 2 ints on [0, 15]
:return: str hex representation of val[0:2]
"""
return '{:02x}'.format(val[0] * 16 + val[1]) |
def display_timedelta(minutes):
"""Converts timedelta in minutes to human friendly format.
Parameters
----------
minutes: int
Returns
-------
string
The timedelta in 'x days y hours z minutes' format.
Raises
------
ValueError
If the timedelta is negative.
"... |
def get_string_typename(numpy_type):
"""
return frovedis types from numpy types
"""
numpy_to_string_type = { "int32": "int",
"int64": "long",
"float32": "float",
"float64": "double",
"str"... |
def _func_or(current, checks):
"""Implementation of Or."""
return any(check(current) for check in checks) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.