content
stringlengths 42
6.51k
|
---|
def _cast_safe(self, value, cast_type = str, default_value = None):
"""
Casts the given value to the given type.
The cast is made in safe mode, if an exception
occurs the default value is returned.
:type value: Object
:param value: The value to be casted.
:type cast_type: Type
:param cast_type: The type to be used to cast the retrieved
value (this should be a valid type, with constructor).
:type default_value: Object
:param default_value: The default value to be used
when something wrong (exception raised) occurs.
:rtype: Object
:return: The value casted to the defined type.
"""
# in case the value is none it's a considered special case
# and the value should be returned immediately to caller
if value == None: return value
try:
# retrieves the value type
value_type = type(value)
# in case the value type is the same
# as the cast type
if value_type == cast_type:
# sets the value as the value casted
value_casted = value
# otherwise
else:
# casts the value using the type
value_casted = cast_type(value)
# returns the value casted
return value_casted
except Exception:
# returns the default value
return default_value
|
def _contains_atom(example, atoms, get_atoms_fn):
"""Returns True if example contains any atom in atoms."""
example_atoms = get_atoms_fn(example)
for example_atom in example_atoms:
if example_atom in atoms:
return True
return False
|
def stringToList(data):
"""
Return a list from the given string.
Example:
print listToString('apple, pear, cherry')
# ['apple', 'pear', 'cherry']
:type data: str
:rtype: list
"""
data = '["' + str(data) + '"]'
data = data.replace(' ', '')
data = data.replace(',', '","')
return eval(data)
|
def snap_to_widest(to_snap, widests):
"""
Snaps the width of each column of the table to the width of the
largest element in the respective column.
"""
new_table = list()
for row in to_snap:
new_row = list()
for i in range(0, len(widests)):
new_row.append(f'{str(row[i]):^{widests[i]}}')
new_table.append(new_row)
return new_table
|
def prepare_query(site_id: str, condition: str) -> str:
"""
Creates GraphQL query
:type site_id: ``str``
:param site_id: Site ID entered by user
:type condition: ``str``
:param condition: filter conditions
:rtype: ``str``
:return: GraphQL query
"""
query = """query getAssetResources($pagination: AssetsPaginationInputValidated) {
site(id: "%s") {
assetResources (
assetPagination: $pagination,
fields: [
"assetBasicInfo.name",
"assetBasicInfo.domain",
"assetBasicInfo.userName",
"assetBasicInfo.userDomain",
"assetBasicInfo.fqdn",
"assetBasicInfo.description",
"assetBasicInfo.type",
"assetBasicInfo.mac",
"assetBasicInfo.ipAddress",
"assetBasicInfo.firstSeen"
"assetBasicInfo.lastSeen"
"assetCustom.model",
"assetCustom.serialNumber",
"assetCustom.manufacturer",
"assetCustom.sku",
"assetCustom.firmwareVersion",
"assetCustom.purchaseDate",
"assetCustom.warrantyDate",
"assetCustom.comment",
"assetCustom.location",
"assetCustom.department",
"assetCustom.contact",
"assetCustom.dnsName",
"assetCustom.stateName",
"operatingSystem.caption",
"operatingSystem.productType",
"url"
],
filters: {
conjunction: OR,
conditions: [%s]
}
) {
total
pagination {
limit
current
next
page
}
items
}
}
}""" % (
site_id,
condition
)
return query
|
def get_utf8_bytes(char):
"""Get the UTF-8 bytes encoding an unicode character
Parameters:
char: unicode character
Returns: integer array of the UTF-8 encoding
"""
# Get the codepoint (integer between 0 and 0x1fffff)
c = ord(char)
assert c < 0x20000
if c < 0x80:
# 0..7F -> 00..7F (ASCII)
return [c]
elif c < 0x800:
# 80..FF -> C2..C3 + 1 (ISO-8859-1 = Latin 1)
# 100..7FF -> C4..DF + 1
return [0xc0 + (c >> 6), 0x80 + (c & 0x3f)]
elif c < 0x10000:
# 800..FFF -> E0 + 2
# 1000..FFFF -> E1..EF + 2
return [0xe0 + (c >> 12), 0x80 + ((c >> 6) & 0x3f), 0x80 + (c & 0x3f)]
else:
# 10000..FFFFF -> F0..F3 + 3
# 100000..1FFFFF -> F4..F7 + 3
return [
0xf0 + (c >> 18),
0x80 + ((c >> 12) & 0x3f),
0x80 + ((c >> 6) & 0x3f),
0x80 + (c & 0x3f)]
|
def get_cr_lum(lum1: float, lum2: float) -> float:
"""Compute contrast ratio of two luminance values."""
val = (lum1 + 0.05) / (lum2 + 0.05)
return val if val >= 1 else 1 / val
|
def chomp(string):
"""
Simple callable method to remove additional newline characters at the end
of a given string.
"""
if string.endswith("\r\n"):
return string[:-2]
if string.endswith("\n"):
return string[:-1]
return string
|
def ard_map(value, in_min, in_max, out_min, out_max):
"""
Arduino's map function
:return:
"""
return out_min + (out_max - out_min) * ((value - in_min) / (in_max - in_min))
|
def find_last_dig(num_str):
"""Find index in string of number (possibly) with error bars immediately
before the decimal point.
Parameters
----------
num_str : str
String representation of a float, possibly with error bars in parens.
Returns
-------
pos : int
String index of digit before decimal point.
Examples
--------
>>> find_last_dig('5.555')
0
>>> find_last_dig('-5.555')
1
>>> find_last_dig('-567.555')
3
>>> find_last_dig('-567.555(45)')
3
>>> find_last_dig('-567(45)')
3
"""
pos = num_str.find(".")
assert pos != 0
if pos < 0:
pos = num_str.find("(")
assert pos != 0
if pos < 0:
pos = len(num_str)
assert pos != 0
pos = pos - 1 # Indexing adjust
return pos
|
def ns(s):
"""remove namespace, but only it there is a namespace to begin with"""
if '}' in s:
return '}'.join(s.split('}')[1:])
else:
return s
|
def compute_acc_bin(conf_thresh_lower, conf_thresh_upper, conf, pred, true):
"""
Computes accuracy and average confidence for bin
Args:
conf_thresh_lower (float): Lower Threshold of confidence interval
conf_thresh_upper (float): Upper Threshold of confidence interval
conf (numpy.ndarray): list of confidences
pred (numpy.ndarray): list of predictions
true (numpy.ndarray): list of true labels
Returns:
(accuracy, avg_conf, len_bin): accuracy of bin, confidence of bin and number of elements in bin.
"""
filtered_tuples = [x for x in zip(pred, true, conf) if x[2] > conf_thresh_lower and x[2] <= conf_thresh_upper]
if len(filtered_tuples) < 1:
return 0,0,0
else:
correct = len([x for x in filtered_tuples if x[0] == x[1]]) # How many correct labels
len_bin = len(filtered_tuples) # How many elements falls into given bin
avg_conf = sum([x[2] for x in filtered_tuples]) / len_bin # Avg confidence of BIN
accuracy = float(correct)/len_bin # accuracy of BIN
return accuracy, avg_conf, len_bin
|
def getItemsFromDefaults(defaults, params):
"""Converts defaults to specific items for this view.
Args:
defaults: the defaults to instantiate
params: a dict with params for this View
"""
result = []
for url, menu_text, access_type in defaults:
url = url % params['url_name'].lower()
item = (url, menu_text % params, access_type)
result.append(item)
return result
|
def probability_of_ij_given_k(i, j, k, category_membership_list, stimuli, m):
"""
Function that calculates the mean of the posterior probability density for non-informative priors.
More specifically, it is the probability that the stimulus displays value j on dimension i given that it comes from
category k (equation 3-7 in [Ande90]_)
Parameters
----------
i : int
Dimension index
j : int
Value on dimension i
k : int
Category index. For example, k can be 0 or 1 or 2 etc
category_membership_list : list
List of lists that contain the category membership details for the stimuli seen so far. For example, if
stimuli #0, #1, #4 belongs to category #0 and stimuli #2 and #3 belongs to category #1, then
category_membership_list = [[0, 1, 4], [2, 3]]
stimuli : list
List of lists that contain the stimuli seen so far. For example, after training phase of experiment 1 of
[MeSc78]_, stimuli = [[1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 1], [0, 0, 0, 0, 0], [0, 1, 0, 0, 0],
[1, 0, 1, 1, 0]]
m : list
List that contains the number of unique values in each dimension. For example, if there are five dimensions and
all the dimensions are binary, then m = [2, 2, 2, 2, 2]
Returns
-------
float
The probability that the stimulus displays value j on dimension i given that it comes from category k.
"""
# Denominator
nk = len(category_membership_list[k])
denominator = nk + m[i]
# Numerator
count = 0
for idx in range(len(category_membership_list[k])):
if stimuli[category_membership_list[k][idx]][i] == j:
count += 1
numerator = count + 1
return numerator / denominator
|
def all_list_element_combinations_as_pairs(l):
"""Returns a list of tuples that contains element pairs from `l` in all possible combinations
without repeats irrespective of order.
:param list l: list to parse into pairs
:return: element_pairs, list of tuples for each pair
:rtype: list
"""
element_pairs = []
for i in range(len(l)):
element_pairs += [(l[i], l[j]) for j in range(i, len(l))]
return element_pairs
|
def step_function(x: float, step_coordinate: float = 0, value_1: float = 0, value_2: float = 1) -> float:
"""Simple step function.
Parameters
----------
x : float
Coordinate.
step_coordinate: float
Step coordiante.
value_1 : float
Function returns value_1 if x < step_coordinate.
value_2 : float
Function returns value_2 if x >= step_coordinate.
Returns
-------
float
"""
return value_1 if x < step_coordinate else value_2
|
def connection_string_to_dictionary(str):
"""
parse a connection string and return a dictionary of values
"""
cn = {}
for pair in str.split(";"):
suffix = ""
if pair.endswith("="):
# base64 keys end in "=". Remove this before splitting, then put it back.
pair = pair.rstrip("=")
suffix = "="
(key, value) = pair.split("=")
value += suffix
cn[key] = value
return cn
|
def max(*numbers):
""" Returns largest number """
if len(numbers) == 0:
return None
else:
maxnum = numbers[0]
for n in numbers[1:]:
if n > maxnum:
maxnum = n
return maxnum
|
def require_dict_kwargs(kwargs, msg=None):
""" Ensure arguments passed kwargs are either None or a dict.
If arguments are neither a dict nor None a RuntimeError
is thrown
Args:
kwargs (object): possible dict or None
msg (None, optional): Error msg
Returns:
dict: kwargs dict
Raises:
RuntimeError: if the passed value is neither a dict nor None
this error is raised
"""
if kwargs is None:
return dict()
elif isinstance(kwargs, dict):
return kwargs
else:
if msg is None:
raise RuntimeError(
"value passed as keyword argument dict is neither None nor a dict")
else:
raise RuntimeError("%s" % str(msg))
|
def alpha_weight(epoch, T1, T2, af):
""" calculate value of alpha used in loss based on the epoch
params:
- epoch: your current epoch
- T1: threshold for training with only labeled data
- T2: threshold for training with only unlabeled data
- af: max alpha value
"""
if epoch < T1:
return 0.0
elif epoch > T2:
return af
else:
return ((epoch - T1) / (T2 - T1)) * af
|
def transform_entity_synonyms(synonyms, known_synonyms=None):
"""Transforms the entity synonyms into a text->value dictionary"""
entity_synonyms = known_synonyms if known_synonyms else {}
for s in synonyms:
if "value" in s and "synonyms" in s:
for synonym in s["synonyms"]:
entity_synonyms[synonym] = s["value"]
return entity_synonyms
|
def path_exists(filename: str) -> bool:
"""
Checks for the given file path exists.
"""
from pathlib import Path
return Path(filename).exists()
|
def new_database_connection_message(payload):
"""
Build a Slack notification about a new database connection.
"""
connection_url = payload['connection']['url']
connection_name = payload['connection']['name']
connection_vendor = payload['connection']['vendor']
connection_provider = payload['connection']['provider']
message = 'The <{}|{}> data source was just connected.'
message = message.format(connection_url, connection_name)
attachments = [
{
'fallback': message,
'color': 'good',
'author_name': 'Mode',
'author_link': 'https://modeanalytics.com/',
'title': 'New Data Source :plus1:',
'text': message,
'fields': [
{
'title': 'Vendor',
'value': connection_vendor
},
{
'title': 'Provider',
'value': connection_provider
}
]
}
]
return attachments
|
def __walk_chain(rel_dict, src_id):
"""
given a dict of pointing relations and a start node, this function
will return a list of paths (each path is represented as a list of
node IDs -- from the first node of the path to the last).
Parameters
----------
rel_dict : dict
a dictionary mapping from an edge source node (node ID str)
to a set of edge target nodes (node ID str)
src_id : str
Returns
-------
paths_starting_with_id : list of list of str
each list constains a list of strings (i.e. a list of node IDs,
which represent a chain of pointing relations)
"""
paths_starting_with_id = []
for target_id in rel_dict[src_id]:
if target_id in rel_dict:
for tail in __walk_chain(rel_dict, target_id):
paths_starting_with_id.append([src_id] + tail)
else:
paths_starting_with_id.append([src_id, target_id])
return paths_starting_with_id
|
def _is_match_one(sub_string_list, src_string):
"""
Whether the sub-string in the list can match the source string.
Args:
sub_string_list (list): The sub-string list.
src_string (str): The source string.
Returns:
bool, if matched return True, else return False.
"""
for match_info in sub_string_list:
if match_info in src_string:
return True
return False
|
def get_frequency_GC_str(string):
""" get the ratio of GC pairs to the total number of pairs from a DNA strings """
GC = []
total = len(string)
for i in string:
if i == 'C' or i == 'G':
GC.append(1)
return float(sum(GC)/total)
|
def is_int(s):
"""
Returns True if string 's' is integer and False if not.
's' MUST be a string.
:param s: string with number
:type s: str
:rtype: bool
"""
try:
int(s)
return True
except ValueError:
return False
|
def bio2ot_absa(absa_tag_sequence):
"""
bio2ot function for absa task
"""
new_absa_sequence = []
n_tags = len(absa_tag_sequence)
for i in range(n_tags):
absa_tag = absa_tag_sequence[i]
#assert absa_tag != 'EQ'
if absa_tag == 'O' or absa_tag == 'EQ':
new_absa_sequence.append('O')
else:
pos, sentiment = absa_tag.split('-')
new_absa_sequence.append('T-%s' % sentiment)
return new_absa_sequence
|
def points_in_window(points):
"""Checks whether these points lie within the window of interest
Points is a list of one start, one end coordinate (ints)
"""
if None in points or points[0] < -5 or points[1] < -5 or points[0] > 5 or points[1] > 5:
return False
return True
|
def formatFloat(number, decimals=0):
"""
Formats value as a floating point number with decimals digits in the mantissa
and returns the resulting string.
"""
if decimals <= 0:
return "%f" % number
else:
return ("%." + str(decimals) + "f") % number
|
def get_color_list_css(color_list):
"""Convert color list to ipycytoscape css format."""
return [f"rgb({r},{g},{b})" for r, g, b in color_list]
|
def index_keyword(lst, keyword):
"""Index of all list members that include keyword """
return [i for i, x in enumerate(lst) if keyword in x]
|
def nWaveAmplitude(M, bulletDiam, bulletLen, xmiss, patm=101e3):
"""
Calculate N-wave overpressure amplitude
Parameters
----------
M -- Mach number
bulletDiam -- bullet diameter in m
bulletLen -- bullet length in m
xmiss -- miss distance in m
patm -- atmosperic pressure in Pa
Returns
-------
pmax -- N-wave overpressure amplitude in Pa
"""
pmax = 0.53 * patm * bulletDiam * ((M ** 2 - 1) ** 0.125) / (
(xmiss ** 0.75) * (bulletLen ** 0.25))
return pmax
|
def emitter_injection_efficiency(i_en=0,i_e=1):
"""
The emitter injection efficiency measures the fraction
of the emitter current carried by the desired electrons
or holes in a NPN or PNP device. The default is for a
NPN device.
Parameters
----------
i_en : float, required
Electron emitter current. The default is 0.
i_e : TYPE, optional
Emitter current. The default is 1.
Returns
-------
A float value corresponding to the emitter injection efficiency
"""
gamma = i_en / i_e
return gamma
|
def xml_match(xml, match):
"""
Finds the first subelement matching match and verifies that its text attribute is 'true'
:param xml: xml as ET instance
:param match: pattern to lookup by find
:return: boolean
"""
if xml is not None:
return xml.find(match).text == 'true'
return False
|
def all_checks_passed(linter_stdout):
"""Helper function to check if all checks have passed.
Args:
linter_stdout: list(str). List of output messages from
pre_commit_linter.
Returns:
bool. Whether all checks have passed or not.
"""
return 'All Checks Passed.' in linter_stdout[-1]
|
def initialiser_array(evaluator, ast, state):
"""Evaluates initial values "= { ... }"."""
vals = list(map(lambda var: evaluator.eval_ast(var, state), ast["vals"]))
return vals
|
def isSchema2Id(id):
""" return true if this is a v2 id """
# v1 ids are in the standard UUID format: 8-4-4-4-12
# v2 ids are in the non-standard: 8-8-4-6-6
parts = id.split('-')
if len(parts) != 6:
raise ValueError(f"Unexpected id formation for uuid: {id}")
if len(parts[2]) == 8:
return True
else:
return False
|
def run_length(result):
""" Calculates the number of repeatd values in a row.
"""
max_run = 0
current_run = 0
for i in range(1, len(result)):
if result[i] == result[i - 1]:
current_run += 1
if current_run > max_run:
max_run = current_run
else:
current_run = 0
return max_run
|
def flipall_angles(angles):
"""
Horizontally flips all angles in the `angles` array.
"""
return [360 - a for a in angles]
|
def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float:
"""
Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
"""
return round(rankine - 459.67, ndigits)
|
def _where_location(record: dict, item: str, last_section_title: str, last_subsection_title: str) -> dict:
"""Get information where a parsed item should be stored in the resulting JSON."""
where = record[item]
if last_section_title:
if last_section_title not in where:
where['@sections'] = {}
where = where['@sections']
key = last_section_title
if key not in where:
where[key] = {}
where = where[key]
else:
if '@top' not in where:
where['@top'] = {}
where = where['@top']
if last_subsection_title:
key = '@subsections'
if key not in where:
where[key] = {}
where = where[key]
if last_subsection_title not in where:
where[last_subsection_title] = {}
where = where[last_subsection_title]
return where
|
def get_choice(meta_ext, meta_file, key):
""" tries to get meta_ext[key], then try meta_file[key]
:param dict meta_ext:
:param dict meta_file:
:param str key:
:return ret:
"""
assert meta_file is not None
if meta_ext is not None:
ret = meta_ext.get(key, None)
if ret is None:
ret = meta_file.get(key)
else:
ret = meta_file.get(key, None)
return ret
|
def get_file_path_from_url(url: str) -> str:
"""
All pages on the site are served as static files.
This function converts a URL into a filepath from the dist folder.
"""
if '.' not in url:
url = f'{url}/index.html'
return url
|
def ret(error_message=None, **kwargs):
"""
Make return JSON object
:param error_message: sets "error" field to given message string
:param kwargs: fields to set on the return JSON
"""
r = {}
if error_message is not None:
r["error"] = error_message
r.update(kwargs)
return r
|
def modpos(pos,L,move):
"""very similar to modcoord, but only for a LxL.
takes as input walk[i][0] or walk[i][1]
returns the pos modified with the move, accounting for PBCs."""
pos += move
# if pos == L: #moved off right or bottom
# return(0)
# if pos == -1:#moved off top or left
# return(L-1)
return(pos)
|
def get_cf_specs_encoding(ds):
"""Get the ``cf_specs`` encoding value
Parameters
----------
ds: xarray.DataArray, xarray.Dataset
Return
------
str or None
See also
--------
get_cf_specs_from_encoding
"""
if ds is not None and not isinstance(ds, str):
for source in ds.encoding, ds.attrs:
for attr, value in source.items():
if attr.lower() == "cf_specs":
return value
|
def calc_reduction_layers(num_cells, num_reduction_layers):
"""Figure out what layers should have reductions."""
reduction_layers = []
for pool_num in range(1, num_reduction_layers + 1):
layer_num = (float(pool_num) / (num_reduction_layers + 1)) * num_cells
layer_num = int(layer_num)
reduction_layers.append(layer_num)
return reduction_layers
|
def make_it_big(prefix):
"""Mirrors the macro ``MAKE_IT_BIG`` in ``absurdly_long_names.hpp``."""
big = [
prefix, "that", "is", "longer", "than", "two", "hundred", "and", "fifty",
"five", "characters", "long", "which", "is", "an", "absolutely", "and",
"completely", "ridiculous", "thing", "to", "do", "and", "if", "you", "did",
"this", "in", "the", "real", "world", "you", "put", "yourself", "comfortably",
"in", "a", "position", "to", "be", "downsized", "and", "outta", "here", "as",
"soul", "position", "would", "explain", "to", "you"
]
return "_".join(big)
|
def no_high(list_name):
"""
list_name is a list of strings representing cards.
Return TRUE if there are no high cards in list_name, False otherwise.
"""
if "jack" in list_name:
return False
if "queen" in list_name:
return False
if "king" in list_name:
return False
if "ace" in list_name:
return False
return True
|
def join_keys(key1, key2, sep="/"):
"""
Args:
key1 (str): The first key in unix-style file system path.
key1 (str): The second key in unix-style file system path.
sep (str): The separator to be used.
.. code-block:: python
:caption: Example
>>> join_keys('/agent1','artifcats')
'/agent1/artifacts'
"""
key1 = key1.rstrip(sep)
key2 = key2.lstrip(sep)
return key1+sep+key2
|
def bold(text: str) -> str:
"""Wrap input string in HTML bold tag."""
return f'<b>{text}</b>'
|
def get_living_neighbors(i, j, generation):
"""
returns living neighbors around the cell
"""
living_neighbors = 0 # count for living neighbors
neighbors = [(i-1, j), (i+1, j), (i, j-1), (i, j+1),
(i-1, j+1), (i-1, j-1), (i+1, j+1), (i+1, j-1)]
for k, l in neighbors:
if 0 <= k < len(generation) and 0 <= l < len(generation[0]):
if generation[k][l] == 1:
living_neighbors += 1
return living_neighbors
|
def test_jpeg(h, f):
"""JPEG data in JFIF or Exif format"""
if h[6:10] in (b'JFIF', b'Exif'):
return 'jpeg'
|
def change_variable_name(text):
"""
doc
:param text:
:return:
"""
lst = []
for index, char in enumerate(text):
if char.isupper() and index != 0:
lst.append("_")
lst.append(char)
return "".join(lst).lower()
|
def isPalindromic(n):
"""
A palindromic number reads the same both ways. such as 9009
"""
s = str(n)
r = s[::-1]
if s == r:
return True
else:
return False
|
def getMovesFromString(string):
"""Returns a list of moves from a move string (e.g. '1. e4 e5 2. Nf3 Nc6 *')"""
moves = []
for i in string.split(" "):
if i in ["*", "1-0", "0-1", "1/2-1/2"]:
break
if i[0].isnumeric():
continue
moves.append(i)
return moves
|
def firesim_tags_to_description(buildtriplet, deploytriplet, commit):
""" Serialize the tags we want to set for storage in the AGFI description """
return """firesim-buildtriplet:{},firesim-deploytriplet:{},firesim-commit:{}""".format(buildtriplet,deploytriplet,commit)
|
def score_sort_cmp(es_hit):
"""comparator for sorting by sentiment"""
return es_hit['vader_score']['compound']
|
def get_parameters(current, puzzle_input, opcode):
"""extracts the parameters from the input and updates the current location
"""
if opcode == '03' or opcode == '04':
params = [puzzle_input[current]]
current += 1
else:
params = [puzzle_input[current],
puzzle_input[current+1],
puzzle_input[current+2]]
current += 3
return params, current
|
def icoalesce(iterable, default=None):
"""Returns the first non-null element of the iterable.
If there is no non-null elements in the iterable--or the iterable is
empty--the default value is returned.
If the value to be returned is an exception object, it is raised instead.
"""
result = next((i for i in iterable if i is not None), default)
if isinstance(result, Exception):
raise result
return result
|
def getitem(obj, key=0, default=None):
"""Get first element of list or return default"""
try:
return obj[key]
except:
return default
|
def spin(pgms, move):
"""Spin the last move program to the front.
>>> spin(['a', 'b', 'c', 'd', 'e'], 1)
['e', 'a', 'b', 'c', 'd']
>>> spin(['a', 'b', 'c', 'd', 'e'], 3)
['c', 'd', 'e', 'a', 'b']
"""
return pgms[-move:] + pgms[:-move]
|
def make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
|
def compatible_shape(shape1,shape2):
"""Find the smallest shape larger than shape1 that can be broadcast
to shape2"""
shape = []
n = min(len(shape1),len(shape2))
for i in range(0,n):
if shape1[-1-i] == 1: shape = [1]+shape
else: shape = [shape2[-1-i]]+shape
return tuple(shape)
|
def ContinuedLine(level3, towns):
"""Return true if this seems continued line."""
for town in towns:
if level3.startswith(town):
return False
return True
|
def ToUnixLineEnding(s):
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
return s.replace('\r\n', '\n').replace('\r', '\n')
|
def deg2dms(val, delim=':'):
""" Convert degrees into hex coordinates """
if val < 0:
sign = -1
else:
sign = 1
d = int( sign * val )
m = int( (sign * val - d) * 60. )
s = (( sign * val - d) * 60. - m) * 60.
return '{}{}{}{}{}'.format( sign * d, delim, m, delim, s)
|
def decode_labels(labels):
"""Validate labels."""
labels_decode = []
for label in labels:
if not isinstance(label, str):
if isinstance(label, int):
label = str(label)
else:
label = label.decode('utf-8').replace('"', '')
labels_decode.append(label)
return labels_decode
|
def pairless_grads(ch_names):
"""Returns indexes of channels for which the first three numbers of the name
are present only once.
This means that if ['MEG 1232', 'MEG 1332', 'MEG 1333'] is given,
then [0] should be returned.
Parameters
----------
ch_names : list
List of channel names, e.g. info['ch_names']
Returns
-------
list
list of indexes to input array where the channels do not have a pair.
"""
stems = [name[:-1] for name in ch_names]
only_once = [stem for stem in stems if stems.count(stem) == 1]
ch_idxs = [name_idx for name_idx, name in enumerate(ch_names) if name[:-1] in only_once]
return ch_idxs
|
def remove_extra_spaces(s):
"""
Remove unnecessary spaces
:param s:
:return:
"""
return " ".join(s.split())
|
def run_in_frontend(src):
""" Check if source snippet can be run in the REPL thread, as opposed to GUI mainloop
(to prevent unnecessary hanging of mainloop).
"""
if src.startswith('_ip.system(') and not '\n' in src:
return True
return False
|
def forward_path_parser(_input):
"""Parsing plain dict to nested."""
def create_keys_recursively(key, current_tree):
"""Update current tree by key(s)."""
if key not in current_tree:
last = keys.pop()
# pylint: disable=undefined-loop-variable
# this value defined in the shared outer-function scope
dict_update = {last: value}
for _key in reversed(keys):
dict_update = {_key: dict_update}
current_tree.update(dict_update)
else:
keys.pop(0) # drop the first item that already in the tree, try next
create_keys_recursively(keys[0], current_tree[key])
output = {}
for key, value in _input.items():
keys = key.split('/')
create_keys_recursively(keys[0], output)
return output
|
def jiffer_status_string(pybert) -> str:
"""Return the jitter portion of the statusbar string."""
try:
jit_str = " | Jitter (ps): ISI=%6.3f DCD=%6.3f Pj=%6.3f Rj=%6.3f" % (
pybert.isi_dfe * 1.0e12,
pybert.dcd_dfe * 1.0e12,
pybert.pj_dfe * 1.0e12,
pybert.rj_dfe * 1.0e12,
)
except:
jit_str = " | (Jitter not available.)"
return jit_str
|
def indices(a, func):
"""
Get indices of elements in an array which satisfies func
>>> indices([1, 2, 3, 4], lambda x: x>2)
[2, 3]
>>> indices([1, 2, 3, 4], lambda x: x==2.5)
[]
>>> indices([1, 2, 3, 4], lambda x: x>1 and x<=3)
[1, 2]
>>> indices([1, 2, 3, 4], lambda x: x in [2, 4])
[1, 3]
"""
return [i for (i, val) in enumerate(a) if func(val)]
|
def chop_duplicate_ends(word):
"""Remove duplicate letters on either end, if the are adjacent.
Args:
words (list): The list of words
Returns:
list: An updated word list with duplicate ends removed for each word.
"""
if word[0] == word[1]:
word = word[1:]
if word[-2:-1] == word[-1:]:
word = word[:-1]
return word
|
def le_dtuple(d1, d2):
"""Return if d1_i <= d2_i as sparse vectors."""
d2_dict = dict(d2)
return all(gen in d2_dict and exp <= d2_dict[gen] for gen, exp in d1)
|
def getCheckedCArgs(argument_list):
"""
Convert the compilation arguments (include folder and #defines)
to checked C format.
:param argument_list: list of compiler argument.
:return: argument string
"""
clang_x_args = []
for curr_arg in argument_list:
if curr_arg.startswith("-D") or curr_arg.startswith("-I"):
clang_x_args.append('-extra-arg=' + curr_arg)
return clang_x_args
|
def associate(first_list, second_list,offset,max_difference):
"""
Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim
to find the closest match for every input tuple.
Input:
first_list -- first dictionary of (stamp,data) tuples
second_list -- second dictionary of (stamp,data) tuples
offset -- time offset between both dictionaries (e.g., to model the delay between the sensors)
max_difference -- search radius for candidate generation
Output:
matches -- list of matched tuples ((stamp1,data1),(stamp2,data2))
"""
first_keys = first_list.keys()
second_keys = second_list.keys()
potential_matches = [(abs(a - (b + offset)), a, b)
for a in first_keys
for b in second_keys
if abs(a - (b + offset)) < max_difference]
potential_matches.sort()
matches = []
for diff, a, b in potential_matches:
if a in first_keys and b in second_keys:
first_keys.remove(a)
second_keys.remove(b)
matches.append((a, b))
matches.sort()
return matches
|
def dtype_reducer(the_dtype, wanted_cols):
"""Remove extraneous columns from the dtype definition.
In cases where a data file includes some columns of data that are
not of particular interest or relevance, this function can remove
those columns that are not needed (or more accurately, retain only
the columns that are desired). This function was originally created
for the purpose of importing the EIA ktek data, which may include
some columns with mixed data types that are difficult to import and
not relevant to this analysis anyway. Avoiding those columns
entirely is easier than developing far more sophisticated functions
to import the data.
Args:
the_dtype (list): A list of tuples with each tuple containing two
entries, a column heading string, and a string defining the
data type for that column. Formatted as a numpy dtype list.
wanted_cols (list): A list of strings that represent the names of
the columns from the ktek data that should be kept.
Returns:
col_loc is a list of the numeric indices for the positions of
the columns retained in the dtype definition (and thus which
columns should be retained when importing the full data file).
shortened_dtype is the dtype definition (in numpy dtype format)
that includes only the desired columns.
"""
# Strip apart the dtype definition
headers, dtypes = zip(*the_dtype)
# Preallocate list for the numeric column indices of the wanted_cols
col_loc = []
# Make a list of the numeric index positions of the desired columns
for entry in wanted_cols:
try:
col_loc.append(headers.index(entry))
except ValueError:
print('Desired column "' + entry + '" not found in the data.')
# Update the headers and dtypes by building them as new lists with
# only the desired columns and then recombining them into the numpy
# dtype definition format
headers = [headers[i] for i in col_loc]
dtypes = [dtypes[i] for i in col_loc]
shortened_dtype = list(zip(headers, dtypes))
return col_loc, shortened_dtype
|
def _format_text(text):
"""Format text."""
text = text.replace("-", "--")
text = text.replace("_", "__")
text = text.replace(" ", "_")
return text
|
def get_all_exported_url_names(json_urlpatterns):
"""
Get all names and namespaces in some URLconf JSON.
:param json_urlpatterns: list of JSON URLconf dicts
:return: list of strings; url_names and namespaces
"""
url_names = set()
for url in json_urlpatterns:
included_urls = url.get("includes")
if included_urls:
if url["namespace"] is not None:
url_names.add(url["namespace"])
url_names |= get_all_exported_url_names(included_urls)
else:
url_names.add(url["name"])
return url_names
|
def covered(string='covered'):
"""
prints a string
Parameters
----------
string : int
the string to be printed
Returns
-------
exit code : int
0
"""
print(string)
return 0
|
def dot(v, w):
"""v_1 * w_1 + ... + v_n * w_n"""
return sum(v_i * w_i
for v_i, w_i in zip(v, w))
|
def extract_pairs(raw):
"""Return a list of tuple pairs from a string of comma-separated pairs"""
try:
pairs = list(set([(p.split("-")[0].strip().upper(), p.split("-")[1].strip().upper()) for p in raw.split(",")]))
except IndexError as e:
raise IndexError("Invalid pair")
for x, y in pairs:
if not (len(x) > 1 and len(y) > 1):
raise Exception(f'Invalid pair: {x}-{y}')
if len(pairs) is 0:
raise Exception("No valid pairs")
return pairs
|
def internalNodeIP(node_id):
"""Return IP address of radio node on internal network"""
return '10.10.10.{:d}'.format(node_id)
|
def get_number_of_stimuli(stimuli_dir):
"""Note that for the natural images, it makes sense to think of the batch
size as the number of bins"""
# for pure conditions (natural or optimized):
if "pure" in stimuli_dir:
n_reference_images = 9
batch_size_natural = (
n_reference_images + 1
) # number of reference images (9) + 1 query image
batch_size_optimized = n_reference_images
# for joint condition:
elif "mixed" in stimuli_dir:
n_reference_images = 5
batch_size_natural = (
n_reference_images + 1
) # number of reference images (9) + 1 query image
batch_size_optimized = n_reference_images - 1
else:
raise ValueError("You are not choosing the correct stimuli_dir!")
return n_reference_images, batch_size_natural, batch_size_optimized
|
def is_valid(id_str, id_len=16):
""" Simple check for a valid zerotier network_id
Args:
id_str (str): Zerotier network id or address
Returns:
bool: True if the id_str is valid, False otherwise
"""
if len(id_str) != id_len:
return False
try:
# expected to be valid hexadecmal string
int(id_str, 16)
except ValueError:
return False
return True
|
def processedcount(file_list):
"""Counts to how many files SSP has already been added to."""
n = 0
for item in file_list:
if item[-7:-4] == 'ssp':
n = n+1
return n
|
def underscore_to_camelcase(name):
"""
Convert new-style method names with underscores to old style camel-case
names.
::
>>> underscore_to_camelcase('assert_equal')
... 'assertEqual'
>>> underscore_to_camelcase('assert_not_equal')
... 'assertNotEqual'
>>> underscore_to_camelcase('assertEqual')
... 'assertEqual'
>>> underscore_to_camelcase('assertNotEqual')
... 'assertNotEqual'
"""
return name[0].lower() + \
name.replace('_', ' ').title().replace(' ', '')[1:]
|
def get_qa_Z_range():
"""
Returns qa Z range
"""
return (0.0, 130.0) # in mm
|
def bellman_ford(nodes, edges, source):
"""
Bellman ford shortest path algorithm
Parameters
----------
nodes : set
names of all nodes in the graph
edges : list
list of dependencies between nodes in the graph
[(node1, node2, weight), ...]
source : str
name of source node
Returns
-------
out : (bool, dict)
(has_cycle, distances) has_cycle var check if cycle in the graph
distance dict show len from source node to all nodes in the graph
"""
# initialize distance to every node as infinity
distances = {node: float('Inf') for node in nodes}
# set distance to source node as zero
distances[source] = 0
# repeat n-1 times
for _ in range(1, len(nodes)):
# iterate over every edge
for src, dest, weight in edges:
if distances[dest] > distances[src] + weight:
# relax
distances[dest] = distances[src] + weight
has_cycle = False
for src, dest, weight in edges:
if distances[dest] > distances[src] + weight:
# If a node can still be relaxed,
# it means that there is a negative cycle
has_cycle = True
return has_cycle, distances
|
def listify(x):
"""
Returns a list
"""
if not hasattr(x, '__len__'):
return [x]
else:
return x
|
def params_get(path, params):
"""Read a key/path from loaded params.
Parameters
----------
path : str
The .-delimited path to the value to return. Currently supports dict keys
but not numeric array indices.
params : dict
Params as read using read_params().
"""
r = params
for p in path.split("."):
r = r[p]
return r
|
def price_range(prices):
""" Set price limits """
min_range, max_range = prices
if not min_range:
min_range = 0
if not max_range:
# How to make infinite?
max_range = 999999999
return min_range, max_range
|
def klucb(x, d, div, upperbound, lowerbound=-float("inf"), precision=1e-6):
"""The generic klUCB index computation.
Input args.:
x,
d,
div:
KL divergence to be used.
upperbound,
lowerbound=-float('inf'),
precision=1e-6,
"""
l = max(x, lowerbound)
u = upperbound
while u - l > precision:
m = (l + u) / 2
if div(x, m) > d:
u = m
else:
l = m
return (l + u) / 2
|
def is_strictly_legal_content(content):
"""
Filter out things that would violate strict mode. Illegal content
includes:
- A content section that starts or ends with a newline
- A content section that contains blank lines
"""
if content.strip("\r\n") != content:
return False
elif not content.strip():
return False
elif "\n\n" in content:
return False
else:
return True
|
def asjson(obj):
"""Return a string: The JSON representation of the object "obj".
This is a peasant's version, not intentended to be fully JSON
general."""
return repr(obj).replace("'", '"')
|
def inversions(constants, variables):
"""Number of swaps"""
if variables:
pow2 = pow(2, variables - 1, 1_000_000_007)
return pow2 * (constants * 2 + variables)
return constants
|
def is_valid(isbn):
"""Varify if given number is a valid ISBN 10 number"""
# Setup for validity check
digits = [int(n) for n in isbn if n.isnumeric()]
if len(digits) == 9 and isbn[-1].upper() == "X":
digits.append(10)
# length check to weed out obvious wrong answers
if len(digits) != 10:
return False
# Validity check
sum_ = sum((len(digits)-i)*v for i, v in enumerate(digits))
return sum_ % 11 == 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.