content stringlengths 42 6.51k |
|---|
def _parent_key(d):
"""
Return the function path of the parent of function specified by 'id' in the given dict.
"""
parts = d['id'].rsplit('|', 1)
if len(parts) == 1:
return ''
return parts[0] |
def fib_memo(n, seen):
"""
Return the nth fibonacci number reasonably quickly.
@param int n: index of fibonacci number
@param dict[int, int] seen: already-seen results
"""
if n not in seen:
seen[n] = (n if n < 2
else fib_memo(n - 2, seen) + fib_memo(n - 1, seen))
return seen[n] |
def flip_string(string):
"""Perform byte-swap to reverse endianess, we use big endian, but atmel processor is little endian"""
i = 0
reverse_string = ''
string_length = len(string)
while i < string_length:
reverse_string += string[string_length-i-1]
i += 1
return reverse_string |
def pix2point(shape, ix, iy, ovs=1):
""" find the nearest pixel to point `ix`, `iy`
in the plane with shape `shape`
ovs is the oversampling factor for spatial antialiasing
"""
cr = ((ix/ovs)*3.0/shape[0] - 2.0) # [0, width] > [-2, 1]
ci = ((iy/ovs)*2.0/shape[1] - 1.0) # [0, height] > [-1, 1]
return cr, ci |
def unescape(s):
""" unescape html tokens.
<p>{{ unescape(content) }}</p>
"""
return (
s.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(""", '"')
.replace("'", "'")
) |
def getValues(currentValues, current, total):
"""
Return either the current values (for this horizon) or all computed results
Parameters
----------
currentValues : Boolean
True: return 'current', False: return 'total'
current : Pointer
Pointer to the current values
total : Pointer
Pointer to the total values
"""
if currentValues:
return current
else:
return total |
def determine_major_version(all_repos_tags):
"""
Determine official major version i.e 4.1 , 4.2..etc using oxauths repo
@param all_repos_tags:
@return:
"""
versions_list = []
for tag in all_repos_tags["oxauth"]:
# Exclude any tag with the following
if "dev" not in tag \
and "latest" not in tag \
and "secret" not in tag \
and "gluu-engine" not in tag:
versions_list.append(float(tag[0:3]))
# Remove duplicates
versions_list = list(set(versions_list))
# Sort
versions_list.sort()
# Return highest version
return versions_list[-1] |
def pre_process(strr):
"""
Write preprocessing to be performed on string to normalize string
For now: string needs to be lower case
Ideas:
Group similar character by unsupervised learning, require CV and replace appropriate alphabet
"""
strr = strr.lower()
return strr |
def shortstr(s,max_len=144,replace={'\n':';'}):
""" Obtain a shorter string """
s = str(s)
for k,v in replace.items():
s = s.replace(k,v)
if max_len>0 and len(s) > max_len:
s = s[:max_len-4]+' ...'
return s |
def slice_arrays(arrays, start=None, stop=None):
"""Slices an array or list of arrays.
"""
if arrays is None:
return [None]
elif isinstance(arrays, list):
return [None if x is None else x[start:stop] for x in arrays]
else:
return arrays[start:stop] |
def removeStopWords(words,stop_words=None):
"""
remove stop words from word list
"""
if stop_words:
return [word for word in words if word not in stop_words]
else:
return words |
def count_variables(expr):
"""Count variables with the same value.
>>> count_variables('xxy')
{
'x': 2,
'y': 1
}
"""
result = {}
variables = []
for x in list(expr):
if x not in variables:
variables.append(x)
for x in variables:
result[x] = expr.count(x)
return result |
def _normalise_drive_string(drive):
"""Normalise drive string to a single letter."""
if not drive:
raise ValueError("invalid drive letter: %r" % (drive,))
if len(drive) > 3:
raise ValueError("invalid drive letter: %r" % (drive,))
if not drive[0].isalpha():
raise ValueError("invalid drive letter: %r" % (drive,))
if not ":\\".startswith(drive[1:]):
raise ValueError("invalid drive letter: %r" % (drive,))
return drive[0].upper() |
def sep_num(number, space=True):
"""
Creates a string representation of a number with separators each thousand. If space is True, then it uses spaces for
the separator otherwise it will use commas
Note
----
Source: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separator-with-spaces
:param number: A number
:type number: int | float
:param space: Separates numbers with spaces if True, else with commas
:type space: bool
:return: string representation with space separation
:rtype: str
"""
if space:
return '{:,}'.format(number).replace(',', ' ')
else:
return '{:,}'.format(number) |
def label_map(x):
"""Mapping the original labels."""
if x == 2:
return 1
else:
return -1 |
def _coerce_bool(some_str):
"""Stupid little method to try to assist casting command line args to
booleans
"""
if some_str.lower().strip() in ['n', 'no', 'off', 'f', 'false', '0']:
return False
return bool(some_str) |
def evap_i(pet, si, simax):
"""evaporation from interception"""
# set to 0 when FAO pet is negative (Wilcox & Sly (1976))
if pet < 0:
pet = 0
if simax == 0:
ei = 0
else:
ei = min(si, pet * (si / simax) ** (2 / 3))
si = si - ei
pet_r = pet - ei
return ei, si, pet_r |
def check_column(board):
"""
list -> bool
This function checks if every column has different numbers and returns
True is yes, and False if not.
>>> check_column(["**** ****", "***1 ****", "** 3****", \
"* 4 1****", " 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
False
>>> check_column(["**** ****", "***1 ****", "** 3****", \
"* 4 1****", " 9 5 ", " 6 83 *", "3 5 **", " 8 2***", " 2 ****"])
True
"""
length = len(board)
for i in range(length):
one_line = []
for line in board:
if line[i] == '*' or line[i] == ' ':
continue
if line[i] in one_line:
return False
else:
one_line.append(line[i])
return True |
def fixDelex(filename, data, data2, idx, idx_acts):
"""Given system dialogue acts fix automatic delexicalization."""
try:
turn = data2[filename.strip('.json')][str(idx_acts)]
except:
return data
if not isinstance(turn, str): #and not isinstance(turn, unicode):
for k, act in turn.items():
if 'Attraction' in k:
if 'restaurant_' in data['log'][idx]['text']:
data['log'][idx]['text'] = data['log'][idx]['text'].replace("restaurant", "attraction")
if 'hotel_' in data['log'][idx]['text']:
data['log'][idx]['text'] = data['log'][idx]['text'].replace("hotel", "attraction")
if 'Hotel' in k:
if 'attraction_' in data['log'][idx]['text']:
data['log'][idx]['text'] = data['log'][idx]['text'].replace("attraction", "hotel")
if 'restaurant_' in data['log'][idx]['text']:
data['log'][idx]['text'] = data['log'][idx]['text'].replace("restaurant", "hotel")
if 'Restaurant' in k:
if 'attraction_' in data['log'][idx]['text']:
data['log'][idx]['text'] = data['log'][idx]['text'].replace("attraction", "restaurant")
if 'hotel_' in data['log'][idx]['text']:
data['log'][idx]['text'] = data['log'][idx]['text'].replace("hotel", "restaurant")
return data |
def _model(source_names):
"""Build additive model string for Gaussian sources."""
return ' + '.join(['normgauss2d.' + name for name in source_names]) |
def test_for_blank_lines_separating_reference_lines(ref_sect):
"""Test to see if reference lines are separated by blank lines so that
these can be used to rebuild reference lines.
@param ref_sect: (list) of strings - the reference section.
@return: (int) 0 if blank lines do not separate reference lines; 1 if
they do.
"""
num_blanks = 0 # Number of blank lines found between non-blanks
num_lines = 0 # Number of reference lines separated by blanks
blank_line_separators = 0 # Flag to indicate whether blanks lines separate
# ref lines
multi_nonblanks_found = 0 # Flag to indicate whether multiple nonblank
# lines are found together (used because
# if line is dbl-spaced, it isnt a blank that
# separates refs & can't be relied upon)
x = 0
max_line = len(ref_sect)
while x < max_line:
if not ref_sect[x].isspace():
# not an empty line:
num_lines += 1
x += 1 # Move past line
while x < len(ref_sect) and not ref_sect[x].isspace():
multi_nonblanks_found = 1
x += 1
x -= 1
else:
# empty line
num_blanks += 1
x += 1
while x < len(ref_sect) and ref_sect[x].isspace():
x += 1
if x == len(ref_sect):
# Blanks at end doc: dont count
num_blanks -= 1
x -= 1
x += 1
# Now from the number of blank lines & the number of text lines, if
# num_lines > 3, & num_blanks = num_lines, or num_blanks = num_lines - 1,
# then we have blank line separators between reference lines
if (num_lines > 3) and ((num_blanks == num_lines) or
(num_blanks == num_lines - 1)) and \
(multi_nonblanks_found):
blank_line_separators = 1
return blank_line_separators |
def check_is_fid_valid(fid, raise_exception=True):
"""
Check if FID is well formed
:param fid: functional ID
:param raise_exception: Indicate if an exception shall be raised (True, default) or not (False)
:type fid: str
:type raise_exception: bool
:returns: the status of the check
:rtype: bool
:raises TypeError: if FID is invalid
:raises ValueError: if FID is not well formatted
"""
if fid is None:
if raise_exception:
raise ValueError("FID shall be set")
return False
if not isinstance(fid, str):
if raise_exception:
raise TypeError("Type of fid: '%s' shall be str, not %s" % (fid, type(fid)))
return False
if len(fid) < 3:
if raise_exception:
raise ValueError("fid shall have at least 3 characters: '%s'" % fid)
return False
if " " in fid:
if raise_exception:
raise ValueError("fid shall not contains spaces: '%s'" % fid)
return False
return True |
def min_bounding_dimension(bounds):
"""Return a minimal dimension along axis in a bounds ([min_x, max_x, min_y, max_y, min_z, max_z]) array."""
return min(abs(x1 - x0) for x0, x1 in zip(bounds, bounds[1:])) |
def convert_data(planet):
"""Convert string values of a dictionary to the appropriate type whenever possible.
Remember to set the value to None when the string is "unknown".
Type conversions:
rotation_period (str->int)
orbital_period (str->int)
diameter (str->int)
climate (str->list) e.g. ["hot", "humid"]
gravity (str->dict) e.g. {"measure": 0.75, "unit"; "standard"}
terrain (str->list) e.g. ["fungus", "forests"]
surface_water (str->float)
population (str->int)
Parameters:
dict: dictionary of a planet
Returns:
dict: dictionary of a planet with its values converted
"""
for key, val in planet.items():
if isinstance(val, str):
if not val or val.lower() in ('n/a', 'none', 'unknown'):
planet[key] = None
else:
if key in ('diameter', 'orbital_period', 'population', 'rotation_period'):
planet[key] = int(val)
elif key in ('climate', 'terrain'):
planet[key] = val.strip().split(', ')
elif key == 'surface_water':
planet[key] = float(val)
elif key == 'gravity':
gravity = val.strip().split()
planet['gravity'] = {"measure": float(gravity[0]), "unit": "standard"}
else:
continue
return planet
# if planet.get('rotation_period') == "unknown":
# planet['rotation_period'] = None
# else:
# planet['rotation_period'] = int(planet['rotation_period'])
# if planet.get('orbital_period') == "unknown":
# planet['orbital_period'] = None
# else:
# planet['orbital_period'] = int(planet['orbital_period'])
# if planet.get('diameter') == "unknown":
# planet['diameter'] = None
# else:
# planet['diameter'] = int(planet['diameter'])
# if planet.get('climate') == "unknown":
# planet['climate'] = None
# else:
# planet['climate'] = planet['climate'].strip().split(', ')
# if planet.get('gravity') == "unknown":
# planet['gravity'] = None
# else:
# splitted = planet['gravity'].strip().split()
# if len(splitted) == 2:
# planet['gravity'] = {"measure": float(splitted[0]), "unit": splitted[1]}
# else:
# planet['gravity'] = {"measure": float(splitted[0]), "unit": "standard"}
# if planet.get('terrain') == "unknown":
# planet['terrain'] = None
# else:
# planet['terrain'] = planet['terrain'].strip().split(', ')
# if planet.get('surface_water') == "unknown":
# planet['surface_water'] = None
# else:
# planet['surface_water'] = float(planet['surface_water'])
# if planet.get('population') == "unknown":
# planet['population'] = None
# else:
# planet['population'] = int(planet['population'])
# return planet |
def get_date(file_name):
"""
Parameters
----------
file_name : file name string
Returns
-------
date string for file in the form yyyymmddhhmm
"""
# Examples:
# Vid-000351067-00-06-2014-10-29-13-20.jpg
# Vid-000330038-00-02-2016-01-14-19-22.jpg
date = None
if len(file_name) > 21:
date_string = file_name[-20:-4]
date = "%s%s%s%s%s" % (date_string[0:4], date_string[5:7], date_string[8:10], date_string[11:13], date_string[14:16])
return date |
def select(q_sols, q_d, w=[1]*6):
"""Select the optimal solutions among a set of feasible joint value
solutions.
Args:
q_sols: A set of feasible joint value solutions (unit: radian)
q_d: A list of desired joint value solution (unit: radian)
w: A list of weight corresponding to robot joints
Returns:
A list of optimal joint value solution.
"""
error = []
for q in q_sols:
error.append(sum([w[i] * (q[i] - q_d[i]) ** 2 for i in range(6)]))
return q_sols[error.index(min(error))] |
def to_str(x, fmt):
"""Convert variable to string."""
x = "" if x is None else x
if not isinstance(x, str):
# Special handling for floating point numbers
if "f" in fmt:
# Number of decimals is specified
if "." in fmt:
n = int(fmt[3:].split(".")[0])
tmp = fmt.format(x)
if len(tmp) > n:
return fmt.replace("f", "e").format(x)
else:
return tmp
# Let Python decides the format
else:
n = int(fmt[3:].split("f")[0])
tmp = str(float(x))
if len(tmp) > n:
fmt = "{{:>{}.{}e}}".format(n, n - 7)
return fmt.format(x)
else:
fmt = "{{:>{}}}".format(n)
return fmt.format(tmp)
else:
return fmt.format(x)
else:
return fmt.replace("g", "").replace("e", "").replace("f", "").format(x) |
def parse_num(maybe_num) -> int:
"""parses number path suffixes, returns -1 on error"""
try:
return int(maybe_num)
except ValueError:
return -1 |
def char_ngrams(n, word, **kwargs):
"""This function extracts character ngrams for the given word
Args:
n (int): Max size of n-gram to extract
word (str): The word to be extract n-grams from
Returns:
list: A list of character n-grams for the given word
"""
del kwargs
char_grams = []
for i in range(len(word)):
# if char ngram of length n doesn't exist, if no ngrams have been extracted for the token,
# add token to the list and return. No need to compute for other windows.
# Ex: token is "you", n=4, return ["you"], token is "doing", n=4 return ["doin","oing"]
if len(word[i : i + n]) < n:
if not char_grams:
char_grams.append((word[i : i + n]))
return char_grams
char_grams.append((word[i : i + n]))
return char_grams |
def is_lower_snake(text):
"""
Check if a string is in a lower_snake_case format
:param text: String to check
:return: Whether string is in lower snake format
"""
if " " in text:
return False
return "_" in text and not text.isupper() |
def parse_file_arg(arg):
"""Handles @file format for users, to load the list of users from said file, one per line."""
if not isinstance(arg, list):
arg = [arg]
ret = []
for val in arg:
if val[0] == '@':
with open(val[1:]) as arg_file:
ret.extend(arg_file.readlines())
else:
ret.append(val)
return [x.strip() for x in ret if x.strip() != ''] |
def linearsearch(A, elem):
"""
Linear Search Algorithm that searches for an element in an array with O(n) time complexity.
inputs: Array A and element e, that has to be searched
output: True/False
"""
for a in A:
if a==elem:
return True
return False |
def is_compressed_filetype(filepath):
"""
Use to check if we should compress files in a zip.
"""
# for now, only include files which Blender is likely to reference
import os
assert(isinstance(filepath, bytes))
return os.path.splitext(filepath)[1].lower() in {
# images
b'.exr',
b'.jpg', b'.jpeg',
b'.png',
# audio
b'.aif', b'.aiff',
b'.mp3',
b'.ogg', b'.ogv',
b'.wav',
# video
b'.avi',
b'.mkv',
b'.mov',
b'.mpg', b'.mpeg',
# archives
# '.bz2', '.tbz',
# '.gz', '.tgz',
# '.zip',
} |
def check_type(obj, acceptable_types, optional=False):
"""Object is an instance of one of the acceptable types or None.
Args:
obj: The object to be inspected.
acceptable_types: A type or tuple of acceptable types.
optional(bool): Whether or not the object may be None.
Returns:
bool: True if the object is an instance of one of the acceptable types.
Raises:
TypeError: If the object is not an instance of one of the acceptable
types, or if the object is None and optional=False.
"""
if not isinstance(acceptable_types, tuple):
acceptable_types = (acceptable_types,)
if isinstance(obj, acceptable_types):
# Object is an instance of an acceptable type.
return True
elif optional and obj is None:
# Object is None, and that is OK!
return True
else:
# Object is something else.
error_message = (
"We were expecting to receive an instance of one of the following "
"types: {types}{none}; but instead we received {obj} which is a "
"{obj_type}.".format(
types=", ".join([repr(t.__name__) for t in acceptable_types]),
none="or 'None'" if optional else "",
obj=obj,
obj_type=repr(type(obj).__name__)
)
)
raise TypeError(error_message) |
def first_close_to_final(x, y, min_rel_proximity=0.05):
"""
returns the chronologically first value of x where
y was close to min_rel_proximity (y[-1] - y[0]) of
the final value of y, i.e., y[-1].
"""
min_abs_proximity = (y[-1] - y[0]) * min_rel_proximity
final_y = y[-1]
for i in range(len(x)):
if abs(y[i] - final_y) < min_abs_proximity:
return x[i] |
def leap_year(year):
"""Determinates if a year is leap"""
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True |
def elem_to_string(*args):
"""Converts list of elements to string"""
return "t %d %d %d\n" % tuple(args) |
def remove_space_characters(field):
"""Remove every 28th character if it is a space character."""
if field is None:
return None
return "".join(c for i, c in enumerate(field) if i % 28 != 27 or c != ' ') |
def create_html_url_href(url: str) -> str:
"""
HTML version of a URL
:param url: the URL
:return: URL for use in an HTML document
"""
return f'<a href="{url}">{url}</a>' if url else "" |
def get_ip(record, direction):
"""
Return required IPv4 or IPv6 address (source or destination) from given record.
:param record: JSON record searched for IP
:param direction: string from which IP will be searched (e.g. "source" => ipfix.sourceIPv4Address or
"destination" => ipfix.destinationIPv4Address)
:return: value corresponding to the key in the record
"""
key_name = "ipfix." + direction + "IPv4Address"
if key_name in record.keys():
return record[key_name]
key_name = "ipfix." + direction + "IPv6Address"
return record[key_name] |
def _byteOrderingEndianess(num, length=4):
"""
Convert from little endian to big endian and vice versa
Parameters
----------
num: int
input number
length:
number of bytes of the input number
Returns
-------
An integer with the endianness changed with respect to input number
"""
if not isinstance(num, int):
raise ValueError("num must be an integer")
if not isinstance(length, int):
raise ValueError("length must be an positive integer")
elif length < 0:
raise ValueError("length cannot be negative")
aux = 0
for i in range(length):
byte_index = num >> ((length - 1 - i) * 8) & 0xFF
aux += byte_index << (i * 8)
return aux |
def re_im_to_complex(realpart, imaginarypart):
"""Convert real and imaginary parts to complex value
*realpart* real part linear units
*imaginarypart* imaginary part linear units
"""
return realpart + 1j*imaginarypart |
def aliquot_sum(input_num: int) -> int:
"""
Finds the aliquot sum of an input integer, where the
aliquot sum of a number n is defined as the sum of all
natural numbers less than n that divide n evenly. For
example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is
a simple O(n) implementation.
@param input_num: a positive integer whose aliquot sum is to be found
@return: the aliquot sum of input_num, if input_num is positive.
Otherwise, raise a ValueError
Wikipedia Explanation: https://en.wikipedia.org/wiki/Aliquot_sum
>>> aliquot_sum(15)
9
>>> aliquot_sum(6)
6
>>> aliquot_sum(-1)
Traceback (most recent call last):
...
ValueError: Input must be positive
>>> aliquot_sum(0)
Traceback (most recent call last):
...
ValueError: Input must be positive
>>> aliquot_sum(1.6)
Traceback (most recent call last):
...
ValueError: Input must be an integer
>>> aliquot_sum(12)
16
>>> aliquot_sum(1)
0
>>> aliquot_sum(19)
1
"""
if not isinstance(input_num, int):
raise ValueError("Input must be an integer")
if input_num <= 0:
raise ValueError("Input must be positive")
return sum(
divisor for divisor in range(1, input_num // 2 + 1) if input_num % divisor == 0
) |
def dict_from_object(obj: object):
"""Convert a object into dictionary with all of its readable attributes."""
# If object is a dict instance, no need to convert.
return (obj if isinstance(obj, dict)
else {attr: getattr(obj, attr)
for attr in dir(obj) if not attr.startswith('_')}) |
def ArchToBits(arch):
"""Takes an arch string like x64 and ia32 and returns its bitwidth."""
if not arch: # Default to x64.
return 64
elif arch == 'x64':
return 64
elif arch == 'ia32':
return 32
assert False, 'Unsupported architecture' |
def _indent_run_instruction(string: str, indent=4) -> str:
"""Return indented string for Dockerfile `RUN` command."""
out = []
lines = string.splitlines()
for ii, line in enumerate(lines):
line = line.rstrip()
is_last_line = ii == len(lines) - 1
already_cont = line.startswith(("&&", "&", "||", "|", "fi"))
is_comment = line.startswith("#")
previous_cont = lines[ii - 1].endswith("\\") or lines[ii - 1].startswith("if")
if ii: # do not apply to first line
if not already_cont and not previous_cont and not is_comment:
line = "&& " + line
if not already_cont and previous_cont:
line = " " * (indent + 3) + line # indent + len("&& ")
else:
line = " " * indent + line
if not is_last_line and not line.endswith("\\") and not is_comment:
line += " \\"
out.append(line)
return "\n".join(out) |
def round_width(width, multiplier, min_depth=8, divisor=8):
"""
Round width of filters based on width multiplier
from: https://github.com/facebookresearch/SlowFast/blob/master/slowfast/models/video_model_builder.py
Args:
width (int): the channel dimensions of the input.
multiplier (float): the multiplication factor.
min_width (int, optional): the minimum width after multiplication.
Defaults to 8.
divisor (int, optional): the new width should be dividable by divisor.
Defaults to 8.
"""
if not multiplier:
return width
width *= multiplier
min_depth = min_depth or divisor
new_filters = max(
min_depth, int(width + divisor / 2) // divisor * divisor
)
if new_filters < 0.9 * width:
new_filters += divisor
return int(new_filters) |
def unique_items_in_order(x) -> list:
"""
Return de-duplicated list of items in order they are in supplied array.
:param x: vector to inspect
:return: list
"""
ret = []
if x is not None:
seen = set()
for item in x:
if item not in seen:
ret.append(item)
seen.add(item)
return ret |
def gtf_or_db(fname):
"""
Determine if a file is GTF or TALON DB.
Parameters:
fname (str): File name / location
Returns:
ftype (str): 'gtf' or 'db' depending on results
"""
ext = fname.split('.')[-1]
if ext == 'gtf': return 'gtf'
elif ext == 'db': return 'db'
else:
raise Exception('File type must be gtf or db. '
'Type received is {}'.format(ext)) |
def percentage_format(value,decimal=2):
"""
Format number as percentage
"""
formatStr = "{:." + str(decimal) + "%}"
return formatStr.format(value)
#return "{:.2%}".format(value) |
def straight_backoff(count):
"""
Wait 1, 2, 5 seconds. All retries after the 3rd retry will wait 5*N-5 seconds.
"""
return (1, 2, 5)[count] if count < 3 else 5 * count - 5 |
def binV2_to_A2(S2,R_acq,mv_per_bin):
"""
Used to convert SII(t)[bin_V**2] to SII(t)[A**2]
"""
return S2*(mv_per_bin*1.0e-3)**2/(R_acq**2) |
def cleanstring(data):
"""Remove multiple whitespaces and linefeeds from string.
Args:
data: String to process
Returns:
result: Stipped data
"""
# Initialize key variables
nolinefeeds = data.replace('\n', ' ').replace('\r', '').strip()
words = nolinefeeds.split()
result = ' '.join(words)
# Return
return result |
def exact_exp_date(results, exp):
"""Returns a string of unique expiry date in yyyy-mm-dd form
results: tuple of (Ticker[0] Strike[1] Type[2] Expiration[3] Last[4] Bid[5] Ask[6])
exp: expiration date that was entered or inferred. however, may not have
day of the month, or may resolve to multiple dates."""
exp_dates = set([])
for result in results[1:]:
exp_dates.add(result[3])
if len(exp_dates) == 0:
print ("WARNING. No matching date found! Try again.")
if len(exp_dates) != 1:
print ("WARNING. multiple dates found! ")
for d in exp_dates: print (" -> ", d)
print ("Try again with exact one.")
exp_date = ' '.join(list(exp_dates))
return exp_date |
def get_name(filename):
"""
Return the name of the file.
Given naming convention '<name>_<type>.<ext>' where none of the variables contains '_'.
"""
return filename.split('.')[0].split('_')[0] |
def repeat(l, n):
""" Repeat all items in list n times
repeat([1,2,3], 2) => [1,1,2,2,3,3]
http://stackoverflow.com/questions/24225072/repeating-elements-of-a-list-n-times
"""
return [x for x in l for i in range(n)] |
def twos_complement(val, nbits):
"""Compute the 2's complement of int value val. Credit: https://stackoverflow.com/a/37075643/9235421"""
if val < 0:
if (val + 1).bit_length() >= nbits:
raise ValueError(f"Value {val} is out of range of {nbits}-bit value.")
val = (1 << nbits) + val
else:
if val.bit_length() > nbits:
raise ValueError(f"Value {val} is out of range of {nbits}-bit value.")
# If sign bit is set.
if (val & (1 << (nbits - 1))) != 0:
# compute negative value.
val = val - (1 << nbits)
return val |
def parse_virustotal(dyn_data: dict) -> dict:
"""
parses out virustotal information from dyn_data dictionary
Not used, just used for data analysis sake
Args:
dyn_data: dictionary read from dynamic data
Returns:
network_dict: dictionary parsing the network information extracted from dyn_data
"""
virustotal_dict = {}
try:
vt = dyn_data['virustotal']
virustotal_dict['positives'] = vt['positives']
virustotal_dict['total'] = vt['total']
return virustotal_dict
except BaseException:
return virustotal_dict |
def poslin(n):
"""
Positive Linear
"""
if n < 0:
return 0
else:
return n |
def is_power_of_two(n):
"""
Determine whether or not given number is a power of two
:param n: given number
:type n: int
:return: whether or not given number is a power of two
:rtype: bool
"""
if n != 0 and n & (n - 1) == 0:
return True
else:
return False |
def check_serie_is_number(serie, max_serie=5000):
"""Check if serie is valid and return boolean.
Check if serie is a integer and if so if it is not
a made up number for research. First check if it can
be converted to a integer and if so check if it has a
smaller value than max_serie. Sometimes a serie
gets a follow letter (e.g. 400B, 400C) so perform the
same checks minus the last character in serie.
"""
is_number = True
try:
int(serie)
except ValueError:
is_number = False
else:
is_number = int(serie) < max_serie
try:
int(serie[:-1])
except ValueError:
is_number = False
else:
is_number = int(serie[:-1]) < max_serie
return is_number |
def _get_test_methods(test_case_name, test_class_map):
"""Takes ``test_class_map`` or ``skip_class_map`` and returns the list of
methods for the test case or ``None`` if no methods were specified for it
:param test_case_name: Name of the test case to check
:param test_class_map: Dictionary mapping test names to a list of methods
:return: List of methods or ``None`` if not specified for this test case
"""
if test_class_map is None or test_case_name not in test_class_map:
return None
return test_class_map[test_case_name] |
def fib(num):
""" the worst implementation of Fibonacci numbers calculation
complexity: T(N) = O(a ^ N), a - constant
Parameters
----------
num : int
requested Fibonacci number
Returns
-------
out : int
Fibonacci number
"""
if num < 2:
return num
val1 = fib(num - 1)
val2 = fib(num - 2)
return val1 + val2 |
def standardize_formula(qstr,rstr,formula_list):
"""
Docstring for function pyKrev.standardize_formula
====================
This function takes a list of formula and replaces any instances of qstr with rstr.
This is an important pre-processing step if isotope names are present in your molecular formula.
Use
----
element_counts(qtr,rstr,Y)
Returns a list of len(Y) in which each item is an atomic formula with qstr replaced by rstr.
Parameters
----------
Y: A list of atomic formula strings.
qstr: A string with the element name to replace (e.g. '11B')
rstr: A string with the element name to replace with (e.g. 'B')
"""
std_formula_list = []
for formula in formula_list:
std_formula_list.append(formula.replace(qstr,rstr,1))
return std_formula_list |
def generic_element(title, subtitle=None, image_url=None, buttons=None):
"""
Creates a dict to use with send_generic
:param title: Content for receiver title
:param subtitle: Content for receiver subtitle (optional)
:param image_url: Content for receiver image to show by url (optional)
:param button: Content for receiver button shown (optional)
:return: dict
"""
element = {
"title": title,
"subtitle": subtitle,
"image_url": image_url,
"buttons": buttons
}
if not subtitle:
element.pop('subtitle')
if not image_url:
element.pop('image_url')
if not buttons:
element.pop('buttons')
return element |
def floatify(item, default=0.0):
"""Another environment-parser: the empty string should be treated as
None, and return the default, rather than the empty string (which
does not become an integer). Default can be either a float or string
that float() works on. Note that numeric zero (or string '0') returns
0.0, not the default. This is intentional.
"""
if item is None:
return default
if item == "":
return default
return float(item) |
def find_last_slash(string):
"""
Search for / in a string. If one or more / was found, divide the string in a list of two string:
the first containf all the character at left of the last / (included),
and the second contains the remanent part of the text.
If no / was found, the first element of the list will be set to ''
"""
len_string = len(string)
check = 0
index = []
i = 0
for chara in string:
if chara == "/" or chara == "\\":
index.append(i)
check = 1
i += 1
if check == 1:
last_slash = max(index)
output_string = [string[0 : last_slash + 1], string[last_slash + 1 :]]
else:
output_string = ["", string]
return output_string |
def is_blank(line):
"""Returns true if the line is empty.
A single hyphen in a line is considered as blank
"""
return line.isspace() or not line or line.strip() == '-' |
def triangleCoordsForSide(s):
"""
Upwards pointing equilateral triangle with equal sides s
origin = 0,0
"""
factor = 3**0.5/2
coords = (
( # path
(0,0), (s,0), (s/2,factor*s),
),
)
return coords |
def floateq(a, b, eps=1.e-12):
"""Are two floats equal up to a difference eps?"""
return abs(a - b) < eps |
def create_choice(name, value) -> dict:
"""A function that will create a choice for a :class:`~SlashOption`
Parameters
----------
name: :class:`str`
The name of the choice
value: :class:`Any`
The value that will be received when the user selected this choice
Returns
-------
:returns: The created choice
:type: :class:`dict`
"""
return {"name": name, "value": value} |
def get_params_or_defaults(params, defaults):
"""Returns params.update(default) restricted to default keys."""
merged = {
key: params.get(key, default)
for key, default in defaults.items()
}
return merged |
def sparse_euclidean2(v1, v2):
"""Calculates the squared Euclidean distance between two sparse
vectors.
Args:
v1 (dict): First sparse vector
v2 (dict): Second sparse vector
Returns:
float. Squared distance between ``v1`` and ``v2``.
"""
d = 0.0
for i,v in v1.items():
v = v - v2.get(i, 0.0)
d = d + v*v
d = d + sum([v*v for i,v in v2.items() if not i in v1])
return d |
def use_c_string(str_format: str, items: dict) -> bool:
"""
Tests if we should use the C type string formatting. Otherwise, defaults to False. Meaning we should use
format_map() instead
:param str_format: The string format
:param items: A dictionary of items to pass to the string formatter
:return: A boolean value if we should use the C type string formatting (%)
"""
value = str_format % items
if value == str_format:
# raises KeyError if the string format has values not present in the dictionary
str_format.format_map(items)
return False
else:
return True |
def HasPositivePatterns(test_filter):
"""Returns True if test_filter contains a positive pattern, else False
Args:
test_filter: test-filter style string
"""
return bool(len(test_filter) > 0 and test_filter[0] != '-') |
def baseconvert(n, k, digits="ACDEFGHIKLMNPQRSTVWY"):
"""Generate a kmer sequence from input integer representation.
Parameters
----------
n : int
Integer representation of a kmer sequence.
k : int
Length of the kmer (i.e. protein sequence length).
digits : str
Digits to use in determining the base for conversion.
(default: "ACDEFGHIKLMNPQRSTVWY")
Returns
-------
str
Kmer sequence, in string format.
Returns empty string if inputs are invalid.
"""
assert len(digits) > 0, "digits argument cannot be empty string."
# digits = "0123456789abcdefghijklmnopqrstuvwxyz"
base = len(digits)
try:
n = int(n)
except (TypeError, ValueError):
return ""
if n < 0 or base < 2 or base > 36:
return ""
# parse integer by digits base to populate sequence backwards
s = ""
while n != 0:
r = int(n % base)
s = digits[r] + s
n = n / base
# fill in any remaining empty slots with first character
if len(s) < k:
for i in range(len(s), k):
s = "%s%s" % (digits[0], s)
return s |
def decompress_amount(x):
"""\
Undo the value compression performed by x=compress_amount(n). The input
x matches one of the following patterns:
x = n = 0
x = 1+10*(9*n + d - 1) + e
x = 1+10*(n - 1) + 9"""
if not x: return 0;
x = x - 1;
# x = 10*(9*n + d - 1) + e
x, e = divmod(x, 10);
n = 0;
if e < 9:
# x = 9*n + d - 1
x, d = divmod(x, 9)
d = d + 1
# x = n
n = x*10 + d
else:
n = x + 1
return n * 10**e |
def convert1Dto3Dindex(index,NX,NY,NZ):
"""Converts 1D array index to 1D array index"""
k = index / (NX*NY)
j = (index - k*NX*NY) / NX
i = index - k*NX*NY - j*NX
return [i,j,k] |
def dest_namespace(name):
"""ArgumentParser dest namespace (prefix of all destinations)."""
return name.replace("-", "_") + "_" |
def lat2txt(lat, fmt='%g'):
"""
Format the latitude number with degrees.
:param lat:
:param fmt:
:return:
:Examples:
>>> lat2txt(60)
'60\N{DEGREE SIGN}N'
>>> lat2txt(-30)
'30\N{DEGREE SIGN}S'
"""
if lat < 0:
latlabstr = u'%s\N{DEGREE SIGN}S' % fmt
latlab = latlabstr % abs(lat)
elif lat > 0:
latlabstr = u'%s\N{DEGREE SIGN}N' % fmt
latlab = latlabstr % lat
else:
latlabstr = u'%s\N{DEGREE SIGN}' % fmt
latlab = latlabstr % lat
return latlab |
def poly_derivative(poly):
"""
args: polynomial
return: derivatoive
"""
if isinstance(poly, list) is False or len(poly) == 0:
return None
derivatives = []
for i in range(len(poly)):
if type(poly[i]) != int and type(poly[i]) != float:
return
if i != 0:
derivatives.append(i * poly[i])
return derivatives |
def true_range(data):
"""True range
Arguments:
data {list} -- List of ohlc data [open, high, low, close]
Returns:
list -- True range of given data
"""
trng = []
for i, _ in enumerate(data):
if i < 1:
trng.append(0)
else:
val1 = data[i][1] - data[i][2]
val2 = abs(data[i][1] - data[i-1][3])
val3 = abs(data[i][2] - data[i-1][3])
if val2 <= val1 >= val3:
trng.append(val1)
elif val1 <= val2 >= val3:
trng.append(val2)
elif val1 <= val3 >= val2:
trng.append(val3)
return trng |
def check_enumerated_value(x):
"""
Enumerated values (video modes, pixel formats, etc.) should be able to be
given as either the lookup key (e.g. 'VM_640x480RGB') or the PyCapture2
code (e.g. 4). Argparse can only return one datatype though, so this func
is used to convert to codes to ints while keeping keys as strings
"""
try:
return int(x)
except ValueError:
return x |
def _build_options_dict(user_input, default_options):
"""Create the full dictionary of trust region fast start options from user input.
Args:
user_input (dict or None): dictionary to update the default options with.
May only contain keys present in the default options.
default_options (dict): the default values.
Returns:
full_options (dict)
"""
full_options = default_options.copy()
user_input = {} if user_input is None else user_input
invalid = [x for x in user_input if x not in full_options]
if len(invalid) > 0:
raise ValueError(
f"You specified illegal options {', '.join(invalid)}. Allowed are: "
", ".join(full_options.keys())
)
full_options.update(user_input)
return full_options |
def f(x,y):
"""dy/dx = f(x,y) = 3x^2y"""
Y = 3.*x**2. * y
return Y |
def find_artifact(artifacts, name):
"""Finds the artifact 'name' among the 'artifacts'
Args:
artifacts: The list of artifacts available to the function
name: The artifact we wish to use
Returns:
The artifact dictionary found
Raises:
Exception: If no matching artifact is found
"""
for artifact in artifacts:
if artifact['name'] == name:
return artifact
raise Exception('Input artifact named "{0}" not found in event'.format(name)) |
def _normalize_whitespace(s):
"""Replaces consecutive whitespace characters with a single space.
Args:
s: The string to normalize, or None to return an empty string.
Returns:
A normalized version of the given string.
"""
return ' '.join((s or '').split()) |
def get_str_cmd(cmd_lst):
"""Returns a string with the command to execute"""
params = []
for param in cmd_lst:
if len(param) > 12:
params.append('"{p}"'.format(p=param))
else:
params.append(param)
return ' '.join(params) |
def beats(one, two):
"""
Evaluates what moves beats what
-------
Returns
bool
true if the move one beats the move two
"""
return (
(one == "rock" and two == "scissors")
or (one == "scissors" and two == "paper")
or (one == "paper" and two == "rock")
) |
def clean_text(text, stopwords):
""" Converts free-text with punctuation, numbers, capital letters etc.
into a list of words
without any of the punctuation and other 'noise'
and excludes the pre-determined 'stopwords'
"""
# remove digits
text = ''.join(i for i in text if not i.isdigit())
# remove extra whitespace (with split and join), lower case
text = ' '.join(text.lower().split())
# forward slash '/' often used to mean 'or'
text = text.replace('/', ' ')
# remove punctuation
import string
text = text.translate(text.maketrans('', '', string.punctuation))
# print('\n**after trans**: ', text)
# remove stop words
words = [word for word in text.split() if word not in stopwords]
# print('\n**after splitting into list: ', words)
return words |
def state_in_addrlist(state, l):
"""
Determine whether the instruction addresses of a state are in a list
provided by ...
"""
if not l:
# empty list
return False
for addr in state.block().instruction_addrs:
if addr in l:
return True
return False |
def make_commands(trace_executable: str, tracin_filenames: list) -> list:
"""Create a list of shell command to run trace on the supplied set of tracin
:param trace_executable: the name of trace executable
:param tracin_filenames: the list of trace input file to be simulated
:return: a list of trace shell command to be executed
"""
trace_commands = []
for tracin_filename in tracin_filenames:
trace_command = [trace_executable, "-p", tracin_filename]
trace_commands.append(trace_command)
return trace_commands |
def ordered_lst_ele(ident_boud_lst):
"""
The task of this function is to identify if the elements boundaries list created are in a proper order i.e., to check if the connected elements
are present next to each other in the list. If the current element is having connections with the element in successive second index position,
then we change the position of the lists.
Arguments: ident_boud_lst- Identified boundary list
Return: ident_boud_lst - correctly ordered boundary list.
"""
# Iterate over the created list
for index, val in enumerate(ident_boud_lst):
current_sublist = ident_boud_lst[index]
index_1 = index + 1
if index_1 < (len(ident_boud_lst) - 1):
next_sublist = ident_boud_lst[index + 1]
# check if there is any elements matching between current list and next sublist
if len(set(current_sublist) & set(next_sublist)) == 0:
index_2 = index + 2
if index_2 < (len(ident_boud_lst) - 1):
# check if there is any match of elements on the next to next sublist
nxt_to_nxt_sublist = ident_boud_lst[index_2]
if len(set(current_sublist) & set(nxt_to_nxt_sublist)) != 0:
# If there is an element matching the element in our current list then change the
# position of the sublists
ident_boud_lst[index_2], ident_boud_lst[index_1] = ident_boud_lst[index_1], ident_boud_lst[
index_2]
return ident_boud_lst |
def remove_duplicates(fresh, existing):
"""
Checks the order ids from existing orders and returns only new ones
from fresh after removing the duplicates
"""
return list([order for order in fresh if order.get("id") and not existing.get(order.get("id"), None)]) |
def get_digits(n, reverse=False):
"""Returns the digits of n as a list, from the lowest power of 10 to the highest. If `reverse`
is `True`, returns them in from the highest to the lowest"""
digits = []
while n != 0:
digits.append(n % 10)
n //= 10
if reverse:
digits.reverse()
return digits |
def convert_boolean_list_to_indices(list_of_booleans):
"""
take a list of boolean values and return the indices of the elements containing True
:param list_of_booleans: list
sequence of booleans
:return: list with integer values
list of the values that were True in the input list_of_booleans
"""
return [n_element for n_element, element in enumerate(list_of_booleans) if element] |
def is_number(s):
""" Returns True if string is a number."""
try:
float(s)
return True
except ValueError:
return False |
def search_for_ISM(edge_IDs, transcript_dict):
""" Given a list of edges in a query transcript, determine whether it is an
incomplete splice match (ISM) of any transcript in the dict. Will also
return FSM matches if they're there"""
edges = frozenset(edge_IDs)
ISM_matches = [transcript_dict[x]
for x in transcript_dict if edges.issubset(x)]
if len(ISM_matches) > 0:
return ISM_matches
else:
return None |
def replace_space(string):
"""Replace a space to %20 for url.
Parameters
----------
string:
A string
Returns
-------
string:
A reformatted string.
"""
return string.replace(' ', '%20') |
def write_txt(w_path, val):
"""Write a text file from the string input.
"""
with open(w_path, "w") as output:
output.write(val + '\n')
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.