content stringlengths 42 6.51k |
|---|
def get_child_schema(self):
"""An optional function which returns the list of child keys that are associated
with the parent key `docs` defined in `self.schema`.
This API returns an array of JSON objects, with the possible fields shown in the example.
Hence the return type is list of lists, because this plugin ret... |
def getItemPos(item, inList):
""" get item position from the list """
for i, j in enumerate(inList):
if j == item:
return i
return -1 |
def list_to_string(l):
"""
Converts a string list in to a string
@param l is the string list
@returns a concatentation of each element in the list
"""
res = ""
for elem in l:
res += elem
return res |
def validate_slots(slots : dict) -> dict:
""" Validate slots
Arguments:
slots {dict} -- slots dictionary to be validate
Returns:
dict -- validated version
"""
#slots["ESMLFileTypes"] = to_validate_text(slots.get("ESMLFileTypes"), ["text", "image"])
return slots |
def score_grid(dim):
"""
Creates empty score grid for use in mc_move
"""
return [ [0 for dummy_col in range(dim)] for dummy_row in range(dim)] |
def pig_latin(word):
"""Translate the string 'word' into Pig Latin
Examples:
>>> pig_latin("apple")
'applehay'
>>> pig_latin("banana")
'ananabay'
"""
if word[0] in "aeiou":
return word + "hay"
else:
return word[1:] + word[0] + "ay" |
def single_object_row_factory(column_names, rows):
"""
returns the JSON string value of graph results
"""
return [row[0] for row in rows] |
def GenerateFilename(group):
"""Generate test filename."""
filename = group
filename += ".html"
return filename |
def getCoOrdinates(xValue, yValue):
"""
retuns an object with x any y values
"""
return {"x": xValue, "y": yValue} |
def append_all(src_str, append, delimiter):
"""
Add the append string into each split sub-strings of the
first string(=src=). The split is performed into src string
using the delimiter . E.g. appendAll("/a/b/,/c/b/,/c/d/", "ADD", ",")
will return /a/b/ADD,/c/b/ADD,/c/d/ADD. A append string with null... |
def _extract_source_ips(finding, key_in_additional_info=None):
"""
Extracts source IP addresses from a GuardDuty finding.
https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings.html
:param finding: a GuardDuty finding
:param key_in_additional_info: key name in 'additionalInfo' field fo... |
def row_selection(row_element,idx_pos):
"""
small helper function for the next function
"""
if row_element in idx_pos:
return True
else:
return False |
def validate_spin(value, _):
"""
Validate spin_option input port.
"""
if value:
allowedspins = ["q", "s", "x", "y", "z"]
if value.value not in allowedspins:
return f"The allowed options for the port 'spin_option' are {allowedspins}." |
def getRowClsName(name):
""" Utility method for naming the test module class that
a row belows to
"""
return("mod-" + name) |
def rem_comment(line):
"""Remove a comment from a line."""
return line.split("#", 1)[0].rstrip() |
def splitParents(parents):
"""Splits the input string into at most 3 parts:
- father's first name
- mother's first name
- mother's last name.
The input is in the format:
"{father_first_name},{mother_first_name} {mother_last_name}"
"""
split = parents.split(',', 1)
if len(split) == 1:
father =... |
def getDirectoryFromPath(path: str) -> str:
"""Retrieves the directory string from a path string."""
path_temp = path.rpartition("/")
new_path = path_temp[0] + path_temp[1]
return new_path |
def serialize(mongo_dict):
"""Serialize just converts the MongoDB "_id" ObjectId into a string "id" in a dictionary
:param mongo_dict: The dict from MongoDB
:type: mongo_dict: dict
:rtype: dict
"""
if mongo_dict and "_id" in mongo_dict:
mongo_dict["id"] = str(mongo_dict.pop("_id"))
... |
def _transpose_list(list_of_lists):
"""Transpose a list of lists."""
return list(map(list, zip(*list_of_lists))) |
def populate_list(dictionary, key, list_to_populate):
"""Functions to populate a list with valuesof the given key"""
value = dictionary[key]
if value != "null":
list_to_populate.append(value)
return list_to_populate |
def _is_prefix(prefix, name):
"""Determines whether one fullname is a prefix of another.
Args:
prefix: The fullname that might be a prefix.
name: The entire fullname.
Returns:
A boolean indicating whether or not the first fullname is a prefix of the
second.
"""
prefix_parts = prefix.spli... |
def format_response_google(data):
""" formatter data from google api books """
if len(data) > 0:
return list(map(lambda item: {
'title': item['volumeInfo']['title'],
'sub_title': item['volumeInfo']['subtitle'] if 'subtitle' in item['volumeInfo'].keys() else None,
'au... |
def arbitrary_item(S):
"""
Select an arbitrary item from set or sequence S.
Avoids bugs caused by directly calling iter(S).next() and
mysteriously terminating loops in callers' code when S is empty.
"""
try:
return next(iter(S))
except StopIteration:
raise IndexError("No item... |
def find_cycle(source_graph):
"""Return True if the directed graph has a cycle.
The graph must be represented as a dictionary mapping vertices to
iterables of neighbouring vertices.
https://codereview.stackexchange.com/a/86067
"""
visited = set()
path = [object()]
path_set = set(path)
... |
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def inner(word):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Return a tuple of strings
return (inner(word1),inner(word2),inner(word3)) |
def hsv2rgb(hsvColor):
"""
Conversione del formato colore HSV in RGB
:param hsvColor: Stringa del colore HSV
:return: Tripla RGB
"""
# hsvColor = '#1C8A88' #LOW
# hsvColor = '#BDEFEF' #HIGH
h = hsvColor.lstrip('#')
rgb = tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
return rgb... |
def isFailed(posBox, posWalls, posGoals):
"""This function used to observe if the state is potentially failed, then prune the search"""
rotatePattern = [[0,1,2,3,4,5,6,7,8],
[2,5,8,1,4,7,0,3,6],
[0,1,2,3,4,5,6,7,8][::-1],
[2,5,8,1,4,7,0,3,6][::-1]]
... |
def combine_signatures(*args, function=set.intersection):
"""Combine signatures (e.g. by taking the intersection)
Args:
*args: list of signature dictonaries
function: set operation to combine the signatures
Returns:
dict of set: combined signature dictionary.
>>> s1 = {"A": {1,... |
def concatenate_comments(tidy_advice: list, format_advice: list) -> list:
"""Concatenate comments made to the same line of the same file."""
# traverse comments from clang-format
for index, comment_body in enumerate(format_advice):
# check for comments from clang-tidy on the same line
commen... |
def _skip_if_p2os(overlay, pkg, distro, preserve_existing, collector):
"""Skip if it's a p2os package"""
collector.append(pkg)
if 'p2os' in pkg:
return False, False
return True, pkg |
def get_class_name(instance_class):
"""Get the instance class name."""
if not hasattr(instance_class, '__bases__'):
instance_class = instance_class.__class__
bases = [x.__name__ for x in instance_class.__bases__]
if 'Field' in bases:
return 'Field'
if 'MediaFile' in bases:
r... |
def repeated(pattern, sep, least=1, most=None):
"""
Returns a pattern that matches a sequence of strings that match ``pattern`` separated by strings
that match ``sep``.
For example, for matching a sequence of ``'{key}={value}'`` pairs separated by ``'&'``, where
key and value contains only lowercas... |
def count(text, min_length=2):
"""
Indexes a count of all words found in text
"""
index = {}
for word in text.split(" "):
if index.get(word.lower()):
index[word.lower()] += 1
elif len(word) >= min_length:
index[word.lower()] = 1
return index |
def is_iterable(obj):
"""
Checks whether the given object is an iterable by calling iter.
:param obj: the object to check
:return: true if the object is iterable
"""
try:
_ = iter(obj)
except TypeError:
return False
else:
return True |
def galois_multiplication(a, b):
"""Galois multiplication of 8 bit characters a and b."""
p = 0
for counter in range(8):
if b & 1: p ^= a
hi_bit_set = a & 0x80
a <<= 1
# keep a 8 bit
a &= 0xFF
if hi_bit_set:
a ^= 0x1b
b >>= 1
return p |
def raises(exception, f, *args, **kwargs):
"""
Determine whether the given call raises the given exception.
"""
try:
f(*args, **kwargs)
except exception:
return 1
return 0 |
def subplot_shape(size):
"""
Get the most square shape for the plot axes values.
If only one factor, increase size and allow for empty slots.
"""
facts = [[i, size//i] for i in range(1, int(size**0.5) + 1) if size % i == 0]
# re-calc for prime numbers larger than 3 to get better shape
while ... |
def unindent(s, skipfirst=True):
"""Return an unindented version of a docstring.
Removes indentation on lines following the first one, using the
leading whitespace of the first indented line that is not blank
to determine the indentation.
"""
lines = s.split("\n")
if skipfirst:
... |
def get_svg_string(svg_name, verbose=False):
"""
Helper function returning an SVG string from the given file
:param svg_name: The filename to search in
:param verbose: Whether to print ancillar information
:return: The contents of the SVG file, or an empty string if none are found.
"""
try:
... |
def say_hello(name: str, salutation: str = "Hello") -> str:
"""Say hello to the user."""
return f"{salutation.capitalize()}, {name.capitalize()}. Welcome to the wonderful world of Python." |
def is_point_in_rect2(point, rect_center, rect_w, rect_h):
"""Checks whether is coordinate point inside the rectangle or not.
Rectangle is defined by center and linear sizes.
:type point: list
:param point: testing coordinate point
:type rect_center: list
:param rect_center: point, center of rectangle
... |
def dot(u, v):
"""Dot product between vectors ``u`` and ``v``."""
return sum(uu * vv for uu, vv in zip(u, v)) |
def mmss_to_frames(fps, m, s=0):
"""
Converts minutes and seconds of video to frames based on fps
:param fps: frames per second of video
:param m: minutes
:param s: seconds
:return: frame number
"""
return int((m * 60 + s) / fps) |
def read_hosts_from_temp(filename, mode):
""" Retrieves list of hosts that were active in previous iteration of ranking algorithm.
Args:
filename: (str) Name of file to retrieve host names from.
mode: (str) Opening file mode.
Returns:
prev_hosts: List of host names read from file.
"""
try:
f = open(fi... |
def editDistance(s1, s2):
""" Calculate edit distance between 2 strings
Args:
s1: string 1
s2: string 2
Returns:
Edit distance between s1 and s2
"""
# ignore the case
s1 = s1.upper()
s2 = s2.upper()
if len(s1) > len(s2):
s1, s2 = s2, s1
distance... |
def average(lst):
"""
Calculates average of a list
"""
avg = sum(lst) / len(lst)
avg_float_decimal = float("{0:.3f}".format(avg))
return avg_float_decimal |
def weightDifference(vG1, vL1, vO1, vG2, vL2, vO2):
"""
Get the difference as weight2 - weight2
:param vG1:
:param vL1:
:param vO1:
:param vG2:
:param vL2:
:param vO2:
:return:
"""
vG = vG2 - vG1
vL = vL2 - vL1
vO = vO2 - vO1
return (vG, vL, vO) |
def convert_blender_file_format(extension):
""" Converts a blender format like JPEG to an extension like .jpeg """
extensions = {
"BMP": ".bmp",
"PNG": ".png",
"JPEG": ".jpg",
"TARGA": ".tga",
"TIFF": ".tiff"
}
if extension in extensions:
return extensio... |
def _border_properties_to_styles(properties):
"""
Convert the properties to border styles.
:param properties: Ordered list of OOXML properties
:return: dictionary of border styles
"""
styles = {}
# - 'border-top', 'border-right', 'border-bottom', 'border-left'
for style, prop in prope... |
def help_get_docstring(func):
""" Extract Docstring from func name"""
import inspect
try:
lines = func.__doc__
except AttributeError:
lines = ""
return lines |
def hex_str(s):
"""
Returns a hex-formatted string based on s.
:param s: Some string.
:type s: str
:return: Hex-formatted string representing s.
:rtype: str
"""
return ' '.join("{:02x}".format(ord(b)) for b in s) |
def listToIndex2item(L):
"""converts list to dict of list index->list item"""
d = {}
for i, item in enumerate(L):
d[i] = item
return d |
def LongestFromList(ls: list):
"""
Determines the object with the longest length inside a list.
Args:
ls: A list containing an array of objects.
Returns:
The object with the longest length from the list.
None if not applicable.
"""
try:
current = ls[... |
def fahrenheit(celsius):
"""Convert celsius to fahrenheit."""
return ((celsius/5)*9)+32 |
def bytes_as_char_array(b): # type: (bytes) -> str
"""
Given a sequence of bytes, format as a char array
"""
return '{ ' + ', '.join('0x%02x' % x for x in b) + ' }' |
def ones_like(x):
"""Return an array of the same shape as `x` containing only ones."""
return x * 0. + 1. |
def count_bags_inside(bag_name, rules):
"""Count total number of bags in bag_name."""
if not rules[bag_name]:
return 0
count = 0
for inside_bag, number_of_bags in rules[bag_name].items():
count += (number_of_bags + number_of_bags
* count_bags_inside(inside_bag, rules))
... |
def _cmplx_add_ ( s , o ) :
"""add complex values
>>> r = v + other
"""
return o + complex ( s ) |
def topic_name_from_path(path, project):
"""Validate a topic URI path and get the topic name.
:type path: string
:param path: URI path for a topic API request.
:type project: string
:param project: The project associated with the request. It is
included for validation purposes.... |
def removeDups(aSeq):
"""Remove duplicate entries from a sequence,
returning the results as a list.
Preserves the ordering of retained elements.
"""
tempDict = {}
def isUnique(val):
if val in tempDict:
return False
tempDict[val] = None
return True
return ... |
def dense_output(t_current, t_old, h_current, rcont):
"""
Dense output function, basically extrapolatin
"""
# initialization
s = (t_current - t_old) / h_current
s1 = 1.0 - s
return rcont[0] + s * (rcont[1] + s1 * (
rcont[2] + s * (rcont[3] + s1 * (rcont[4] + s * (rcont[5] + s1 *... |
def powerset(s):
"""Computes all of the sublists of s"""
rv = [[]]
for num in s:
rv += [x+[num] for x in rv]
return rv |
def getKey(data, key, default=None):
"""
Returns the key from the data if available or the given default
:param data: Data structure to inspect
:type data: dict
:param key: Key to lookup in dictionary
:type key: str
:param default: Default value to return when key is not set
:type defau... |
def switch_player(current_player):
"""Switches the player from x to o"""
if current_player == "x":
return "o"
else:
return "x" |
def getAxisVector(axis, sign=1):
"""
Return a vector for a signed axis
"""
i = int(axis)
v = [0, 0, 0]
v[i] = 1 * (1 if sign >= 0 else -1)
return tuple(v) |
def difference(array, k=1):
"""Calculate l[n] - l[n-k]
"""
if (len(array) - k) < 1:
raise ValueError()
if k < 0:
raise ValueError("k has to be greater or equal than zero!")
elif k == 0:
return [i - i for i in array]
else:
return [j - i for i, j in zip(array[:-k], ... |
def get_rh(pial_list):
"""
Is there a better way of doing this?
"""
for p in pial_list:
if p.endswith('rh.pial'):
return p |
def velocity_to_bin(velocity, step=4):
"""
Velocity in a midi file can take on any integer value in the range (0, 127)
But, so that each vector in the midiparser is fewer dimensions than it has to be,
without really losing any resolution in dynamics, the velocity is shifted
down to the previous mu... |
def get_mesos_cpu_status(metrics):
"""Takes in the mesos metrics and analyzes them, returning the status
:param metrics: mesos metrics dictionary
:returns: Tuple of the output array and is_ok bool
"""
total = metrics['master/cpus_total']
used = metrics['master/cpus_used']
available = total ... |
def apply_bids_label_restrictions(value):
"""Sanitize file names for BIDS.
"""
# only alphanumeric allowed
# => remove everything else
if value is None:
# Rules didn't find anything to apply, so don't put anything into the
# spec.
return None
from six import string_type... |
def MakeOldStyle(newstyle_fieldpath):
"""New style: a.b.000003.c -> old style: a.b[3].c .
Args:
newstyle_fieldpath: new-style path to convert.
Returns:
Old-style version of path.
"""
tokens = newstyle_fieldpath.split(".")
oldstyle = ""
is_first = True
for token in tokens:
if token.isdig... |
def gradient_add(grad_1, grad_2, param, verbose=0):
"""
Sum two gradients
:param grad_1: (TensorFlow Tensor) The first gradient
:param grad_2: (TensorFlow Tensor) The second gradient
:param param: (TensorFlow parameters) The trainable parameters
:param verbose: (int) verbosity level
:return... |
def bytes_to_long(data):
"""
Convert byte string to integer
:param data: byte string
:return: integer
"""
try:
return int.from_bytes(data, 'big')
except TypeError:
return bytes_to_long(data.encode('utf-8'))
except AttributeError:
return int(data.encode('hex'), 16) |
def check_bounds(value):
"""Check if the given value is out-of-bounds (0 to 4095)
:args: the value to be checked
:returns: the checked value
"""
try:
if int(value) > 4095:
return 4095
elif int(value) < 0:
return 0
else:
return value
... |
def get_recursively(search_dict, field):
"""
Takes a dict with nested lists and dicts, and searches all dicts
for a key of the field provided.
"""
fields_found = []
for key, value in search_dict.items():
if key == field:
fields_found.append(value)
elif isinstance(v... |
def reversedbinary(i,numbits):
"""Takes integer i and returns its binary representation
as a list, but in reverse order, with total number of bits
numbits. Useful for trying every possibility of numbits choices
of two."""
num = i
count = 0
revbin = []
while count < numbits:
revbi... |
def add_md(text, s, level=0):
"""Adds text to the readme at the given level"""
if level > 0:
if text != "":
text += "\n"
text += "#" * level
text += " "
text += s + "\n"
if level > 0:
text += "\n"
return text |
def GetFragTuple(fragid):
"""
Fragment ids should have the form: "NAME:NUMBER" or "NAME-NUMBER". This
splits the fragment into the name and number value.
Args:
fragid (str): the fragment id string.
Return:
(tuple): fragment name, fragment number
"""
markers = [":", "-", "+"]
... |
def list_check(lista):
"""
If a list has only one element, return that element. Otherwise return the whole list.
"""
try:
e2 = lista[1]
return lista
except IndexError:
return lista[0] |
def Slide_body(cont_Object_f):
"""
:param cont_Object_f: The sequence of "f" values of Object objects contained in this Slide
:type cont_Object_f: Array
"""
return '\n'.join(cont_Object_f) |
def easing(current_time, begin, change, total_time):
"""
current_time = how much time has passed since start
begin = starting value
change = final value - starting value
total_time = how long ease should take
"""
return change * current_time / float(total_time) + begin |
def to_ascii(s):
"""Convert the bytes string to a ASCII string
Usefull to remove accent (diacritics)"""
if s is None:
return s
if isinstance(s, str):
return s
try:
return str(s, 'utf-8')
except UnicodeDecodeError:
return s |
def escaped(txt, specs):
"""
Escape txt so it is latex safe.
Parameters
----------
txt : string
value to escape
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
"""
ret = txt.replace("_", "\_")
... |
def sleeptime(retries):
"""
purpose: compute suggested sleep time as a function of retries
paramtr: $retries (IN): number of retries so far
returns: recommended sleep time in seconds
"""
if retries < 5:
my_y = 1
elif retries < 50:
my_y = 5
elif retries < 500:
my_y... |
def _setDefaults(configObj={}):
""" set up the default parameters to run drizzle
build,single,units,wt_scl,pixfrac,kernel,fillval,
rot,scale,xsh,ysh,blotnx,blotny,outnx,outny,data
"""
paramDict={"build":True,
"single":True,
"in_units":"cps",
"wt_scl... |
def delta(a, b):
"""
Function that returns the Kronecker delta delta(a, b).
Returns 1 if a = b and 0 otherwise.
"""
if a==b: return 1
else: return 0 |
def get_lowcase_bool(value):
"""
Transform Python False, True into false, true
>>> get_javascript_value(True)
true
>>> get_javascript_value(10)
10
"""
if isinstance(value, bool):
if value:
return 'true'
else:
return 'false'
else:
retur... |
def site_time_zone(request, registry, settings):
"""Expose website URL from ``tm.site_time_zone`` config variable to templates.
By best practices, all dates and times should be stored in the database using :term:`UTC` time. This setting
allows quickly convert dates and times to your local time.
Exampl... |
def lookup_module_function( module_reference, function_name ):
"""
Acquires a function reference from a module given an function name.
Takes 2 arguments:
module_reference - Module whose interface is searched for function_name.
function_name - String specifying the function whose handle is s... |
def getfields(jsondict: dict, types: bool = False):
"""Return list of field names or a name:type dict if types=True"""
if types:
return {
f["name"]: f["type"].replace("esriFieldType", "") for f in jsondict["fields"]
}
else:
return [f["name"] for f in jsondict["fields"]] |
def video_player(obj):
"""
Receives object with 'video' FileField and returns HTML5 player.
"""
return {'object': obj} |
def pad_sequence(seqlist, pad_token):
"""Left pad list of token id sequences.
Args:
seqlist (list): list of token id sequences
pad_token (int): padding token id
Returns:
final (list): list of padded token id sequences
"""
maxlen = max(len(x) for x in seqlist)
final = ... |
def read_signature(obs_by_pos):
"""
Returns a string made from the positions where bases were able to be
observed from the read.
"""
return ','.join(["%d:%s" % (pos, obs_by_pos[pos])
for pos in sorted(obs_by_pos)]) |
def _mixrange(short_hand):
"""Working with splitting on on command and dashes."""
ranges = []
# Taken from https://stackoverflow.com/a/18759797
for item in short_hand.split(','):
if '-' not in item:
ranges.append(int(item))
else:
l, h = map(int, item.spl... |
def expr_prod(factor: float, expression: str) -> str:
"""helper function for building an expression with an (optional) pre-factor
Args:
factor (float): The value of the prefactor
expression (str): The remaining expression
Returns:
str: The expression with the factor appended if nec... |
def _xr_to_keyset(line):
"""
Parse xfsrestore output keyset elements.
"""
tkns = [elm for elm in line.strip().split(":", 1) if elm]
if len(tkns) == 1:
return "'{}': ".format(tkns[0])
else:
key, val = tkns
return "'{}': '{}',".format(key.strip(), val.strip()) |
def get_side(given_name):
"""
Assuming the given name adheres to the naming convention of crab this
will extract the side/location element of the name.
:param given_name: Name to extract from
:type given_name: str or pm.nt.DependNode
:return: str
"""
parts = given_name.split('_')
... |
def create_dna( num, alphabet='actg'):
"""
num : integer
alphabet : string, optional, The default is 'actg'.
Returns : string
To create a random string of dna of desired length.
"""
import random
return ''.join([random.choice(alphabet) for i in range(num)]) |
def sequential_search(alist, item):
"""Sequential search
Complexity:
item is present: best case=1, worst case=n, avg=n/2
item not present: best case=n, worst case=n, avg=n
Args:
alist (list): A list.
item (int): The item to search.
Returns:
bool: Boolean with th... |
def get_unique_name(existing, initial):
"""Get a name either equal to initial or of the form initial_N, for some
integer N, that is not in the set existing.
:param existing: Set of names that must not be chosen.
:param initial: Name, or name prefix, to use"""
if initial not in existing:
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.