content stringlengths 42 6.51k |
|---|
def is_user(user):
"""
Validates user dict exists.
:param user: A dict object representing user
:return (bool, str): Bool for whether or not user is valid, String for justification.
"""
return (True, None) if user else (False, 'No user found') |
def plural(n, singular, plural, with_number=True):
"""Return the singular or plural form of a word, according to the number.
If ``with_number`` is true (default), the return value will be the number
followed by the word. Otherwise the word alone will be returned.
Usage:
>>> plural(2, "ox", "oxen"... |
def nub(l, reverse=False):
"""
Removes duplicates from a list.
If reverse is true keeps the last duplicate item
as opposed to the first.
"""
if reverse:
seen = {}
result = []
for item in reversed(l):
if item in seen: continue
seen[item] = 1
result.append(item)
return revers... |
def check_custom_dataloader(data: dict) -> bool:
"""Check if custom dataloader is used in calibration or evaluation."""
return any(
[
data.get("quantization", {}).get("dataloader", {}).get("name") == "custom",
data.get("evaluation", {}).get("dataloader", {}).get("name") == "custo... |
def is_any_list_overlap(list_a, list_b):
"""
Is there any overlap between two lists
:param list_a: Any list
:param list_b: Any other list
:return: True if lists have shared elements
"""
return any({*list_a} & {*list_b}) |
def sort_array(arr):
"""
Sorts only the odd numbers leaving the even numbers in place
:param: arr Array of numbers
:return sorted numbers with only the odds sorted by value and evens retain their place
:rtype: list
"""
odds = sorted([x for x in arr if x % 2], reverse=True)
return [x if x... |
def getclass(obj):
"""
Unfortunately for old-style classes, type(x) returns types.InstanceType. But x.__class__
gives us what we want.
"""
return getattr(obj, "__class__", type(obj)) |
def is_vowel(ch):
""" check if a char is a vowel """
if ch.lower() in list('aeiou'):
return True
return False |
def kth_element_to_last(linked_list, k):
"""Returns kth to last element of a linked list.
Args:
linked_list: An instance object of LinkedList.
k: Integer >=1, k=1 is last element, k=2 second to last, and so on.
Returns:
If kth to last element exists, returns value of data field.
... |
def extract_id(url):
"""
>>> extract_id('/bacon/eggs/')
'eggs'
"""
return url and url.split('/')[-2] |
def enketo_error500_mock(url, request): # pylint: disable=unused-argument
"""
Returns mocked Enketo Response object for all queries to enketo.ona.io that
may result in an HTTP 500 error response.
"""
return {'status_code': 500,
'content': "Something horrible happened."} |
def csv_int2bin(val):
"""format CAN id as bin
100 -> 1100100
"""
return f"{val:b}" |
def _convert_ratio_to_int(ratio: float):
"""
Round the ratio to 2 decimal places, multiply by 100, and take the integer part.
"""
return int((round(ratio, 2) * 100)) |
def is_search_type(splunk_record_key):
"""Return True if the given string is a search type key.
:param splunk_record key: The string to check
:type splunk_record_key: str
:rtype: bool
"""
return splunk_record_key == 'searchtype' |
def set_axis_limits(ax, xlimits=None, ylimits=None):
"""Sets the x- and y-boundaries of the axis (if provided)
:param ax: axis object
:param xlimits: a 2-tuple (lower_bound, upper_bound)
:param ylimits: a 2-tuple (lower_bound, upper_bound)
:returns: ax
"""
if xlimits is not None:
ax... |
def _type_name(x):
"""Generates a description of the type of an object."""
if isinstance(x, dict):
key_types = set(_type_name(key) for key in x.keys())
val_types = set(_type_name(key) for key in x.values())
return "({} containing {} keys and {} values)".format(
type(x), key_types, val_types)
i... |
def line(p1, p2, debug = False):
"""Creates a line from two points
From http://stackoverflow.com/a/20679579
Args:
p1 ([float, float]): x and y coordinates
p2 ([float, float]): x and y coordinates
Returns:
(float, float, float): x, y and _
"""
A = (p1[1] - p2[1])
B =... |
def sphere_function(vals):
"""
A very easy test function
Parameters:
vals - a list specifying the point in N-dimensionsla space to be
evaluated
"""
return sum(val**2 for val in vals) |
def f(x):
"""A real-valued function to optimized."""
return sum(x)**2 |
def splice_in_seq(new_seq: str, old_seq: str, full_seq: str) -> str:
"""
Replace old_seq with new_seq in full_seq. full_seq is expected to contain old_seq
>>> splice_in_seq("CASS", "CASR", "ABCDEFGCASRZZZ")
'ABCDEFGCASSZZZ'
>>> splice_in_seq("$$", "CASS", "ABCDEFGCASSYLMZ")
'ABCDEFG$$YLMZ'
>... |
def first_shift_is_valid(cur_individual):
""" checks if the first shift is not an extension """
return cur_individual[:2] != '00' |
def powerhalo(r,rs=1.,rc=0.,alpha=1.,beta=1.e-7):
"""return generic twopower law distribution
inputs
----------
r : (float) radius values
rs : (float, default=1.) scale radius
rc : (float, default=0. i.e. no core) core radius
alpha : (float, default=1.) inner halo slope
... |
def get_destroyed_endpoint(vol, array):
"""Return Destroyed Endpoint or None"""
try:
return bool(
array.get_volume(vol, protocol_endpoint=True, pending=True)[
"time_remaining"
]
!= ""
)
except Exception:
return False |
def clean_up_hero_name(hero_name):
"""
#This function will fix the hero name with a consistent naming scheme
"""
hero_name_replace = {
"spiderwoman":"Spider Woman",
"spider woman":"Spider Woman",
"spider-woman":"Spider Woman",
"spiderman":"Spider Man",
"spider man... |
def _build_js_asset(js_uri):
"""Wrap a js asset so it can be included on an html page"""
return '<script src="{uri}"></script>'.format(uri=js_uri) |
def unique_list_str(L):
""" Ensure each element of a list of strings is unique by appending a number to duplicates.
Note that this fails to generate uniqueness if a trio "Name", "Name", "Name_1" exists.
"""
L_unique = []
count = {}
for s in L:
if s in count:
s_unique = st... |
def _inches_to_meters(length):
"""Convert length from inches to meters"""
return length * 2.54 / 100.0 |
def calculate_cpu_metric(data, code, ram):
"""
This function calculates the cpu's data and general capability based upon the memory and RAM available to it. It
doesn't consider the speed of the chip. It calculates based on the following equation:
metric = (data/max_data + code/max_code + ram/max_ram) / ... |
def ensure_append_true_if_timed_append(
config,
extra_config,
app_type,
app_path,
):
"""
Sets the "APPEND" App Configuration variable automatically to "TRUE" if the "timed_append" option
is enabled.
:param config: Configuration dictionary (the one that gets exported to l... |
def text_convert(input) -> str:
"""
input: raw scraped html
"""
return "" if input is None else input.get_text().strip() |
def derive_sentiment_message_type(compound):
"""
Derives the type of the message based status of the sentiment
:param compound
:return: type of the message
"""
if compound > 0:
return "success"
elif compound == 0:
return "info"
else:
return "error" |
def set_to_zero(working_set, index):
"""Given a set and an index, set all elements to 0 after the index."""
if index == len(working_set) - 1:
return working_set
else:
for i in range(index + 1, len(working_set)):
working_set[i] = 0
return working_set |
def flattener(data):
"""
Flatten a nested dictionary. Namespace the keys with a period, assuming no periods in the keys.
:param dictionary: the nested dictionary
:return: the flattened dictionary with namespaces
>>> flattener([]) is None
True
>>> flattener(3) is None
True
>>> flatte... |
def cap(number, min_, max_):
"""Cap a value between a lower and/or upper bound (inclusive)"""
if min_ is not None and number < min_:
return min_
if max_ is not None and number > max_:
return max_
return number |
def get_errors(read, to_db=True):
""" list of all the errors from the read variables
:param read: the log file content
:param to_db: if False than the type on each item in the list is text, otherwise the type is json """
err = []
div = read.split("ERROR ")
for item in div:
if ite... |
def _nths(x,n):
""" Given a list of sequences, returns a list of all the Nth elements of
all the contained sequences
"""
return [l[n] for l in x] |
def nodes_to_int(head, reverse=True):
"""Converts linked list number structure to number string
for testing purposes.
:returns Number string representing node structure
"""
if head is None:
return None
curr = head
num_str = str(curr.data)
while curr.next is not None:
... |
def check_dictionary(src2trg: dict) -> dict:
"""
Check validity of PanLex dictionary:
- Each source token only has one target token
- Source and target tokens are strings
:param src2trg dict: PanLex dictionary
:rtype dict: validated PanLex dictionary
"""
out = {}
for k, v in... |
def update_dcid(dcid, prop, val):
"""Given a dcid and pv, update the dcid to include the pv.
Args:
dcid: current dcid
prop: the property of the value to add to the dcid
val: the value to add to the dcid
Returns:
updated dcid as a string
"""
val_dcid = val.split(":")[-... |
def turn_psql_url_into_param(postgres_url: str) -> dict:
"""
>>> turn_psql_url_into_param(
... 'postgres://USERNAME:PASSWORD@URL:PORT/USER?sslmode=SSLMODE') == {
... 'db_user':'USERNAME', 'db_password': 'PASSWORD', 'db_host': 'URL', 'db_port':
... 'PORT', 'db_name': 'USER', 'sslmode': 'SSLMODE'}
... |
def get_tests_to_run(test_list, test_params, cutoff, src_timings):
"""
Returns only test that will not run longer that cutoff.
Long running tests are returned first to favor running tests in parallel
Timings from build directory override those from src directory
"""
def get_test_time(test):
... |
def vol_color(errupt_date):
"""Returns string representing color of the volcano marker based on last erruption date.
Parameters
----------
errupt_date : str
Describes last erruption date according to data format.
One of the following 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'U', 'Q', ... |
def convert_bool(string):
"""Check whether string is boolean."""
if string == "True":
return True, True
elif string == "False":
return True, False
else:
return False, False |
def FilterStations(MasterStationList,data_files):
"""
Filter the files to download by those stations required
If station of remote file exists in master list, want to download,
else not.
"""
DownloadStationList=[]
for dfile in data_files:
station=dfile.filen.split('.')[0][:-5]... |
def calculate_time(start, end):
"""Pretty prints the time taken for an operation.
Args:
start (float): Start time of an operation.
end (float): End time of an operation.
Returns:
str: Pretty format the time taken for an operation.
"""
time_taken = int(round((end - start), ... |
def decimal_to_binary(num=2):
"""
Input: num, an int
Returns binary representation of num
"""
if num < 0:
is_neg = True
num = abs(num)
else:
is_neg = False
result = ''
if num == '0':
result = '0'
while num > 0:
result = str(num % 2) + result
... |
def gemini_path(request):
"""Return the path of a gemini database"""
gemini_db = "tests/fixtures/HapMapFew.db"
return gemini_db |
def flatten_weights(list_of_mats):
"""
Flatten the weights for storage
"""
flat_ndlist = []
for arr in list_of_mats:
flat_ndlist.append(arr.flatten().tolist())
flat_list = [item for sublist in flat_ndlist for item in sublist]
return flat_list |
def _phone2char(phones, char_max_len):
"""_phone2char."""
ini = -1
chars = []
phones_index = 0
for phone in phones:
if phone != ini:
chars.append(phone)
ini = phone
phones_index += 1
if len(chars) == char_max_len:
break
return chars, ph... |
def is_covered(read, position):
"""Returns true if position is covered by read, otherwise false."""
return position >= read[0] and position < read[0]+read[1] |
def hex_to_decimal(number):
"""
Calculates the decimal of the given hex number.
:param number: hex number in string or integer format
:return integer of the equivalent decimal number
"""
decimal = []
decimal_equivalents = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
... |
def find_next_biggest_with_same_1s(n):
"""Finds the next biggest number with the same number of 1 bits.
- Flips the rightmost 0 that has ones on its right (increases the value)
- Rearrange 1s on its right to lowest positions and flips highest of them
(decreases the value and creates same number of 1s... |
def has_length(dataset):
"""
Checks if the dataset implements __len__() and it doesn't raise an error
"""
try:
return len(dataset) is not None
except TypeError:
# TypeError: len() of unsized object
return False |
def integer_kth_root(n: int, k: int) -> int:
"""
Find the integer k-th root of n.
Credits:
http://stackoverflow.com/questions/15978781/how-to-find-integer-nth-roots
Solution based on Newton's method.
:param k: The root exponent.
:param n: The number to be rooted.
:return: The greatest i... |
def safe_value_fallback2(dict1: dict, dict2: dict, key1: str, key2: str, default_value=None):
"""
Search a value in dict1, return this if it's not None.
Fall back to dict2 - return key2 from dict2 if it's not None.
Else falls back to None.
"""
if key1 in dict1 and dict1[key1] is not None:
... |
def mod_inv(a, p):
"""Return x with x * a == 1 (mod p) for integers a, p.
p >= 1 must hold.
Raise ZerodivsionError if inversion is not possible
"""
assert p >= 1
a1, a2, x1, x2 = p, a % p, 0, 1
# Invert a modulo p with the extended Euclidean algorithm
while a2 > 0:
# assert x1 ... |
def _adjust_files(xs, adjust_fn):
"""Walk over key/value, tuples applying adjust_fn to files.
"""
if isinstance(xs, dict):
if "path" in xs:
out = {}
out["path"] = adjust_fn(xs["path"])
for k, vs in xs.items():
if k != "path":
ou... |
def affiliation(n, C):
"""Return the affiliation of n for a given
community C
Parameters
----------
n : object
C : list of sets
Community structure to search in
Returns
-------
aff : list of ints
Index of affiliation of n
Examples
--------
>>> C = [set(['a'... |
def _GetParallelUploadTrackerFileLinesForComponents(components):
"""Return a list of the lines for use in a parallel upload tracker file.
The lines represent the given components, using the format as described in
_CreateParallelUploadTrackerFile.
Args:
components: A list of ObjectFromTracker objects that ... |
def jaccard(xs, ys):
"""
Computes the Jaccard Similarity Coefficient
:param xs: set containing all the words in the random paper
:param ys: set containing all the words in the every paper
:return: return the Jaccard index, how similar are both sets
"""
return float(len(set(xs) & set(ys))) / ... |
def sorted_merge(a, b):
""" 10.1 Sorted Merge: You are given two sorted arrays, A and B, where A
has a large enough buffer at the end to hold B. Write a method to merge B
into A in sorted order.
"""
if len(a) == 0 and len(b) == 0:
return []
if len(a) == 0:
return b
if len(b) ... |
def set_scrollbars_hidden(hidden: bool) -> dict:
"""
Parameters
----------
hidden: bool
Whether scrollbars should be always hidden.
**Experimental**
"""
return {"method": "Emulation.setScrollbarsHidden", "params": {"hidden": hidden}} |
def str_delimited(results, header=None, delimiter="\t"):
"""
Given a tuple of tuples, generate a delimited string form.
>>> results = [["a","b","c"],["d","e","f"],[1,2,3]]
>>> print(str_delimited(results,delimiter=","))
a,b,c
d,e,f
1,2,3
Args:
result: 2d sequence of arbitrary ty... |
def get_dot_file_path(gname):
"""
For a graph named gname, this method returns the path to its dot file in
the dot_atlas directory.
Parameters
----------
gname : str
Returns
-------
str
"""
return "dot_atlas/good_bad_trols_" + gname + ".dot" |
def ns_id(tagname, suds_ns):
"""Adds namespace to tag"""
return '{{{0}}}{1}'.format(suds_ns[1], tagname) |
def _to_tuple(x):
"""
Converts an object into a tuple. If the object is not iterable, creates a one-element tuple containing the object.
Parameters
----------
x : object
Returns
-------
out : tuple
Tuple representing the object.
"""
try:
return tuple(x)
exce... |
def build_message(attr_name, val1, val2, details=""):
""" Build error message for is_has_traits_almost_equal and
is_val_almost_equal to return.
"""
type1 = type(val1)
type2 = type(val2)
msg = "Different {} {}. Types: {} vs {}. Values: \n{} \nvs \n{}"
msg = msg.format(attr_name, details, type... |
def transformBigValue(value):
"""
===========================================================================
Transform numerical input data using
X/100
===========================================================================
**Args**:
**Returns**:
None
"""
r ... |
def _swift_bool(bstring):
"""
Convert a SWIFT-VOevent style boolean string ('true'/'false') to a bool.
"""
if bstring == 'true':
return True
elif bstring == 'false':
return False
else:
raise ValueError("This string does not appear to be a SWIFT VOEvent "
... |
def strToBool(string):
""" Convert `"True"` and `"False"` to their boolean counterparts. """
if string.lower() == "true":
return True
elif string.lower() == "false":
return False
else:
err_str = f"{string} is not a boolean value!"
raise ValueError(err_str) |
def updateTasks(newTasks, oldTasks):
"""
Compare the old tasks against the new ones. This function is essential due
to the fact that a jupyter-notebook user may rewrite a task and the latest
version is the one that needs to be kept.
:param newTask: new Task code
:param tasks: existing tasks
... |
def boto_all(func, *args, **kwargs):
"""
Iterate through all boto next_token's
"""
resp = {}
ret = []
while True:
resp = func(*args, **kwargs)
for val in resp.values():
if type(val) is list:
ret.extend(val)
if not resp.get('NextToken', None):... |
def is_iterable(an_object, include_strings=True):
""" Returns True if an object is iterable, False otherwise. Iterable
types include lists, tuples, dicts, strings, numpy arrays, etc.
If include_strings is False, then strings are not considered iterable.
This is useful because often we use is_iterable()... |
def fluctuations(N_avg,N2_avg,**kwargs):
"""Calculate fluctuations in N from averages <N> and <N^2>."""
return N2_avg - N_avg**2 |
def format_list(data):
"""Return a formatted strings
:param data: a list of strings
:rtype: a string formatted to a,b,c
"""
return ', '.join(sorted(data)) |
def fibonacci(n):
"""TO RETURNS THE nth VALUE OF THE FABONACCI SERIES."""
fib = [0, 1]
if n < 0:
print('The number cannot be negative.')
return('The number cannot be negative.')
elif n > 999:
print('The number is too big. Please enter a number between 0 and 999.')
return(... |
def get_objects_name(objects):
""" Retrieves the names of objects.
Parameters:
objects (list): Objects to get names.
Returns:
list: Object names.
"""
names = []
for object in objects:
if object.name[-5:-3] == '}.':
names.append(object.name[:-4])
... |
def get_info(obj):
"""
get info from account obj
:type obj: account object
:param obj: the object of account
:return: dict of account info
"""
if obj:
return dict(db_instance_id=obj.dbinstance_id,
account_name=obj.account_name,
account_status=o... |
def make_pairs(seq1, seq2, merge_list, accumulator=0):
""" PART D: make_pairs() takes in two sequences (seq1, seq2) and returns a list of tuples. Each tuple contains a value from seq1 whose index matches the value in seq2. The "accumulator" argument is set to a default value of zero. On each recursive call the accu... |
def flatten_list(lst):
"""Function flattening list of lists.
Arguments:
lst - list (of lists).
Returns:
flattened - flattened list."""
flattened = []
for l in lst:
if isinstance(l, list):
flattened += flatten_list(l)
else:
flattened... |
def maybe(pattern):
""" a pattern that may or may not be present
:param pattern: an `re` pattern
:type pattern: str
:rtype: str
"""
return r'(?:{:s})?'.format(pattern) |
def rshift(integer: int, shift: int) -> int:
"""Logical right binary shift."""
if integer >= 0:
return integer >> shift
return (integer + 0x100000000) >> shift |
def logic(index, skip):
""" check modulus """
if index % skip == 0:
return True
return False |
def _find_one(target, name_or_provider):
"""Returns a list with the single given provider for a target.
This function supports legacy providers (referenced by name) and modern
providers (referenced by their provider object).
Args:
target: A target or list of targets whose providers should be
searc... |
def should_be_deactivated(message):
"""
Determines whether a message stands for an option to be turned off.
Args:
message(str): A message to test
Returns:
bool: True if the message is negative, False otherwise
"""
NEGATIVE_TERMS = ["deactivated", "disabled", "false", "no", "none"... |
def transformer(text):
"""Scrieti o functie care converteste in sir de caractere.
Convertire din UpperCamelCase in lowercase_with_underscores.
"""
out = ""
for c in text:
if c.isupper() and out == "":
out += c.lower()
elif c.isupper and not out[-1].isalnum():
... |
def complement(base):
""" Complement nucleotide """
d = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}
if base in d:
return d[base]
return base |
def nocomment(astr, com='!'):
"""
just like the comment in python.
removes any text after the phrase 'com'
"""
alist = astr.splitlines()
for i in range(len(alist)):
element = alist[i]
pnt = element.find(com)
if pnt != -1:
alist[i] = element[:pnt]
return '\... |
def walk_dict(d, path):
"""Walks a dict given a path of keys.
For example, if we have a dict like this::
d = {
'a': {
'B': {
1: ['hello', 'world'],
2: ['hello', 'again'],
}
}
}
Then ``walk_dict... |
def fmttimeshort(n):
""" fmttimeshort """
if n == 0:
return 'complete!'
try:
n = int(n)
assert n >= 0 and n < 5184000 # 60 days
except:
return '<unknown>'
m, s = divmod(n, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
if d >= 7:
return '-'
eli... |
def retrieve_time_from_location(location):
"""Used with the sort function."""
return location['time'] |
def cpu_profile(func, repetitions=1):
"""Profile the function `func`.
"""
import cProfile
import pstats
profile = cProfile.Profile()
profile.enable()
success = True
for _ in range(repetitions):
success = func()
if not success:
break
profile.disable()
#... |
def format_int(n: int) -> bytes:
"""Format an integer using a variable-length binary encoding."""
if n < 128:
a = [n]
else:
a = []
while n > 0:
a.insert(0, n & 0x7f)
n >>= 7
for i in range(len(a) - 1):
# If the highest bit is set,... |
def rhombus_area(diagonal_1, diagonal_2):
"""Returns the area of a rhombus"""
area = (diagonal_1 * diagonal_2) / 2
return area |
def break_str(prereqs):
"""
Break a string into multiline text.
"""
return ' \\\n\t'.join(prereqs) |
def get_set_vertices(g_or_n):
"""Get number of vertices from the graph, or just pass n itself
Return set of graph vertices, V = {1, 2,...n}
"""
if isinstance(g_or_n, int):
n = g_or_n
else:
g = g_or_n
n = len(g.vs)
V = list(range(1, n+1))
return V, n |
def y(x: float, slope: float, initial_offset: float = 0) -> float:
"""Same function as above, but this time with type annotations!"""
return slope * x + initial_offset |
def mod_test(equation, val):
"""
Comparison for the modulo binary search.
:equation: Equation to test
:val: Input to the division
"""
r1 = equation(val)
if r1 == None:
return None
if r1 == 0:
return 0
elif r1 != val:
return 1
elif r1 == val:
retu... |
def docker_command(command):
"""Format command as needed to run inside your db docker container.
:param str command: postgres command
:return: Terminal command
:rtype: str
"""
# Template for executing commands inside the db container
command_template = 'docker-compose exec -T db psql ' \
... |
def _to_capitalize(word: str):
""" :Header segment to capitalize
"""
return '-'.join([i.capitalize() for i in word.split('-')]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.