content stringlengths 42 6.51k |
|---|
def is_valid_input(barcode):
"""
This function verifies if the barcode is 12 digits and if they are all positive numbers.
:param barcode: parameter that takes the user's input to check if it is a valid 12 digit or not
:return: Fruitful. a True or False Boolean value.
"""
if len(barcode) == 12 and barcode.isnumeric(): # checks the user's input to see if it is a valid 12 digit barcode
return True # true when the barcode is 12 digits
return False # returns false when it is not 12 digits input |
def heat_color (grade) :
"""Function to assign colors to coverage tables"""
if grade < 10.0 :
percentage_color = 'ff6666'
elif grade < 30.0 :
percentage_color = 'ffb366'
elif grade < 50.0 :
percentage_color = 'ffff66'
elif grade < 70.0 :
percentage_color = 'd9ff66'
elif grade < 90.0 :
percentage_color = '66ff66'
else :
percentage_color = '668cff '
return percentage_color |
def deleted_files(new, old):
"""The paths of all deleted files.
new and old are folder hashes representing the new state (i.e. the local copy)
and old state (i.e. what is currently on the web config.server)"""
return [f for f in old.keys() if f not in new] |
def _unparsed_dict_from_argv(argv):
"""Split command line arguments into a dict, without applying coercions.
"""
arg_dict = dict()
for arg in argv:
name, value = arg.split('=', 1)
arg_dict[name] = value
return arg_dict |
def n_ary_mask(d, n, offset):
"""Create a n-ary mask with n entries (a list of bool with each nth entry True)
Parameters
----------
d: int
numbers of entries in the mask
n: int
period of the mask
offset: int
offset of the True entries
Returns
-------
list of bool
True/False mask with each nth entry True
"""
return [(i + offset) % n == 0 for i in range(d)] |
def trim(lines):
"""
Remove lines at the start and at the end of the given `lines` that are :class:`~taxi.timesheet.lines.TextLine`
instances and don't have any text.
"""
trim_top = None
trim_bottom = None
_lines = lines[:]
for (lineno, line) in enumerate(_lines):
if hasattr(line, 'is_text_line') and line.is_text_line and not line.text.strip():
trim_top = lineno
else:
break
for (lineno, line) in enumerate(reversed(_lines)):
if hasattr(line, 'is_text_line') and line.is_text_line and not line.text.strip():
trim_bottom = lineno
else:
break
if trim_top is not None:
_lines = _lines[trim_top + 1:]
if trim_bottom is not None:
trim_bottom = len(_lines) - trim_bottom - 1
_lines = _lines[:trim_bottom]
return _lines |
def apply_mirror_boundary_conditions(coord, dim):
"""
Return the correct coordinate according to mirror boundary conditions
coord: a coordinate (x or y) in the image
dim: the length of the axis of said coordinate
"""
# If the coordinate is outside of the bounds of the axis, take its reflection inside the image
if coord < 0:
coord = -coord
elif coord >= dim:
coord = 2*(dim-1) - coord % (2*(dim-1))
# Else, do nothing
return int(coord) |
def parse_season_period(season_period_string):
"""Returns the season and period value from an id
Argument
--------
season_period_string : str
A string representation of the season_period_id
Returns
-------
tuple
A tuple of ``(season, period)``
"""
season, period = season_period_string.split("_")
season = int(season)
period = int(period)
return (season, period) |
def align_offset(offset, n):
"""given a byte offset, align it and return an aligned offset
"""
if n <= 0:
return offset
return n * ((offset + n - 1) // n) |
def stripNonAlpha(s):
""" Remove non alphabetic characters. E.g. 'B:a,n+a1n$a' becomes 'Banana' """
return ''.join([c for c in s if c.isalpha()]) |
def cache_hash(args: list, kargs: dict) -> int:
"""
Ensures that the hash calc does not trigger pickling which fails for FPLPandas objects.
"""
return hash((args, frozenset(kargs.items()))) |
def path(y):
"""Equation: x = a(y-h)^2 + k"""
a = - 110.0 / 160.0**2
x = a*y**2 + 110.0
return x, y |
def get_part_number(content) ->int:
"""Find part number"""
pindex = content.find('part-')
pnum = -1
if pindex > 0:
pnum = int(content[pindex+5:pindex+10])
return pnum |
def to_hex(string, spacer=" "):
"""
Converts a string to a series of hexadecimal characters.
Use the optional spacer argument to define a string that is placed between
each character.
Example:
>>> print to_hex("hello!", ".")
68.65.6C.6C.6F.21
>>> print to_hex("boop")
62 6F 6F 70
"""
return spacer.join('%02X' % ord(byte) for byte in string) |
def error_email_subject_doi(identity, doi):
"""email subject for an error email"""
return u"Error in {identity} JATS post for article {doi}".format(
identity=identity, doi=str(doi)
) |
def get_percentage(dif: int) -> int:
"""Calculate the percentage to die or recover dependent on the average time
Parameters
----------
dif: int
contains the difference between the average and the current time
Returns
-------
int:
percentage to die or recovers
"""
percentage = 5
if dif == 2:
percentage = 20
elif dif == 1:
percentage = 35
elif dif == 0:
percentage = 75
return percentage |
def changing_number_of_semicolons(number, digits=0):
""" """
return f"{number:.{digits}f}" |
def _create_html_file_content(translations):
"""Create html string out of translation dict.
Parameters
----------
tralnslations : dict
Dictionary of word translations.
Returns
-------
str:
html string of translation
"""
content = []
for i1, t in enumerate(translations):
if i1 > 0:
content.append("<br>")
content.append('<div class="translation">')
content.append('<div class="word">')
for w in t.word:
content.append("<h2>{word}</h2>".format(word=w))
content.append("</div>") # end `word`
for i2, t2 in enumerate(t.parts_of_speech):
if i2 > 0:
content.append("<br>")
content.append('<div class="part-of-speech">')
if t2.part is not None:
content.append('<p class="part-name">[{part}]</p>'.format(part=t2.part))
content.append("<ol>")
for m in t2.meanings:
content.append('<div class="meaning">')
mng = ["<strong><li>"]
for i3, mn in enumerate(m.meaning):
if i3 > 0:
mng.append(", ")
mng.append("<span>{meaning}</span>".format(meaning=mn))
mng.append("</li></strong>")
content.append("".join(mng))
content.append('<div class="examples">')
for e in m.examples:
exmpl = "<p><span>{ex}</span>".format(ex=e[0])
if e[1]:
exmpl += "<br><span>{tr}</span>".format(tr=e[1])
exmpl += "</p>"
content.append(exmpl)
content.append("</div>") # end `examples`
content.append("</div>") # end `meaning`
content.append("</ol>")
content.append("</div>") # end `part-of-speech`
content.append("</div>") # end `translation`
return "\n".join(content) |
def str2bool (v):
"""
Convert string expression to boolean
:param v: Input value
:returns: Converted message as boolean type
:rtype: bool
"""
return v.lower() in ("yes", "true", "t", "1") |
def _match_url_start(ref, val):
"""
Checks that the val URL starts like the ref URL.
"""
ref_parts = ref.rstrip("/").split("/")
val_parts = val.rstrip("/").split("/")[0:len(ref_parts)]
return ref_parts == val_parts |
def sum_of_squares(n: int) -> int:
"""
returns the sum of the first n squares
using the mathematical fact that
1^2 + 2^2 + ... + n^2 = n(n+1)(2n+1)/6
"""
return n * (n + 1) * (2 * n + 1) // 6 |
def _render(M):
"""Return a string representation of the matrix, M."""
return '\n'.join((''.join(row) for row in M)) |
def first_true_pred(predicates, value):
"""
Given a list of predicates and a value, return the index of first predicate,
s.t. predicate(value) == True.
If no such predicate found, raises IndexError.
>>> first_true_pred([lambda x: x%2==0, lambda x: x%2==1], 13)
1
"""
for num, pred in enumerate(predicates):
if pred(value):
return num
raise IndexError |
def make_variable_names_with_time_steps(number_of_lags, data_column_names):
"""
lagged W first, instantaneous W last, i.e.,
..., x1_{t-2}, x2_{t-2}, ..., x1_{t-1}, x2_{t-1}, ..., x1_{t}, x2_{t}, ...
"""
variable_names = []
for i in range(number_of_lags, 0, -1):
variable_names_lagged = [s + '(t-{})'.format(i) for s in data_column_names]
variable_names += variable_names_lagged
variable_names_t = [s + '(t)' for s in data_column_names]
variable_names += variable_names_t
return variable_names |
def hz2fft(fb, fs, nfft):
"""
Convert Bark frequencies to fft bins.
Args:
fb (np.array): frequencies in Bark [Bark].
fs (int): sample rate/ sampling frequency of the signal.
nfft (int): the FFT size.
Returns:
(np.array) : fft bin numbers.
"""
return (nfft + 1) * fb / fs |
def _tasklines_from_tasks(tasks):
"""
Parse a set of tasks (e.g. taskdict.tasks.values()) into tasklines
suitable to be written to a file.
"""
tasklines = []
for task in tasks:
metapairs = [metapair for metapair in task.items()
if metapair[0] != 'text']
meta_str = "; ".join("{}:{}".format(*metapair)
for metapair in metapairs)
tasklines.append('{} | {}\n'.format(task['text'], meta_str))
return tasklines |
def _vax_to_ieee_single_float(data):
"""Converts a float in Vax format to IEEE format.
data should be a single string of chars that have been read in from
a binary file. These will be processed 4 at a time into float values.
Thus the total number of byte/chars in the string should be divisible
by 4.
Based on VAX data organization in a byte file, we need to do a bunch of
bitwise operations to separate out the numbers that correspond to the
sign, the exponent and the fraction portions of this floating point
number
role : S EEEEEEEE FFFFFFF FFFFFFFF FFFFFFFF
bits : 1 2 9 10 32
bytes : byte2 byte1 byte4 byte3
"""
f = []
nfloat = int(len(data) / 4)
for i in range(nfloat):
byte2 = data[0 + i * 4]
byte1 = data[1 + i * 4]
byte4 = data[2 + i * 4]
byte3 = data[3 + i * 4]
# hex 0x80 = binary mask 10000000
# hex 0x7f = binary mask 01111111
sign = (byte1 & 0x80) >> 7
expon = ((byte1 & 0x7f) << 1) + ((byte2 & 0x80) >> 7)
fract = ((byte2 & 0x7f) << 16) + (byte3 << 8) + byte4
if sign == 0:
sign_mult = 1.0
else:
sign_mult = -1.0
if 0 < expon:
# note 16777216.0 == 2^24
val = sign_mult * (0.5 + (fract / 16777216.0)) * pow(2.0, expon - 128.0)
f.append(val)
elif expon == 0 and sign == 0:
f.append(0)
else:
f.append(0)
# may want to raise an exception here ...
return f |
def get_catch_message(percent_complete, creature) -> str:
"""
Used to generate the display message when we try to catch a creature.
"""
if percent_complete <= 25:
return "Not even close!"
elif percent_complete <= 50:
return "Well, that could have gone worse"
elif percent_complete <= 70:
return "I'll totally get it next time!"
elif percent_complete < 100:
return "Damn...so close!"
else:
return "Gotcha! {0} was caught".format(creature.creature.in_battle_name()) |
def flattened_indices_from_row_col_indices(row_indices, col_indices, num_cols):
"""Get the index in a flattened array given row and column indices."""
return (row_indices * num_cols) + col_indices |
def in_line(patterns, line):
"""Check if any of the strings in the list patterns are in the line"""
return any([p in line for p in patterns]) |
def binary_search_recursive(array, lb, ub, target):
"""
Search target element in the given array by recursive binary search
- Worst-case space complexity: O(n)
- Worst-case performance: O(log n)
:param array: given array
:type array: list
:param lb: index of lower bound
:type lb: int
:param ub: index of upper bound
:type ub: int
:param target: target element to search
:type target: Any
:return: index of target element, -1 for not found
:rtype: int
"""
# check base case
if len(array) == 0 or ub < lb:
return -1
mid = lb + (ub - lb) // 2
# if element is present at the middle itself
if target == array[mid]:
return mid
# if element is larger than mid, then it
# can only be present in right subarray
elif target > array[mid]:
return binary_search_recursive(array, mid + 1, ub, target)
# else the element can only be present
# in left subarray
else:
return binary_search_recursive(array, lb, mid - 1, target) |
def get_parser_from_config(base_config, attributes, default_parser):
"""
Checks the various places that the parser option could be set and returns
the value with the highest precedence, or `default_parser` if no parser was found
@param base_config: a set of log config options for a logfile
@param attributes: a set of attributes to apply to a logfile
@param default_parser: the default parser if no parser setting is found in base_config or attributes
"""
# check all the places `parser` might be set
# highest precedence is base_config['attributes']['parser'] - this is if
# `com.scalyr.config.log.attributes.parser is set as a label
if "attributes" in base_config and "parser" in base_config["attributes"]:
return base_config["attributes"]["parser"]
# next precedence is base_config['parser'] - this is if
# `com.scalyr.config.log.parser` is set as a label
if "parser" in base_config:
return base_config["parser"]
# lowest precedence is attributes['parser'] - this is if
# `parser` is a label and labels are being uploaded as attributes
# and the `parser` label passes the attribute filters
if "parser" in attributes:
return attributes["parser"]
# if we are here, then we found nothing so return the default
return default_parser |
def convert_to_boolean(string):
"""
Shipyard can't support passing Booleans to code, so we have to convert
string values to their boolean values.
"""
if string in ['True', 'true', 'TRUE']:
value = True
else:
value = False
return value |
def number_alleles(alleles, ref_allele):
"""
Add VCF_type numbering to alleles
:param alleles: list
List of alleles
:param ref_allele: str
Reference allele
:return: dict
A dictionary mapping alleles to number
"""
numbering = dict()
counter = 1
for a in alleles:
if a != ref_allele:
numbering[a] = counter
counter += 1
numbering[ref_allele] = 0
return numbering |
def make_a_tweet(revision, message, url):
"""
Generate a valid tweet using the info passed in.
"""
return revision + ': ' + message + ' | ' + url |
def reverse_recursive(lst):
"""Returns the reverse of the given list.
>>> reverse_recursive([1, 2, 3, 4])
[4, 3, 2, 1]
>>> import inspect, re
>>> cleaned = re.sub(r"#.*\\n", '', re.sub(r'"{3}[\s\S]*?"{3}', '', inspect.getsource(reverse_recursive)))
>>> print("Do not use lst[::-1], lst.reverse(), or reversed(lst)!") if any([r in cleaned for r in ["[::", ".reverse", "reversed"]]) else None
"""
"*** YOUR CODE HERE ***"
if len(lst) == 0:
return []
return [lst[-1]] + reverse_recursive(lst[:-1]) |
def get_positions_to_update(screen_layout, table_position, delta):
""" return dict of items representing categories and updated positions within screen layout
"""
positions = {}
for category, data in screen_layout.items():
(y_pos, x_pos) = data.get('position', (0, 0))
if y_pos > table_position:
positions[category] = (y_pos - delta, x_pos)
return positions |
def to_swap_case(word: str):
"""
The 'swapcase()' method converts all uppercase
characters to lowercase and all lowercase characters
to uppercase characters of the 'word' string.
:param word: the string to be swapcased
:return: the swap-cased string
"""
return word.swapcase() |
def defaultRecordSizer(recordLines):
"""
return the total number of characters in the record text
"""
size = 0
for line in recordLines:
size += len(line)
return size |
def _create_udf_name(func_name: str, command_id: str, context_id: str) -> str:
"""
Creates a udf name with the format <func_name>_<commandId>_<contextId>
"""
return f"{func_name}_{command_id}_{context_id}" |
def get_class_name(obj):
"""Get class name in dot separete notation
>>> from datetime import datetime
>>> obj = datetime.datetime(2000, 1, 1)
>>> get_class_name(obj) -> "datetime.datetime"
>>> from collections import deque
>>> obj = deque([1, 2, 3])
>>> get_class_name(obj) -> "collections.deque"
"""
return obj.__class__.__module__ + "." + obj.__class__.__name__ |
def is_dict(d):
""" additional template function, registered with web.template.render """
return type(d) is dict |
def tree_checker(tree):
""""Help function to check binary tree correctness."""
if tree is None or tree.value is None:
return True
if tree.right_child is not None and tree.right_child.value < tree.value:
return False
if tree.left_child is not None and tree.left_child.value > tree.value:
return False
return all([tree_checker(tree.left_child),
tree_checker(tree.right_child)]) |
def is_foul_on_opponent(event_list, team):
"""Returns foul on opponent"""
is_foul = False
is_foul_pt2 = False
for e in event_list[:2]:
if e.type_id == 4 and e.outcome == 0 and e.team != team:
is_foul = True
elif e.type_id == 4 and e.outcome == 1 and e.team == team:
is_foul_pt2 = True
return is_foul and is_foul_pt2 |
def getValue(obj, path, defaultValue=None, convertFunction=None):
""""Return the value as referenced by the path in the embedded set of dictionaries as referenced by an object
obj is a node or edge
path is a dictionary path: a.b.c
convertFunction converts the value
This function recurses
"""
if obj is None:
return defaultValue
if not path:
return convertFunction(obj) if convertFunction and obj is not None else (defaultValue if obj is None else obj)
current = obj
part = path
splitpos = path.find(".")
if splitpos > 0:
part = path[0:splitpos]
path = path[splitpos + 1:]
else:
path = None
bpos = part.find('[')
pos = 0
if bpos > 0:
pos = int(part[bpos + 1:-1])
part = part[0:bpos]
if part in current:
current = current[part]
if type(current) is list or type(current) is tuple:
if bpos > 0:
current = current[pos]
else:
result = []
for item in current:
v = getValue(item, path, defaultValue=defaultValue, convertFunction=convertFunction)
if v is not None:
result.append(v)
return result
return getValue(current, path, defaultValue=defaultValue, convertFunction=convertFunction)
return defaultValue |
def location_to_index(location, spacing, shape):
"""Convert a location to an index.
Parameters
----------
location: tuple of float or None
Location of source in m. If None is passed at a certain location
of the tuple then the source is broadcast along the full extent
of that axis. For example a source of `(0.1, 0.2, 0.1)` is a
point source in 3D at the point x=10cm, y=20cm, z=10cm. A source of
`(0.1, None, 0.1)` is a line source in 3D at x=10cm, z=10cm extending
the full length of y.
spacing : float
Spacing of the grid in meters. The grid is assumed to be
isotropic, all dimensions use the same spacing.
shape : tuple of int
Shape of the grid. This constrains the valid indices allowed.
Returns
-------
tuple of int or slice
Location of source in grid. Where source is broadcast along
the whole axis a slice is used.
"""
index = tuple(int(loc // spacing) if loc is not None else None for loc in location)
# Ensure index is positive
index = tuple(max(0, ind) if ind is not None else None for ind in index)
# Ensure index is less than shape
index = tuple(min(s-1, ind) if ind is not None else None for s, ind in zip(shape, index))
index = tuple(ind if ind is not None else slice(None) for ind in index)
return index |
def replace_unknown_token(token, dictionary):
""" Checks whether the token is in the given dictionary.
If not it is replaced by an UNK token
Arguments:
token {string} -- the token to be checked and eventually replaced
dictionary {dict} -- the dictionary
Returns:
string -- the new token
"""
if token not in dictionary:
return "_unk_"
return token |
def _number(string):
"""
Extracts an int from a string.
Returns a 0 if None or an empty string was passed.
"""
if not string:
return 0
elif string == "":
return 0
else:
try:
return int(string)
except ValueError:
return float(string) |
def get_nice_size(size, base=1000.0):
"""
Convert number of bytes to string with KB, MB, GB, TB suffixes
"""
if size < base:
return '%sB' % (size)
if size < base**2:
return '%.2fKB' % (size / base)
if size < base**3:
return '%.2fMB' % (size / base**2)
if size < base**4:
return '%.2fGB' % (size / base**3)
return '%.2fTB' % (size / base**4) |
def field_key(key):
"""Create the correct key for a field
Needed because you cannot pass '*password' as a kwarg
"""
if key == "password":
return "*password"
else:
return key |
def inodefree(parameter='nodisk'):
"""
Get percentage of inodes free on filesystem
"""
return 'disk', '0' |
def contains(value, lst):
""" (object, list of list of object) -> bool
Return whether value is an element of one of the nested lists in lst.
>>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])
True
"""
found = False # We have not yet found value in the list.
for i in range(len(lst)):
for j in range(len(lst[i])):
if lst[i][j] == value:
found = True
#for sublist in lst:
# if value in sublist:
# found = True
return found |
def _stringify_tensor(obj):
"""Try to stringify a tensor."""
if hasattr(obj, 'name'): return obj.name
else: return str(obj) |
def splitList(listToSplit, num_sublists=1):
"""
Function that splits a list into a given number of sublists
Reference: https://stackoverflow.com/questions/752308/split-list-into-smaller-lists-split-in-half
"""
length = len(listToSplit)
return [ listToSplit[i*length // num_sublists: (i+1)*length // num_sublists]
for i in range(num_sublists) ] |
def parse_gff_attributes(attr_str):
"""
Parses a GFF/GTF attribute string and returns a dictionary of name-value
pairs. The general format for a GFF3 attributes string is
name1=value1;name2=value2
The general format for a GTF attribute string is
name1 "value1" ; name2 "value2"
The general format for a GFF attribute string is a single string that
denotes the interval's group; in this case, method returns a dictionary
with a single key-value pair, and key name is 'group'
"""
attributes_list = attr_str.split(";")
attributes = {}
for name_value_pair in attributes_list:
# Try splitting by '=' (GFF3) first because spaces are allowed in GFF3
# attribute; next, try double quotes for GTF.
pair = name_value_pair.strip().split("=")
if len(pair) == 1:
pair = name_value_pair.strip().split("\"")
if len(pair) == 1:
# Could not split for some reason -- raise exception?
continue
if pair == '':
continue
name = pair[0].strip()
if name == '':
continue
# Need to strip double quote from values
value = pair[1].strip(" \"")
attributes[name] = value
if len(attributes) == 0:
# Could not split attributes string, so entire string must be
# 'group' attribute. This is the case for strictly GFF files.
attributes['group'] = attr_str
return attributes |
def isMatch(text, pattern):
"""
:type s: str
:type p: str
:rtype: bool
isMatch will return whether a string matches a provided patter. The pattern supports literals, ?, and * wildcard characters with the following rules:
? matches exactly one of any character
* matches 0 or more of any character (ex. "*a" will match "a", "aaa", and "")
Cannot handle cases such as s = "aaaaaa" p = "?a*" because the "a*" will match all 'a' characters and will leave any other matches with no characters left to parse
"""
# if empty s, every character must be optional
if len(text) == 0:
# funky python list comprehension
return pattern == "*" or all([x == "*" for x in pattern[1::2]])
if pattern == "*" and text != "":
return False
# Uncomment this to support multiple * characters in a row.
# pattern = "*".join([x for x in pattern.split("*") if x != ''])
# string is reversed, so start at the last index
pattern_index = len(pattern) - 1
prev_char = None
# Loop through the reversed string
for string_index, character in enumerate(reversed(text)):
# if prev_char is set, it means we're currently matching against a * wildcard group
if prev_char == character:
continue
elif prev_char != None:
# we've hit the end of the repeating character match group
prev_char = None
pattern_index = pattern_index - 1
# if we got to the end of the pattern, but not the end of the string, we don't match
if pattern_index < 0:
return False
if pattern[pattern_index] == "*":
# if the first character in the pattern...
if pattern_index == 0 and string_index == len(text) - 1:
return True
pattern_index = pattern_index - 1
if character == pattern[pattern_index]:
prev_char = pattern[pattern_index]
else:
pattern_index = pattern_index - 1
elif pattern[pattern_index] == "?":
pattern_index = pattern_index - 1
else:
if character != pattern[pattern_index]:
return False
pattern_index = pattern_index - 1
return True |
def shake(iterable, cmp_function):
"""
The cocktail shaker sort is an improvement on the Bubble Sort. The improvement
is basically that values "bubble" both directions through the array, because
on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards.
Example:
# Sort ascending
li = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
def cmp_function(a, b):
if a == b:
return 0
elif a < b:
return -1
else:
return 1
li = shake(li, cmp_function)
# li is now [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# for descending order use the following cmp_function
def cmp_function(a, b):
if a == b:
return 0
elif a < b:
return 1
else:
return -1
Input:
iterable - list object
cmp_function - the function used for comparing
Output:
list object sorted
"""
range_index = range(len(iterable) - 1)
swapped = True
while swapped:
swapped = False
# go ascending
for i in range_index:
if cmp_function(iterable[i], iterable[i + 1]) == 1:
# swap
iterable[i], iterable[i + 1] = iterable[i + 1], iterable[i]
swapped = True
# we can exit the outer loop here if no swaps occurred.
if not swapped:
break
swapped = False
# go descending
for i in reversed(range_index):
if cmp_function(iterable[i], iterable[i + 1]) == 1:
# swap
iterable[i], iterable[i + 1] = iterable[i + 1], iterable[i]
swapped = True
return iterable
# while True:
# for index in (range_index, reversed(range_index)):
# swapped = False
# for i in index:
# if cmp_function(iterable[i], iterable[i+1]) == 1:
# # swap
# iterable[i], iterable[i+1] = iterable[i+1], iterable[i]
# swapped = True
#
# if not swapped:
# return |
def two_oldest_ages(ages):
"""Return two distinct oldest ages as tuple (second-oldest, oldest)..
>>> two_oldest_ages([1, 2, 10, 8])
(8, 10)
>>> two_oldest_ages([6, 1, 9, 10, 4])
(9, 10)
Even if more than one person has the same oldest age, this should return
two *distinct* oldest ages:
>>> two_oldest_ages([1, 5, 5, 2])
(2, 5)
"""
# NOTE: don't worry about an optimized runtime here; it's fine if
# you have a runtime worse than O(n)
# NOTE: you can sort lists with lst.sort(), which works in place (mutates);
# you may find it helpful to research the `sorted(iter)` function, which
# can take *any* type of list-like-thing, and returns a new, sorted list
# from it.
uniq_ages = set(ages)
# we need to convert the set back into a list in order to use the built in list functions
# We can't use list and need to use sorted because set is unordered. Also sorted instead of sort since sort does not return anything, it mutates the list in place while sorted will create a new list.
oldest = sorted(uniq_ages)[-2:]
return tuple(oldest) |
def format_list(l):
"""pleasing output for dc name and node count"""
if not l:
return "N/A"
return "{ %s }" % ", ".join(l) |
def _is_inv_update_task(task_id, num_tasks):
"""Returns True if this task should update K-FAC's preconditioner."""
if num_tasks < 3:
return False
return task_id == num_tasks - 1 |
def validate_range(value, lower=None, upper=None):
""" validate that the given value is between lower and upper """
try:
if (lower is None or lower <= value) and (upper is None or value <= upper):
return value
except TypeError:
pass
return None |
def _is_chrome_only_build(revision_to_bot_name):
"""Figures out if a revision-to-bot-name mapping represents a Chrome build.
We assume here that Chrome revisions are always > 100000, whereas WebRTC
revisions will not reach that number in the foreseeable future.
"""
revision = int(revision_to_bot_name.split('--')[0])
bot_name = revision_to_bot_name.split('--')[1]
return 'Chrome' in bot_name and revision > 100000 |
def InsertAtPos(src, pos, other):
"""Inserts C{other} at given C{pos} into C{src}.
@note: This function does not modify C{src} in place but returns a new copy
@type src: list
@param src: The source list in which we want insert elements
@type pos: int
@param pos: The position where we want to start insert C{other}
@type other: list
@param other: The other list to insert into C{src}
@return: A copy of C{src} with C{other} inserted at C{pos}
"""
new = src[:pos]
new.extend(other)
new.extend(src[pos:])
return new |
def deepget(mapping, path):
"""Access deep dict entry."""
if ':' not in path:
return mapping[path]
else:
key, sub = path.split(':', 1)
return deepget(mapping[key], sub) |
def file_as_bytes(file):
"""Reads file as binary.
Args:
file: File to read as binary
Returns:
binary file
"""
with file:
return file.read() |
def encode_rot13(string: str):
"""Encodes the string using ROT-13.
Example:
>>> encode_rot13('hello')\n
'uryyb'
>>> decode_rot13('uryyb')\n
'hello'
"""
import codecs
return codecs.encode(string, "rot13") |
def tagsoverride(msg, override):
"""
Merge in a series of tag overrides, with None
signaling deletes of the original messages tags
"""
for tag, value in override.items():
if value is None:
del msg[tag]
else:
msg[tag] = value
return msg |
def tuple_to_string(coord):
"""Return a colon-delimited string.
Parameters
----------
coord : tuple of 3 ints
The coordinate to transform.
Returns
-------
str
The colon-delimited coordinate string.
"""
return ":".join([str(x) for x in coord]) |
def categories_to_string(categories, queryset=False):
"""
Args:
categories: [{"title": "Business"}, ...] OR
[models.Category] (if queryset=True)
Returns:
['<category.title', ...]
"""
if queryset:
new_categories = [i.title for i in categories]
else:
new_categories = [i['title'] for i in categories]
return str(sorted(new_categories)) |
def get_pecha_num_list(pechas):
"""Extract all the pecha numbers from `catalog_data.
Args:
pechas (list): list of pecha metatdata in list.
Returns:
list: list of pecha numbers.
"""
return [int(pecha[0][2:8]) for pecha in pechas] |
def _text_box(value, max_rows = 5, max_chars = 50):
"""
a = dictable(a = range(10)) * dict(b = range(10))
b = (dictable(a = range(5)) * dict(b = range(5))) * dict(c = range(10))
self = c = dictable(key = ['a', 'b'] * 5, rs = [a,b]*5)
"""
v = str(value)
res = v.split('\n')
if max_rows:
res = res[:max_rows]
if max_chars:
res = [row[:max_chars] for row in res]
return res |
def filter_by_device_name(items, device_names, target_device_name):
"""Filter a list of items by device name.
Args:
items: A list of items to be filtered according to their corresponding
device names.
device_names: A list of the device names. Must have the same legnth
as `items`.
target_device_name: A `str` representing the desired device name.
Returns:
Filtered items from `items`.
"""
assert len(items) == len(device_names)
assert all(device_names), "device_names are not all non-empty strings"
# Note: we use `endswith` instead of `==` for device-name filtering because
# in some cases, the device names from kernel/op execution can have slightly
# different values than the device names from
# `distribution.extended.worker_devices`.
return [items[i] for i, device_name in enumerate(device_names)
if device_name.endswith(target_device_name)] |
def parseMeasurement(messageLine, streamFormat):
"""Parses get_stream measurement line into list of tuples.
Must contain same amount of items that the formatting has provided"""
meas = messageLine.strip().split('\t')
if len(meas) == len(streamFormat):
# zip() is a neat python built in function that combines two lists to one list of tuples when typed to list()
return list(zip(streamFormat, meas))
else:
return None |
def validateLabel(value):
"""
Validate descriptive label.
"""
if 0 == len(value):
raise ValueError("Descriptive label for friction model not specified.")
return value |
def make_carousel(columns, ratio=None, size=None):
"""
create carousel message content.
reference
- `Common Message Property <https://developers.worksmobile.com/jp/document/100500808?lang=en>`_
"""
content = {"type": "carousel", "columns": columns}
if ratio is not None:
content["imageAspectRatio"] = ratio
if size is not None:
content["imageSize"] = size
return content |
def stripfalse(seq):
"""Returns a sequence with all false elements stripped out of seq.
"""
return [x for x in seq if x] |
def build_query_string(query_words):
"""Builds an OR concatenated string for querying the Twitter Search API.
Args:
query_words (list): list of words to be concatenated.
Returns:
list: List of words concatenated with OR.
"""
result = ''.join(
[q + ' OR ' for q in query_words[0:(len(query_words) - 1)]])
return result + str(query_words[len(query_words) - 1]) |
def parse_description(description):
"""
Strip figures and alt text from description
"""
return "\n".join(
[
a for a in description.split("\n")
if ("figure::" not in a) and (":alt:" not in a)
]) |
def _depth_first_select(rectangles):
"""Find a rectangle of minimum area for bisection."""
min_area, j = None, None
for i, (_, (u, v), (s, t), _, _, _, _) in enumerate(rectangles):
area = (s - u)*(t - v)
if min_area is None or area < min_area:
min_area, j = area, i
return rectangles.pop(j) |
def is_roughly_water_color(color):
"""Water is black, land is white."""
r, g, b, *_ = color
average_pixel_value = (r + g + b) / 3
return average_pixel_value <= 128 |
def validate_date(date: str) -> bool:
"""This method validates a date to be in yyyy-mm-dd format.
Args:
date (str): date string
Returns:
bool: True/False based on valid date string
"""
if "-" not in date:
return False
date_elements = date.split("-")
if len(date_elements) != 3:
return False
year = date_elements[0]
month = date_elements[1]
day = date_elements[2]
if len(year) != 4:
return False
if len(month) > 2:
return False
if int(month) > 12 or int(month) < 1:
return False
if len(day) > 2:
return False
if int(day) > 31 or int(day) < 1:
return False
return True |
def parse_residue_spec(resspec):
"""
Light version of:
vermouth.processors.annotate_mud_mod.parse_residue_spec
Parse a residue specification:
<mol_name>#<mol_idx>-<resname>#<resid>
Returns a dictionary with keys 'mol_name',
'mol_idx', and 'resname' for the fields that are specified.
Resid will be an int.
Parameters
----------
resspec: str
Returns
-------
dict
"""
molname = None
resname = None
mol_idx = None
resid = None
mol_name_idx, *res = resspec.split('-', 1)
molname, *mol_idx = mol_name_idx.split('#', 1)
if res:
resname, *resid = res[0].split('#', 1)
error_msg = ('Your selection {} is invalid. Was not able to assign {}'
'with value {}')
out = {}
if mol_idx:
try:
mol_idx = int(mol_idx[0])
except ValueError:
raise IOError(error_msg.format(resspec, 'mol_idx', mol_idx))
out['mol_idx'] = mol_idx
if resname:
out['resname'] = resname
if molname:
out['molname'] = molname
if resid:
try:
out['resid'] = float(resid[0])
except ValueError:
raise IOError(error_msg.format(resspec, 'mol_idx', mol_idx))
return out |
def normalize(pair):
"""Convert the (count, species) pair into a normalized list of atomic and mass
numbers.
"""
o_mass, o_atomic = pair
if o_mass < 0:
return [(o_mass, o_atomic)]
if o_atomic == 0:
return [(1, 0) for _ in range(o_mass)]
if o_mass == o_atomic:
return [(1, 1) for _ in range(o_mass)]
return [(o_mass, o_atomic)] |
def table_to_dict(opts, spec):
"""
Convert a table specification to a list of dictionaries of information.
Enter: opts: a dictionary of options.
spec: a table specification: one of n, l, m, n-l, l-m.
Exit: speclist: a list, each of which has a dictionary of information with
values to iterate through in order.
"""
if spec == 'n':
return [{'n': n} for n in range(opts['minn'], opts['maxn'] + 1)]
if spec == 'l':
return [{'l': l} for l in range(0, opts['maxn'])]
if spec == 'm':
return [{'m': m} for m in range(
-opts['maxn'] - 1 if opts['allm'] else 0, opts['maxn'])]
if spec == 'n-l':
return [{'n-l': nml} for nml in range(1, opts['maxn'] + 1)]
if spec == 'l-m':
return [{'l-m': lmm} for lmm in range(0, opts['maxn'])]
raise 'Invalid table specification %s' % spec |
def get_dict_buildin(dict_obj, _types=(int, float, bool, str, list, tuple, set, dict)):
"""
get a dictionary from value, ignore non-buildin object
"""
return {key: dict_obj[key] for key in dict_obj if isinstance(dict_obj[key], _types)} |
def list_sample(collection, limit = 3):
"""
given an ordered collection (list, tuple, ...), return a string representation
of the first limit items (or fewer), e.g. "itemA, itemB, itemC and 7 more"
"""
ln = len(collection)
if ln > 1:
if ln <= limit:
return '%s and %s' % (', '.join(str(ws) for ws in collection[:min(limit, ln)]), collection[min(limit, ln)])
return '%s and %d others' % (', '.join(str(ws) for ws in collection[:min(limit, ln)]), ln - limit)
if ln > 0:
return collection[0]
return '' |
def convert_currency(val):
"""
125000.00
Convert the string number value to a float
- Remove $
- Remove commas
- Convert to float type
"""
new_val = val.replace(',', '').replace('$', '')
return float(new_val) |
def calc_s11_s22_s33(s2211, s1133):
"""Calculates s11, s22, s33 based on s22-s11 and s11-s33 using
the constraint s11+s22+s33=0
"""
s22 = 2.0*(s2211)/3.0 + s1133/3.0
s11 = s22 - s2211
s33 = s11 - s1133
return s11, s22, s33 |
def _replace_param_fixed_length(param):
"""
Generate a fixed length data element if param matches the expression [<type>_WITH_LENGTH_<length>]
where <type> can be: STRING, INTEGER, STRING_ARRAY, INTEGER_ARRAY, JSON.
E.g. [STRING_WITH_LENGTH_15]
:param param: parameter value
:return: tuple with replaced value and boolean to know if replacement has been done
"""
new_param = param
param_replaced = False
if param.startswith('[') and param.endswith(']'):
if any(x in param for x in ['STRING_ARRAY_WITH_LENGTH_', 'INTEGER_ARRAY_WITH_LENGTH_']):
seeds = {'STRING': 'a', 'INTEGER': 1}
seed, length = param[1:-1].split('_ARRAY_WITH_LENGTH_')
new_param = list(seeds[seed] for x in range(int(length)))
param_replaced = True
elif 'JSON_WITH_LENGTH_' in param:
length = int(param[1:-1].split('JSON_WITH_LENGTH_')[1])
new_param = dict((str(x), str(x)) for x in range(length))
param_replaced = True
elif any(x in param for x in ['STRING_WITH_LENGTH_', 'INTEGER_WITH_LENGTH_']):
seeds = {'STRING': 'a', 'INTEGER': '1'}
# The chain to be generated can be just a part of param
start = param.find('[')
end = param.find(']')
seed, length = param[start + 1:end].split('_WITH_LENGTH_')
generated_part = seeds[seed] * int(length)
placeholder = '[' + seed + '_WITH_LENGTH_' + length + ']'
new_param = param.replace(placeholder, generated_part)
param_replaced = True
if seed == 'INTEGER':
new_param = int(new_param)
return new_param, param_replaced |
def escape_str(escape_func,s,*args):
"""
Applies escape_func() to all items of `args' and returns a string based
on format string `s'.
"""
return s % tuple(escape_func(v) for v in args) |
def parse(domain):
"""
Split domain into queryable parts in reverse.
Arguments:
domain (str): full domain name
Examples:
>>> parse('www.google.com')
['.', 'com.', 'google.com.', 'www.google.com.']
"""
parts = domain.split('.')
parts.extend('.')
parts.reverse()
if '' in parts:
parts.remove('')
for i in range(len(parts)-1):
if not i:
parts[i+1] = parts[i+1]+parts[i]
continue
parts[i+1] = parts[i+1]+'.'+parts[i]
return parts |
def bottom_node(nodes, y, x):
""" find the first right node
and returns its position """
try:
return str(x) + " " + str(nodes.index('0', y+1))
except(KeyError, ValueError):
return '-1 -1 ' |
def ddm_irref_score(a, score):
"""a <-- rref(a)"""
# a is (m x n)
m = len(a)
if not m:
return []
n = len(a[0])
i = 0
pivots = []
for j in range(n):
# nonzero pivots
nz_ip = [ip for ip in range(i, m) if a[ip][j]]
# No pivots
if not nz_ip:
continue
# Find a pivot from the ground domain if possible
ip = max(nz_ip, key=lambda ip: score(a[ip][j]))
# Swap pivot to the current row
a[i], a[ip] = a[ip], a[i]
# normalise row
ai = a[i]
aij = ai[j]
for l in range(j, n):
ai[l] /= aij # ai[j] = one
# eliminate above and below to the right
for k, ak in enumerate(a):
if k == i or not ak[j]:
continue
akj = ak[j]
ak[j] -= akj # ak[j] = zero
for l in range(j+1, n):
ak[l] -= akj * ai[l]
# next row
pivots.append(j)
i += 1
# no more rows?
if i >= m:
break
return pivots |
def is_isogram(word: str) -> bool:
"""Determine if word is an isogram."""
lowercase_word = word.lower()
distinct_letters = len(set(lowercase_word))
total_letters = len(lowercase_word)
return distinct_letters == total_letters |
def round_if_near(value: float, target: float) -> float:
"""If value is very close to target, round to target."""
return value if abs(value - target) > 2.0e-6 else target |
def fix_string(code):
"""
Fix indentation and empty lines from string coming out of the function.
"""
lines = code.split('\n')
# Remove first line if empty
if not lines[0]:
lines = lines[1:]
# Detect tabsize
size = 0
while lines[0][size] in ' ':
size += 1
lines = list(map(lambda l: l[size:], lines))
if not lines[-1]:
lines = lines[:-1]
code = '\n'.join(lines)
return code |
def find_separator(prompt, start, sep):
"""Find separator skipping parts enclosed in brackets."""
level = 1
length = len(prompt)
while start < length:
if start + 1 < length and prompt[start] == '\\':
start += 1
elif level == 1 and prompt[start] == sep:
return start
elif prompt[start] == '{':
level += 1
elif prompt[start] == '}':
if level <= 1:
return -1
level -= 1
start += 1
return -1 |
def close(session_attrs, fulfillment_state, message):
"""
Close session in Lex.
"""
response = {
'sessionAttributes': session_attrs,
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': {'contentType': 'PlainText', 'content': message}
}
}
return response |
def _escape(data, entities={}):
""" Escape &, <, and > in a string of data.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
try:
data = data.decode('utf-8')
except (TypeError, AttributeError):
## Make sure our stream is a string
## If it comes through as bytes it fails
pass
data = data.replace("&", "&")
data = data.replace("<", "<")
data = data.replace(">", ">")
for chars, entity in list(entities.items()):
data = data.replace(chars, entity)
return data |
def map_activity_model(raw_activity):
""" Maps request data to the fields defined for the Activity model """
return {
'activity_id': raw_activity['key'],
'description': raw_activity['activity'],
'activity_type': raw_activity['type'],
'participants': raw_activity['participants'],
'accessibility': raw_activity['accessibility'],
'price': raw_activity['price'],
'link': raw_activity['link']
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.