content stringlengths 42 6.51k |
|---|
def removeNonAscii(s):
""" Useful utilitiy to fix up, e.g. email files"""
# http://stackoverflow.com/questions/1342000/how-to-replace-non-ascii-characters-in-string
return "".join(i for i in s if ord(i) < 128) |
def count_digit(n, digit):
"""Return how many times digit appears in n.
>>> count_digit(55055, 5)
4
>>> count_digit(1231421, 1)
3
>>> count_digit(12, 3)
0
"""
if n ==0:
return 0
if n % 10 == digit :
return count_digit(n//10,digit) + 1
else:
return cou... |
def get_decoded_sent(text, predictions):
""" Decodes the tokenized text and returns the sentence with predicted
words.
Args:
text (str): Original text submitted by user.
predictions (list): List of predicted words.
Returns:
str: Input sentence containing predicted words.
"... |
def tail(tup):
"""Implement `tail`."""
return tup[1:] |
def func(beta, x):
"""
Just a linear function. Used by odr_fit but can use on its own.
:param beta: Array [intercept, gradient]
:param x: independent variable (generally x)
"""
# Expression of the line that we want to fit to the data
y = beta[0] + beta[1] * x
return y |
def squared_error(y, t, scale=0.5):
"""Return the scaled squared error. Note that the error is not averaged,
i.e. it does not compute the mean squared error.
Args:
y (list): Actual outputs. 1 dimensional.
t (list): Target outputs. Same dimensions as `y`.
Returns:
list: Scaled s... |
def distance(str1, str2):
"""
func: calculate levenshtein distance between two strings.
:param str1: string1
:param str2: string2
:return: distance
"""
m, n = len(str1) + 1, len(str2) + 1
matrix = [[0] * n for _ in range(m)]
matrix[0][0] = 0
for i in range(1, m):
matrix[i... |
def is_inside_interval(point, m, t):
"""Returns: true if point is bigger than m-t and less than m+t"""
return point >= m - t and point <= m + t |
def addDictionaries(d1,d2):
"""
Add the elements of two dictionaries. Missing entries treated as zero.
"""
lsum = [( key, d1[key]+d2[key]) for key in d1 if key in d2]
lsum += [( key, d1[key]) for key in d1 if key not in d2]
lsum += [( key, d2[key]) for key in d2 if key... |
def greatest_common_divisor(a, b):
"""
Calculate Greatest Common Divisor (GCD).
>>> greatest_common_divisor(24, 40)
8
"""
return b if a == 0 else greatest_common_divisor(b % a, a) |
def frange(start: float, end: float, step: float = .01):
"""Customized range version for floats to two decimal places"""
values = list()
counter = start
while counter <= end:
values.append(round(counter, 2))
counter += step
values.append(round(counter, 2))
return values |
def keyExists(myDict, key):
"""Returns True or False if 'key' is in 'myDict'"""
return key in list(myDict.keys()) |
def get_day(d, m, y, leap):
"""
Calculator method
Uses the algorithm to find the day
:return: Day corresponding to the DD-MM-YYYY date
:rtype: str
"""
# Initializing the mappings
dd = {0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday'}
# 1800-1899: Friday, 1... |
def sumsq(data, start=0):
"""Return the sum of the squares of a sequence of numbers.
>>> sumsq([2.25, 4.5, -0.5, 1.0])
26.5625
If optional argument start is given, it is added to the sequence. If the
sequence is empty, start (defaults to 0) is returned.
"""
return sum((x*x for x in data), ... |
def calculate_abs_power(panel_array):
""" Calculate absolute power of a given panel array"""
non_zero_panels = list(filter(lambda x: x != 0 , panel_array))
product = 1
for x in non_zero_panels:
product *= x
return abs(product) |
def categories_to_columns(categories, prefix_sep = ' is '):
"""contructs and returns the categories_col dict from the categories_dict"""
categories_col = {}
for k, v in categories.items():
val = [k + prefix_sep + vi for vi in v]
categories_col[k] = val
return categories_col |
def _get_dim_size(start, stop, step):
"""Given start, stop, and stop, calculate the number of elements
of this slice."""
assert step != 0
if step > 0:
assert start < stop
dim_size = (stop - start - 1) // step + 1
else:
assert stop < start
dim_size = (start - stop - 1)... |
def pentagon_n(n):
"""Returns the nth pentagon number"""
return int(n * (3 * n - 1) / 2) |
def get_gauss_job_type(setting_dict):
"""
Check the job type according to the setting_dict
Args:
setting_dict (str): A dict containing setting generated
from parse_gauss_options
Returns:
(str): A str represents the job type
"""
# Check if composi... |
def json_or_yaml(filename):
"""
This function would be obsolete when pyyaml supports yaml 1.2
With yaml 1.2 pyyaml can also read json files
:return:
"""
import re
from pathlib import Path
commas = re.compile(r',(?=(?![\"]*[\s\w\?\.\"\!\-\_]*,))(?=(?![^\[]*\]))')
"""
Find all com... |
def modsplit(module):
"""Split module into submodules."""
return tuple(module.split(".")) |
def parse_metadata(section):
"""Given the first part of a slide, returns metadata associated with it."""
metadata = {}
metadata_lines = section.split('\n')
for line in metadata_lines:
colon_index = line.find(':')
if colon_index != -1:
key = line[:colon_index].strip()
... |
def lucas_mod(n, mod):
"""
Compute n-th element of the Fibonacci sequence.
"""
x, y = 0, 1 # U_n, U_{n+1}, n=0
for b in bin(n)[2:]:
x, y = ((y - x) * x + x * y) % mod, (x * x + y * y) % mod # double
if b == "1":
x, y = y, (x + y) % mod # add
return x |
def fullname(_o):
"""return fqn of this module"""
# _o.__module__ + "." + _o.__class__.__qualname__ is an example in
# this context of H.L. Mencken's "neat, plausible, and wrong."
# Python makes no guarantees as to whether the __module__ special
# attribute is defined, so we take a more circumspect... |
def invert_dict(d):
"""Inverts a dictionary, returning a map from val to a list of keys.
If the mapping key->val appears in d, then in the new dictionary
val maps to a list that includes key.
d: dict
Returns: dict
"""
inverse = {}
for key in d:
val = d[key]
inverse.setdef... |
def sanitize_file_name(filename):
""" Replaces unsafe symbols in filenames
Args:
filename (str): file name
"""
filename = filename.replace(' ', '_')
filename = filename.replace("'", "")
filename = filename.replace('"', '')
return filename |
def getPersonRecordId(record):
"""Returns a fairly unique person record identifier.
May not be absolutely unique.
"""
return "{}_{}_{}_{}_{}".format(
record['year'],
record['record_number'],
record['parish'],
record['first_name'],
record['last_name']) |
def create_has_sentiments_present_vector(vector1, vector2):
"""
Create a short vector. If the the vectors are not equal
to zero it returns [1,1], if either of the vectors are equal
to zero it will return a zero for that vector. For example, if
vector1 is a zero vector, but vector2 has values, the fu... |
def flatten_list(lobj):
"""
Recursively flattens a list
:param lobj: List to flatten
:type lobj: list
:rtype: list
For example:
>>> import putil.misc
>>> putil.misc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7]
"""
ret = []
for item in lob... |
def count_fn(true_fn_flags, ground_truth_classes, class_code):
"""
Count how many true FN are left in true_fn_flags for class given by class_code
Args
true_fn_flags: list of flags that are left 1 if ground truth has not been detected at all
ground_truth_classes: list of classes correspondin... |
def poly(br_score):
""" Calculate weighted break score """
return 1/(1+br_score) |
def recursive_fibonacii(x):
"""assumes x an int >= 0
returns Fibonacci of x"""
if x == 0 or x == 1:
return 1
else:
return recursive_fibonacii(x-1) + recursive_fibonacii(x-2) |
def coord_translate_axis_origin(vertices):
"""Translates the vertices to the origin (0, 0, 0)"""
#Finding minimum value of x,y,z
minx = min(i[0] for i in vertices)
miny = min(i[1] for i in vertices)
minz = min(i[2] for i in vertices)
#Calculating new coordinates
translated_x = [i[0]-minx fo... |
def quick_sort(arr):
"""
Breaks down array into smaller sections
then swaps subsections into order
uses local partition() and sub_quick_sort(),
which assumes whole array should be sorted
"""
def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(... |
def turn_off_last_bit(S):
"""
Turns off the rightmost 1-bit in a word, producing 0 if none.
By product, the position of toggled 1-bit is returned, -1 if none.
Examples
========
When a 1-bit is present:
>>> S, b = turn_off_last_bit(0b1011000)
>>> bin(S)
'0b1010000'
>>> b
3
... |
def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" ") -> list:
""" Convert text to word list
:param text: test list
:param filters: filter rules, filter all punctuation marks, tabs, newlines, etc. by default
:param lower: whether to convert text to lowerc... |
def trade_params(classification, trade_flow, year, origin, destination,
product):
"""
Return a dictionary of parameters for requesting trade data and
visualizations.
Args:
classification (str): specifies which product classification to use
(e.g. 'hs92', 'hs96', 'hs0... |
def imgtype2ext(typ):
"""Converts an image type given by imghdr.what() to a file extension."""
if typ == 'jpeg':
return 'jpg'
if typ is None:
raise Exception('Cannot detect image type')
return typ |
def calc_speed_coefficient(thrust, total_mass):
""" Calculate a ships maximum speed multipler for the server speed limit
The maximum speed a ship can achieve on a server is a combination of the
thrust:mass ratio of the ship and the server speed limit. This function
returns a cofficient between 0.5 and ... |
def _strip_result(context_features):
"""Keep only the latest instance of each keyword.
Arguments
context_features (iterable): context features to check.
"""
stripped = []
processed = []
for feature in context_features:
keyword = feature['data'][0][1]
if keyword not in pro... |
def create_sim_props(k, phase):
"""Create simulation properties for planet.
Parameters
----------
k : integer
The Radial Velocity semiamplitude.
phase : list
Orbital phase of the object orbiting the star.
Returns
-------
dictionary
Dictionary containing RV Semi.... |
def clamp(value, smallest, largest):
"""Return `value` if in bounds else returns the exceeded bound"""
return max(smallest, min(value, largest)) |
def normalizeTextCase(text):
"""
Normalize the text casing.
"""
return text.lower() |
def _make_args(cmd, opts, os_opts, separator='-', flags=None, cmd_args=None):
"""
Construct command line arguments for given options.
"""
args = [""]
flags = flags or []
for k, v in opts.items():
arg = "--" + k.replace("_", "-")
args = args + [arg, v]
for k, v in os_opts.item... |
def _interpolate(a, b, fraction):
"""Returns the point at the given fraction between a and b, where
'fraction' must be between 0 and 1.
"""
return a + (b - a)*fraction; |
def strip(s, color=False):
"""strip(s, color=False) -> str
Strips the : from the start of a string
and optionally also strips all colors if
color is True.
"""
if len(s) > 0:
if s[0] == ":":
s = s[1:]
if color:
s = s.replace("\x01", "")
s = s.replace("\x0... |
def indices_for_prop_level_3d(prop_level: int, start_point: tuple) -> set:
"""
Returns the indices at a given propagation level away from start_point
in 3D
"""
x, y, z = start_point
indices = set([])
# Will double add corners, but no worries because we use a set
for i in range(-prop_leve... |
def open_data(filename):
"""open the data in a file (no need for an exact extension)"""
return open(filename).read() |
def high_entropy_passphrases_v2(s):
"""Check whether a sequece is a valid passphrase."""
mmap = {}
for word in s.split(' '):
k = ''.join(list(sorted(word)))
if k not in mmap:
mmap[k] = 0
mmap[k] += 1
if mmap[k] > 1:
return False
return True |
def parse_cookies_str(cookies):
"""
parse cookies str to dict
:param cookies: cookies str
:type cookies: str
:return: cookie dict
:rtype: dict
"""
cookie_dict = {}
for record in cookies.split(";"):
key, value = record.strip().split("=", 1)
cookie_dict[key] = value
... |
def appendToNewListAndReturnList(sequenceObject, element):
"""Return new list with one item (specified by elelement) appended"""
#newList = copy_module.deepcopy(list)
newList = list(sequenceObject)
newList.append(element)
return newList |
def to_list(x):
"""
Function to convert a list of list of elements to list of elements
:param x: list of list of objects
:return: list of objects
"""
return [a for b in x for a in b] |
def flatten(list):
""" Flattens a list of lists into a list."""
return [item for sublist in list for item in sublist] |
def get_total_timings(results, env, overhead_time):
""" Sum all timings and put their totals in the env """
total_framework_time = 0
total_strategy_time = 0
total_compile_time = 0
total_verification_time = 0
total_kernel_time = 0
if results:
for result in results:
if 'fra... |
def _unbool(element, true=object(), false=object()):
"""
A hack to make True and 1 and False and 0 unique for _uniq.
"""
if element is True:
return true
elif element is False:
return false
return element |
def is_empty_line(line: str) -> bool:
"""
Determines whether a line is empty or not.
"""
return len(line) == 0 or line.isspace() |
def join_nargs_arg(arg_value):
"""
Joins nargs argument values and returns a single array containing all the
individual values.
If the arg_value is not a list or a list of lists, the arg_value is
returned.
This function exists to handle the legacy syntax where arguments used
"append" over ... |
def undunder_keys(_dict):
"""Returns dict with the dunder keys converted back to nested dicts
eg::
>>> undunder_keys({'a': 'hello', 'b__c': 'world'})
{'a': 'hello', 'b': {'c': 'world'}}
:param _dict : (dict) flat dict
:rtype : (dict) nested dict
"""
def f(key, value):
... |
def build_source_url(username, repository):
"""
Create valid GitHub url for a user's repository.
:param str username: username of the repository owner
:param str repository: name of the target repository
"""
base_url = 'https://github.com/{username}/{repository}'
return base_url.format(user... |
def flatten(iterable, tr_func=None, results=None):
"""Flatten a list of list with any level.
If tr_func is not None, it should be a one argument function that'll be called
on each final element.
:rtype: list
>>> flatten([1, [2, 3]])
[1, 2, 3]
"""
if results is None:
results = ... |
def get_lat_long(rec):
"""
Parameters
----------
rec : dict
Audio recording record.
Returns
-------
Tuple of (latitude,longtidue) as floats.
Return (None,None) is error or missing
"""
try:
lat = rec["location"]["lat"]
long = rec["location"]["ln... |
def set_bits(register, value, index, length=1):
"""
Set selected bits in register and return new value
:param register: Input register value
:type register: int
:param value: Bits to write to register
:type value: int
:param index: Start index (from right)
:type index: int
:param le... |
def add_digits(s):
"""Assumes s is a string of digits
Returns the sum of the digits in s"""
val = 0
for c in s:
val += int(c)
return val |
def validate_search_inputs(row_id, search_column, search_value):
"""Function that determines if row_id, search_column and search_value are defined correctly"""
return_value = {
"valid": True,
"msg": None
}
a_search_var_defined = True if search_column or search_value else False
if r... |
def parse_message(message):
"""
!meme [meme name]; [(optional) text1]; [(optional) text2]
"""
args = []
template, top, bot = '', '', ''
try:
args = message.split('!meme')[1].split(';')
print(args)
cnt = len(args)
if cnt >= 1:
template = args[0].lst... |
def a2idx(j, n=None):
"""Return integer after making positive and validating against n."""
if type(j) is not int:
try:
j = j.__index__()
except AttributeError:
raise IndexError("Invalid index a[%r]" % (j,))
if n is not None:
if j < 0:
j += n
... |
def dict2overview_list(d):
"""Convert an overview dict to a list based on its keys."""
result = [0, 0, 0, 0]
for key in d:
if 'num_posts' in key:
result[0] = d[key]
if 'num_' in key and 'post' not in key:
result[1] = d[key]
if 'per' in key:
result[... |
def generate_bounds_for_fragments(x_size, y_size, move_size, image_dimension):
"""
Generate bounds for fragments, for an image of arbitrary size
Inputs:
x_size - width of the image
y_size - height of the image
move_size - pixels to move (horizontally and vertically) between each ste... |
def print_list(normal_list):
"""
:param normal_list: A normal Python list
:return: List items in a SQL command
"""
sql_list = str(normal_list)[1:-1] # Add quotes around each item within the list
return(sql_list) |
def create_element(type, props=None, *children):
""" Convenience function to create a dictionary to represent
a virtual DOM node. Intended for use inside ``Widget._render_dom()``.
The content of the widget may be given as a series/list of child nodes
(virtual or real), and strings. Strings are converte... |
def is_if_then(tokens):
""":note: we assume single-line if have been
transformed in preprocessing step."""
return tokens[0:1+1] == ["if","("] |
def fib_1_recursive(n):
"""
Solution: Brute force recursive solution.
Complexity:
Description: Number of computations can be represented as a binary
tree has height of n.
Time: O(2^n)
"""
if n < 0:
raise ValueError('input must be a positive whole number')
if n in [0, 1]:
return n
return fib_1_recursi... |
def last_updated_cell(i):
"""Make and return the last_updated cell at Column E."""
return "E{}".format(str(i)) |
def lie_bracket(element_1, element_2):
"""
Unfolds a Lie bracket. It is assumed that the second element is homogeneous (the bracket grows to the left).
Returns a string encoding the result of unfolding: each addend is represented as a sequence of indeces (which
are separated by '.'), the addends are sep... |
def get_area(coords):
"""Returns area of blank space"""
return (coords[1][0] - coords[0][0] + 1)*(coords[1][1] - coords[0][1] + 1) |
def euclidean_area(poly, precision=6):
"""
An implementation of Green's theorem, an algorithm to calculate area of
a closed polgon. This works for convex and concave polygons that do not
intersect oneself whose vertices are described by ordered pairs.
https://gist.github.com/rob-murray/11245628
... |
def int_to_hex_str(value, length=2):
"""
Convert an integer to a hex string.
Args:
value (int): The value to be converted
length (int): The number of characters of the output string. Default: 2
"""
# Make sure 'length' is of even length
if length % 2 != 0: length += 1
# G... |
def lr_schedule(epoch):
"""Learning Rate Schedule
Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs.
Called automatically every epoch as part of callbacks during training.
# Arguments
epoch (int): The number of epochs
# Returns
lr (float32): learning rate
... |
def calc_absorption(_SystemFrequency_, _SpeedOfSound_, _Salinity_, _Temperature_, _XdcrDepth_):
"""
Calculate the water absorption.
:param _SystemFrequency_: System frequency
:param _SpeedOfSound_: Speed of Sound m/s
:param _Salinity_: Salinity in ppt.
:param _Temperature_: Water Temperature in... |
def is_prime(num):
"""
This function checks whether the input natural number larger than 1 is a prime number.
:param num:
:return: boolean
"""
i = 2
while i ** 2 <= num:
if num % i == 0:
return False
i += 1
return True |
def next_pow2(x):
"""Find the closest pow of 2 that is great or equal or x,
based on shift_bit_length
Parameters
----------
x : int
A positive number
Returns
-------
_ : int
The cloest integer that is greater or equal to input x.
"""
if x < 0:
raise At... |
def is_valid_svd_string(ein_string: str) -> bool:
"""
Check the input ein_string is properly formatted for use in svd_flex
Args:
ein_string: See svd_flex for formatting restrictions
Returns:
is_valid: True if the format is valid, false otherwise
"""
# Parse ein_string into in... |
def get_location(metadata):
"""Get location from ip context metadata."""
city = metadata["city"]
country = metadata["country"]
country_code = metadata["country_code"]
location = []
if city:
location.append("{},".format(city))
if country:
location.append(country)
if count... |
def normalize_value(value):
"""Convert empty string to None"""
if value == '':
value = None
return value |
def create_add_message(event):
"""
Generates a add message that is broad-casted to all
market data subscribers.
"""
message = {}
message.update({'message-type': 'A'})
message.update({'timestamp': event['timestamp']})
message.update({'order-number': event['order_id']})
if event['side'] == 'bid':
message.upd... |
def get_matlab_prefix(filename: str) -> str:
"""
Returns the prefix of MatLab files, which sometimes have multiple "." characters in their filenames.
"""
return ".".join(filename.split(".")[:-2]) |
def rotate(string, n):
"""Rotate characters in a string.
Expects string and n (int) for number of characters to move.
"""
pref: str = ''
suf: str = ''
for pos in range(len(string)):
if n < 0:
if (len(string) + n) <= pos:
pref += string[pos]
els... |
def nfact(n: int) -> int:
"""
>>> nfact(5)
120
"""
if n == 0: return 1
return n*nfact(n-1) |
def snake_to_camelcase(name: str) -> str:
"""Convert snake-case string to camel-case string."""
return "".join(n.capitalize() for n in name.split("_")) |
def getValidKeywords(kw, func):
""" returns a dictionary containing the keywords arguments (in a list?) valid for a function.
Parameters
----------
kw : (check)
(check)
func : (check)
(check)
Returns
-------
filename : str
Path to the audio example file included ... |
def build_dummy_module_call(group_name, fifo_name, module_in, PE_ids):
"""Build the call of the dummy module
Parameters
----------
group_name: str
fifo_name: str
module_in: int
PE_ids: list
"""
dir_str = "out" if module_in == 0 else "in"
lines = []
lines.append("\n")
li... |
def pprettyprint(parsedxml):
"""pretty printer mainly for testing"""
st = bytes
if type(parsedxml) is st:
return parsedxml
(name, attdict, textlist, extra) = parsedxml
if not attdict: attdict={}
attlist = []
for k in attdict.keys():
v = attdict[k]
attlist.append("%s=%... |
def get_resized_size(org_h, org_w, long_size=513):
"""get_resized_size"""
if org_h > org_w:
new_h = long_size
new_w = int(1.0 * long_size * org_w / org_h)
else:
new_w = long_size
new_h = int(1.0 * long_size * org_h / org_w)
return new_h, new_w |
def parse_enum_constant(enum_constant_or_name, enum_type):
"""
Return the enumerated constant corresponding to 'enum_constant_or_name', which
can be either this constant or a its name (string).
"""
if isinstance(enum_constant_or_name, enum_type):
return enum_constant_or_name
else:
... |
def sort_vms_by_total_disksize(vms):
"""
sort vms by disk size from adding up the sizes of their attached disks
"""
return sorted(vms, key=lambda vm: vm.get_total_disksize(), reverse=True) |
def clearStaticTunnelTemplate(user):
"""
Generates ASA configuration to clear static IP allocation for users.
:param user: username ids that has a unique address pool and tunnel group
:type user: str
:return: configuration for the ASA
:rtype: str
"""
config = ""
... |
def eval_amount(item, namespace):
"""Evaluate expressions within the "amount" field of the item.
WARNING: not safe for use with untrusted input!
"""
if isinstance(item, dict) and isinstance(item.get("amount"), str):
amount = eval(item["amount"], {}, dict(namespace))
return {**item, "amo... |
def resp_to_string(resp):
"""Convert a resp (from the requests lib) to a string."""
if resp is None:
return "<resp is None!>"
msg = "\n----------------- Request -----------------"
msg += "\n[{2}] {0} {1}".format(
resp.request.method, resp.request.url, resp.status_code,
)
for k, v... |
def _elevation_color(elevation, sea_level=1.0):
"""
Calculate color based on elevation
:param elevation:
:return:
"""
color_step = 1.5
if sea_level is None:
sea_level = -1
if elevation < sea_level/2:
elevation /= sea_level
return 0.0, 0.0, 0.75 + 0.5 * elevation
... |
def time_str_fixer(timestr):
"""
timestr : str
output
rval : str
if year is 2006, hysplit trajectory output writes year as single digit 6.
This must be turned into 06 to be read properly.
"""
if isinstance(timestr, str):
temp = timestr.split()
year = str(int(temp[0])).zf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.