content stringlengths 42 6.51k |
|---|
def remove_empty_line(content: str) -> str:
"""
Remove all full empty line
"""
lines = content.split("\n")
lines_new = list()
for line in lines:
if line.strip():
lines_new.append(line)
new_content = "\n".join(lines_new)
return new_content |
def unflatten_dict(dictionary: dict, sep: str = ".") -> dict:
"""
Unflattens a dict, where keys and the keys from their subdirs are
separated by :param:`sep`
Parameters
----------
dictionary : dict
the dictionary to unflatten
sep : str
the separation string
Returns
... |
def warning_prettyprint(message, category, filename, lineno, line=None) -> str:
"""
Monkeypatch the default warning message printing so it's prettier.
"""
result = (
f'\nWARNING\n-------\n{message}\n\n'
)
return result |
def wrap_border(x, y, grid):
""" Detects border collision and adjusts
x and/or y to wrap to the other side
"""
rows = len(grid)
cols = len(grid[0])
if x >= cols:
x = x - cols
elif x < 0:
x = cols + x
if y >= rows:
y = y - rows
elif y < 0:
y = ro... |
def choose_string(g1, g2):
"""Function used by merge_similar_guesses to choose between 2 possible
properties when they are strings.
If the 2 strings are similar, or one is contained in the other, the latter is returned
with an increased confidence.
If the 2 strings are dissimilar, the one with the... |
def insertion_sort(array):
"""insertion sort""" #list = [8,4,23,42,16,15]
for i in range (1 , len(array)): # we consider the first element as sorted
temp = array[i] # pointer is the current element
# now we start comparing the anchor to the elements before it
j = i - 1
while j >=... |
def append_arguments(params_a, params_b):
""" Concatenates two argument strings. """
if len(params_a) == 0:
return params_b
elif len(params_b) == 0:
return params_a
else:
return params_a + ',' + params_b |
def update(cur_aggregate, new_value):
"""For a new value new_value, compute the new count, new mean, the new m_2.
* mean accumulates the mean of the entire dataset.
* m_2 aggregates the squared distance from the mean.
* count aggregates the number of samples seen so far.
"""
(count, mean, m_2) =... |
def get_fontext_synonyms(fontext):
"""
Return a list of file extensions extensions that are synonyms for
the given file extension *fileext*.
"""
return {'ttf': ('ttf', 'otf'),
'otf': ('ttf', 'otf'),
'afm': ('afm',)}[fontext] |
def as_word(number):
"""Convert a number in a word.
If this gets complex we will add the inflect module instead.
"""
ordinal = {
1: 'First',
2: 'Second',
3: 'Third'}
return ordinal.get(number, '{}th'.format(number)) |
def get_indexes(lst, sub_lst, compare_function=None):
"""Return the indexes of a sub list in a list.
:param lst: the list to search in
:param sub_lst: the list to match
:param compare_function: the comparaison function used
:type lst: list
:type sub_lst: list
:type compare_function: functi... |
def linear_search_recursive(array, item, index=0):
"""O(1) beacuse we are recursing here"""
# implement linear search recursively here
if item is not None:
if item == array[index]:
return index
else:
return linear_search_recursive(array, item, index+1)
# once implemented... |
def pad_trunc(data, maxlen):
""" For a given dataset pad with zero vectors or truncate to maxlen """
new_data = []
# Create a vector of 0's the length of our word vectors
zero_vector = []
for _ in range(len(data[0][0])):
zero_vector.append(0.0)
for sample in data:
if len(sampl... |
def isVertical(start, end):
"""
Given a line decide if it is vertical
"""
return start[0] == end[0] |
def create_dict(breadcrumbs, value=None):
"""
Created a dict out of the breadcrumbs in a recursive manner.
each entry in the breadcrumb should be a valid dictionary key.
If value is None, the last string within' the breadcrumbs becomes the
final value.
:param breadcrumbs:
:param value:
:... |
def optimizeAngle(angle):
"""
Because any rotation can be expressed within 360 degrees
of any given number, and since negative angles sometimes
are one character longer than corresponding positive angle,
we shorten the number to one in the range to [-90, 270[.
"""
# First, we put the new ang... |
def check_threshold(service, config_high_threshold, config_low_threshold, curr_util):
""" Checks whether Utilization crossed discrete threshold
Args:
service: Name of the micro/macroservice
config_high_threshold: Upper limit threshold to utilization set in config file
config_low_thresho... |
def registra_aluno(nome, ano_entrada, ano_nascimento, **misc):
"""Cria a entrada do registro de um aluno."""
registro = {'nome': nome,
'ano_entrada': ano_entrada,
'ano_nascimento': ano_nascimento}
for key in misc:
registro[key] = misc[key]
return regist... |
def tuple2str(t, n):
"""
Returns string representation of product state.
Parameters
----------
t : tuple
Product state.
n : int
Total number of spin-orbitals in the system.
"""
s = ""
for i in range(n):
if i in t:
s += "1"
else:
... |
def get_hashtag_spans(tokens):
"""
Finds the spans (start, end) of subtokes in a list of tokens
Args:
tokens: list[str]
Returns:
spans: list[tuple[int]]
"""
is_part = ["##" in t for t in tokens]
spans = []
pos_end = -1
for pos_start, t in enumerate(is_part):
if pos_start <= pos_end:
continue
if ... |
def parameter_key_function(parameter):
""" returns a key for sorting parameters """
value = {'RFC_IMPORT':1,
'RFC_CHANGING':2,
'RFC_TABLES':3,
'RFC_EXPORT':4}
return value[parameter['direction']] |
def version_tuple(version):
"""Get version tuple"""
parts = version.split('.')
return tuple(int(x) if x.isnumeric() else x for x in parts) |
def containsAny(seq, aset):
""" Check whether sequence seq contains ANY of the items in aset. """
for c in seq:
if c in aset: return True
return False |
def isbn_check (isbn):
"""
(string)-->(True or False)
Determines whether a 10 digit string is a valid ISBN. Isolates last number in input string, and computes/compares this value to the correct 10th digit obtained from a string with the first 9 digits of the input string.
Returns true if true, fals... |
def boyer_moore_voting_algorithm(arr: list) -> int:
"""
:param arr: list
:return: int
"""
res = arr[0] # Initialization
counter = 0 # Counter
for i in range(len(arr)):
if counter == 0:
res = arr[i]
counter = 1
elif res == arr[i]:
counter... |
def set_file_name(site, dates):
"""
Create the file name for the echogram based on the mooring site name,
and the date range plotted.
:param site: mooring site name
:param dates: date range shown in the plot
:return file_name: file name as a string created from the inputs
"""
file_name ... |
def gcd(a, b):
"""Compute gcd(a,b)
:param a: first number
:param b: second number
:returns: the gcd
"""
pos_a, _a = (a >= 0), abs(a)
pos_b, _b = (b >= 0), abs(b)
gcd_sgn = (-1 + 2*(pos_a or pos_b))
if _a > _b:
c = _a % _b
el... |
def round_grade(grade: int) -> int:
"""
Round the grade according to policy.
Parameters
----------
grade: int
Raw grade.
Returns
-------
rounded_grade: int
Rounded grade.
"""
if grade < 38:
rounded_grade = grade
else:
closest_multiple_5 = (gr... |
def Msg (TYPE, **kw):
"""
Craft a message
"""
m = kw
m['TYPE'] = TYPE
return m |
def check_if_duplicates(lst_img):
""" Check if given list contains any duplicates """
set_of_elems = set()
for elem in lst_img:
if elem in set_of_elems:
return True
else:
set_of_elems.add(elem)
return False |
def real_space_shape_2d_tag_from_real_space_shape_2d(real_space_shape_2d):
"""Generate a sub-grid tag, to customize phase names based on the sub-grid size used.
This changes the phase name 'phase_name' as follows:
real_space_shape_2d = None -> phase_name
real_space_shape_2d = 1 -> phase_name_real_spac... |
def constructLimitsOffsets(limit, offset):
""" Create a list of limit and offset pairs for partial fetching of maximum 100 apps.
Arguments:
limit -- the number of apps to fetch
offset -- the offset from where to start fetching
Returns:
A list of limit,offset pairs where limit is no larger than 100
"... |
def same_shape(t1: tuple, t2: tuple) -> bool:
"""
Returns True if t1 and t2 are the same shape.
False, otherwise."""
try:
return len(t1) == len(t2)
except:
return False |
def _q_start(query_seq, q_seq):
"""
returns the starting pytyon string index of query alignment (q_seq) in the query_sequence (query_seq)
:param query_seq: string full query sequence
:param q_seq: string alignment sequence (may contain gaps as "-")
:return:
:example:
>>_q_start(query_seq = ... |
def get_time_signature_code(number: int) -> str:
"""Return a string for a time signature number."""
if number > 10:
div, mod = divmod(number, 10)
return chr(57472 + div) + chr(57472 + mod)
return chr(57472 + number) |
def computeFraction( poi_messages, all_messages ):
""" compute the fraction of messages to/from a person that are from/to a POI """
fraction = 0
if poi_messages == 'NaN' or all_messages == 'NaN':
fraction = 'NaN'
else:
fraction = float(poi_messages)/all_messages
return fraction |
def get_file_id(service, file_name, mime_type=None, parent_id=None):
"""Return the ID of a Google Drive file
:param service: A Google Drive API service object
:param file_name: A string, the name of the file
:param mime_type: A string, optional MIME type of file to search for
:param parent_id: A st... |
def parse_float_gt0(value):
"""Returns value converted to a float. Raises a ValueError if value cannot
be converted to a float that is greater than zero.
"""
value = float(value)
if value <= 0:
msg = 'Invalid value [{0}]: require a number greater than zero'
raise ValueError(msg.forma... |
def hexpad(val: int, size: int = 4):
"""Compile integer into 4 char padded hex."""
if val > (1 << 8 * size) - 1:
raise Exception(
f"Cannot pack value larger than {hex((1 << 8 * size) - 1)}")
return hex(val)[2:].zfill(size).upper() |
def parse_key(key):
"""Deconstructs a DB key into the timestamp and designator.
"""
if not isinstance(key, str): key = key.decode()
des, ts, = key.split(',')
return (des, int(ts),) |
def closest_bin(q, bin_edges):
"""
Find closest bin to a q-value
:param float q: q-value
:param list bin_edges: list of bin edges
"""
for i in range(len(bin_edges)):
if q > bin_edges[i] and q <= bin_edges[i+1]:
return i
return None |
def stars_and_color_presence_checker(board: list) -> bool:
"""Checks if color blocks have same numbers and if stars and
ziros are in cells, in which they shouldn't be. Returns ture if
anything wrong is found.
>>> stars_and_color_presence_checker(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
... |
def snake_index_to_coordinates(index, x_dimension, y_dimension):
"""Obtain the column and row coordinates corresponding to a snake ordering
index on a 2-d grid.
"""
if index > x_dimension * y_dimension - 1:
raise ValueError('Index exceeds x_dimension * y_dimension - 1.')
row = index // x_di... |
def _compute_max_name_width(contracts: dict) -> int:
"""Return the maximum width needed by the function name column."""
return max(
len(function) for contract, functions in contracts.items() for function in functions
) |
def tags(reserved, request, response):
"""
:param reserved: Reserved for future use
:param request: Original request sent to device
:param response: Reply from device for request
:return: return a list of strings
:rtype: list
"""
r = []
if len(request) > 0:
r = ["scythe", "at... |
def to_iterable(value, allow_none=True):
"""
Tries to convert the given value to an iterable, if necessary.
If the given value is a list, a list is returned; if it is a string, a list
containing one string is returned, ...
:param value: Any object
:param allow_none: If True, the method returns ... |
def is_datetime_string(string: str) -> bool:
"""
Check if the string is date-like.
Parameters
----------
string : str
Returns
-------
is_date: bool
"""
from dateutil.parser import parse
try:
parse(string)
return True
except ValueError:
return F... |
def brand_penetration_rate(number_of_brand_purchasers, total_purchasers):
"""Returns the percentage of penetration rate for a brand.
Args:
number_of_brand_purchasers (int): Total number of unique purchasers of a brand.
total_purchasers (int): Total unique purchasers.
Returns:
Perce... |
def is_metoffice(sheet_cell):
"""Is this variable produced by the Met Office?"""
if not sheet_cell:
return False
not_producing_values = ['CHECK', 'FALSE']
for value in not_producing_values:
if value == sheet_cell.upper():
return False
return True |
def quicksort(ar:list):
"""
Sort a list with quicksort algorithm.
The quicksort algorithm splits a list into
two parts and recursively sorts those parts
by making swaps based on the elements value
in relation to the pivot value. It is an
O(n log(n)) sort.
Args:
ar: list to so... |
def significant(n, digits=3):
""""Returns a number rounded to some (default 3) significant digits.
significant(5882) == '5880'
significant(0.40032, 4) == '0.400'"""
if digits < 1:
raise ValueError('Digits must be >= 1')
integer_digits = len(str(int(n))) - (n < 0)
if i... |
def readable_lines(cmd):
"""
Goes through and places new lines to split up a command to make it
readable.
"""
result = ""
line_length = 0
for section in cmd:
if line_length + len(section) + 8 > 80:
line_length = 4
result += '\\\n'
result += ' ' * l... |
def check_imo_number(imo):
"""
do a basic integrity check of an IMO number
Args:
imo(str): the IMO number as a string
Returns:
True: if valid IMO number
False: invalid IMO number
"""
if len(imo) > 7:
return False
try:
lastdigit = imo[6]
total... |
def MakeUnique (s, in_use):
"""Return an identifier based on C{s} that is not in the given set.
The returned identifier is made unique by appending an underscore
and, if necessary, a serial number.
The order is : C{x}, C{x_}, C{x_2}, C{x_3}, ...
@param in_use: The set of identifiers already in us... |
def add_chars(w1, w2):
"""
Return a string containing the characters you need to add to w1 to get w2.
You may assume that w1 is a subsequence of w2.
>>> add_chars("owl", "howl")
'h'
>>> add_chars("want", "wanton")
'on'
>>> add_chars("rat", "radiate")
'diae'
>>> add_chars("a", "... |
def calc_bandwidth_rbs(bandwidth_mhz: float) -> str:
"""
Convert bandwidth in mhz to rbs
Args:
bandwidth_mhz: float, Bandwidth in mhz
Returns:
Bandwidth in rbs
"""
bandwidth_rbs = int(5 * bandwidth_mhz)
return str(bandwidth_rbs) |
def sizeof_fmt(num: int, suffix: str = "B") -> str:
"""
Human readable version of file size.
Supports:
- all currently known binary prefixes (https://en.wikipedia.org/wiki/Binary_prefix)
- negative and positive numbers
- numbers larger than 1,000 Yobibytes
- arbitrary units
... |
def make_segments(utts, recname, min_utt_len=2.0):
"""
Make kaldi friendly segments of the format recname-VWXYZ
Input: uttlist imported from transcription json, recname
"""
seglines = []
speakers = []
utt_ids = []
i = 0
for utt in utts:
utt_id = '{0}-{1:0=5d}'.format(recna... |
def get_descriptors(format=False):
"""Get DREAM challenge descriptors"""
if format:
result = [
"Intensity",
"Pleasantness",
"Bakery",
"Sweet",
"Fruit",
"Fish",
"Garlic",
"Spices",
"Cold",
... |
def distance(a, b):
"""
Calculate distance between coordinates a and b.
Params
------
a : tuple
b : tuple
Returns
-------
out : float
Squared distance between coordinates a and b.
"""
return (a[0] - b[0])**2 + (a[1] - b[1])**2 |
def break_():
"""Create a break statement."""
return ['break'] |
def turn_rightmost_0_bit(n: int) -> int:
"""
Turn on the rightmost 0-bit.
>>> bin(turn_rightmost_0_bit(0b11110001))
'0b11110011'
"""
return n | (n + 1) |
def array_to_string(arr, do_not_flatten_strings=True):
"""
Converts an array of objects to a comma separated string
"""
res = ""
if arr is None:
return None
if do_not_flatten_strings and isinstance(arr, str):
return arr
if hasattr(arr, '__iter__'):
for part in ... |
def find_all(l: list, sub: list) -> list:
"""
returns list of indices of all finds
"""
res = []
for l_i in range(len(l)):
match = True
for sub_i in range(len(sub)):
if l_i+sub_i >= len(l) or l[l_i+sub_i] != sub[sub_i]:
match = False
break... |
def init_global_params(run_settings):
"""
initialize global parameters
:run_settings: run settings dict, must contain
- dims
- max_iterations
- num_centroids
- threshold
:returns: GlobalParams list
"""
global_params = []
global_params.append(run_settings['num_... |
def __none_to_zero(string):
"""
Return '0' if the string is "none" or "null";
return the string itself otherwise.
@type string: C{string}
@param string: The string to test for values of "none" or "null".
@rtype: C{string}
@return: '0' if the string is "none" or "null", the string itself
... |
def AddIdx(idx):
"""Adds index value to a string for auto name generation."""
return '-%s' % str(idx) |
def dummy_get_app(*dummy):
""" dummy app """
return ["get"] |
def record_optional_paths(database, include_path_candidate, header):
"""Add optional path set into include path candidates database.
Optional include path if the source file location is
identical location of included header file location"""
if include_path_candidate not in database[header]["include_path... |
def sd(array):
"""
Calculates the standard deviation of an array/vector
"""
import numpy as np
array=np.array(array)
result= np.std(array)
return result |
def are_at_least_one_None(list_parameters):
"""returns list_parameters.at least one.is_None"""
for parameter in list_parameters:
if parameter is None:
return True
else:
continue
return False |
def ensure_str(obj):
"""
Converts bytes to a utf-8 string.
"""
if obj is None:
return None
if isinstance(obj, str):
return obj
if isinstance(obj, bytes):
return obj.decode('utf-8')
else:
raise TypeError("Must be bytes or str") |
def clean_numeric(x):
""" Convierte cualquier string a numeric limpiando cualquier formato. """
if isinstance(x, str):
x = ''.join(e for e in x if e.isnumeric() or e == '.')
return x |
def _squash_devicegroup(device_group, device_group_hierarchy_children):
"""Recursive function for determining all of a device group's child device groups"""
result = [device_group]
if device_group in device_group_hierarchy_children:
for child_dg in device_group_hierarchy_children[device_group]:
... |
def blacklist_lookup(ip_address, blacklist_mem_db):
""" Queries the in memory DB of blacklisted addresses for an IPv4 address. Returns the blacklist name
or `None` of no matching IP was found.
:param blacklist_mem_db: Object containing the in memory blacklist db.
:param ip_address: String IPv4 Network... |
def rotate(grid):
"""Rotate grid 90 deg to the right."""
rows = grid.split('\n')
return '\n'.join(''.join(chars) for chars in zip(*reversed(rows))) |
def get_results_value(results):
""" Gets the value in the last column of the first row of the ga results
:param results: dict: results from the ga analytics query
:return: int: the value from the results
"""
if results.get('rows', []):
return results.get('rows')[0][-1]
return None |
def strip_left(s, pattern):
"""
Strips a string left (start) of string if found. Otherwise, returns the original string.
:param s: str
:param pattern: str
:rtype: str
"""
if s.startswith(pattern):
return s[len(pattern):-1]
else:
return s |
def sum_positive_numbers(n):
"""
:returns sum of positive numbers
"""
if n == 0:
return 0
else:
return n + sum_positive_numbers(n - 1) |
def get_table_name(element):
"""
The function will return a fully qualified table name according to the logic applied to the processed element.
In this case, input data already provides the table name directly but it can be extended to more complex use cases.
"""
return 'PROJECT_ID:DATASET.' + element['type'] |
def guess_input_handler(seqs, add_seq_names=False):
"""Returns the name of the input handler for seqs."""
if isinstance(seqs, str):
if '\n' in seqs: # can't be a filename...
return '_input_as_multiline_string'
else: # assume it was a filename
return '_input_as_string'
... |
def make_posix_path(windows_path):
"""Convert a Windows path to a posix path"""
return windows_path.replace('\\', '/').replace('C:', '/c') |
def which(executable):
"""Equivalent of witch(1). Returns the path (if any) of executable."""
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(executable)
if fpath:
if is_exe(executable):
return executa... |
def _prefix_keys(old_dict, prefix):
"""Adds a prefix to all keys in a dict"""
new_dict = {}
for key, value in old_dict.items():
new_key = u"{} - {}".format(prefix, key)
new_dict[new_key] = old_dict[key]
return new_dict |
def get_package(package_info: dict) -> str:
"""Construct the package name and exact version to install."""
package_tag = f"{package_info['name']}=={package_info['version']}"
# The package is a local file
source = package_info.setdefault("source", {})
if source.get("type") == "file":
# Trim ... |
def typedvalue(value):
"""
Convert value to number whenever possible, return same value
otherwise.
>>> typedvalue('3')
3
>>> typedvalue('3.0')
3.0
>>> typedvalue('foobar')
'foobar'
"""
try:
return int(value)
except ValueError:
pass
try:
retu... |
def updateGameReleaseDate(gtitle: str, new_rdate: str) -> str:
"""Return a query to update the release date of a given game."""
return (f"UPDATE game "
f"SET release_date='{new_rdate}' "
f"WHERE title='{gtitle}';"
) |
def check_orientation(orientation):
"""
Check if orientation is valid input or not. Return True if is 'horizontal',
False if 'vertical', raise Error if invalid input
:param str orientation: str, allowed values are 'horizontal' and 'vertical'
:return: True if is horizontal, False if vertical
:rt... |
def get_step_lrf(n, decay, period):
""" Decays the learning rate by `decay` every `period` epochs.
Args:
n (int): current epoch
decay (float): 0.97
period (int): 1
"""
lrf = decay ** (n // period)
return lrf |
def merge_specializations(data, duplicated_courses, id):
"""
Merges specializations for the same course
"""
specializations = []
for course in data["courses"]:
if course["id"] == id:
for specialization in course["specializations"]:
specializations.append(specializ... |
def prettyTime(t):
""" prettyTime(t): input t comes in as seconds. Output is a str
with units attached (secs, mins, hrs, etc.)
"""
if t < 120:
return '%.2f secs' % (t)
t = t / 60.0
if t < 120:
return '%.2f mins' % (t)
t = t / 60.0
if t < 25:
return '%.2f hrs' % (t... |
def snake_to_camel(name):
"""Returns the camel case of the given snake cased input"""
parts = name.split('_')
return parts[0] + "".join(x.title() for x in parts[1:]) |
def _read_whole_file(file_path):
"""
Read a text file into a single string.
Assumes UTF-8 encoding.
"""
with open(file_path, "r", encoding="utf-8") as f:
return f.read() |
def trailing_zeros(number):
"""
Returns the 1-based index of the first bit set to 1 from the right side of a
32bit integer
>>> trailing_zeros(0)
32
>>> trailing_zeros(0b1000)
4
>>> trailing_zeros(0b10000000)
8
"""
if not number:
return 32
index = 0
while (numb... |
def all_prefixes(li):
"""
Returns all prefixes of a list.
Args:
li: list from which to compute all prefixes
Returns:
list of all prefixes
"""
return [tuple(li[:i + 1]) for i in range(len(li))] |
def version_is_compatible(imp_version, version):
"""Determine whether versions are compatible.
:param imp_version: The version implemented
:param version: The version requested by an incoming message.
"""
version_parts = version.split('.')
imp_version_parts = imp_version.split('.')
try:
... |
def counter_count(string):
"""String's counter() method is used."""
return {i: string.count(i) for i in string} |
def count_local_minmax(A):
"""
Count local max and min
@author Akafael
"""
n = len(A)
# Trivial Solution
if n <= 1:
return 1
# Calculate the diff
B = []
count = 0
isRising = False
isFalling = False
for i in range(1, n - 1):
B.append(A[i + 1] - A[i]... |
def distance_weights(pool, labels):
"""Calculate weights based on distance"""
weights = [0 for _ in range(len(labels))]
for i in pool:
for label in labels:
pool_label = i[0]
distance = i[1]
if pool_label == label:
weights[label] += 1 / distance... |
def bitwise_contains(a: int, b: int) -> bool:
"""Return True if any bit of mask `b` is contained in `a`."""
return bool(a & b) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.