content
stringlengths 42
6.51k
|
---|
def my_merge(list_1, list_2, key=lambda x: x):
""" Quick function to improve the performance of branch_and_bound
Uses the mergesort algorithm to save the headache of resorting the
entire agenda every time we modify it.
Given two sorted lists and a key, we merge them into one sorted list and
return the answer. Preference is given to the elements of the first list
in the cases of ties
"""
list_res = []
while list_1 and list_2:
if key(list_1[0]) <= key(list_2[0]):
list_res.append(list_1.pop(0))
else:
list_res.append(list_2.pop(0))
if list_1:
[list_res.append(elem) for elem in list_1]
elif list_2:
[list_res.append(elem) for elem in list_2]
return list_res
|
def path_to_model(path):
"""Return model name from path."""
epoch = str(path).split("phase")[-1]
model = str(path).split("_dir/")[0].split("/")[-1]
return f"{model}_epoch{epoch}"
|
def speed_wave(lst):
"""
Delete even indexes of list
:param lst: list of list
:return: list of odd indexes of the original list
"""
return lst[0::2]
|
def replace_tokens(string, os_name, os_code_name, os_arch):
"""Replace RPM-specific tokens in the repository base URL."""
for key, value in {
'$basearch': os_arch,
'$distname': os_name,
'$releasever': os_code_name,
}.items():
string = string.replace(key, value)
return string
|
def frame_ranges_to_string(frames):
"""
Take a list of numbers and make a string representation of the ranges.
>>> frame_ranges_to_string([1, 2, 3, 6, 7, 8, 9, 13, 15])
'[1-3, 6-9, 13, 15]'
:param list frames: Sorted list of frame numbers.
:return: String of broken frame ranges (i.e '[10-14, 16, 20-25]').
"""
if not frames:
return '[]'
if not isinstance(frames, list):
frames = list(frames)
frames.sort()
# Make list of lists for each consecutive range
ranges = [[frames.pop(0)]]
current_range_index = 0 # index of current range
for x in frames:
if x - 1 == ranges[current_range_index][-1]:
ranges[current_range_index].append(x)
else:
current_range_index += 1
ranges.append([x])
range_strings = []
for x in ranges:
if len(x) > 1:
range_strings.append('-'.join([str(x[0]), str(x[-1])]))
else:
range_strings.append(str(x[0]))
complete_string = '[' + ', '.join(range_strings) + ']'
return complete_string
|
def strip_some_punct(s):
"""
Return a string stripped from some leading and trailing punctuations.
"""
if s:
s = s.strip(''','"};''')
s = s.lstrip(')')
s = s.rstrip('&(-_')
return s
|
def _get_changelist(perforce_str):
"""Extract change list from p4 str"""
import re
rx = re.compile(r'Change: (\d+)')
match = rx.search(perforce_str)
if match is None:
v = 'UnknownChangelist'
else:
try:
v = int(match.group(1))
except (TypeError, IndexError):
v = "UnknownChangelist"
return v
|
def remove(base, string):
"""Remove a substring from a string"""
return base.replace(string, "")
|
def score(dice, category):
"""
The dice game [Yacht](https://en.wikipedia.org/wiki/Yacht_(dice_game)) is from
the same family as Poker Dice, Generala and particularly Yahtzee, of which it
is a precursor. In the game, five dice are rolled and the result can be entered
in any of twelve categories. The score of a throw of the dice depends on
category chosen.
"""
# First we check if the category asked is within the 'ONES - SIXES' range and
# return the corresponding sum of the digits present.
if category in [1, 2, 3, 4, 5, 6]:
return sum([x for x in dice if x == category])
# Full House is the most tricky. We sort the dices and check of occurences of the
# first and the last term. If they are 2,3 or 3,2 then just return the sum, else 0
elif category == 'FULL_HOUSE':
lst = sorted(dice)
i = lst.count(dice[0])
j = lst.count(dice[-1])
if (i == 2 and j == 3) or (i == 3 and j == 2):
return sum(dice)
else:
return 0
elif category == 'FOUR_OF_A_KIND':
return [x*4 if dice.count(x) >= 4 else 0 for x in dice][0]
elif category == 'LITTLE_STRAIGHT':
if sorted(dice) == [1, 2, 3, 4, 5]:
return 30
else:
return 0
elif category == 'BIG_STRAIGHT':
if sorted(dice) == [2, 3, 4, 5, 6]:
return 30
else:
return 0
elif category == 'CHOICE':
return sum(dice)
elif category == 'YACHT':
return [50 if dice.count(x) == 5 else 0 for x in dice][0]
|
def input_lines_to_dict(lines) -> dict:
"""Accept lines from passport batch file and create a dictionary"""
passport = {}
for line in lines:
entries = line.split(" ")
for entry in entries:
key_value = entry.split(":")
passport[key_value[0].upper()] = key_value[1]
return passport
|
def simple_differences(desired_distances, actual_distances):
"""
Returns as error the subtraction between desired and actual values
"""
errors = desired_distances - actual_distances
return errors
|
def delete_inline_comments(x):
"""Delete comments inline
lesly.add(0) # holi --> lesly.add(0)
Args:
x (str): A string with Javascript syntax.
Returns:
[str]: Python string
Examples:
>>> from ee_extra import delete_inline_comments
>>> delete_inline_comments('var x = \n ee.Image(0) # lesly')
>>> # var x = \n ee.Image(0)
"""
lines = x.split("\n")
newlines = []
for line in lines:
if line == "":
newlines.append("")
continue
if line[0] == "#":
newlines.append(line)
else:
if "#" in line:
michi_index = [index for index, lchr in enumerate(line) if lchr == "#"][
0
]
newlines.append(line[:michi_index].rstrip())
else:
newlines.append(line)
return "\n".join(newlines)
|
def info_from_ApiKeyAuth(api_key, required_scopes):
"""
Check and retrieve authentication information from api_key.
Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one.
:param api_key API key provided by Authorization header
:type api_key: str
:param required_scopes Always None. Used for other authentication method
:type required_scopes: None
:return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API
:rtype: dict | None
"""
return {'uid': 'user_id'}
|
def is_word(s):
""" String `s` counts as a word if it has at least one letter. """
for c in s:
if c.isalpha(): return True
return False
|
def _get_dist(mit_edge):
"""Extract distribution information from an edge."""
edge_type = mit_edge["type"]
dist = None
if edge_type == "uncontrollable_probabilistic":
dist_type = mit_edge["properties"]["distribution"]["type"]
if dist_type == "gaussian":
mean = mit_edge["properties"]["distribution"]["mean"]
sd = mit_edge["properties"]["distribution"]["variance"]**0.5
dist = "N_{}_{}".format(mean, sd)
elif dist_type == "uniform":
lb = mit_edge["properties"]["distribution"]["lb"]
ub = mit_edge["properties"]["distribution"]["ub"]
dist = "U_{}_{}".format(lb, ub)
else:
print("Unaccounted for distribution: {}".format(dist_type))
elif edge_type == "controllable":
return None
elif edge_type == "uncontrollable_bounded":
lb = mit_edge["properties"]["lb"]
ub = mit_edge["properties"]["ub"]
dist = "U_{}_{}".format(lb, ub)
else:
raise ValueError("Edge type not found: {}".format(edge_type))
return dist
|
def list_to_dict(keyslist,valueslist):
"""
convert lists of keys and values to a dict
"""
if len(keyslist) != len(valueslist):
return {}
mydict = {}
for idx in range(0,len(keyslist)):
mydict[keyslist[idx]] = valueslist[idx]
return mydict
|
def generate_traits_list(traits: dict) -> list:
"""Returns a list of trait values
Arguments:
traits: a dict containing the current trait data
Return:
A list of trait data
"""
# compose the summary traits
trait_list = [traits['local_datetime'],
traits['canopy_height'],
traits['access_level'],
traits['species'],
traits['site'],
traits['citation_author'],
traits['citation_year'],
traits['citation_title'],
traits['method']
]
return trait_list
|
def get_verts(voxel,g):
"""return list (len=8) of point coordinates (x,y,z) that are vertices of the voxel (i,j,k)"""
(i,j,k) = voxel
dx,dy,dz = g['dx'],g['dy'],g['dz']
v1_0,v1_1,v1_2 = g['xlo'] + i*dx, g['ylo'] + j*dy, g['zlo'] + k*dz
vertices = [(v1_0,v1_1,v1_2),
(v1_0+dx,v1_1,v1_2),
(v1_0+dx,v1_1+dy,v1_2),
(v1_0,v1_1+dy,v1_2),
(v1_0,v1_1,v1_2+dz),
(v1_0+dx,v1_1,v1_2+dz),
(v1_0+dx,v1_1+dy,v1_2+dz),
(v1_0,v1_1+dy,v1_2+dz)]
return vertices
|
def gtAlgoH16(str):
""" Proprietary hash based on the Park-Miller LCG """
seed = 0xaa
mult = 48271
incr = 1
modulus = (1 << 31) - 1 # 0x7FFFFFFF
h = 0
x = seed
for c in bytearray(str):
x = (((x + c) * mult + incr) & 0xFFFFFFFF) % modulus
h = h ^ x
# Derive 16-bit value from 32-bit hash by XORing its two halves
r = ((h & 0xFFFF0000) >> 16) ^ (h & 0xFFFF)
return r
|
def calculate_param_b(
operating_frequency: float,
atmosphere_height_of_max: float,
atmosphere_semi_width: float,
atmosphere_max_plasma_frequency_squared: float) -> float:
"""
Calculates the B parameter following Hill 1979
"""
atmosphere_base_height = atmosphere_height_of_max - atmosphere_semi_width
top = -2 * atmosphere_height_of_max * atmosphere_max_plasma_frequency_squared * atmosphere_base_height ** 2
bottom = (operating_frequency * atmosphere_semi_width) ** 2
return top/bottom
|
def anon_alters(subid, node_list):
"""
Takes list of node names as input and returns an anonymized list of node IDs.
Node IDs use the following convention: 'SubID-NodeID'
"""
anon_list = [str(subid) + '-' + str(n).zfill(2) for n in list(range(1, len(node_list) + 1))]
mapper = dict(zip(node_list, anon_list))
return mapper
|
def get_perm_indices_path(data_dir, data_fn):
"""Get path of pickled perm_indices file."""
return '{}/{}_perm_indices.pkl'.format(data_dir, data_fn)
|
def plural(length):
"""
return "s" if length is not 1 else return empty string
example:
0 items
1 item
2 items
Parameters
----------
length: int
length of item list
Returns
-------
str: "s", ""
"""
return "s" if length != 1 else ""
|
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if ((cp >= 0x4E00 and cp <= 0x9FFF) or (cp >= 0x3400 and cp <= 0x4DBF)
or (cp >= 0x20000 and cp <= 0x2A6DF)
or (cp >= 0x2A700 and cp <= 0x2B73F)
or (cp >= 0x2B740 and cp <= 0x2B81F)
or (cp >= 0x2B820 and cp <= 0x2CEAF)
or (cp >= 0xF900 and cp <= 0xFAFF)
or (cp >= 0x2F800 and cp <= 0x2FA1F)):
return True
return False
|
def clone_attribute(iterable, attribute):
"""clone parameters"""
return [(j.name, j.estimator)
for i in iterable
for j in getattr(i, attribute)]
|
def expected_data_sets():
"""Hardcode the names of existing datasets.
We could also use `dir` or `vars`, but this is quicker for now...
"""
return ("Santa_Clara", "Waterbury")
|
def _get_contact_name(args, required):
"""
Force user to input contact name if one wasn't given in the args.
Used for SEND, READ, and SETPREF commands.
:param args: Command-line args to be checked for the contact name
:param required: If the contact name must be specified, or it's optional
:return: The contact name, or None
"""
contact_name = ''
# build the contact name (can span multiple words)
for name in args.contact_name:
contact_name += name + ' '
contact_name = contact_name.strip()
while not contact_name and required:
print('You must specify a Contact Name for Send and Read and SetPref commands. ' +
'Enter one now:')
try:
contact_name = input('Enter a new contact name (CTRL + C to give up): ').strip()
except (EOFError, KeyboardInterrupt):
# gave up
print()
return None
return contact_name
|
def _flattened(lst):
"""Returned list flattend at first level."""
return sum(lst, [])
|
def cria_posicao(c, l):
"""
Construtor posicao.
Recebe duas cadeias de carateres correspondentes a coluna c e ha linha l de uma
posicao e devolve a posicao correspondente. Caso algum dos seus argumentos nao seja
valido, a funcao gera um erro com a mensagem 'cria_posicao: argumentos invalidos'.
:param c: string, coluna da posicao.
:param l: string, linha da posicao.
:return: tuple, posicao do tabuleiro de jogo.
"""
if not isinstance(c, str) or (c != 'a' and c != 'b' and c != 'c'):
raise ValueError('cria_posicao: argumentos invalidos')
if not isinstance(l, str) or (l != '1' and l != '2' and l != '3'):
raise ValueError('cria_posicao: argumentos invalidos')
return c, l
|
def determ(p1, p2, p3):
""" Helping function for convex_hull() that calculates the determinant of 3 points
pre: p1, p2, p3 are tuples of the form (x, y) where x represents
the x-axis location and y represents the y-axis location of the point
on the cartesian plane
post: returns the determinant of the three points (p1, p2, & p3)
"""
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
return (x1*y2 + x3*y1 + x2*y3 - x3*y2 - x2*y1 - x1*y3)
|
def bb_data_to_coordinates(data):
"""
Get bb data as -> [x1,y1,h,w], compute coordinates as -> [x1, y1, x2, y2]
"""
x1 = data[0]
y1 = data[1]
x2 = data[0] + data[3] - 1
y2 = data[1] + data[2] - 1
return [x1,y1, x2, y2]
|
def z2a(z):
"""Converts z to a.
Parameters
----------
z : float
Redshift.
"""
return 1./(1.+z)
|
def qs(ll):
"""return len(l) ?s sepeated by ',' to use in queries"""
return ','.join('?' for l in ll)
|
def parseFieldMap(field_map_full):
""" take field map from json to list of group dictionaries """
groups = []
for item in field_map_full:
for k,v in item.iteritems():
groups.append(v)
return groups
|
def _match_attributes(elm, attribs):
""" Match the element attributes. """
for key, value in attribs.items():
if elm.get(key) != value:
return False
return True
|
def sample_function(x, y=10):
"""
This text here is the documentation of this function
and everyone should also write docs for their functions.
"""
print('You are in the function')
a = 3
global b
b = 10
key = 'Some Function'
return(a,b, key)
|
def start_points(seq, start):
"""Get starting points"""
return [t[0] for t in enumerate(seq) if t[1] == start]
|
def makebb(pnts):
"""
Find the bounding box for a list of points.
Arguments:
pnts: Sequence of 2-tuples or 3-tuples
Returns:
A list [minx, maxx, miny, maxy[, minz, maxz]].
"""
x = [p[0] for p in pnts]
y = [p[1] for p in pnts]
rv = [min(x), max(x), min(y), max(y)]
if len(pnts[0]) == 3:
z = [p[2] for p in pnts]
rv += [min(z), max(z)]
return rv
|
def check_zeros(counts):
"""
helper function to check if vector is all zero
:param counts:
:return: bool
"""
if sum(counts) == 0:
return True
else:
return False
|
def ms_to_kts(spd):
"""
Parameters
Speed (ms^-1)
Returns
Speed (knots)
"""
spdkts = spd * 1.94384449
return spdkts
|
def _is_within_open_bracket(s, index, node):
"""Fix to include left '['."""
if index < 1:
return False
return s[index-1] == '['
|
def generate_statement_result(read_io, write_io, processing_time, next_page_token, is_first_page,
values=[{'IonBinary': 1}]):
"""
Generate a statement result dictionary for testing purposes.
"""
page = {'Values': values, 'NextPageToken': next_page_token}
statement_result = {}
if read_io:
statement_result['ConsumedIOs'] = {'ReadIOs': read_io, 'WriteIOs': write_io}
if processing_time:
statement_result['TimingInformation'] = {'ProcessingTimeMilliseconds': processing_time}
if is_first_page:
statement_result['FirstPage'] = page
else:
statement_result['Page'] = page
return statement_result
|
def as_number_type(type_, value):
"""Transform a string to a number according to given type information"""
if type_ == "integer":
return int(value)
elif type_ == "number":
return float(value)
else:
raise NotImplementedError(f"as_number_type does not support type {type_}")
|
def join_lines_OLD(lines):
"""Return a list in which lines terminated with the backslash line
continuation character are joined."""
result = []
s = ''
continuation = False
for line in lines:
if line and line[-1] == '\\':
s = s + line[:-1]
continuation = True
continue
if continuation:
result.append(s+line)
s = ''
continuation = False
else:
result.append(line)
if continuation:
result.append(s)
return result
|
def calc(term):
"""
input: term of type str
output: returns the result of the computed term.
purpose: This function is the actual calculator and the heart of the application
"""
# This part is for reading and converting arithmetic terms.
term = term.replace(' ', '')
term = term.replace('^', '**')
term = term.replace('=', '')
term = term.replace('?', '')
term = term.replace('%', '/100.00')
term = term.replace('rad', 'radians')
term = term.replace('mod', '%')
functions = ['sin', 'cos', 'tan', 'pow', 'cosh', 'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e']
# This part is for reading and converting function expressions.
term = term.lower()
for func in functions:
if func in term:
withmath = 'math.' + func
term = term.replace(func, withmath)
try:
# here goes the actual evaluating.
term = eval(term)
# here goes to the error cases.
except ZeroDivisionError:
print("Can't divide by 0. Please try again.")
except NameError:
print('Invalid input. Please try again')
except AttributeError:
print('Please check usage method and try again.')
except TypeError:
print("please enter inputs of correct datatype ")
return term
|
def repos(ln, old_pos, new_pos):
"""
Return a new list in which each item contains the index of the item
in the old order.
Uses the ranges approach (best for large arrays).
"""
lb = min(new_pos, old_pos)
ub = max(new_pos, old_pos)
adj_range = []
if new_pos < old_pos:
adj_range.append(old_pos)
adj_range += list(range(lb, ub))
else:
adj_range += list(range(lb + 1, ub + 1))
adj_range.append(old_pos)
return list(range(0, lb)) + adj_range + list(range(ub, ln - 1))
|
def haccredshiftsforstep(stepnumber ,
zin = 200. ,
zfinal = 0. ,
numsteps = 500) :
"""Changed haccredshiftsforstep to match Adrian's time stepper doc"""
ain = 1.0/(1.0 + zin)
afinal = 1.0/(1.0 + zfinal)
astep = (afinal - ain)/numsteps
aatstep = astep * (stepnumber +1.)+ ain
z = 1.0/aatstep - 1.0
return z
|
def fibonacci(n):
"""Compute the value of the Fibonacci number F_n.
Parameters
==========
n : int
The index of the Fibonacci number to compute.
Returns
=======
float
The value of the nth Fibonacci number.
"""
# Check the input
if not isinstance(n, int):
raise TypeError(f"n has to be of type int, received {type(n)}.")
# Compute the value recursively
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
|
def mysql_quote(x):
"""Quote the string x using MySQL quoting rules. If x is the empty string,
return "NULL". Probably not safe against maliciously formed strings, but
whatever; our input is fixed and from a basically trustable source."""
if not x:
return "NULL"
x = x.replace("\\", "\\\\")
x = x.replace("'", "''")
x = x.replace("\n", "\\n")
return "'{}'".format(x)
|
def unbits(s, endian = 'big'):
"""unbits(s, endian = 'big') -> str
Converts an iterable of bits into a string.
Arguments:
s: Iterable of bits
endian (str): The string "little" or "big", which specifies the bits endianness.
Returns:
A string of the decoded bits.
Example:
>>> unbits([1])
'\\x80'
>>> unbits([1], endian = 'little')
'\\x01'
>>> unbits(bits('hello'), endian = 'little')
'\\x16\\xa666\\xf6'
"""
if endian == 'little':
u = lambda s: chr(int(s[::-1], 2))
elif endian == 'big':
u = lambda s: chr(int(s, 2))
else:
raise ValueError("unbits(): 'endian' must be either 'little' or 'big'")
out = ''
cur = ''
for c in s:
if c in ['1', 1, True]:
cur += '1'
elif c in ['0', 0, False]:
cur += '0'
else:
raise ValueError("unbits(): cannot decode the value %r into a bit" % c)
if len(cur) == 8:
out += u(cur)
cur = ''
if cur:
out += u(cur.ljust(8, '0'))
return ''.join(out)
|
def s3_key_for_revision_content(wiki, pageid, revid):
"""Computes the key for the S3 object storing gzipped revision content."""
return '{:s}page_{:08d}/rev_{:08d}_data.gz'.format(
wiki['s3_prefix'],
pageid,
revid
)
|
def lj(r, epsilon, sigma, R):
"""Return lennard jones force and potential."""
F = 4 * epsilon / (r-R) * (12 * (sigma / (r-R))**12 - 6 * (sigma / (r-R))**6)
V = 4 * epsilon * ((sigma / (r-R))**12 - (sigma / (r-R))**6)
return(V, F)
|
def get_dict_from_header_form_line(line):
""" Returns dict with attributes for a given header form line. """
if '**' not in line:
return
result = dict()
strip_line = line.strip().split('** ')[-1]
if 'true-depth calculation' in strip_line.lower() or ':' not in strip_line:
result['info'] = strip_line.strip()
return result
key, value = strip_line.split(':', 1)
result[key.strip()] = value.strip()
if '#' not in value:
return result
for item in value.split('#'):
k, v = [part.strip() for part in item.split(':')]
result[k] = v
return result
|
def get_links(links, num):
"""
function to get num number of links out of links list
:param links: contain the list of links
:param num: contain the number of links to be extracts out of list
:return links
"""
il = links[:num]
for i in range(num):
if links:
links.pop(0)
else:
break
return il
|
def numstr(x):
""" Convert argument to numeric type.
Attempts to convert argument to an integer. If this fails, attempts to
convert to float. If both fail, return as string.
Args:
x: Argument to convert.
Returns:
The argument as int, float, or string.
"""
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return str(x)
|
def get_color_belief(rgb_color, ratio=0.5):
""" Return color proportional to belief (darker is stronger)"""
red, green, blue, alpha = rgb_color
return red, green, blue, (alpha * ratio)
|
def untag(tagged_sentence):
"""
Remove the tag for each tagged term.
:param tagged_sentence: a POS tagged sentence
:type tagged_sentence: list
:return: a list of tags
:rtype: list of strings
"""
return [w for w, _ in tagged_sentence]
|
def _is_url(string):
"""Checks if the given string is an url path. Returns a boolean."""
return "http" in string
|
def data_validation(data):
"""Validate that the given data format is a list of dictionary.
Parameters
----------
data : :obj:`Any`
Data to be validated.
Returns
-------
:obj:`bool`
True: The data is a list of dictionary.\n
False: The data is not a list of dictionary.
"""
valid = True
if isinstance(data, list):
for i in range(len(data)):
if not isinstance(data[i], dict):
print("Data Format Error - the input data should be a list of dictionary")
valid = False
break
else:
valid = False
return valid
|
def eV(E):
"""
Returns photon energy in eV if specified in eV or KeV. Assumes that any
value that is less than 100 is in KeV.
Parameters
----------
E : float
The input energy to convert to eV
Returns
-------
E : float
Energy converted to eV from KeV
"""
if E < 100:
E *= 1000.0
return float(E)
|
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 not path:
return convertFunction(obj) if convertFunction and obj 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:
result.append(v)
return result
return getValue(current, path, defaultValue= defaultValue, convertFunction=convertFunction)
return defaultValue
|
def skipnonsettingsinst(instances):
"""Removes non /settings sections. Useful for only returning settings monolith members.
Example: Members with paths `/redfish/v1/systems/1/bios/` and
`/redfish/v1/systems/1/bios/settings`
will return only the `/redfish/v1/systems/1/bios/settings` member.
:param instances: list of :class:`redfish.ris.ris.RisMonolithMemberv100`
instances to check for settings paths.
:type instances: list
:returns: list of :class:`redfish.ris.ris.RisMonolithMemberv100` setting instances
:rtype: list
"""
instpaths = [inst.path.lower() for inst in instances]
cond = list(filter(lambda x: x.endswith(("/settings", "settings/")), instpaths))
paths = [path.split('settings/')[0].split('/settings')[0] for path in cond]
newinst = [inst for inst in instances if inst.path.lower() not in paths]
return newinst
|
def contains(a1,a2,b1,b2):
"""
Check whether one range contains another
"""
return ((a1 >= b1) & (a2 <= b2))
|
def tr(texte):
"""
>>> tr("unittestisbetter")
[20, 13, 8, 19, 19, 4, 18, 19, 8, 18, 1, 4, 19, 19, 4, 17]
"""
texte = "".join(t for t in texte if t != " ")
texte = texte.lower()
l = []
for c in texte:
l += [ord(c) - 97]
return l
|
def mark_tail(phrase, keyword, pattern = '%s<span class="tail"> %s</span>'):
"""Finds and highlights a 'tail' in the sentense.
A tail consists of several lowercase words and a keyword.
>>> print mark_tail('The Manual of Pybtex', 'Pybtex')
The Manual<span class="tail"> of Pybtex</span>
Look at the generated documentation for further explanation.
"""
words = phrase.split()
if words[-1] == keyword:
pos = -[not word.islower() for word in reversed(words[:-1])].index(True) - 1
return pattern % (' '.join(words[:pos]), ' '.join(words[pos:]))
else:
return phrase
|
def _is_uint(number):
"""Returns whether a value is an unsigned integer."""
try:
return number == int(number) and number >= 0
except ValueError:
return False
|
def EGCD(a, b):
"""
Extended Euclidean algorithm
computes common divisor of integers a and b.
a * x + b * y = gcd(a, b)
returns gcd, x, y or gcd, y, x.
Sorry, I can't remember
"""
if a == 0:
return (b, 0, 1)
else:
b_div_a, b_mod_a = divmod(b, a)
g, x, y = EGCD(b_mod_a, a)
return (g, y - b_div_a * x, x)
|
def between(minl:int, maxl:int) -> str:
""" Match the previous pattern at between `minl` and `maxl` times, greedily.
>>> import superexpressive as se
>>> se.between(4,8)
'{4,8}'
>>> import superexpressive as se
>>> se.DIGIT + se.between(6,8)
'\\\\d{6,8}'
"""
return f"{{{minl},{maxl}}}"
|
def sigmoid_deriv(x):
"""
Calculates the sigmoid derivative for the given value.
:param x: Values whose derivatives should be calculated
:return: Derivatives for given values
"""
return x * (1. - x)
|
def SedovTaylorSolution(time,energy,density):
"""
Adiabatic solution for a blastwave
See http://www.astronomy.ohio-state.edu/~ryden/ast825/ch5-6.pdf
Parameters
----------
time : float/array
time(s) to calculate at in seconds
energy : float
energy of the blastwave in erg
density : float
density of the background in g cm^-3
Returns
-------
radius : float/array
a radius for each time inputted
"""
return 1.17 * (energy * time**2 / density)**0.2
|
def path_from_schedule(jobs, start):
""" The evaluation is based on building the travel path.
For example in the network A,B,C with 4 trips as:
1 (A,B), 2 (A,C), 3 (B,A), 4 (C,A)
which have the travel path: [A,B,A,C,B,A,C,A]
The shortest path for these jobs is: [A,C,A,B,A] which uses the order:
2 (A,C), 4 (C,A), 1 (A,B), 3(B,A)
"""
path = [start]
for A, B in jobs:
if A != path[-1]:
path.append(A)
path.append(B)
return path
|
def sdp_LM(f, u):
"""Returns the leading monomial of `f`. """
if not f:
return (0,) * (u + 1)
else:
return f[0][0]
|
def renormalize(values, old_min, old_max, new_min, new_max):
"""
Transforms values in range [old_min, old_max] to values in range [new_min, new_max]
"""
return (new_max - new_min) * (values - old_min) / (old_max -
old_min) + new_min
|
def delete_shot_properties(shot):
"""
Delete no longer necessary properties from shot item.
"""
for key in ['match_shot_resutl_id', 'real_date', 'id']:
if key in shot:
del(shot[key])
return shot
|
def populate_metadata(case, config):
""" Provide some top level information for the summary """
return {"Type": "Summary",
"Title": "Performance",
"Headers": ["Proc. Counts", "Mean Time Diff (% of benchmark)"]}
|
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ):
"""Return the 1-based UTF-16 code unit offset equivalent to the 1-based
unicode codepoint offset |codepoint_offset| in the Unicode string
|line_value|"""
# Language server protocol requires offsets to be in utf16 code _units_.
# Each code unit is 2 bytes.
# So we re-encode the line as utf-16 and divide the length in bytes by 2.
#
# Of course, this is a terrible API, but until all the servers support any
# change out of
# https://github.com/Microsoft/language-server-protocol/issues/376 then we
# have to jump through hoops.
if codepoint_offset > len( line_value ):
return ( len( line_value.encode( 'utf-16-le' ) ) + 2 ) // 2
value_as_utf16 = line_value[ : codepoint_offset ].encode( 'utf-16-le' )
return len( value_as_utf16 ) // 2
|
def calculate_stimulation_freq(flash_time: float) -> float:
"""Calculate Stimulation Frequency.
In an RSVP paradigm, the inquiry itself will produce an
SSVEP response to the stimulation. Here we calculate
what that frequency should be based in the presentation
time.
PARAMETERS
----------
:param: flash_time: time in seconds to present RSVP inquiry letters
:returns: frequency: stimulation frequency of the inquiry
"""
# We want to know how many stimuli will present in a second
return 1 / flash_time
|
def fastMaxVal(to_consider, available_weight, memo={}):
"""Assumes to_consider a list of items,
available_weight a weight
memo supplied by recursive calls
Returns a tuple of the total value of a
solution to 0/1 knapsack problem and
the items of that solution"""
if (len(to_consider), available_weight) in memo:
result = memo[(len(to_consider), available_weight)]
elif to_consider == [] or available_weight == 0:
result = (0, ())
elif to_consider[0].get_weight() > available_weight:
result = fastMaxVal(to_consider[1:], available_weight, memo)
else:
next_item = to_consider[0]
# Explore left branch
with_value, with_to_take = fastMaxVal(to_consider[1:], available_weight - next_item.get_weight(), memo)
with_value += next_item.get_value()
# Explore right branch
without_value, without_to_take = fastMaxVal(to_consider[1:], available_weight, memo)
# Choose better branch
if with_value > without_value:
result = (with_value, with_to_take + (next_item,))
else:
result = (without_value, without_to_take)
memo[(len(to_consider), available_weight)] = result
return result
|
def HasProviderInterface(value):
""" Return if the default value has the provider interface """
return hasattr(value, "shouldProvide") and hasattr(value, "getValue")
|
def generate_d3_object(word_counts: dict, object_label: str,
word_label: str, count_label: str) -> object:
"""Generates a properly formatted JSON object for d3 use.
:param word_counts: dictionary of words and their count
:param object_label: The label to identify this object.
:param word_label: A label to identify all "words".
:param count_label: A label to identify all counts.
:return: The formatted JSON object.
"""
json_object = {'name': str(object_label), 'children': []}
for word, count in list(word_counts.items()):
json_object['children'].append({word_label: word, count_label: count})
return json_object
|
def Status2Int(protect_status):
"""
returns the int-value related to the input-str
Read / Write := 0
Write protect := 1
"""
rtn_value = 0
if 'yes' in protect_status.lower():
rtn_value = 1
return rtn_value
|
def day_count(day, data):
"""count the number of people available on a particular day"""
count = 0
for pid in data:
count = count + data[pid]["avail"][day]
return count
|
def number_of_frames_is_int(input):
"""
Validate Number of Frame input.
"""
try:
int(input)
return True
except ValueError:
return False
|
def histogram(ratings, sample_weight, min_rating=None, max_rating=None):
"""
Returns the (weighted) counts of each type of rating that a rater made
"""
if min_rating is None:
min_rating = min(ratings)
if max_rating is None:
max_rating = max(ratings)
num_ratings = int(max_rating - min_rating + 1)
hist_ratings = [0 for x in range(num_ratings)]
for r, w in zip(ratings, sample_weight):
hist_ratings[r - min_rating] += w
return hist_ratings
|
def count_iterable(i):
""" want this: len(ifilter(condition, iterable)) """
return sum(1 for e in i)
|
def shift(coord_paths, shift_vector):
"""
Take an array of paths and shift them by the coordinate.
"""
new_paths = []
for path in coord_paths:
new_path = []
for point in path:
new_path.append( (point[0] + shift_vector[0], point[1]+ shift_vector[1]))
new_paths.append(new_path)
return new_paths
|
def convert_to_demisto_severity(severity: str) -> int:
"""Maps xMatters severity to Cortex XSOAR severity
Converts the xMatters alert severity level ('Low', 'Medium',
'High') to Cortex XSOAR incident severity (1 to 4)
for mapping.
:type severity: ``str``
:param severity: severity as returned from the HelloWorld API (str)
:return: Cortex XSOAR Severity (1 to 4)
:rtype: ``int``
"""
# In this case the mapping is straightforward, but more complex mappings
# might be required in your integration, so a dedicated function is
# recommended. This mapping should also be documented.
return {
'low': 1, # low severity
'medium': 2, # medium severity
'high': 3, # high severity
}[severity.lower()]
|
def host_is_local(hostname, port):
# https://gist.github.com/bennr01/7043a460155e8e763b3a9061c95faaa0
"""returns True if the hostname points to the localhost, otherwise False."""
return True
# HACK(ethanrublee) getfqdn takes a long time and blocks the control loop.
hostname = socket.getfqdn(hostname)
if hostname in ('localhost', '0.0.0.0'):
return True
localhost = socket.gethostname()
localaddrs = socket.getaddrinfo(localhost, port)
targetaddrs = socket.getaddrinfo(hostname, port)
for (family, socktype, proto, canonname, sockaddr) in localaddrs:
for (rfamily, rsocktype, rproto, rcanonname, rsockaddr) in targetaddrs:
if rsockaddr[0] == sockaddr[0]:
return True
return False
|
def get_numeric_event_attribute_value(event, event_attribute):
"""
Get the value of a numeric event attribute from a given event
Parameters
-------------
event
Event
Returns
-------------
value
Value of the numeric event attribute for the given event
"""
if event_attribute in event:
return event[event_attribute]
return None
|
def is_Replicated(distribution):
""" Check if distribution is of type Replicated
Parameters
----------
distribution : str, list, tuple
Specified distribution of data among processes.
Default value 'b' : Block
Supported types:
'b' : Block
'r' : Replicated
Returns
-------
result : boolean
"""
return distribution == 'r'
|
def find_example1(sequence):
"""
Returns True if the given sequence contains a string,
else returns False.
"""
# Returns True or False
for k in range(len(sequence)):
if type(sequence[k]) == str:
return True
return False
|
def split_robot_response(msg):
"""
Split byte string from RobotServer into parts corresponding to:
message id, status, timestamps, tail (rest of the bytes)
"""
elements = msg.split(b':')
msg_id, status, timestamps, pose = elements[:4]
tail = elements[4:]
return msg_id, status, timestamps, pose, tail
|
def retrieve_num_instances(service):
"""Returns the total number of instances."""
instance_counts = service["instance-counts"]
return instance_counts["healthy-instances"] + instance_counts["unhealthy-instances"]
|
def strike(text: str) -> str:
"""
Return the *text* surrounded by strike HTML tags.
>>> strike("foo")
'<s>foo</s>'
"""
return f"<s>{text}</s>"
|
def get_assignment_detail(assignments):
"""
Iterate over assignments detail from response.
:param assignments: assignments detail from response.
:return: list of assignment elements.
"""
return [{
'ID': assignment.get('id', ''),
'FirstName': assignment.get('firstName', ''),
'LastName': assignment.get('lastName', ''),
'ReceiveEmails': assignment.get('receiveEmails', ''),
'Email': assignment.get('email', ''),
'Username': assignment.get('username', '')
} for assignment in assignments]
|
def _group_all(mapping):
"""
Maps every practice contained in the supplied mapping to a single entity,
which we give an ID of None as it doesn't really need an ID
"""
return {practice_code: None for practice_code in mapping.keys()}
|
def detect_depth(depths):
"""
Count number of increases between measurements.
Inputs: depths, a list of ints.
Returns: an int.
"""
return sum(x < y for x, y in zip(depths, depths[1:]))
|
def hash_djb2(s, seed=5381):
"""
Hash string with djb2 hash function
:type s: ``str``
:param s: The input string to hash
:type seed: ``int``
:param seed: The seed for the hash function (default is 5381)
:return: The hashed value
:rtype: ``int``
"""
hash_name = seed
for x in s:
hash_name = ((hash_name << 5) + hash_name) + ord(x)
return hash_name & 0xFFFFFFFF
|
def get_ratios(vect1, vect2):
"""Assumes: vect1 and vect2 are equal length lists of numbers
Returns: a list containing the meaningful values of
vect1[i]/vect2[i]"""
ratios = []
for index in range(len(vect1)):
try:
ratios.append(vect1[index]/vect2[index])
except ZeroDivisionError:
ratios.append(float('nan')) #nan = Not a Number
except:
raise ValueError('get_ratios called with bad arguments')
return ratios
|
def muli(registers, a, b, c):
"""(multiply immediate) stores into register C the result of multiplying register A and value B."""
registers[c] = registers[a] * b
return registers
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.