content stringlengths 42 6.51k |
|---|
def extract_bits(data, shift, length):
"""Extract a portion of a bit string. Similar to substr()."""
bitmask = ((1 << length) - 1) << shift
return ((data & bitmask) >> shift) |
def pack(obj):
"""
Takes an object and packs it into a JSONable form consisting purely of
dictionaries, lists, numbers, strings, booleans, and Nones. If the object has
a `_pack_` method, that will be called without arguments and the result
returned, otherwise if it's one of the above types it'll be returned directly
(or after having its contents packed).
"""
if hasattr(obj, "_pack_"):
return obj._pack_()
elif isinstance(obj, (list, tuple)):
return [ pack(o) for o in obj ]
elif isinstance(obj, dict):
return {
pack(k): pack(v)
for (k, v) in obj.items()
}
elif isinstance(obj, (int, float, str, bool, type(None))):
return obj
else:
raise ValueError(
"Cannot pack value '{}' of type {}.".format(
repr(obj),
type(obj)
)
)
return None |
def shouldDeleteAllMail(serverHostName, inboundServer, username):
"""
Given the hostname of the calendar server, the hostname of the pop/imap
server, and the username we're using to access inbound mail, determine
whether we should delete all messages in the inbox or whether to leave
all unprocessed messages.
@param serverHostName: the calendar server hostname (config.ServerHostName)
@type serverHostName: C{str}
@param inboundServer: the pop/imap server hostname
@type inboundServer: C{str}
@param username: the name of the account we're using to retrieve mail
@type username: C{str}
@return: True if we should delete all messages from the inbox, False otherwise
@rtype: C{boolean}
"""
return (
inboundServer in (serverHostName, "localhost") and
username == "com.apple.calendarserver"
) |
def fib(n): # this line defines the function 'fib' where n is the input value
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i |
def valid_ipv4_host_address(host):
"""Determine if the given host is a valid IPv4 address."""
# If the host exists, and it might be IPv4, check each byte in the
# address.
return all([0 <= int(byte, base=10) <= 255 for byte in host.split('.')]) |
def solution(n: int = 10) -> str:
"""
Returns the last n digits of NUMBER.
>>> solution()
'8739992577'
>>> solution(8)
'39992577'
>>> solution(1)
'7'
>>> solution(-1)
Traceback (most recent call last):
...
ValueError: Invalid input
>>> solution(8.3)
Traceback (most recent call last):
...
ValueError: Invalid input
>>> solution("a")
Traceback (most recent call last):
...
ValueError: Invalid input
"""
if not isinstance(n, int) or n < 0:
raise ValueError("Invalid input")
MODULUS = 10**n
NUMBER = 28433 * (pow(2, 7830457, MODULUS)) + 1
return str(NUMBER % MODULUS) |
def parse_id_uri(uri):
"""Get the components of a given uri (with identifier at the last position).
:param str uri: URI
:returns: prefix (ex: http://rdf.wikipathways.org/...)
:returns: prefix_namespaces: if there are many namespaces, until the penultimate (ex: .../Pathway/WP22_r97775/...)
:returns: namespace: if there are many namespaces, the last (ex: .../Interaction/)
:returns: identifier (ex: .../c562c/)
:rtype: tuple[str,str,str,str]
"""
# Split the uri str by '/'.
splitted_uri = uri.split('/')
# Get the uri components into different variables.
prefix = '/'.join(splitted_uri[0:3])
prefix_namespaces = '/'.join(splitted_uri[3:-2])
namespace = splitted_uri[-2]
identifier = splitted_uri[-1]
return prefix, prefix_namespaces, namespace, identifier |
def adapt_dbm_reset_ast(dbm_reset_ast):
"""Transforms the expression ast of a reset into a clock reset ast.
Args:
dbm_reset_ast: The reset expression ast.
Returns:
The clock reset ast.
"""
clock = dbm_reset_ast["expr"]["left"]
val = dbm_reset_ast["expr"]["right"]
return {"clock": clock, "val": val, "astType": "ClockReset"} |
def ele_L(w, L):
"""
:param
w: Angular frequency [1/s], (s:second)
L: Inductance [ohm * s]
:return:
"""
return 1j * w * L |
def get_id_to_graph_index_map(object_ids, node_index, edge_index):
"""
Get object id to graph index map
:param object_ids: a list object ids
:param node_index: index of each node
:param edge_index: index of edges
:return: a dictionary mapping object id (or pairs) to graph index
"""
id_to_index_map = {}
for i, ni in enumerate(node_index):
id_to_index_map[object_ids[ni]] = i
for i, (s, t) in enumerate(edge_index):
id_to_index_map[(object_ids[s], object_ids[t])] = i
return id_to_index_map |
def get_length(inp):
"""Returns the length"""
return float(len(inp[0])) |
def delete_none_values(source: dict) -> dict:
"""Delete keys with None values from dictionary.
Args:
source (dict): dict object from which none values will be deleted
"""
new_dict = {}
for key, value in source.items():
if isinstance(value, dict):
new_dict[key] = delete_none_values(value)
elif value not in [[], {}, None]:
new_dict[key] = value
return new_dict |
def deep_get(d, keys, default=None):
"""
Source: https://stackoverflow.com/questions/25833613/python-safe-method-to-get-value-of-nested-dictionary
Example:
d = {'meta': {'status': 'OK', 'status_code': 200}}
deep_get(d, ['meta', 'status_code']) # => 200
deep_get(d, ['garbage', 'status_code']) # => None
deep_get(d, ['meta', 'garbage'], default='-') # => '-'
"""
assert type(keys) is list
if d is None:
return default
if not keys:
return d
return deep_get(d.get(keys[0]), keys[1:], default) |
def extend_list_x(list_x, list_y):
"""
:param list_x:
:param list_y:
:type:list:list:
:return: list_x after list_y combined in
"""
list_x[:0] = list_y
return list_x |
def get_markers(transcript_pairs):
"""equivalent to build text however this does not include the start time"""
markers = []
last_speaker = ''
for speaker, transcript_data in transcript_pairs:
if speaker != last_speaker:
markers.append({
'speaker': speaker,
'start_time': transcript_data['start_time']})
last_speaker = speaker
return markers |
def scrub(table_name):
"""Snippet to prevent SQL injection attcks! PEW PEW PEW!"""
return ''.join(chr for chr in table_name if chr.isalnum()) |
def ignore_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Stub for unknown roles."""
# pylint: disable=unused-argument
return ([], []) |
def path_absoluta(_arquivo: str) -> str:
"""
extrai a path absoluta de um arquivo
:param _arquivo: str
:return: str
"""
return _arquivo.rsplit('/', 1)[0] |
def wrap_metadata(metadata):
"""Wrap metadata and its type in an HTML comment.
We use it to hide potentially (un)interesting metadata from the UI.
"""
return u'<!-- @{0}: {1} -->\n'.format(*metadata) |
def _tpu_system_device_name(job):
"""Returns the device name for the TPU_SYSTEM device of `job`."""
if job is None:
return "/device:TPU_SYSTEM:0"
else:
return "/job:%s/device:TPU_SYSTEM:0" % job |
def make_domain_config(resources: dict):
"""
Given a dict that maps resource names to JSON schemas, creates a configuration dict
for the Eve `DOMAIN` setting.
"""
return {
name: {
"jsonschema": schema,
"allow_unknown": True,
"schema": {"id": {"type": "uuid"}},
}
for name, schema in resources.items()
} |
def other_existing_acl(get_existing, interface, direction):
"""Gets entries of this ACL on the interface
Args:
get_existing (list): list from get_acl_interface
interface (str): **FULL** name of interface
direction: (str): egress | ingress
Returns:
List: each entry if another element (in/out)
Dictionary: the entry if it exists, else {}
"""
# now we'll just get the interface in question
# needs to be a list since same acl could be applied in both dirs
acls_interface = []
if get_existing:
for each in get_existing:
if each.get('interface') == interface:
acls_interface.append(each)
else:
acls_interface = []
if acls_interface:
this = {}
for each in acls_interface:
if each.get('direction') == direction:
this = each
else:
acls_interface = []
this = {}
return acls_interface, this |
def build_class_arg_key(obj, prefix: str = "class_") -> str:
"""Build a standard description key for a given object attribute."""
return prefix + str(type(obj)) |
def array_replace(input_array, elem_to_replace, substitution_elem):
"""Replace all occurance of the elem_to_replace with substitution elements
"""
for i, elem in enumerate(input_array):
if elem == elem_to_replace:
# substitute the element
input_array[i] = substitution_elem
return input_array |
def _binaryExponent(base, exponent):
"""Calculate base^exponent using the binary exponentiation algorithm.
Depends on another function that verifies that all parameters are
properly given.
Arguments:
base: Intiger or floating point number.
exponent: Intiger number.
Returns:
base^exponent
Raises
RuntimeError: When trying to perform 0^0
"""
# For an exponent <= 4 the algorithm makes no sense.
# log_2(4) = 2 and 4 = 0b100, which will result in the exact same
# process as the binary exponentiation algorithm.
#
# Avoiding it, we are actually saving a few operations (the bitwise and the
# comparison).
result = 1
if (exponent == 0 and base == 0):
raise RuntimeError("Magic error happened: 0^0.")
elif (exponent == 0 and base != 0):
return 1
elif (exponent < 5):
for _ in range(exponent):
result *= base
else:
while (exponent > 0):
# Current bit = 1
if (exponent & 1):
result *= base
base *= base
exponent = exponent >> 1
return result |
def custom_flatten(xs):
"""flatten a list that looks like [a,[b,[c,[d,[e]]]]]
needed because the list can be hundreds of thousands of elements long,
and the recursion in regular flatten can't handle it."""
result = []
while len(xs) != 1:
result.append(xs[0])
xs = xs[1]
if len(xs) == 1:
result.append(xs[0])
return result |
def hashWord(word):
"""Hashes a word into its similarity equivalent.
MXM becomes 010, ASDF becomes 0123, AFAFA becomes 01010, etc.
"""
seen = {}
out = []
i = 0
for c in word:
if c not in seen:
seen[c] = str(i)
i += 1
out.append(seen[c])
return ''.join(out) |
def strbin2dec(strbin):
"""
Convert a string representing a binary value into a
string representing the same value in decimal format.
"""
strdec = "0"
for i in range(1, strbin.__len__()+1):
strdec = str(int(strdec)+int(strbin[-i])*int(pow(2, i-1)))
return strdec |
def make_comment(content: str) -> str:
"""Return a consistently formatted comment from the given `content` string.
All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single
space between the hash sign and the content.
If `content` didn't start with a hash sign, one is provided.
"""
content = content.rstrip()
if not content:
return "#"
if content[0] == "#":
content = content[1:]
NON_BREAKING_SPACE = " "
if content and content[0] == NON_BREAKING_SPACE and not content.lstrip().startswith("type:"):
content = " " + content[1:] # Replace NBSP by a simple space
if content and content[0] not in " !:#'%":
content = " " + content
return "#" + content |
def get_defines(defines):
"""
Return a string with the list of defines ready to drop in icarus
"""
icarusdefs = ""
if not defines:
return icarusdefs
defs = defines.split(';')
for _def in defs:
if _def:
icarusdefs += "-D " + _def + " "
return icarusdefs |
def float_from_sat(amount: int) -> float:
"""Return the float monetary value equivalent of a satoshi amount."""
return float(amount / 1e8) |
def get_node_string(node):
""" returns string for node or vpc pair of nodes """
try: node = int(node)
except ValueError as e: return "%s" % node
if node > 0xffff:
n1 = (node>>16) & 0xffff
n2 = node & 0xffff
if n1 > n2:
return "(%s,%s)" % (n2,n1)
return "(%s,%s)" % (n1,n2)
elif node == 0:
# when 'expected' node not found, we set to value of zero
# therefore, 0 is reserved value for 'deleted'
return "deleted"
else:
return "%s" % node |
def to_camel_case(text):
"""
text: string in the format "word-other-another" or "word_other_another"
return: string the format "wordOtherAnother"
"""
char_list = ([char for char in str(text)])
for i in range(len(char_list)):
if (char_list[i] == "-" or char_list[i] == "_") and i <= len(char_list):
char_list[i+1] = char_list[i+1].upper()
for char in char_list:
if char == "-" or char == "_":
char_list.remove(char)
return "".join(char_list) |
def create_forder(v):
"""Identify all unique, negative indices and return them reverse sorted
(-1 first).
"""
flat_v = sum(v, [])
x = [i for i in flat_v if i < 0]
# Converting to a set and back removes duplicates
x = list(set(x))
return sorted(x, reverse=True) |
def insertion_sort(array):
"""Implementation of the Insertion Sort algorithm"""
for i in range(len(array)):
for j in range(len(array)):
if array[i] < array[j]:
# swap
temporary = array[i]
array[i] = array[j]
array[j] = temporary
else:
continue
return array |
def order_by_line_nos(objs, line_nos):
"""Orders the set of `objs` by `line_nos`
"""
ordering = sorted(range(len(line_nos)), key=line_nos.__getitem__)
return [objs[i] for i in ordering] |
def HasSeparator(line):
"""To tell if a separator ends in line"""
if line[-1] == '\n':
return True
return False |
def id_query(doc_id):
"""Create a query for a document with the given id.
Parameters
----------
doc_id : |ObjectId|
The document id to match.
Returns
-------
dict
A query for a document with the given `doc_id`.
"""
return {'_id': doc_id} |
def convert_co2_to_miles_driven(co2_saved):
"""Converts CO2 emissions to a mileage driven
equivalent for vehicles in the U.S. using EPA
methodology: https://www.epa.gov/energy/greenhouse-gases-equivalencies-calculator-calculations-and-references#miles
"""
pounds_in_metric_ton = 2204.62
tons_co2_per_gallon = 0.0089
avg_gas_mileage_us_fleet = 22
mileage_equivalent = co2_saved / pounds_in_metric_ton / tons_co2_per_gallon * avg_gas_mileage_us_fleet
return mileage_equivalent |
def ds9_region_file(fname):
"""ds9 region file name from FITS image name"""
return fname.replace(".fits",".fits.reg") |
def is_valid_version_code(ver):
"""Checks that the given version code is valid."""
letters = ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
numbers = list(range(1990, 2050))
if ver is not None and len(ver) == 5 and int(ver[:4]) in numbers and \
ver[4] in letters:
return True
else:
False |
def vadd(p1, p2):
"""Adds vectors p1 and p2 (returns a new vector)."""
return [x+y for x,y in zip(p1, p2)] |
def color(r, g, b):
"""Convert an RGB triplet of 0-255 values to a 24 bit representation."""
if r < 0 or r > 255 or g < 0 or g > 255 or b < 0 or b > 255:
raise ValueError('Color values must be 0 to 255.')
return (r << 16) | (g << 8) | b |
def hamming_weight(number):
"""Returns the number of bits set in number"""
return bin(number).count("1") |
def set_attr_from_dict(obj, attr_name, map, key, ignore_errors=False):
"""
Tries to set attribute *attr_name* of object *obj* with the value of *key* in the dictionary *map*.
The item *key* is removed from the *map*.
If no such *key* is in the dict, nothing is done.
Any TypeErrors or ValueErrors are silently ignored, if *ignore_errors is set.
Returns true is *key* was present in *map* and the attribute was successfully set. Otherwise False is returned.
"""
try:
value = map.pop(key)
except KeyError:
return False
try:
setattr(obj, attr_name, value)
except (TypeError, ValueError):
if ignore_errors:
return False
raise
return True |
def get_reach_times(controller_time, reach_indices):
"""Fetch reach times from experimental DIO/analog/microcontroller data sources
Attributes
------------
controller_time : list
list containing CONVERTED controller times (use match_times first!)
reach_indices : list
list containing reach indices corresponding to entries in controller data
Returns
---------
reach_times : list
list containing start and stop reach times in trodes time
"""
reach_times = {'start': [], 'stop': []}
reach_start = reach_indices['start']
reach_stop = reach_indices['stop']
for i in reach_start:
reach_times['start'].append(controller_time[i])
for i in reach_stop:
reach_times['stop'].append(controller_time[i])
return reach_times |
def dictionary_to_kv(d: dict) -> str:
"""
Given a dictionary, encode it in key value format.
:param d: The dictionary to be encoded.
:return: The encoded key-value version of the dictionary.
"""
assert d
return "&".join(
"=".join((str(k), str(v))) for k, v in d.items()
) |
def get_label(e):
"""Returns the label of entity `e`."""
if hasattr(e, 'prefLabel') and e.prefLabel:
return e.prefLabel.first()
if hasattr(e, 'label') and e.label:
return e.label.first()
elif hasattr(e, '__name__'):
return e.__name__
elif hasattr(e, 'name'):
return str(e.name)
elif isinstance(e, str):
return e
else:
return repr(e) |
def files_dirs_to_delete(valid_targets, files, empty_dirs):
"""Compare local and remote directory trees looking for files to delete. Combine with empty dirs from get_songs().
:param iter valid_targets: List of valid target files from get_songs().
:param iter files: List/dict keys of all files on the FlashAir card.
:param iter empty_dirs: List of empty directories on the FlashAir card to remove.
:return: Set of abandoned files to delete and empty directories to remove. One API call deletes either.
:rtype: set
"""
delete_files_dirs = set(empty_dirs)
for path in files:
if path in valid_targets:
continue
if path.lower().endswith('.mp3'):
delete_files_dirs.add(path)
return delete_files_dirs |
def list_comparator(x, y):
""" Uses the first element in the list for comparison """
return x[0] < y[0] |
def SUB_STR_BYTES(string, index, length):
"""
Returns the substring of a string.
The substring starts with the character at the specified UTF-8 byte index (zero-based) in the string
and continues for the number of bytes specified.
https://docs.mongodb.com/manual/reference/operator/aggregation/substrBytes/
for more details
:param string: The string or expression of string
:param index: Indicates the starting point of the substring.
:param length: Can be any valid expression as long as it resolves to a non-negative integer or number
:return: Aggregation operator
"""
return {'$substrBytes': [string, index, length]} |
def binary(num, size):
"""
num: int
size: int
Takes in a number and returns it's binary equivalent.
Adds trailing zeroes at the beginning to make the
length of binary equivalent equal to size.
"""
binary_out = ''
while num > 0:
binary_out += str(num % 2)
num //= 2
binary_out += (size - len(binary_out)) * '0'
return binary_out[::-1] |
def bitwise_not(int_val, bitsize=None):
"""Perform a bitwise not on an integer value, inverting each bit.
The builtin ~ operator can perform this but works on signed integers.
The optional "bitsize" parameter allows the complement to be forced
to a specific number of bits, or defaults to the minimum needed to
represent "int_val"
7 -> 111
~7 -> 000
11 -> 1011
~11 -> 0100
"""
bitsize = bitsize or int.bit_length(int_val) or 1
# All 1s up to the allocated bitsize
mask = (1 << bitsize) - 1
# XOR to mask down to the correct bit size
return int_val ^ mask |
def convertConfigDict(origDict, sep="."):
"""
For each key in the dictionary of the form <section>.<option>,
a separate dictionary for is formed for every "key" - <section>,
while the <option>s become the keys for the inner dictionary.
Returns a dictionary of dictionary.
"""
result = {}
for keys in origDict:
tempResult = result
parts = keys.split(sep)
for part in parts[:-1]:
tempResult = tempResult.setdefault(part, {})
tempResult[parts[-1]] = origDict[keys]
return result |
def GetUsedPercentage(avail, total):
"""Gets used percentage.
Returns:
Used percentage if total is not zero.
Returns 0.0 if avail == total == 0. This occurs for '/sys/fs/cgroup/cpu' and
'/sys/fs/cgroup/freezer' whose f_blocks=0L and f_bavail=0L.
Raises:
ZeroDivisionError if total == 0 and avail != 0.
"""
if avail == total == 0:
return 0.0
return 100 - 100 * avail / total |
def format_time(spend):
"""format the given time"""
spend = float(spend)
if spend < 0:
raise ValueError('time must > 0')
elif spend < 1000:
result = spend, 'ms'
elif spend < 1000 * 60:
result = spend / 1000, 's'
elif spend < 1000 * 60 * 60:
result = spend / 1000 / 60, 'min'
elif spend < 1000 * 60 * 60 * 24:
result = spend / 1000 / 60 / 60, 'h'
else:
result = spend / 1000 / 60 / 60 / 24, 'd'
result = '{:.3f} {}'.format(*result)
return result |
def duration_str(difference, short=False, exact=False, decimal=False,
maxunit=False):
"""
Return difference as a human-readable string.
"""
if not maxunit:
maxunit = "year"
# <seconds>, <long name>, <short name>, <maximum before rounding>
_levels = [
(60 * 60 * 24 * 365.25, "year", "y", 0),
(60 * 60 * 24 * 7, "week", "w", 52 * 2),
(60 * 60 * 24, "day", "d", 7 * 2),
(60 * 60, "hour", "h", 24 * 2),
(60, "minute", "m", 60 * 2),
(1, "second", "s", 60),
]
levels = []
seenmax = False
for l in _levels:
if l[1] == maxunit:
seenmax = True
if seenmax:
levels.append(l)
ret = ""
remaining = difference
for seconds, long_name, short_name, maximum in levels:
if long_name == maxunit:
maximum = 0
use_decimal = (decimal and seconds == 1)
if use_decimal:
of_this = remaining / seconds
remaining = 0
else:
of_this = remaining // seconds
remaining = remaining % seconds
if not exact and maximum and difference / seconds > maximum:
break
if of_this > 0:
if use_decimal:
rounded = round(of_this, 3)
else:
rounded = round(of_this)
formatted_long_name = (
long_name if rounded == 1 else (long_name + 's'))
if use_decimal:
ret += '%.3f%s ' % (
rounded, short_name if short else
(" " + formatted_long_name))
else:
ret += '%d%s ' % (
rounded, short_name if short else
(" " + formatted_long_name))
return (ret or ('0' + (levels[-1][2] if short else levels[-1][1]))).strip() |
def slash_join(*args: str) -> str:
"""
Joins ``args`` with a single "/"
>>> slash_join('http://example.com', 'a/', '/foo/')
'http://example.com/a/foo/'
"""
if not args:
return ''
append_slash = args[-1].endswith('/')
url = '/'.join([arg.strip('/') for arg in args])
return url + '/' if append_slash else url |
def get_tag_name(tags):
""" Return a list of the tag names """
output = []
for tag in tags:
output.append(tag["tagname"])
return output |
def libname_from_dir(dirname: str) -> str:
"""Reconstruct the library name without it's version"""
parts = []
for part in dirname.split("-"):
if part[0].isdigit():
break
parts.append(part)
return "-".join(parts) |
def complementary_seq(dna_seq):
""" Yields the complementary DNA sequence
Only convert the character in comp_dict.
Otherwise remain the same.
"""
comp_dict = {"A": "T", "T": "A", "C": "G", "G": "C"}
return "".join([comp_dict[nuc] if nuc in comp_dict else nuc for nuc in dna_seq]) |
def binarize_ic50(ic50, ic50_threshold):
"""
Binarize ic50 based on a threshold
"""
if ic50 <= ic50_threshold:
return 1
return 0 |
def build_creative_name(bidder_code, order_name, creative_num, size=None, prefix=None):
"""
Returns a name for a creative.
Args:
bidder_code (str): the bidder code for the header bidding partner
order_name (int): the name of the order in DFP
creative_num (int): the num_creatives distinguising this creative from any
duplicates
Returns:
a string
"""
if prefix != None:
if size==None:
return '{prefix}_1x1'.format(prefix=prefix)
return '{prefix}_{width}x{height}'.format(
prefix=prefix,width=size["width"], height=size["height"] )
if size == None:
return '{bidder_code}: HB {order_name}, #{num}'.format(
bidder_code=bidder_code, order_name=order_name, num=creative_num)
else:
return '{bidder_code}: HB {order_name}, {width}x{height} #{num}'.format(
bidder_code=bidder_code, order_name=order_name, width=size["width"],
height=size["height"],num=creative_num) |
def _convert_None_to_str(value):
"""
returns input value or 'None' string value if input is None
The DictParser representation of a pygeometa MCF can't handle an
actual value of: None. All dict keys must be strings.
>>> _convert_None_to_str('foo')
'foo'
>>> _convert_None_to_str('None')
'None'
>>> _convert_None_to_str(None)
'None'
"""
if value is None:
return 'None'
return value |
def selsort (a):
"""selection sorter"""
for i in range(len(a)-1):
for j in range(i+1, len(a)):
if a[i] > a[j]:
a[i], a[j] = a[j], a[i]
return a |
def my_pow(x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1 # 0 ^ 0 = 1
if x == 0:
return 0
if n < 0:
x = 1 / x
n = -n
# bottom up
res = 1
while n > 0:
# pow(x, n) = pow(x * x, n // 2) * x if n is odd
if n % 2 == 1:
res = res * x
x = x * x
n = n // 2
return res |
def response(id, username, message, token, status_code):
"""
method to make http response for authorization token
"""
return {
"id": id,
"username": username,
"message": message,
"auth_token": token
}, status_code |
def _find_minmax_indices(invec):
"""Finds the indices corresponding to the minimum and maximum values
in an integer vector.
:args invec: The input integer array.
"""
vec = [abs(i) for i in invec]
this_min = vec.index(min([i for i in vec if i > 0]))
rvec = [i for i in reversed(vec)]
this_max = 2 - rvec.index(max(rvec))
return (this_min,this_max) |
def cache_control(request, event, version=None):
"""We don't want cache headers on unversioned and WIP schedule sites.
This differs from where we actually cache: We cache unversioned
sites, but we don't want clients to know about it, to make sure
they'll get the most recent content upon cache invalidation.
"""
if version:
if version == "wip":
return False
return True
return False |
def _add(*dicts):
"""Union the input dictionaries
NOTE(yi.sun): This is to avoid pulling in @bazel_skylib//lib:dicts.bzl for
one function.
"""
output = {}
for d in dicts:
output.update(d)
return output |
def get_intersect_list(lst1, lst2):
"""
Find the intersection of two lists
:param lst1: List One
:param lst2: List Two
:return: A list of intersect elements in the two lists
"""
lst3 = [value for value in lst1 if value in lst2]
return lst3 |
def average_best_three(grade1: int, grade2: int, grade3: int, grade4: int) -> int:
"""
from input of four numbers average biggest three
average_best_three(1, 10, 20, 30)
20
"""
min_grade = min(grade1, grade2, grade3, grade4)
sum = grade1 + grade2 + grade3 + grade4 - min_grade
average = sum / 3
return int(average) |
def tiddlytag(tg):
"""Format the tags for tiddlywiki5;
when the tag includes white space, it is surrounded by '[[' ']]'.
:param str tg: A tag.
:return: Decorated tag.
"""
if ' ' in tg:
return '[[' + tg + ']]'
else:
return tg |
def dict_shape(obj):
"""retrieves the shape of dict - (len(dict),)"""
return (len(obj),) |
def removeVowels(word):
"""
Recursive Function to remove alll vowels in a words/sentence.
Parameters:
word (string); the word in which the vowels are to be removed.
Returns:
A string with no vowels after the all recursions are complete.
Raises:
TypeError: If user enters an invalid number such as floats.
Exception: If any unexpected error occurs. Eg, RuntimeError when there are
too many recursive calls.
"""
try:
if not(isinstance(word,str)): #Checking if input is a valid string.
raise TypeError
if len(word) == 0: #Base Case
return word
elif word[0] in "AEIOUaeiou":
return removeVowels(word[1:]) #Skip that letter and proceed with the rest of letters in word
else: # keep the first letter and proceed until length of word becomes 0.
return word[0] + removeVowels(word[1:])
except TypeError: #If the provided input is not a string.
print("Error: Please provide a valid word/sentence of type string and try again.")
except: #If any other unexpected error occurs
print("Error in removing vowels. Please try again.") |
def _is_exported(ident_name):
"""
Returns `True` if `ident_name` matches the export criteria for an
identifier name.
This should not be used by clients. Instead, use
`pdoc.Module.is_public`.
"""
return not ident_name.startswith('_') |
def colorStrToTup(colStr):
"""Takes a 6 character color tuple in hex,
and converts it to a 255, 255, 255 color tuple.
Case insensitive
"""
colStr = colStr.lower()
return tuple(int(s, 16) for s in (colStr[:2], colStr[2:4], colStr[4:])) |
def get_power_level(serial_number, coord_x, coord_y):
"""Gets the power level for a given coordinate."""
rack_id = coord_x + 10
power_level = rack_id * coord_y
power_level += serial_number
power_level *= rack_id
power_level = (power_level // 100) % 10
power_level -= 5
return power_level |
def get_kinyanjui_groh_type(ita):
"""
This function will take a ita value and return the Fitzpatrick skin tone scale
https://openaccess.thecvf.com/content/CVPR2021W/ISIC/papers/Groh_Evaluating_Deep_Neural_Networks_Trained_on_Clinical_Images_in_Dermatology_CVPRW_2021_paper.pdf
:param ita:
:return:
"""
if ita <= 10:
return "6"
elif 10 < ita <= 19:
return "5"
elif 19 < ita <= 28:
return "4"
elif 28 < ita <= 41:
return "3"
elif 41 < ita <= 55:
return "2"
elif 55 < ita:
return "1"
else:
print(f"None cat: {ita}") |
def _activity_set(act_cs):
"""Return a set of ints from a comma-separated list of int strings.
Attributes:
act_cs (str) : comma-separated list of int strings
Returns:
set (int) : int's in the original string
"""
ai_strs = [ai for ai in act_cs.split(",")]
if ai_strs[-1] == "":
ai_strs = ai_strs[:-1]
if ai_strs[0] == ".":
aset = set()
else:
aset = set([int(ai) for ai in ai_strs])
return aset |
def fill_with_tabs(text, tab_col):
"""Adds tabs to a string until a certain column is reached.
:Parameters:
- `text`: the string that should be expanded to a certain column
- `tab_col`: the tabulator column to which should be filled up. It is *not*
a character column, so a value of, say, "4" means character column 32.
:type text: string
:type tab_col: int
:Return:
- The expanded string, i.e., "text" plus one or more tabs.
:rtype: string
"""
number_of_tabs = tab_col - len(text.expandtabs()) / 8
return text + max(number_of_tabs, 1) * "\t" |
def split_dep(dep):
"""
Split NOT character '!' from dependency. Used by gen_dependencies()
:param dep: Dependency list
:return: string tuple. Ex: ('!', MACRO) for !MACRO and ('', MACRO) for
MACRO.
"""
return ('!', dep[1:]) if dep[0] == '!' else ('', dep) |
def do_operation(operators, operands):
""" Perform an operation (+ or *) on operands """
second = operands.pop()
first = operands.pop()
operation = operators.pop()
result = str(eval(first + operation + second))
return result |
def split(s, delimiter=','):
"""Split a string on given delimiter or newlines and return the results stripped of
whitespace"""
return [
item.strip() for item in s.replace(delimiter, '\n').splitlines() if item.strip()
] |
def sign(n):
"""
get the sign of a number
"""
return (n > 0) - (n < 0) |
def CollectionToApi(collection):
"""Converts a collection to an api: 'compute.disks' -> 'compute'."""
return collection.split('.', 1)[0] |
def group_cc_emails(audit_ccs, assessment_ccs):
"""Returns grouped cc emails between audit and assessment.
Args:
audit_ccs: List of audit ccs
assessment_ccs: List of assessment ccs
Returns:
Grouped list of ccs
"""
audit_ccs = frozenset(audit_ccs)
assessment_ccs = frozenset(assessment_ccs)
grouped_ccs = list(audit_ccs.union(assessment_ccs))
return grouped_ccs |
def to_f(c):
"""Convert Celsius to Fahrenheit"""
return round(c * 9 / 5.0 + 32, 1) |
def get_all_attacking_arg_uids_from_history(history):
"""
Returns all arguments of the history, which attacked the user
:param history: SessionHistory
:return: [Arguments.uid]
:rtype: list
"""
try:
splitted_history = history.get_session_history_as_list()
uids = []
for part in splitted_history:
if 'reaction' in part:
parts = part.split('/')
pos = parts.index('reaction')
uids.append(part.split('/')[pos + 3])
return uids
except AttributeError:
return [] |
def querystring_order(current_order, fieldname):
"""Return order fields according to the current GET-parameters but change the order-parameter of the given field"""
fieldname_rev = "-" + fieldname
ordering = current_order.split(",")
if fieldname in ordering:
ordering.remove(fieldname)
ordering.insert(0, fieldname_rev)
elif fieldname_rev in ordering:
ordering.remove(fieldname_rev)
else:
ordering.insert(0, fieldname)
return ",".join(filter(None, ordering)) |
def bow_wave(x, x0, xm, y0, d_y0):
"""
The bow wave function uses the "exit velocity" of the previous function and creates a rebounding curve, a so called
bow wave.
# Parameters
:param x:
:param x0:
:param xm:
:param y0:
:param d_y0:
:return:
"""
return y0 + d_y0 * (1. - (x - x0) / (xm - x0)) * (x - x0) |
def avg(lst):
"""
Calculate the average of an array of numbers.
"""
assert len(lst) > 0,"List must contain something"
return sum(lst)/len(lst) |
def is_any_strings_in_string(haystack, needles):
"""
:param haystack: string to search
:param needles: list of strings to check for in the haystack
:return: Returns True if there is any needle in the haystack
"""
return any([cur_needle in haystack for cur_needle in needles]) |
def _contains (container, contained):
"""
This is a private method used only by the Maximal Rectangle algorithms that follow.
Given two spaces, it checks if one of them contains the other. In this way, the
contained space can be removed.
:param container: The space that is supposed to contain the other.
:param contained: The space that is contained
:return: True if the second space is contained, False otherwise.
"""
x1, y1, sizex1, sizey1 = container
x2, y2, sizex2, sizey2 = contained
if x1 <= x2 and y1 <= y2 and x1 + sizex1 >= x2 + sizex2 and y1 + sizey1 >= y2 + sizey2:
return True
return False |
def let_count(word: str) -> dict:
"""
Returns the count of letters in a string as a dictionary
"""
return {x: word.count(x) for x in set([x for x in word])} |
def vect3_reverse(v):
"""
Reverses a 3d vector.
v (3-tuple): 3d vector
return (3-tuple): 3d vector
"""
return (v[0]*-1, v[1]*-1, v[2]*-1) |
def bbox_ocv2std(bbox):
"""
convert from [xs ys w h] to [xs ys xe ye]
The h/w version is used for opencv non-max suppression (nms) algorithm
"""
return [bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]] |
def get_image_type(data):
"""Return a tuple of (content type, extension) for the image data."""
if data[:2] == "\xff\xd8":
return ("image/jpeg", ".jpg")
return ("image/unknown", ".bin") |
def residue_amino(residue) :
"""Expects an MMTK residue, returns the three letter amino acid code in upper case"""
if residue :
return residue.name[0:3].upper()
else :
return None |
def _reduce_datetimes(row):
"""Receives a row, converts datetimes to strings."""
row = list(row)
for i in range(len(row)):
if hasattr(row[i], "isoformat"):
row[i] = row[i].isoformat()
return tuple(row) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.