content stringlengths 42 6.51k |
|---|
def isStandard(x):
""" Is this encoding required by the XML 1.0 Specification, 4.3.3? """
return x.upper() in ['UTF-8', 'UTF-16'] |
def _set_bool(val):
"""Helper to convert the given value to boolean."""
true_values = ['true', 'yes', 'y', 'on', '1']
return isinstance(val, str) and val.lower() in true_values |
def count_occurences(column):
"""Part of the coincidence index of a message`s columns: the letters count process"""
letters_count = {c: 0 for c in column}
for c in column:
letters_count[c] += 1
return letters_count |
def intersection(lst1, lst2):
"""returns the intersection between two lists"""
if (lst1 == None or lst2 == None):
return []
lst3 = [value for value in lst1 if value in lst2]
return lst3 |
def is_npy(s):
"""
Filter check for npy files
:param str s: file path
:returns: True if npy
:rtype: bool
"""
if s.find(".npy") == -1:
return False
else:
return True |
def _get_baseline_value(baseline, key):
"""
We need to distinguish between no baseline mode (which should return
None as a value), baseline mode with exceeded timeout (which is stored
as None, but should return 0).
"""
if key in baseline:
return 0 if baseline[key] is None else baseline[k... |
def dsigmoid(x):
"""
Derivative of sigmoid function
:param x: array-like shape(n_sample, n_feature)
:return: derivative value (array like)
"""
return x * (1. - x) |
def _escape(txt):
"""Basic html escaping."""
txt = txt.replace('&', '&')
txt = txt.replace('<', '<')
txt = txt.replace('>', '>')
txt = txt.replace('"', '"')
return txt |
def computeF1(goldList, predictedList):
"""Assume all questions have at least one answer"""
if len(goldList) == 0:
if len(predictedList) == 0:
return (1, 1, 1)
else:
return (0, 0, 0)
# raise Exception("gold list may not be empty")
"""If we return an empty list... |
def strfmt(value):
"""
Apply a format to a real value for writing out the data values.
This routine is used to format an input real value either in
exponential format or in floating point format depending on
the magnitude of the input value.
This works better for constant width columns than the... |
def get_permission_names(perm_int):
"""Takes an integer representing a set of permissions and returns a list
of corresponding permission names."""
pms = {'God': 16, 'Admin': 8, 'Builder': 2, 'Player': 1, 'DM': 4}
perm_list = []
for key, value in pms.items():
if perm_int & value:
... |
def Mreq(mg,deltaGcat):
"""
Computes the requested maintenance rate from
mg the maintenance free energy trait and the catabolic energy
**REF**
"""
return(-mg/deltaGcat) |
def transpose_table(table):
"""
Transposes a table, turning rows into columns.
:param table: A 2D string grid.
:type table: [[``str``]]
:return: The same table, with rows and columns flipped.
:rtype: [[``str``]]
"""
if len(table) == 0:
return table
else:
num_columns ... |
def num_to_num(nums):
"""Converts the numeric list to alphabetic list
likewise, chr()reutrns the charactor from a number based on Unicode"""
num_list = [chr(i -1 + ord('a')) for i in nums]
return ''.join(num_list) |
def limit_tag_output_to_id_and_name(attribute_dict, is_event_level):
"""
As tag list can be full of in unnecessary data, we want to limit this list to include only the ID and Name fields.
In addition, returns set of the found tag ids.
Some tags have a field called inherited. When it is set to 1 it says... |
def int_to_bin(num_int, length):
"""convert int to binary string of given length"""
num_str = bin(num_int)[2:]
str_len = len(num_str)
if length <= str_len:
return num_str[str_len - length : str_len]
else:
return num_str.zfill(length) |
def _search_node(key, tree):
"""Support function for search the tree for a node based on the key.
This returns the node if found else None is returned.
"""
if not tree:
return None
elif key == tree.key:
return tree
elif key < tree.key:
return _search_node(key, tree.left... |
def convert_dict_id_values_to_strings(dict_list):
"""This function ensures that the ``id`` keys in a list of dictionaries use string values.
:param dict_list: List (or tuple) of dictionaries (or a single dictionary) containing API object data
:type dict_list: list, tuple, dict, None
:returns: A new dic... |
def lista_str(cadena):
"""Transforma una cadena a lista sin espacios
cadena -- Cadena que se desea pasar a list
"""
lista = []
cadena = cadena.replace(' ', '', -1)
for i in cadena:
lista.append(i)
return lista |
def root() -> dict:
"""
Root Get
"""
return {"msg": "This is the Example API"} |
def electric_source(data, meta):
"""
Fix up electricity for how much the Grids consume
"""
# flip sign because we consume the electricity
E = -1.0 * meta['HERON']['activity']['electricity']
data = {'driver': E}
return data, meta |
def flatten(dict_item):
"""Flatten lists in dictionary values for better formatting."""
flat_dict = {}
for k, v in dict_item.items():
flat_dict[k] = ",".join(v) if type(v) is list else v
return flat_dict |
def coordinateHashToXYTupleList(coordinateHash):
"""
Converts a coordinateHash to a list of tuples
:param dict coordinateHash: a hash using
{x1:[y1:True,y2:True..],x1:[y1:True,y2:True..]} format
:return: list of (x,y) tuples.
"""
return [(x, y) for x, _y in coordinateHash.items() for y, _ ... |
def _extractDotSeparatedPair(string):
"""
Extract both parts from a string of the form part1.part2.
The '.' used is the last in the string.
Returns a pair (part1, part2).
Useful for parsing machine.buildType filenames.
"""
i = string.rfind('.')
return string[:i], string[i+1:] |
def compute_intersection(arr_1, arr_2):
"""
Question 14.1: Compute the intersection of two sorted arrays
"""
idx_1 = 0
idx_2 = 0
intersection = []
while idx_1 < len(arr_1) and idx_2 < len(arr_2):
if arr_1[idx_1] == arr_2[idx_2]:
if not len(intersection) or arr_1[idx_1] !=... |
def normalize(collection):
"""
Normalize the value of all element in a collection
each element will be divided by the sum
"""
if isinstance(collection, dict):
total = 0
result = {}
for key in collection:
total += collection[key]
if total == 0:
... |
def update_newton(yvals, y0):
"""Calculate the variable increment using Newton's method.
Calculate the amount to increment the variable by in one iteration of
Newton's method. The goal is to find the value of x for which y(x) = y0.
`yvals` contains the values [y(x0), y'(x0), ...] of the function and it... |
def splitter(h):
""" Splits dictionary numbers by the decimal point."""
if type(h) is dict:
for k, i in h.items():
h[k] = str(i).split('.');
if type(h) is list:
for n in range(0, len(h)):
h[n] = splitter(h[n])
return h |
def get_next_slug(base_value, suffix, max_length=100):
"""
Gets the next slug from base_value such that "base_value-suffix" will not exceed max_length characters.
"""
suffix_length = len(str(suffix)) + 1 # + 1 for the "-" character
if suffix_length >= max_length:
raise ValueError("Suffix {}... |
def median_of_3(num1, num2, num3):
"""Utility functions to compute the median of 3 numbers"""
return num1 + num2 + num3 - min(num1, num2, num3) - max(num1, num2, num3) |
def _count_parenthesis(value):
"""Count the number of `(` and `)` in the given string."""
return sum([i for i, c in enumerate(value) if c in ["(", ")"]]) |
def create_scale(tonic, pattern, octave=1):
"""
Create an octave-repeating scale from a tonic note
and a pattern of intervals
Args:
tonic: root note (midi note number)
pattern: pattern of intervals (list of numbers representing
intervals in semito... |
def dict_to_list(states, dictionary):
"""
:param states: no. of states
:param dictionary: input distribution
:return: a list of values for each states
"""
rows = []
for i in states:
rows.append(list(dictionary[i].values()))
return rows.copy() |
def is_hex(s):
"""check if string is all hex digits"""
try:
int(s, 16)
return True
except ValueError:
return False |
def flatten_list(l):
"""Flattens a nested list
"""
return [x for nl in l for x in nl] |
def change_fmt(val, fmt):
"""
"""
if val > 0:
return "+" + fmt(val)
else:
return fmt(val) |
def _sparql_var(_input):
"""Add the "?" if absent"""
return _input if _input.startswith('?') else '?' + _input |
def normpath(pathname):
"""Make sure no illegal characters are contained in the file name."""
from sys import platform
illegal_chars = ":?*"
for c in illegal_chars:
# Colon (:) may in the path after the drive letter.
if platform == "win32" and c == ":" and pathname[1:2] == ":":
... |
def find_sum(inputs, target):
"""
given a list of input integers, find the (first) two numbers
which sum to the given target, and return them as a 2-tuple.
Return None if the sum could not be made.
"""
for i in inputs:
if i < target // 2 + 1:
if target - i in inputs:
... |
def rec_multiply(a_multiplier, digit, carry):
"""Function to multiply a number by a digit"""
if a_multiplier == '':
return str(carry) if carry else ''
prefix = a_multiplier[:-1]
last_digit = int(a_multiplier[-1])
this_product = last_digit * digit + carry
this_result = this_product % 1... |
def sec2hms(seconds):
"""Seconds to hours, minutes, seconds"""
hours, seconds = divmod(seconds, 60**2)
minutes, seconds = divmod(seconds, 60)
return (int(hours), int(minutes), seconds) |
def total_takings(monthly_takings):
"""
A regular flying circus happens twice or three times a month. For each month, information about the amount of money taken at each event is saved in a list, so that the amounts appear in the order in which they happened. The months' data is all collected in a dictionary ca... |
def safe_lookup(dictionary, *keys, default=None):
"""
Recursively access nested dictionaries
Args:
dictionary: nested dictionary
*keys: the keys to access within the nested dictionaries
default: the default value if dictionary is ``None`` or it doesn't contain
the keys
... |
def _is_eqsine(opts):
"""
Checks to see if 'eqsine' option is set to true
Parameters
----------
opts : dict
Dictionary of :func:`pyyeti.srs.srs` options; can be empty.
Returns
-------
flag : bool
True if the eqsine option is set to true.
"""
if "eqsine" in opts:... |
def clean_requirement(requirement):
"""Return only the name portion of a Python Dependency Specification string
the name may still be non-normalized
"""
return (
requirement
# the start of any valid version specifier
.split("=")[0]
.split("<")[0]
.split(">")[0]
... |
def gyroWordToFloat(word):
"""Converts the 16-bit 2s-complement ADC word into appropriate float.
Division scaling assumes +-250deg/s full-scale range.
Args:
word - 16-bit 2's-complement ADC word.
Return:
float
"""
if word & 0x8000:
return float((word ^ 0xffff) +... |
def normalize_str(name: str) -> str:
"""
return normalized string for paths and such
"""
return name.strip().replace(' ', '_').lower() |
def build_search_filter(search_params: dict):
"""
Build a search filter for the django ORM from a dictionary of query params
Args:
search_params:
Returns:
"""
search_filter = {
'hide': False
}
if 'species' in search_params:
search_filter['species__in'] = search... |
def version_tuple_to_str(version):
"""Join version tuple to string."""
return '.'.join(map(str, version)) |
def MergePList(plist1, plist2):
"""Merges |plist1| with |plist2| recursively.
Creates a new dictionary representing a Property List (.plist) files by
merging the two dictionary |plist1| and |plist2| recursively (only for
dictionary values). List value will be concatenated.
Args:
plist1: a dictionary rep... |
def font_color_helper(background_color, light_color=None, dark_color=None):
"""Helper function to determine which font color to use"""
light_color = light_color if light_color is not None else "#FFFFFF"
dark_color = dark_color if dark_color is not None else "#000000"
tmp_color = background_color.strip(... |
def trade(first, second):
"""Exchange the smallest prefixes of first and second that have equal sum.
>>> a = [1, 1, 3, 2, 1, 1, 4]
>>> b = [4, 3, 2, 7]
>>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7
'Deal!'
>>> a
[4, 3, 1, 1, 4]
>>> b
[1, 1, 3, 2, 2, 7]
>>> c = [3, 3, 2, 4, 1]
... |
def add_addon_extra_info(ret, external_account, addon_name):
"""add each add-on's account information"""
if addon_name == 'dataverse':
ret.update({
'host': external_account.oauth_key,
'host_url': 'https://{0}'.format(external_account.oauth_key),
})
return ret |
def get_experiment_type(filename):
"""
Get the experiment type from the filename.
The filename is assumed to be in the form of:
'<reliability>_<durability>_<history kind>_<topic>_<timestamp>'
:param filename: The filename to get the type.
:return: A string where the timesptamp is taken out fro... |
def worth_to_put_in_snippet(code_line: str) -> bool:
"""Check if a line of source code is worth to be in a code snippet"""
if "async " in code_line or "def " in code_line:
return True
if code_line.strip().startswith("assert"):
return True
return False |
def letter_to_color(letter):
"""
Transfer a letter into a color
A corresponds to red. B corresponds to yellow. C corresponds to green. D corresponds to blue.
:param letter: an input letter
:type letter: string
:return: a color
:rtype: string
"""
if letter == "A":
return "rgb(... |
def _parse_yaml_boolean(value: str) -> bool:
"""
Parse string according to YAML 1.2 boolean spec:
http://yaml.org/spec/1.2/spec.html#id2803231
:param value: YAML boolean string
:return: bool if string matches YAML boolean spec
"""
value = str(value)
if value == 'true':
return Tru... |
def is_binary_string(string_):
"""
detect if string is binary (https://stackoverflow.com/a/7392391)
:param string_: `str` to be evaluated
:returns: `bool` of whether the string is binary
"""
if isinstance(string_, str):
string_ = bytes(string_, 'utf-8')
textchars = (bytearray({7, ... |
def _get_transition_attr(trans_prod, transition_attr_operations):
"""Return the attribute of a transition constructed by taking the product
of transitions in trans_prod.
@type trans_prod: `list` of `Transitions` objects
@type transition_attr_operations: `dict` whose key is the transition attribute key
... |
def get_type_name(obj):
"""
Given an object, return the name of the type of that object. If `str(type(obj))` returns
`"<class 'threading.Thread'>"`, this function returns `"threading.Thread"`.
"""
try:
return str(type(obj)).split("'")[1]
except Exception:
return str(type(obj)) |
def concat_track_data(tags, audio_info):
"""Combine the tag and audio data into one dictionary per track."""
track_data = {}
for k, v in audio_info.items():
track_data[k] = {**v, "t": tags[k]}
return track_data |
def num2int(num):
"""
>>> num2int('1,000,000')
1000000
"""
return int(num.replace(',', '')) |
def notification_event(events):
"""
Property: NotificationConfig.NotificationEvents
"""
valid_events = ["All", "InProgress", "Success", "TimedOut", "Cancelled", "Failed"]
for event in events:
if event not in valid_events:
raise ValueError(
'NotificationEvents mus... |
def isprime(n):
"""Returns True if n is prime. O(sqrt(n))"""
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - ... |
def remove_prefix(string, prefix):
"""
Removes a prefix from the string, if it exists.
"""
if string.startswith(prefix):
return string[len(prefix):]
else:
return string[:] |
def _clear_return(element, *return_values):
"""Return Results after Clearing Element."""
element.clear()
if len(return_values) == 1:
return return_values[0]
return return_values |
def split_by_lines(text, remove_empty=False):
"""
Split text into lines. Set <code>remove_empty</code> to true to filter out
empty lines
@param text: str
@param remove_empty: bool
@return list
"""
lines = text.splitlines()
return remove_empty and [line for line in lines if line.strip()] or lines |
def color_text(color_enabled, color, string):
"""Return colored string."""
if color_enabled:
# LF should not be surrounded by the escape sequence.
# Otherwise, additional whitespace or line-feed might be printed.
return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
... |
def cmp_func(y: float, behavior: str, f, x: float) -> bool:
"""Decide whether y < f(x), but where "<" can be specified.
:param y: number to compare to f(x)
:param behavior: string that can be 'less' or 'greater'
:param f: function of 1 variable
:param x: number at which to evaluate f, and then comp... |
def shebang_command(path_to_file):
"""Get the shebang line of that file
Which is the first line, if that line starts with #!
"""
try:
first_line = open(path_to_file).readlines()[0]
if first_line.startswith('#!'):
return first_line[2:].strip()
except (IndexError, IOError,... |
def nonrigid_rotations(spc_mod_dct_i):
""" dtermine if a nonrigid rotation model is specified and further
information is needed from the filesystem
"""
rot_model = spc_mod_dct_i['rot']['mod']
return bool(rot_model == 'vpt2') |
def project(atts, row, renaming={}):
"""Create a new dictionary with a subset of the attributes.
Arguments:
- atts is a sequence of attributes in row that should be copied to the
new result row.
- row is the original dictionary to copy data from.
- renaming is a mapping of name... |
def northing_and_easting(dictionary):
"""
Retrieve and return the northing and easting strings to be used as
dictionary keys
Parameters
----------
dictionary : dict
Returns
-------
northing, easting : tuple
"""
if not 'x' and 'y' in dictionary.keys():
northing = 'l... |
def byte2str(e):
"""Return str representation of byte object"""
return e.decode("utf-8") |
def calculate_map(aps):
"""
Prints the average precision for each class and calculates micro mAP and macro mAP.
@param aps: average precision for each class
@param dictionary: mapping between label anc class name
@return: micro mAP and macro mAP
"""
total_instances = []
precisions = []
... |
def doc_arg(name, brief):
"""argument of doc_string"""
return " :param {0}: {1}".format(name, brief) |
def parse_option_settings(option_settings):
"""
Parses option_settings as they are defined in the configuration file
"""
ret = []
for namespace, params in option_settings.items():
for key, value in params.items():
ret.append((namespace, key, value))
return ret |
def get_session_id_to_name(db, ipython_display):
"""Gets a dictionary that maps currently running livy session id's to their names
Args:
db (dict): the ipython database where sessions dict will be stored
ipython_display (hdijupyterutils.ipythondisplay.IpythonDisplay): the display that
i... |
def fact(n):
"""Return the factorial of the given number."""
r = 1
while n > 0:
r = r * n
n = n - 1
return r |
def is_square(apositiveint):
"""
Checks if number is a square
Taken verbatim from https://stackoverflow.com/questions/2489435/how-could-i-check-if-a-number-is-a-perfect-square
"""
x = apositiveint // 2
seen = set([x])
while x * x != apositiveint:
x = (x + (apositiveint // x)) // 2
... |
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
Running time: O(n) because we are using a loop to traverse through each item in the list
Memory usage: O(1) because we aren't creating any additional data structures in the function"""
# Check that all adjacent... |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict.
If the same key appars multiple times, priority goes to key/value
pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def season_id(x):
"""takes in 4-digit years and returns API formatted seasonID
Input Values: YYYY
Used in:
"""
if len(str(x)) == 4:
try:
return "".join(["2", str(x)])
except ValueError:
raise ValueError("Enter the four digit year for the first half of the ... |
def groupByReactionCenter(transformationCenter):
"""
returns: A Dictionary with 'reactionCenter' keys.
"""
centerDict = {}
# extract rules with teh same reaction center
for idx, rule in enumerate(transformationCenter):
# print rule
element = [tuple(x.elements()) for x in rule if... |
def _get_n_top(n_top, folder):
"""
Get path and name of topology file
:param str n_top: None or path and file name of topology file.
:param str folder: None or folder containing one topology file.
:return: path to the topology file
:rtype: str
:raises ValueError: This is raised if more than... |
def count_any_question_yes(group_input: str) -> int:
"""count questions any group member answered with yes"""
return len(set("".join([line.strip() for line in group_input.split("\n")]))) |
def string_serializer(obj):
"""
Helper Function to Serialize Objects. Keeps List / Dict Structure, but will Convert everything else to String.
"""
if type(obj) in [list, tuple]:
return list(map(string_serializer, obj))
if type(obj) == dict:
copy = {}
for k, v in obj.items():
... |
def files_data_generation(candidates, namesmeasures):
"""Select all possible files that are related with the given measures."""
selected = []
for name in namesmeasures:
sele_name = []
for i in range(len(candidates)):
if name in candidates[i]:
sele_name.append(cand... |
def get_release_date(data):
"""Get release date."""
date = data.get("physicalRelease")
if not date:
date = data.get("inCinemas")
return date |
def get_url_attrs(url, url_attr):
"""Return dict with attrs for url."""
if isinstance(url, str):
return {url_attr: url}
return url.copy() |
def pole_increment(x,y,t):
"""This provides a small increment to a pole located mid stream
For use with variable elevation data
"""
z = 0.0*x
if t<10.0:
return z
# Pole 1
id = (x - 12)**2 + (y - 3)**2 < 0.4**2
z[id] += 0.1
# Pole 2
id = (x - 14)**2 + (y - 2)... |
def extract_layout_switch(dic, default=None, do_pop=True):
"""
Extract the layout and/or view_id value
from the given dict; if both are present but different,
a ValueError is raised.
Futhermore, the "layout" might be got (.getLayout) or set
(.selectViewTemplate);
thus, a 3-tuple ('layout_id... |
def fix_template_expansion(content, replacements):
"""
fix template expansion after hook copy
:param content: the duplicated hook content
:param replacements: array of dictionaries
cookiecutter_key => template key expanded
"""
for replacement in replacements:
for... |
def _expand_xyfvc(x, y):
"""
Undo _redux_xyfvc() transform
"""
c = 3000.0
return (x+1)*c, (y+1)*c |
def build_index(interactors):
""" Build the index (P x D) -> N for all interactors of the current protein.
"""
index = dict() # P x D -> N
sorted_interactors = sorted(list(interactors))
for p, d in sorted_interactors:
index[(p, d)] = sorted_interactors.index((p, d))
return index |
def long_hex(number):
"""
converts number to hex just like the inbuilt hex function but also
pads zeroes such that there are always 8 hexidecimal digits
"""
value_hex = hex(number)
# pad with 0's. use 10 instead of 8 because of 0x prefix
if(len(value_hex) < 10):
value_hex =... |
def normalize(frame):
""" Return normalized frame """
frame -= 128.0
frame /= 128.0
return frame |
def scalarmult(scalar, list1):
"""scalar multiply a list"""
return [scalar * elt for elt in list1] |
def collapse_array_repr(value):
"""
The full repr representation of PVT model takes too much space to print all values inside a array.
Making annoying to debug Subjects that has a PVT model on it, due to seventy-four lines with only numbers.
"""
import re
return re.sub(r"array\(\[.*?\]\)", "arr... |
def comment_troll_name(results):
""" The same as troll_name """
name = results['by']
return name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.