content stringlengths 42 6.51k |
|---|
def multiply(arrList1, arrList2):
"""
Return the element-wise product of two mxn arrayLists.
>>> multiply([[1, 2, 3]], [[4, 5, 6]])
[[4, 10, 18]]
>>> multiply([[1, 2, 3], [4, 5, 6]], [[6, 5, 4], [3, 2, 1]])
[[6, 10, 12], [12, 10, 6]]
>>> multiply([[]], [[]])
[[]]
"""
assert len(... |
def utf8(x: str):
"""
Returns the UTF8 encoding of the given string.
"""
return x.encode('UTF8') |
def is_git_path(path):
"""Whether the path is to a git sub-directory
>>> is_git_path('/path/to/.git/file')
True
"""
return '/.git' in path |
def getErrorPage(errorcode, msg = ""):
"""\
Get the HTML associated with an (integer) error code.
"""
if errorcode == 400:
return {
"statuscode" : "400",
"data" : u"<html>\n<title>400 Bad Request</title>\n<body style='background-color: black; color: white;'>\n<h2>4... |
def dereference_yaml(schema, struct):
"""Recursively search a dictionary-like object for $ref keys.
Each $ref key is replaced with the contents of the referenced field in the overall
dictionary-like object.
"""
if isinstance(struct, dict):
if "$ref" in struct:
ref_field = struct... |
def sort_keys(keys):
"""
Specially designed for alignment datas
"""
ref = []
bi_align = []
hard = []
weight = []
for k in keys:
if 'ref' in k:
ref.append(k)
elif 'bi_align' in k:
bi_align.append(k)
elif '.hard' in k:
hard.append... |
def get_features_from_line(line):
"""
Given a text line it returns
a) only the last element of the tuple if the line is a tuple.
That element we assume to be a list of features.
b) the line's elements if the line is not a tuple
:param line:
:return:
"""
from ast import literal_... |
def _swap_2opt(route, i, k):
""" Swapping the route """
new_route = route[0:i]
new_route.extend(reversed(route[i:k + 1]))
new_route.extend(route[k + 1:])
return new_route |
def luminance(r, g, b):
""" Returns an indication (0.0-1.0) of how bright the color appears.
"""
return (r*0.2125 + g*0.7154 + b+0.0721) * 0.5 |
def runner_protocol_decode(buf):
"""
decode for runner protocol
:param buf:
:return:
"""
if not buf:
return None, "runner protocol undefined."
if len(buf) != 4:
return None, "runner protocol invalid."
buf = bytearray(buf)
# request buf type
buf_type = buf[0]
... |
def _has_value(value, conf):
"""The value of an argument not passed in the command is *None*, except:
* if **action** is ``store_true`` or ``store_false``: in this case, the
value is respectively ``False`` and ``True``.
This function take theses cases in consideration and check if an argument
... |
def word_processor(current):
"""
:param current: lst, store the new order of the characters provide by user
:return string: str, string version of current
"""
string = ''
for i in range(len(current)):
ch = current[i]
string += ch
return string |
def hidden(file):
"""Exclude hidden files"""
return not file.startswith('.'); |
def quote_strings(s):
""" PP=Flythru-4 -> PP='Flythru-4' """
from re import sub
# seq=NIH:i5c1 -> seq="NIH:i5c1"
s = sub(r"(NIH:[A-Za-z0-9_-]*)",r"'\1'",s)
# PP=Flythru-4 -> PP='Flythru-4', but not 'pairs(-10us,...'
s = sub(r"=([A-Za-z][A-Za-z0-9_-]*)([^A-Za-z0-9_\(])",r"='\1'\2",s)
# {enabl... |
def traverse_dict(parent, child_parent_dict):
"""
traverse trough child_parent_dict to find final parent
Args:
parent:
child_parent_dict:
Returns:
"""
while parent in child_parent_dict.keys():
if parent == child_parent_dict.get(parent):
break
else:
... |
def dic_to_string(dic={}):
"""
transform dic to a command line string.
input
dic - commands as a dict
output
string contains all commands
example:
command_dic = {
"-a": "b",
"--c": "d"
}
dic_to_string(command_dic)
-> "-a b --c d " (notice the space at the ... |
def robustdiv(a, b):
"""Like / but handles 0."""
if b:
return a / b
return 0 |
def _parse_message(exc):
"""Return a message for a notification from the given exception."""
return '%s: %s' % (exc.__class__.__name__, str(exc)) |
def merge_recursively(left: list, right: list) -> list:
"""Equivalent to merge, but using recursion and creating new sub-lists at
each recursion call.
You should use merge instead of this function, because the space complexity
of this algorithm is higher, since it uses the slice operation, which
cr... |
def merge_settings_dicts(a, b, path=None, overwrite_conflicts=True):
"""merges b into a, modify a in place
Found at http://stackoverflow.com/a/7205107/1472229
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dic... |
def single(x):
""" single """
ret = 3 * x * x * x
return ret |
def quote_pad(string):
"""
Returns a string padded with quotes.
str -> str
"""
quote = "'"
return quote + string + quote |
def xy(a):
"""Returns arrays of x,y coords for plotting as bars."""
x = []
y = []
#x = [-.5]
#y = [0.]
for idx, val in enumerate(a):
x.append(idx - .5)
y.append(val)
x.append(idx + .5)
y.append(val)
#x.append(len(a) - .5)
#y.append(0)
return x,y |
def strip_comments(s):
"""Strips the comments from a multi-line string.
>>> strip_comments('hello ;comment\\nworld')
'hello \\nworld'
"""
COMMENT_CHAR = ';'
lines = []
for line in s.split('\n'):
if COMMENT_CHAR in line:
lines.append(line[:line.index(COMMENT_CHAR)])
... |
def simple_power_law(v, a, c, v0):
"""Simple power law:
.. math::
S_v = c \\left( \\frac{v}{v_0} \\right)^a
Parameters
----------
v : `list`
Frequency in Hz.
a : `float`
Spectral Index.
c : `float`
Constant.
v0 : `float`
Reference frequency.
... |
def is_match(text, pattern):
"""Basic Regex Parser that only includes '.' and '*'. Case sensitive."""
def match(t_char, p_char):
"""Defines the comparision between characters in the text and pattern."""
if t_char == p_char or p_char == ".":
return True
return False
# Sc... |
def concat_options(message, line_length, options):
"""Concatenate options."""
indent = len(message) + 2
line_length -= indent
option_msg = u''
option_line = u''
for option in options:
if option_line:
option_line += ', '
# +1 for ','
if len(option_line) + len(o... |
def url(query):
"""Helper to get an url without GET parameters."""
if query:
return query.split('?')[0] |
def state_heuristic(puzzle, solved):
"""
Given a puzzle, return how many moves is in solved state
"""
sum = 0
for i, row in enumerate(puzzle):
for j, num in enumerate(row):
if puzzle[i][j] != solved[num]:
solved_i, solved_j = solved[num]
sum +... |
def parse_cpe(full_cpe):
"""
This function extracts vendor, product and version from CPE in the full form
cpe:2.3:[aoh]:*{10} = string 'cpe:2.3' is followed by a/o/h and ten groups.
:param full_cpe: CPE match string in its full form
:return: vendor, product, and version
"""
if '\\:' in full... |
def is_mnp_job(job):
"""
Check if the given job is an MNP job.
:param job: the job dictionary returned by AWS Batch api
:return: true if the job is mnp, false otherwise
"""
return "nodeProperties" in job and "numNodes" in job["nodeProperties"] |
def specific_gains(string):
"""Convert string with gains of individual amplification elements to dict"""
if not string:
return {}
gains = {}
for gain in string.split(','):
amp_name, value = gain.split('=')
gains[amp_name.strip()] = float(value.strip())
return gains |
def get_required_mqtt_field(p_message, p_field):
""" Get the given field from a JSON message.
"""
try:
l_ret = p_message[p_field]
except (KeyError, TypeError):
l_ret = 'The "{}" field was missing in the MQTT Message.'.format(p_field)
return l_ret |
def deserialize_sanitizer_options(options):
"""Read options from a variable like ASAN_OPTIONS into a dict."""
pairs = options.split(':')
return_dict = {}
for pair in pairs:
k, v = pair.split('=')
return_dict[k] = v
return return_dict |
def _merge_or_diff(old, new, is_merge, require_old_key, path='',
require_old_key_exceptions=None):
"""Merges two dictionaries, mutating the dictionary "old"."""
nothing = ()
require_old_key_exceptions = require_old_key_exceptions or set()
if old is None:
old = {}
requ... |
def rq_to_r(rq):
"""
Convert to reduced coordinate
r - 1
rq = -------
... |
def calculate_combos(adapters):
""" Calculate number of combos to last adapter """
adapters.append(0)
adapters.sort()
combinations = dict.fromkeys(adapters, 0)
combinations[0] = 1
for adapter in adapters:
for diff in range(1, 4):
if adapter + diff in adapters:
... |
def _substitute_vertex_indices(simplex, substitution_map):
"""
Substitute all indices in a simplex according to the given substitution map.
:param simplex: Simplex defined by a list of vertex indices.
:type simplex: List[int]
:param substitution_map: List of (old value, new value) tuples.
:retu... |
def format_arg_value(arg_val):
"""Return a string representing a (name, value) pair.
>>> format_arg_value(("x", (1, 2, 3)))
"x=(1, 2, 3)"
"""
arg, val = arg_val
return "%s=%r" % (arg, val) |
def is_string_p(elm):
"""
Tries to check if the element is a NavigableString
It checks by verifying that the element has a None name
* **elm**: the element
* **return**: True if the element looks like a NavigableString
"""
return elm is not None and elm.name is None |
def check_suffix_exists(obj_name, suffix):
"""
Checks whether given suffix in given Maya node or not
:param obj_name: str, name of the object to check suffix of
:param suffix: str, suffix to check
:return: bool, Whether given suffix already exists in given node or not
"""
base_name_split = ... |
def _deprecated_udev_rule(vid, pid=None):
""" Helper function that return udev rules
Note: these are no longer the recommended rules, this is just used to check for them
"""
if pid:
return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", MODE:="0666"' % (vid, pid)
else:
... |
def get_affected_products(rule_obj):
"""
From a rule_obj, return the set of affected products from rule.yml
"""
return set(rule_obj['products']) |
def is_valid_uuid (uuid):
"""
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
... |
def remove_duplicates_badSolution( li ):
""" DO NOT DO THIS. It shows a lack of understanding of set(). """
newli=[]
seen = set()
for item in li:
if item not in seen:
seen.add( item )
newli.append(item)
return newli |
def clip_point(xmin, ymin, xmax, ymax, x, y):
"""Clips the point (i.e., determines if the point is in the clip
rectangle).
Parameters
----------
xmin, ymin, xmax, ymax, x, y : float
Returns
-------
bool
`True`, if the point is inside the clip rectangle; otherwise,
`Fals... |
def __add(thiselement, char):
"""Shorthand for adding a character...."""
if thiselement == None:
return char
return thiselement + char |
def test_positive_digit(s):
"""
Return True only for datatype that can be cast as a positive integer
"""
if s.isdigit():
return int(s) > 0 |
def _list_to_json(list_of_obj):
""" Convert a object list to a JSON list """
output = '{ "list": %s }' % str(list_of_obj)
return output |
def sum_2_level_dict(two_level_dict):
"""Sum all entries in a two level dict
Arguments
----------
two_level_dict : dict
Nested dict
Returns
-------
tot_sum : float
Number of all entries in nested dict
"""
tot_sum = 0
for j in two_level_dict.values():
tot... |
def dd_to_dms(dd):
"""Convert decimal degrees to degrees, minutes, seconds.
:param dd: decimal degrees as float
:rtype : tuple of degrees, minutes, seconds
"""
dd = abs(dd)
minutes, seconds = divmod(dd*3600, 60)
degrees, minutes = divmod(minutes, 60)
seconds = float('{0:.2f}'.format(seco... |
def first(iterable, condition = lambda x: True):
"""
Returns the first item in the `iterable` that satisfies the `condition`.
If the condition is not given, returns the first item of the iterable.
Returns -1 if no item satysfing the condition is found.
>>> first( (1,2,3), condition=lambda x: x % 2 ... |
def asymptotic_mean(mu, alpha, beta, run_time):
"""
Calculates Hawkes asymptotic mean.
"""
return (mu * run_time) / (1 - alpha / beta) |
def um_time_to_time(d):
"""
Convert a list with format [year, month, day, hour, minute, second]
to a number of seconds.
Only days are supported.
"""
assert d[0] == 0 and d[1] == 0 and d[3] == 0 and d[4] == 0 and d[5] == 0
return d[2]*86400 |
def get_extension(file_name):
"""
Returns file extension
>>> get_extension("foo.txt")
'txt'
"""
return file_name.split(".")[-1] |
def time_formatter(time_s):
"""
Formats time in seconds input to more intuitive form h, min, s or ms, depending on magnitude
:param time_s: [float] time in seconds
:return:
"""
if time_s < 0.01:
return int(time_s * 1000.0 * 1000) / 1000.0, "ms"
elif 100 < time_s < 3600:
retur... |
def remove_excessive_new_lines(string):
"""Change string so there are at most four line breaks."""
newlines = 0
index = string.find('\n')
while index != -1:
newlines += 1
if newlines >= 4:
# snip string after the fourth new line
return string[:index]
... |
def active_or_inactive(dir_n_timestamp, directories_time_list):
"""
Return active and inactive devices based on 5 Mins activity
"""
status = []
for td in directories_time_list:
if td == 'inactive':
status.append('Inactive')
else:
if len(td.split(' ')) == 1:
... |
def convert_byte_dict_to_str_dict(inp: dict) -> dict:
"""
Convert dictionaries with keys and values as bytes to strings
Args:
inp: Dictionary with key and values in bytes
Returns:
Dictionary with key and value as string
"""
new_dict = dict()
for k, v in inp.items():
... |
def calculate_warm_val_from_temp(temp):
"""
This is used to convert a color temp into the value that the warm LED
should display. This formula is based on a line of best fit from some
testing I did with a light meter.
"""
return round((0.0000000325 * pow(temp, 3)) - (0.00005 * pow(temp, 2)) + (0... |
def balanced_accuracy(sensitivity, specificity, factor=0.5):
"""Balanced accuracy
Wikipedia entry https://en.wikipedia.org/wiki/Accuracy_and_precision
Parameters
----------
sensitivity : float in [0, 1]
sensitivity.
specificity : float in [0, 1]
specificity.
factor : floa... |
def swap1(num1, num2):
"""Works for integers"""
num1 += num2
num2 = num1 - num2
num1 = num1 - num2
return num1, num2 |
def merge(a, b):
"""Merge two arrays in order."""
sorted_array = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
sorted_array.append(a[0])
a.remove(a[0])
else:
sorted_array.append(b[0])
b.remove(b[0])
if len(a) == 0:
sorted_a... |
def boto3_tag_list_to_ansible_dict(tags_list, tag_name_key_name=None, tag_value_key_name=None):
""" Convert a boto3 list of resource tags to a flat dict of key:value pairs
Args:
tags_list (list): List of dicts representing AWS tags.
tag_name_key_name (str): Value to use as the key for all tag k... |
def ComputeLibraryDependencies(direct_lib_dict):
"""Computes transitive closure of library dependencies.
Args:
direct_lib_dict: a dictionary containing direct library dependencies.
Returns:
A dictionary in which each entry key is a library name and the value is a
list of all libraries on which that ... |
def btc_to_satoshi(btc: float) -> int:
"""Convert a btc value to satoshis
Args:
btc: The amount of btc to convert
Returns:
The integer of satoshis for this conversion
"""
return int(btc * 100000000) |
def final_metric(low_corr: float, high_corr: float) -> float:
"""Metric as defined on the page
https://signate.jp/competitions/423#evaluation
Args:
low_corr (float): low model spearman
high_corr (float): high model spearman
Returns:
float: final evaluation metric as defi... |
def IsInVisibleWindow(object):
"""Is object inside a visible window?"""
# Find toplevel Frame object
def Parent(object): return getattr(object,"Parent",None)
def IsFrame(object): return hasattr(object,"Title")
##debug("IsInVisibleWindow: object=%r" % object)
while not IsFrame(object) and Parent... |
def any_it(self, func):
"""
Returns True if any calling the given function returns True for any item.
**Examples**
:::python
assert it('asdf').any(lambda x: x > 'a')
assert not it('bsdf').all(lambda x: x <= 'a')
"""
return any(func(i) for i in self) |
def join_rule(value):
"""
>>> join_rule([['A', 'B'], ['C', 'D']])
'AB/CD'
"""
return "/".join("".join(row) for row in value) |
def _get_doc_length(doc):
"""Get length of (tokenized) document.
Parameters
----------
doc : list of (list of (tuple of int))
Given document.
Returns
-------
int
Length of document.
"""
return sum(item[1] for item in doc) |
def _convert_rho_to_krho(rho, size_ds: int):
"""
Converts the ``rho`` parameter (also noted: math:`\\varrho`) between :math:`0 < \\varrho < 1` in a value between 0 and the size of the reference dataset.
:param list rho: The value(s) of :math:`\\varrho` to be converted
:param int size_ds: The size of th... |
def check_ordinal(received_text):
"""Replace ordinal numbers with full letter representation"""
ordinals = {
'1st': 'first',
'2nd': 'second',
'3rd': 'third',
'4th': 'fourth',
'5th': 'fifth',
'6th': 'sixth',
'7th': 'seventh',
'8th':... |
def sectionBytes(section):
"""return [firstByte, byteCount]"""
assert len(section) == 3
firstByte = section[0]*512
byteCount = section[1]*section[2]
return [firstByte, byteCount] |
def deconvert_string(s, sep_space=1):
"""Deconverts a f-string of python3.6 and beyond to a simple python string
Args:
s: f-string to deconvert
sep_space: space between commas of format arguments
Return:
deconverted string in the old python3 string format
Example: ... |
def normalize_string(string_value):
"""
Normalize a unicode or regular string
:param string_value: either a unicode or regular string or None
:return: the same type that came in
"""
return string_value.strip().lower() if string_value is not None else None |
def problem_5_6(n):
""" Write a program to swap odd and even bits in an integer with as few
instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit
3 are swapped, etc).
"""
def is_set_bit(x, i):
return (x & (1 << i)) != 0
def toggle_bit(x, i):
return (x ^ (1 <... |
def nested_hash(obj):
"""Create a hash of nested, mutable data structures.
It shall be noted, that the uniqeness of those hashes in general cases is
not assured but it should be enough for the cases occurring during the
merging process.
"""
try:
return hash(obj)
except TypeError:
... |
def decode_fizz_buzz(i, prediction):
"""Function to decode model prediction
Parameters
----------
i: int
Input number
prediciction: int
Label predicted by the neural network
Returns
-------
str
Decoded ouput of either the number, fizz, buzz or fizzbuzz
"""
... |
def array_to_string(array, format="%3.3f "):
"""Return a string from an array, with given formatting. """
s = ""
for i in array:
s = s + format % i
return s |
def two_digit_special(number) -> bool:
"""It will check whether the entered number is a two digit special number or not."""
s = 0
n = number
p = 1
a = n
if(n > 9 and n < 100):
while(n != 0):
r = n % 10
p = p*r
s = s+r
n = n//10
if(s... |
def validate_alphabets(user_input):
"""
Method to validate that a string contains letters only
:response:boolean
:params: user data, string
"""
if not user_input.isalpha():
return False
return True |
def update_number_of_orientations(integration_density, integration_volume):
"""
Update the number of orientation for powder averaging.
Option for advance modal.
"""
ori = int((integration_density + 1) * (integration_density + 2) / 2)
if integration_volume == 0:
return f"Averaging over {o... |
def rectangle_to_cv_bbox(rectangle_points):
"""
Convert the CVAT rectangle points (serverside) to a OpenCV rectangle.
:param tuple rectangle_points: Tuple of form (x1,y1,x2,y2)
:return: Form (x1, y1, width, height)
"""
# Dimensions must be ints, otherwise tracking throws a exception
return (int(rectangle_points[... |
def entitydata_type(type_id):
"""
Returns type URI/CURIE/ref for indicated type id.
"""
if type_id == "_type":
return "annal:Type"
elif type_id == "_list":
return "annal:List"
elif type_id == "_view":
return "annal:View"
elif type_id == "_field":
return "annal... |
def normalize_str(string):
"""String to number."""
try:
if string.isdigit():
result = int(string)
else:
result = round(float(string), 3)
return result
except (ValueError, AttributeError):
return string |
def remove_numbers(text):
"""
Remove numbers from text as they aren't of value to our model
:text: string
:return: string
"""
return ''.join(char for char in text if not char.isdigit()) |
def number_with_precision(number, precision=3):
"""
Formats a ``number`` with a level of ``precision``.
Example::
>>> number_with_precision(111.2345)
111.235
"""
formstr = '%01.' + str(precision) + 'f'
return formstr % number |
def uniq(x):
"""Remove duplicated items and return new list.
If there are duplicated items, first appeared item remains and
others are removed.
>>> uniq([1,2,3,3,2,4,1])
[1, 2, 3, 4]
"""
y=[]
for i in x:
if not y.count(i):
y.append(i)
return y |
def compute_TF(doc_info):
"""
tf = (frequency of the term in the doc/total number of terms in the doc)
"""
tf_scores = []
for idx, doc in enumerate(doc_info):
tf_score_table = {}
for word in doc['freq_dict'].keys():
count = doc['freq_dict'][word]
tf_score_tab... |
def gateway_environment(gateway_environment, testconfig):
"""Set HTTP_PROXY to staging gateway."""
proxy_endpoint = testconfig["integration"]["service"]["proxy_service"]
gateway_environment.update({"HTTP_PROXY": f"http://{proxy_endpoint}"})
return gateway_environment |
def interpret(instruction: str) -> tuple:
"""
Split and interpret a piloting instruction and return a tuple of action and
units.
Paramaters:
instruction (str): Instruction to interpret
Returns
tuple: Tuple of action and units
"""
action, units = instruction.split(" ", 1)
units ... |
def exc_default(func, val, exc=Exception):
"""Specify a default value for when an exception occurs."""
try:
return func()
except exc:
return val |
def _mpv_coax_proptype(value, proptype=str):
"""Intelligently coax the given python value into something that can be understood as a proptype property."""
if type(value) is bytes:
return value;
elif type(value) is bool:
return b'yes' if value else b'no'
elif proptype in (str, int, float)... |
def _PerModeSmall36(x):
"""Takes Numeric Code and returns String API code
Input Values: 1:"Totals", 2:"PerGame", 3:"Per36"
Used in:
"""
measure = {1:"Totals",2:"PerGame",3:"Per36"}
try:
return measure[x]
except:
raise ValueError("Please enter a number between 1 and "+str(l... |
def get_famplex_id(family):
"""Generate an appropriate FPLX ID for an HGNC family"""
if family['abbreviation']:
return family['abbreviation'].strip().replace(', ', '_')
else:
replaces = {' ': '_', '-': '_', ',': ''}
name = family['name'].strip()
for k, v in replaces.items():
... |
def decode_mixed(x):
"""Convert bytes in Numpy arrays into strings. Leave other stuff alone.
Parameters
----------
x : object
Input object.
Returns
-------
object
If `x` has a ``decode()`` method, ``x.decode()`` will be returned.
Otherwise `x` will be returned unch... |
def make_filename(s):
"""Transform argument string into a standard filename
Convert a possible filename into a standard form.
s Filename to process.
The new filename string.
"""
s = s.strip()
s = s.replace(' ', '_')
s = s.replace('(', '')
s = s.replace(')', '')
s = ... |
def get_simple_forecast(avg_temp: float) -> str:
"""Return a simple forecast representation.
:param avg_temp: Average temperature of the day forecast to simplify
"""
if avg_temp >= 20:
output = "good"
elif avg_temp >= 10:
output = "soso"
else:
output = "bad"
return ... |
def sanitize_text(text: str) -> str:
"""
remove risky characters in a latex text file
:param text:
:return:
"""
text = text.replace("%", r"\%")
text = text.replace("_", r"\_")
return text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.