content stringlengths 42 6.51k |
|---|
def image_path_from_desc(desc):
""" Get the path to the image from its description. """
return "/tensorflow/data/img/" + desc["name"] + ".jpeg" |
def probability_of_improvement_sub(mu, std, target):
"""Sub function to compute the probability of improvement acquisition function.
Args:
mu: n x 1 posterior mean of n query points.
std: n x 1 posterior standard deviation of n query points (same order as
mu).
target: target value to be improved ... |
def getTrueFalseMessage(condition, trueMessage, falseMessage):
"""Returns trueMessage if condition is True, otherwise returns falseMessage.
:param bool condition: condition parameter
:param str trueMessage: True case string message
:param str falseMessage: False case string message
:return: appropr... |
def operation_in(value, test):
"""Check if value is in the test list."""
found = False
for test_in in test:
if test_in in value:
found = True
break
return found |
def can_inventory_groups(configs):
"""A simple function that validates required inputs to inventory groups.
Args:
The input flags converted to a dict.
Returns:
Boolean
"""
required_execution_config_flags = [
configs.get('domain_super_admin_email'),
configs.get('grou... |
def getFolder(filename: str) -> str:
"""
Returns the folder on which the given path is stored
Args:
filename: the path of the file
Returns:
the folder of the same given file
"""
filename = filename.replace("\\", "/")
try:
filename = filename[0:-filename[... |
def is_float(test_str):
"""Returns True if the string appears to be a valid float."""
try:
float(test_str)
return True
except ValueError:
pass
return False |
def BTToDLLUtil(root):
"""This is a utility function to convert the binary tree to doubly linked list. Most of the core task
is done by this function."""
if root is None:
return root
# Convert left subtree and link to root
if root.left:
# Convert the left subtree
left = BTToDLLUtil(root.left)
# Find... |
def get_color_from_color_code(color_code):
"""Converts a color code to a color name.
Args:
color_code (list): color code
Returns:
str: color name
"""
if color_code[0]:
return 'red'
elif color_code[1]:
return 'green'
elif color_code[2]:
return 'blue'
... |
def make_good_url(url=None, addition="/"):
"""Appends addition to url, ensuring the right number of slashes
exist and the path doesn't get clobbered.
>>> make_good_url('http://www.server.com/anywhere', 'else')
'http://www.server.com/anywhere/else'
>>> make_good_url('http://test.com/', '/somewhere/o... |
def find_tuple_values(tpl, values):
"""
Allow to find a key which is related to a value in python tuple
"""
return [str(obj[0]) for obj in tpl if obj[1] in values] |
def convert2json_type(obj: set) -> list:
"""Convert sets to lists for JSON serialization."""
if isinstance(obj, set):
return list(obj)
else:
raise TypeError(f"Object of type {type(obj)} is not JSON serializable.") |
def if_string_then_convert_to_bytes(val):
"""
Convert string to bytes array
Parameters
----------
val : str or bytes
Returns
-------
out : bytes
"""
if isinstance(val, str):
return bytearray(val, 'ascii')
return val |
def get_endpoint_headers(headers):
"""
Given a dictionary-like headers object, return the names of all
headers in that set which represent end-to-end (and not intermediate
or connection headers).
"""
intermediate_headers = [
'connection',
'keep-alive',
'proxy-authenticate... |
def get_provenance_record(plot_file, caption, run):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'caption': caption,
'statistics': ['mean'],
'domains': ['global'],
'plot_type': 'metrics',
'authors': [
'rumbold_heather',
... |
def _parse_filter_args_str(input):
"""
Parse user input specification.
:param Iterable[Iterable[str]] input: user command line input,
formatted as follows: [[arg=txt, arg1=txt]]
:return dict: mapping of keys, which are input names and values
"""
lst = []
for i in input or []:
... |
def is_bool(value):
""" Checks if the value is a bool """
return value.lower() in ['true', 'false', 'yes', 'no', 'on', 'off'] |
def append_default_columns(start, num):
"""appends num string to a list as col_[index]"""
columns = []
for i in range(start, num):
columns.append("col_" + str(i + 1))
return columns |
def numfmt(x, pos):
"""
Plotting subfunction to automate tick formatting from metres to kilometres
B.G
"""
s = '{:d}'.format(int(round(x / 1000.0)))
return s |
def hms_to_s(h=0, m=0, s=0):
""" Get total seconds from tuple (hours, minutes, seconds) """
return h * 3600 + m * 60 + s |
def group_by_keys(dict_list, keys):
"""
>>> data = [
... {'a': 1, 'b': 2},
... {'a': 1, 'b': 3}
... ]
>>> group_by_keys(data, ['a', 'b'])
{(1, 2): [{'a': 1, 'b': 2}], (1, 3): [{'a': 1, 'b': 3}]}
"""
groups = {}
for d in dict_list:
value = tuple((d[k] for k in keys... |
def split_list_into_sublists(items):
"""Split the list of items into multiple sublists.
This is to make sure the string composed from each sublist won't exceed
80 characters.
Arguments:
- items: a list of strings
"""
chuncks = []
chunk = []
chunk_len = 0
for item in items:
chunk_len += len(... |
def get_union_set(group):
""" Task 1: gets union set of all questions in a group.
Just add every letter to a set to get the union.
:param group: list of strings
"""
question_set = set()
for declaration in group:
for letter in declaration:
question_set.add(letter)
return... |
def parse_chunk_header_file_range(file_range):
"""Parses a chunk header file range.
Diff chunk headers have the form:
@@ -<file-range> +<file-range> @@
File ranges have the form:
<start line number>,<number of lines changed>
Args:
file_range: A chunk header file range.
Returns:
A tuple (ran... |
def generate_colour_for_number(value, scale_upper_bound=100):
"""
This will just be a scale between red and green and
non-numeric values being gray because I said so
This'd be a whole lot easier if I could use the HSV colour space tbh
"""
try:
number = float(value)
except ValueError:... |
def collapse_into_one_list(data):
"""
Collapse list of list of strings into one list of strings
:param data: list of list of strings
:return: list of strings
"""
data_ = list()
for i in range(len(data)):
for j in range(len(data[i])):
data_.append(data[i][j])
return d... |
def find_duplicates(_list):
"""a more efficient way to return duplicated items
ref: https://www.iditect.com/guide/python/python_howto_find_the_duplicates_in_a_list.html
:arg list _list: a python list
"""
first_seen = set()
first_seen_add = first_seen.add
duplicates = set(i for i in _list if... |
def get_mean(grade_list):
"""Calculate the mean of the grades"""
suma = 0 # Do you think 'sum' is a good var name? Run pylint to figure out!
for grade in grade_list:
suma = suma + grade
mean = suma / len(grade_list)
return mean |
def remove_new_lines(text: str) -> str:
"""
Strip away new lines at end.
Args:
t: Text
Returns:
Text without newline at end.
"""
if isinstance(text, str):
return text.replace("\\n", "").strip()
return text |
def unlistify(l, depth=1, typ=list, get=None):
"""Return the desired element in a list ignoring the rest.
>>> unlistify([1,2,3])
1
>>> unlistify([1,[4, 5, 6],3], get=1)
[4, 5, 6]
>>> unlistify([1,[4, 5, 6],3], depth=2, get=1)
5
>>> unlistify([1,(4, 5, 6),3], depth=2, get=1)
(4, 5, 6... |
def get_best_name(phenomena):
"""
Create a best_name field which takes the best name as defined by the preference order
:param phenomena: phenomena attributes in form [{"name":"standard_name","value":"time"},{"name":"---","value":"---"},{}...]
:return: best_name(string)
"""
preference_order = ["... |
def add_slash(text: str):
"""returns the same text with slash at the end"""
return text + '/' |
def common_contains(obj, key):
"""Checks the existence of a key or index in a mapping.
Works with numpy arrays, lists, and dicts.
Args:
``obj`` (list,array,dict): Mapping
``key`` (int): Index or key of the element to retrieve
Returns:
``True`` if ``key`` in ``obj``, ot... |
def fibonacci(num):
""" Muy bonito, pero no se usa por la naturaleza del problema
https://projecteuler.net/problem=2
"""
memory = {0: 1, 1: 1}
result = 0
def fib(a):
if a in memory:
return memory[a]
memory[a] = fib(a - 1) + fib(a - 2)
return memory[a]
... |
def _meta_attributes(meta):
"""Extract attributes from a "meta" object."""
meta_attrs = {}
if meta:
for attr in dir(meta):
if not attr.startswith("_"):
meta_attrs[attr] = getattr(meta,attr)
return meta_attrs |
def both_cov(s):
""" Ensure tracking object has both population and sample cov """
if s.get('n_samples')>1:
if s.get('scov') is None and s['pcov'] is not None:
s['scov'] = s['n_samples']/(s['n_samples']-1)*s['pcov']
if s.get('pcov') is None and s['scov'] is not None:
s['p... |
def produced_files(nhosts, jobid, njobtasks):
"""
Associates file (to be written) to each job ID
:param nhosts: total number of hosts
:param jobid: job ID
:param njobtasks: N of tasks per job
:return: hosts_files: list of files (and associated host) for this jobID
"""
return [(
... |
def compute_interval_overlaps(A, B, min_overlap=0, is_sorted=False):
"""
Given two lists, A and B, of interval tuples in the form (name, start, end)
return a list of tuples of the form:
(A_name, B_name, overlap_start, overlap_end)
for every pair of intervals that overlaps by at least <min_overlap>... |
def svc_ids(svc):
"""
Returns the account ID and service ID of a given service.
"""
return svc['accountId'], svc['id'] |
def ConvertSequenceToUnicode(sequence, names_to_index):
"""
Returns a unicode string from a sequence.
@param sequence: the node sequence from a trace
@param names_to_index: converts function ids to an index for unicode sequencing.
"""
start_unicode_index = 65
unicode_string = ''
for node... |
def xemm_signal(prices, fees):
"""
Signal generation to bakctest a Cross-Exchange Market Maker strategy.
Parameters
----------
prices: dict
with the historical ticks or prices, must be a dictionary with the following structure:
{'origin_exchange: {timestamp: {}}, 'destination_e... |
def transpose_blocks(blocks, block_len):
"""
Returns a transposition of the elements in items.
E.g. ["AB","CD"] -> [["A", "C"], ["B", "D"]]
"""
transpositions = []
for i in range(block_len):
transpositions.append([block[i] for block in blocks])
return transpositions |
def computeColorIndex(coverage, cutoffs, numColors) :
"""Computes index into color list from coverage.
Keyword arguments:
coverage - The coverage percentage.
cutoffs - The thresholds for each color.
"""
numIntervals = min(numColors, len(cutoffs)+1)
for c in range(numIntervals-1) :
i... |
def remove_tweet_id(tweet):
"""
DESCRIPTION:
removes the id from a string that contains an id and a tweet
e.g "<id>,<tweet>" returns "<tweet>"
INPUT:
tweet: a python string which contains an id concatinated with a tweet of the following format:
... |
def SortedObject(obj):
"""Returns sorted object (with nested list/dictionaries)."""
if isinstance(obj, dict):
return sorted((k, SortedObject(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(SortedObject(x) for x in obj)
if isinstance(obj, tuple):
return list(sorted(SortedObject(x... |
def PRA2HMS (ra):
"""
Convert a right ascension in degrees to hours, min, seconds
* ra = Right ascension in deg.
"""
################################################################
p = ra / 15.0
h = int(p)
p = (p - h) * 60.0
m = int(p)
s = (p - m) * 60.0
out = " %2.2d %2... |
def _is_simple_numeric(data):
"""Test if a list contains simple numeric data."""
for item in data:
if isinstance(item, set):
item = list(item)
if isinstance(item, list):
if not _is_simple_numeric(item):
return False
elif not isinstance(item... |
def format_time(start, end):
"""
Format length of time between ``start`` and ``end``.
:param start: the start time
:param end: the end time
:return: a formatted string of hours, minutes, and seconds
"""
hours, rem = divmod(end - start, 3600)
minutes, seconds = divmod(rem, 60)
return... |
def PropBankId(name):
"""Convert PropBank name to SLING id."""
underscore = name.find('_')
period = name.find('.')
if underscore != -1 and period > underscore:
name = name[:underscore] + name[period:]
return '/pb/' + name.replace(".", "-") |
def reversed_dict(choices):
"""Create a reverse lookup dictionary"""
return dict([(b, a) for a, b in choices]) |
def get_grid_size(grid):
"""Get sizes of grid."""
sizes = []
sub_grid = grid
while isinstance(sub_grid, list):
sizes.append(len(sub_grid))
sub_grid = sub_grid[0]
return sizes[::-1] |
def straightforward_search_1d(a):
"""
@fn straightforward_search_1d
"""
if (a[0] >= a[1]):
return 0
N = a.length()
if (a[N - 1] >= a[N - 2]):
return N - 1;
for i in range(1, N - 1):
if (a[i] >= a[i - 1] and a[i] >= a[i + 1]):
return i
return -1 |
def li(lst):
"""return list of li html tags."""
return ['<li>%s</li>' % element for element in lst] |
def i2b(n, minimal = -1):
"""Integer to Bytes (Big Endian)"""
# If the integer is null, just return the empty byte with the desired
# length.
if n == 0:
return b"\0" if minimal <= 0 else b"\0" * minimal
b = b""
while n > 0:
neon = n & 255
# Latin is used so that we have the whole [0;256[ range for ourselv... |
def match_all(string):
"""Whether the resulting query will not filter anything"""
return string.strip() == "" |
def average(data_list):
"""
Computes average value for a list of values.
average(data_list) -> average
@type data_list: list
@param data_list: list of values to compute the average.
@rtype: float
@return: the floating-point average.
"""
if data_list is None:
return ... |
def comp(array1, array2):
"""
:param array1: list with numbes to evaluate
:param array2: squares of array1
:rtype bool
:return: if squares of array1 are in array2
"""
if array1 is None or array2 is None:
return True
if len(array1) == 0 or len(array2) == 0:
return True
... |
def constructCommonRating(tup1, tup2):
"""
Args:
tup1 and tup2 are of the form (user, [(movie, rating)])
Returns:
((user1, user2), [(rating1, rating2)])
"""
user1, user2 = tup1[0], tup2[0]
mrlist1 = sorted(tup1[1])
mrlist2 = sorted(tup2[1])
ratepair = []
index1, inde... |
def is_overridden(obj):
"""Check whether a function has been overridden.
Note, this only works for API calls decorated with OverrideToImplementCustomLogic
or OverrideToImplementCustomLogic_CallToSuperRecommended.
"""
return getattr(obj, "__is_overriden__", True) |
def sigmoid_derivative(activation_values):
"""
Derivative of the sigmoid function
:param activation_values: activation values
:return: result of applying the derivative function
"""
return activation_values * (1.0 - activation_values) |
def parse_csv_string(s):
"""Parse a simple comma-separated tokens to a list of strings,
as used in the qop parameter in Digest authentication.
"""
return [x for x in (x.strip() for x in s.split(',')) if x != ''] |
def sortLocalSymbol(s):
"""Given tuple of (occ date/right/strike, symbol) return
tuple of (occ date, symbol)"""
return (s[0][:6], s[1]) |
def parse_package_line(line):
"""The line looks like this:
package: name='com.facebook.testing.tests' versionCode='1' versionName=''"""
for word in line.split():
if word.startswith("name='"):
return word[len("name='") : -1] |
def parse_header(header):
"""
Extract size= and barcode= fields from the FASTA/FASTQ header line
>>> parse_header("name;size=12;barcode=ACG;")
('name', 12, 'ACG')
>>> parse_header("another name;size=200;foo=bar;")
('another name', 200, None)
"""
fields = header.split(';')
query_name... |
def conf_to_xml(conf):
"""
Converts LensConf given as dictionary to xml string
:param conf: a Dictionary
:return: LensConf xml string representation
>>> conf_to_xml(None)
'<conf></conf>'
>>> conf_to_xml({})
'<conf></conf>'
>>> conf_to_xml({'a':'b'})
'<conf><properties><entry><key... |
def has_ioslike_error(s):
"""Test whether a string seems to contain an IOS-like error."""
tests = (
s.startswith('%'), # Cisco, Arista
'\n%' in s, # A10, Aruba, Foundry
'syntax error: ' in s.lower(), # Brocade VDX, F5 BIGIP
s.startswi... |
def urldecode_plus(s):
"""Decode urlencoded string (including '+' char).
Returns decoded string
"""
s = s.replace('+', ' ')
arr = s.split('%')
res = arr[0]
for it in arr[1:]:
if len(it) >= 2:
res += chr(int(it[:2], 16)) + it[2:]
elif len(it) == 0:
res... |
def filter_insignificant(chunk, tag_suffixes=['DT', 'CC']): # pylint: disable = W0102
"""
Removes insignificant words from the chunk
"""
good = []
for word, tag in chunk:
relevant = True
for suffix in tag_suffixes:
if tag.endswith(suffix):
relevant ... |
def _GetMetaDict(items, key, value):
"""Gets the dict in items that contains key==value.
A metadict object is a list of dicts of the form:
[
{key: value-1, ...},
{key: value-2, ...},
...
]
Args:
items: A list of dicts.
key: The dict key name.
value: The dict key value.
R... |
def get_tile_start_end_index(tile_number, tile_size,
tile_offset=None, tile_separation=None):
"""Calculate the starting and ending index along a single dimension"""
if not tile_separation:
tile_separation = tile_size
if not tile_offs... |
def is_palindrome(s):
""" (str) -> bool
Precondition: String only contains lowercase alphabetic letters.
Return True iff s is a palindrome.
>>> is_palindrome('madam')
True
>>> is_palindrome('run')
False
"""
return s == s[::-1] |
def split_long_sent(tokenizer, tokens, tags, shapes):
"""This method is never used"""
max_len = 384
lst = [tokenizer.tokenize(w) for w in tokens]
lst = [item for sublist in lst for item in sublist]
output = []
if len(lst) >= max_len * 2:
# print(len(lst))
idx = len(tokens) // 3
... |
def read_to_bracketed(delimiter, rest):
"""
Read characters from rest string which is expected to start with a '['.
If rest does not start with '[', return a tuple (None, rest, 'does not begin with [').
If rest string starts with a '[', then read until we find ']'.
If no ']' is found, return a tupl... |
def _get_doc_offset(offset, document):
"""
:type offset: list[str]
:type document: dict
>>> _get_doc_offset(['a'], {'a': 4})
4
>>> _get_doc_offset(['a', 'b'], {'a': {'b': 4}})
4
>>> _get_doc_offset(['a'], {})
Traceback (most recent call last):
...
KeyError: 'a'
"""
v... |
def bs (link):
""" Replace \\ with \\\\ because RST wants it that way. """
return link.replace ('\\', '\\\\') |
def keys_output(mode, used_key_one, used_key_two, used_key_three):
"""
Return the keys used for encryption or decryption,
based on mode that was used.
"""
if mode == "E":
return print("Keys used for encryption were: '{}', '{}', '{}'.".format(
used_key_one, used_key_two, used_key_... |
def toLowerCase(str):
"""
:type str: str
:rtype: str
"""
return str.lower() |
def create_grid(size=4): # Fonction renvoyant une grille de taille size
"""
Creates and returns a two-dimensional (size x size) square matrix.
:param size: Size of the grid (default 4)
:return: List with "size" elements, each of them a list of "size" elements filled with 0.
"""
game_grid = []
... |
def give_time_series(x,y):
"""Rearrange X,Y value pairs or points according to X's order"""
xall = []
yall = []
for x1,y1 in sorted(zip(x,y)):
xall.append(x1)
yall.append(y1)
return (xall,yall) |
def format_code_dep(code):
"""As the department number is not always filled in
the same way in the data, returns the two digit code."""
return f"0{code}" if len(code) == 1 else code |
def to_hex(ch):
"""Converts linear channel to sRGB and then to hexadecimal"""
# Author: @brecht
# Link: https://devtalk.blender.org/t/get-hex-gamma-corrected-color/2422/2
if ch < 0.0031308:
srgb = 0.0 if ch < 0.0 else ch * 12.92
else:
srgb = ch ** (1.0 / 2.4) * 1.055 - 0.055
re... |
def is_iterable(obj):
"""
Returns whether or not given Python object is iterable
:param obj: object
:return: bool
"""
try:
it = iter(obj)
except TypeError:
return False
return True |
def normalize(a):
"""Returns a normalized version of vector a.
a - [float, float]
return - [float, float]
"""
length = (a[0]**2+a[1]**2)**0.5
if(length> 0 ):
return [a[0]/length, a[1]/length]
else:
print("normalize error")
return a |
def convert_to_iops_actuals(iops_dict):
"""
Convert IOPS to MBPS fom percentage.
In case IOPS values are actual,
converts them to int from str
:param iops_dict: IOPS dict to convert.
:return: IOPS values converted to MBPS.
"""
iops_in_mbps = {}
for key, value in iops_dict.items():
... |
def calculate_kinetic_energy(mass, velocity):
"""Returns kinetic energy of mass [kg] with velocity level."""
return 0.5 * mass * velocity ** 2 |
def bounded_wegstein(f, x0, x1, y0, y1, x, yval, xtol, ytol):
"""False position solver with Wegstein acceleration."""
_abs = abs
if y1 < 0.: x0, y0, x1, y1 = x1, y1, x0, y0
dy = yval-y0
x_old = x = x if x0 < x < x1 or x1 < x < x0 else x0+dy*(x1-x0)/(y1-y0)
y = f(x)
yval_ub = yval + ytol
... |
def _merge_two_sorted_list(sorted_list_head, sorted_list_tail):
"""Merge two soretd list into one soreted list."""
sorted_list_result = list()
head_index = 0
tail_index = 0
len_head = len(sorted_list_head)
len_tail = len(sorted_list_tail)
while head_index < len_head and tail_index < len_tai... |
def status_to_str(status_code):
"""
Translates an int status code to a string that represents the status
Args:
status_code (int): the code of the status
Returns:
str: the string that represents the status
"""
statuses = {
10: "TAXI_WAITING",
11: "TAXI_MOVING_TO_... |
def parse_timeout(arg):
"""Parse timeout argument"""
if not arg:
return None
return int(arg) |
def fmt_bytesize(num: float, suffix: str = "B") -> str:
"""Change a number of bytes in a human readable format.
Args:
num: number to format
suffix: (Default value = 'B')
Returns:
The value formatted in human readable format (e.g. KiB).
"""
for unit in ["", "Ki", "Mi", "Gi", "Ti",... |
def addStoichiometry(sm, rxns, rxnIds, objFunc):
"""Add stoichiometry information to matrix"""
for r in rxns:
rid = r.getId()
rxnIds.append(rid)
for sp in r.getListOfReactants():
spName = sp.getSpecies()
# Be sure to skip boundary compounds
if spName n... |
def _filter_features(
batch,
feature_whitelist):
"""Remove features that are not whitelisted.
Args:
batch: A dict containing the input batch of examples.
feature_whitelist: A list of feature names to whitelist.
Returns:
A dict containing only the whitelisted features of the input batch.
""... |
def get_single_identifier(ext_id):
"""
Returns (type, value) tuple from a single external-id
"""
return ext_id.get('common:external-id-type'), ext_id.get('common:external-id-value') |
def makeMonthList(pattern):
"""Return a list of 12 elements based on the number of the month."""
return [pattern % m for m in range(1, 13)] |
def exponent_fmt(x, pos):
""" The two args are the value and tick position. """
return '{0:.0f}'.format(10 ** x) |
def filter_pre_string(_string: str, lines_to_cut: int) -> str:
"""
Filter the xml out of html
:param str _string:
:param int lines_to_cut:
"""
filtered_array = _string.splitlines()[lines_to_cut:]
filtered_string = "".join(filtered_array)
filtered_string = filtered_string.strip()
re... |
def parse_dispatch_specs(outfile_cli):
"""Return internal spec from CLI string field spec
>>> from pprint import pprint as pp
Model attribution
-----------------
Syntaxes uses MODEL:PATH
>>> pp(parse_dispatch_specs('model:/foo/bar'))
{'model': '/foo/bar'}
But if you don'... |
def add_string(a, b):
"""
Like `add` but coerces to strings instead of integers.
"""
return str(a) + str(b) |
def get_grid_edges(points):
"""Get edges of grid containing all points."""
grid_edges = []
for index in range(2):
point = []
for func in (min, max):
funciest_point = func(points, key=lambda item: item[index])
point.append(func(funciest_point))
grid_edges.appen... |
def distance(node1: dict, node2: dict) -> float:
"""
Dado dois nos, calcula a distancia euclidiana
"""
return ((node1['x'] - node2['x'])**2 + (node1['y'] - node2['y'])**2)**(1/2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.