content stringlengths 42 6.51k |
|---|
def mean(l):
"""
compute arithmetic mean of a list of numbers
"""
return float(sum(l)) / float(len(l)) |
def myformat(val, precision):
"""Nice"""
if val is None:
return ' ****'
fmt = "%%5.%sf" % (precision, )
return fmt % val |
def _to_dict_walk(node):
""" Converts mapping objects (subclassed from dict)
to actual dict objects, including nested ones
"""
node = dict(node)
for key, val in node.items():
if isinstance(val, dict):
node[key] = _to_dict_walk(val)
return node |
def _get_fzn_array(fzo):
""" Get the list of objects of an FZN object
Args:
fzo: FZN object
Returns:
Array of FZN objects
"""
return fzo if isinstance(fzo, list) else fzo.value |
def convert_time_to_seconds(days=0, hours=0, minutes=0, seconds=0):
"""
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
Common function to converting time in seconds
:param days:
:param hours:
:param minutes:
:param seconds:
:return:
"""
seconds = int(seconds)
if days:
... |
def sequence_equals(seq1, seq2, distance=0):
"""Determine if two DNA string sequences are equal, also considering two
sequences with <= the specified hamming distance apart as equal. Deletions
are not allowed.
:param seq1: first sequence
:type seq1: str
:param seq2: second sequence
:type se... |
def string_contains(text: str, words: str) -> bool:
"""Check if a string contain a specific word
Args:
x (str): your string with the text
words (str): the word or the text you want to search
Returns:
(bool) if the words it's present in the x string
"""
return any([w in text... |
def format_topic_code(topic_code: str) -> str:
"""Takes a topic code string and formats it as
human readable text.
"""
return str.title(topic_code.replace('_', ' ')) |
def convert_channel_id_to_short_channel_id(channel_id):
"""
Converts a channel id to blockheight, transaction, output
"""
return channel_id >> 40, channel_id >> 16 & 0xFFFFFF, channel_id & 0xFFFF |
def to_bytes(something, encoding='utf8'):
"""
cast string to bytes() like object, but for python2 support it's bytearray copy
"""
if isinstance(something, bytes):
return something
if isinstance(something, str):
return something.encode(encoding)
elif isinstance(something, bytearra... |
def get_group_command_url(environment: str,
enterprise_id: str,
group_id: str) -> str:
"""
Build and return pipeline url for scapi endpoint
:param environment:
:param enterprise_id:
:param group_id:
:return: Url
"""
url = f'https://{env... |
def GetSymmPerChannelQuantParams(extraParams):
"""Get the dictionary that corresponds to test_helper::TestSymmPerChannelQuantParams."""
if extraParams is None or extraParams.hide:
return {}
else:
return {"scales": extraParams.scales, "channelDim": extraParams.channelDim} |
def build_person(first_name, last_name):
"""Return a dictionary of information about a person."""
person = {'first':first_name, 'last': last_name}
return person |
def vec2id(x, limits):
"""
:param x: A discrete (multidimensional) quantity (often the state vector)
:param limits: The limits of the discrete quantity (often statespace_limits)
Returns a unique id by determining the number of possible values of ``x``
that lie within ``limits``, and then seeing whe... |
def clamp(lower, value, upper):
"""Given a value and lower/upper bounds, 'clamp' the value so that
it satisfies lower <= value <= upper."""
return max(lower, min(value, upper)) |
def get_keys_hint(shortcuts):
"""Generate hint text to be used in tooltips from a list of QShortcut
@note: It's convention to put this between parentheses in single-line
tooltips, but it's left to be done by the caller since that may not
be the case in longer tooltips and this can also be used ... |
def swap(arg):
"""Swaps the first two elements of the tuple."""
if len(arg) < 2:
raise IndexError("swap() tuple too short")
def index(x):
return 1 - x if x < 2 else x
return tuple(arg[index(n)] for n in range(len(arg))) |
def _get_tc_counts(Nt1o1, Nt0o1, Nt1o0, Nt0o0):
"""Get treatment and control group sizes from `_get_counts` output.
Parameters
----------
Nt1o1 : int
Number of entries where (treatment, outcome) == (1,1).
Nt0o1 : int
Number of entries where (treatment, outcome) == (0,1).
Nt1o0 :... |
def get_degen_dependence_lengths(weight_shapes, independent = False):
"""
get dependence_lengths for inverse_prior class,
i.e. the lengths in the param array which correspond
to contiguous dependent random variables.
assumes each layer is degenerate in the parameters
across the nodes
"""
if independent:
retur... |
def _escape(data, quote='"', format=None):
"""Escape special characters in a string."""
if format == 'xml':
return (
str(data).
replace('&', '&').
replace('<', '<').
replace('>', '>'))
elif format == 'control':
return (
s... |
def make_hash(*texts):
"""
The text is hashed together with its makefile because the built corpus
will look different on many settings. For example, if word annotations
are taken from the corpus or generated by our tools.
"""
import hashlib
return hashlib.sha1("".join(texts).encode("UTF-8"))... |
def application_state(app):
"""Return the consolidated state for application *app*.
The *app* parameter must be a dict as returned by
:meth:`~RavelloClient.get_application`.
The consolidated state for an application is the set of distinct states
for its VMs. As special cases, None is returned if t... |
def list_find_or_append(lst, item):
""" If item is in the list, return its index. Otherwise, append it to the
list and return its index.
Note: may modify the list
"""
try:
return lst.index(item)
except ValueError:
lst.append(item)
return len(lst) - 1 |
def cum_val(vals,target):
"""returns the fraction of elements with value < taget. assumes vals is sorted"""
niter_max = 10
niter = 0
m,M = 0,len(vals)-1
while True:
mid = int((m+M)/2)
if vals[mid]<target:
m = mid
else:
M = mid
niter+=1
... |
def collect_id(event):
"""Collects the trace_id from the event.
Args:
event (json): Json representing an event of a trace.
Returns:
The trace_id of the event
"""
return event.get('trace_id') |
def dict_strip_quotes(dict_item: dict) -> dict:
"""
Strip quote characters from dict values.
:param dict_item: A dictionary to work with.
:return dict: A dictionary with quotes stripped.
"""
_output = {}
delimiter = '\"'
for _key, _value in dict_item.items():
_output.update({_ke... |
def html_color(col):
""" Generates an html colour from a tuple of three values. """
return ''.join(['%02x' % c for c in col]) |
def get_schema(data_df):
"""Return dict from column names to the corresponding column type."""
return {col_name: str(data_df[col_name].dtype) for col_name in list(data_df)} |
def find_flipped_bit(s1, s2):
""" For two adjacent elements in a gray code, determine which bit is the
one that was flipped.
"""
if len(s1) == 0 or len(s2) == 0:
raise ValueError("Empty string inputted.")
if len(s1) != len(s2):
raise ValueError("Strings compared in gray code must h... |
def p_correct_given_pos(sens, fpr, b):
"""Returns a simple Bayesian probability for the probability
that a prediction is correct, given that the prediction
was positive, for the prevailing sensitivity (sens),
false positive rate (fpr) and base rate of positive
examples.
"""
assert 0 <= sens... |
def downcase(string):
"""Returns string with lowercase characters"""
string = string.lower()
return string |
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... |
def scale_bounding_box(bounding_box,scale):
"""Scales bounding box coords (in dict from {x1,y1,x2,y2}) by x and y given by sclae in dict form {x,y}"""
scaled_bounding_box = {
"x1" : int(round(bounding_box["x1"]*scale["x"]))
,"y1" : int(round(bounding_box["y1"]*scale["y"]))
,"x2" : int(ro... |
def what_to_relative(sentence):
"""
change what+to into relative form
Input=sentence Output=sentence
"""
# init
i = 0
while i < len(sentence) - 1:
if sentence[i] == 'what' and sentence[i + 1] == 'to':
sentence = sentence[:i] + ['the', 'thing... |
def xor(A,B):
"""Returns (A and not B) or (not A and B);
the difference with A^B is that it works also with different types and returns one of the two objects..
"""
return (A and not B) or (not A and B) |
def has_access(user, users):
"""A list of users should look as follows: ['!deny', 'user1',
'user2'] This means that user1 and user2 have deny access. If we
have something longer such as ['!deny', 'user1', '!allow',
'user2'] then user2 has access but user1 does not have access. If
no keywords are fou... |
def validate_relays(relays):
"""
Validate that each relay specifies either chip,line or name
"""
for ident,cfg in relays.items():
has_chip_line = "chip" in cfg and "line" in cfg
has_name = "name" in cfg
if has_chip_line and has_name:
return (False, "Relay %s: cann... |
def alloc_to_share_ratio(share, total_shares, allocation, total_alloc):
"""
Calculate the allocation to share (advantage) ratio given to a region or group.
Parameters
----------
share : int
The proportion to be checked.
total_shares : int
The total amount of sha... |
def lcamel(n: str) -> str:
"""Convert a string in upper or lower camel case to lower camel case"""
return n[0].lower() + n[1:] |
def dn2rad_aster( Lgain, Loffset, DN ):
"""
Conversion of DN to Radiance for Aster
rad2ref_aster( Lgain, Loffset, DN )
"""
result = Lgain * DN + Loffset
return result |
def _keep_going(epochs, timesteps, episodes,
num_epochs, num_timesteps, num_episodes):
"""Determine whether we've collected enough data"""
if (num_epochs) and (epochs >= num_epochs):
return False
# If num_episodes is set, stop if limit reached.
elif num_episodes and episodes >= ... |
def match_any_params(group=1):
"""
If there is a previous capture group in the regex then group needs to be the index of match_any_params
"""
return rf"\((?:[^)(]*(?{group})?)*+\)" |
def putBitsIntoList_2(n, L):
"""Takes an integer and puts L of it's least sig bits into a list"""
ret = []
for i in range(L):
ret.append(n%2)
n = n/2
return ret |
def selection_sort(items):
"""Implementation of the selection sort algorithm using Python
inside parameter we can pass some items which are heterogeneous
comparable
"""
length = len(items)
for i in range(length):
least = i
for j in range(i + 1, length):
if items[j] <... |
def linux_linebreaks(source):
"""Convert Windows CRLF, Mac CR and <br>'s in the input string to \n"""
result = source.replace('\r\n', '\n').replace('\r', '\n')
# There are multiple valid variants of HTML breaks
result = result.replace('<br>', '\n').replace('<br/>', '\n').replace('<br />', '\n')
retu... |
def contact(content):
"""
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
"""
if not content:
return ''
if not content.is_authenticated():
content = "Anonymous"
elif content.first_name:
... |
def replace_file_special_chars(filename_path):
"""This is a *very* incomplete function which I added to fix a bug:
http://sourceforge.net/apps/trac/w3af/ticket/173308
And after realizing that it was very hard to perform a replace
that worked for all platforms and when the thing to sanitize was a
pa... |
def fibonacci(n):
"""
this function has one parameter (n).
this function should return the nth value
in the fibonacci series.
the function is implemented using recursion.
each number in the fibonacci sequence
is the sum of the two numbers that precede it.
the sequence goes:
0, 1, 1, 2, 3, 5, 8... |
def route2parameters(routelist):
"""
Return a list of parameters found in the given routelist
"""
params = []
for c in routelist:
if isinstance(c, dict):
params.append({
'type': 'string',
'paramType': 'path',
'name': c['name'],
... |
def reverse_rec(head):
"""
It's a bit unnatural to implement `reverse` in a recursive but not
tail recursive way because it requires returning two items (thus
requiring a helper function) and is less efficient than the tail
recursive version, but for the purpose of an academic exercise, here
it ... |
def schedule(graph):
"""
Method to perform topological sorting of the input graph (in adjacency list format) to find a valid schedule
Complexity: O(V+E) time and O(V+E) space
:return: The correct order of courses to be taken or null list if no valid order found
:rtype: List[int]
"""
numCourses = len(graph) # n... |
def sum_n_natural_numbers(n: int) -> int:
""""n: 1 + 2 + 3 + ... + n"""
result = 0
for i in range(1, n + 1):
result += i
return result |
def selection_sort(arr):
"""Returns the array arr sorted using the selection sort algorithm
>>> import random
>>> unordered = [i for i in range(5)]
>>> random.shuffle(unordered)
>>> selection_sort(unordered)
[0, 1, 2, 3, 4]
"""
if len(arr) <= 1: return arr
smallest = min(arr)
d... |
def kadane(arr):
"""
Implementation of Kadane's algorithm for finding the sub-array
with the largest sum.
O(n) Time Complexity
O(1) Space Complexity.
"""
# stores max sum sub-array found so far
max_so_far = arr[0]
# stores max sum of sub-array ending at current position
max_ending_here = arr[0... |
def urljoin(*fragments):
"""Concatenates multi part strings into urls"""
return '/'.join(fragments) |
def remove_duplicates(items, key):
"""
Remove all duplicates from a list of dict (items), based on unique keys
"""
clean_items = []
for i, item in enumerate(items):
if not any(item[key] == item_[key] for item_ in items[i+1:]):
clean_items.append(item)
return... |
def thirds(x):
"""gets value in the range of [0, 1] where 0 is the center of the pictures
returns weight of rule of thirds [0, 1]"""
x = ((x - (1 / 3) + 1.0) % 2.0 * 0.5 - 0.5) * 16
return max(1.0 - x * x, 0.0) |
def convert_to_one_letter_code_sing(seq):
"""
Converts a single amino acid one letter code to the 3 letter code.
Arguments:
-seq (str) - one letter AA code.
"""
conversion = {
"GLY": "G", "PRO": "P", "VAL": "V", "ALA": "A", "LEU": "L",
"ILE": "I", "MET": "M", "CYS": "C", "P... |
def _moog_par_format_synlimits (synlimits):
"""
moogpars['synlimits']
synlimits = [syn_start,syn_end,wl_step,opacity_width]
"""
if synlimits is None:
return ""
lines = ["synlimits "]
# synstart,synend,wlstep,opacity_width
lines.append((" "+" {:<.2f}"*4).format(*list(map(float,... |
def filter_data(data: dict) -> dict:
"""
Remove unwanted/aberrant lines from data
Parameters
----------
data : dictionary of lists of lists
{'gps': list of lists, 'alti': list of lists, 'hr': list of lists, 'cad': list of lists}
Returns
-------
data : dictionary of lists
... |
def power(n, r, q):
"""
This function produces power modulo some number.
"""
total = n
for i in range(1, r):
total = (total * n) % q
return total |
def split_at_offsets(line, offsets):
"""Split line at offsets.
Return list of strings.
"""
result = []
previous_offset = 0
current_offset = 0
for current_offset in sorted(offsets):
if current_offset < len(line) and previous_offset != current_offset:
result.append(line[... |
def subdivide_dict(dictionary, num_subdivisions):
"""
Distributes the k: v pairs in dict to N dicts.
"""
subdicts = [{} for i in range(num_subdivisions)]
for i, k in enumerate(dictionary.keys()):
sub_index = i % num_subdivisions
subdicts[sub_index][k] = dictionary[k]
return subdi... |
def guessShaper(key):
"""
REDUNDANT see unetsl.cerberus.__main__
"""
kl = key.lower()
if "crop" in kl:
return "crop"
return "upsample" |
def update_suite_config(suite_config, roots=None, excludes=None):
"""
Update suite config based on the roots and excludes passed in.
:param suite_config: suite_config to update.
:param roots: new roots to run, or None if roots should not be updated.
:param excludes: excludes to add, or None if excl... |
def scale_shortener(scale):
"""Function to trim number of significant figures for flux scales when
required for dictionary keys or saving pickle files.
:param scale: Flux Scale
:return: Flux Scale to 4.s.f
"""
return "{0:.4G}".format(float(scale)) |
def scalar_product(a, b):
"""Compute the polynomial scalar product int_-1^1 dx a(x) b(x).
The args must be sequences of polynomial coefficients. This
function is careful to use the input data type for calculations.
"""
la = len(a)
lc = len(b) + la + 1
# Compute the even coefficients of th... |
def split_records(line_record):
"""split_records(line_record)-> list of strings(records)
standard separator list separator is space, records containting encapsulated by " """
split_result=[]
quote_pos=line_record.find('"')
while quote_pos!=-1:
if quote_pos>0:
split_res... |
def vi700(b4, b5):
"""
Vegetation Index 700 (Gitelson et al., 2002).
.. math:: VI700 = (b5 - b4)/(b5 + b4)
:param b4: Red.
:type b4: numpy.ndarray or float
:param b5: Red-edge 1.
:type b5: numpy.ndarray or float
:returns VI700: Index value
.. Tip::
Gitelson, A. A., Kaufm... |
def merge_deep(source, destination):
"""
>>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
>>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
>>> merge_deep(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
True
... |
def find_delimiter_in(value):
"""Find a good delimiter to split the value by"""
for d in [';', ':', ',']:
if d in value:
return d
return ';' |
def required_confirmations(number_of_validators):
"""the number of confirmations required"""
return (number_of_validators * 50 + 99) // 100 |
def get_linear(x1, y1, x2, y2, offset=1000):
""" Return a and b for ax+b of two points x1,y1 and x2,y2 """
# If two points distincts
if x1 != x2:
# Compute the slope of line
a = (((y1 - y2)) *offset) // (x1 - x2)
b = y1*offset - a*x1
else:
a = 0
b = 0
return a,b,offset |
def half_int_float_to_str(f):
"""Given the decimal representation of a half-integer or integer, returns
the string fraction representation.
Example:
> half_int_float_to_str(1.5)
'3/2'
"""
if int(f) - f == 0:
return str(int(f))
else:
return str(int(2 * f)) + '/2' |
def _escape(st):
"""Escape Strings for Dot exporter."""
return st.replace('"', '\\"') |
def miller_rabin(n):
""" primality Test
if n < 3,825,123,056,546,413,051, it is enough to test
a = 2, 3, 5, 7, 11, 13, 17, 19, and 23.
Complexity: O(log^3 n)
"""
assert(n >= 1)
if n == 2:
return True
if n <= 1 or not n & 1:
return False
primes = [2, 3, 5,... |
def is_prime(val):
""" improve this with testing """
if val < 2:
return False
elif val == 2:
return True
return False |
def receive(register, cur_instruction, target, other_register):
"""Receive instruction."""
try:
register[target] = other_register['sound'].pop(0)
except IndexError:
return cur_instruction - 1
return cur_instruction |
def linear_fit(x, a, b):
"""
Wrapper function for scipy to fit a line of best fit to datapoints.
"""
return a*x + b |
def match_labels(ref_label, test_label):
"""Returns 1 in one of the labels in substring of the second"""
return int(ref_label in test_label or test_label in ref_label) |
def findEnd(text):
"""
Finds th position where some logical item ends.
It can be ';' a semicolon or
'\n' a newline or
the end of a whole text.
@param {string} text.
@return {number} Position of the end.
"""
semicolonPos = text.find(';'... |
def factorial(number):
"""this fonction computes the factorial"""
result = 1
for i in range(number):
result = result * (i + 1)
return result |
def validMountainArray( arr):
"""
:type arr: List[int]
:rtype: bool
"""
if len(arr)<3:
return False
i=1
while(i<len(arr) and arr[i]>arr[i-1]):
i+=1
if(i==1 or i==len(arr)):
return False
while(i<len(arr) and arr[i]<arr[i-1]):
i+=1
return i==le... |
def _get_received_from(received_header):
"""
Helper function to grab the 'from' part of a Received email header.
"""
received_header = received_header.replace('\r', '').replace('\n', '')
info = received_header.split('by ')
try:
return info[0]
except:
'' |
def combine(value, dict):
""" merge two dictionaries """
result = {}
result.update (value)
result.update (dict)
return result |
def get_conda_platform_from_python(py_platform):
"""
Converts a python platform string to a corresponding conda platform
Parameters
----------
py_platform : str
The python platform string
Returns
-------
str
The conda platform string
"""
# Provides the conda pl... |
def remove_duplicates(seq):
"""
Returns a new list keeping only the unique elements in the original sequence. Preserves the ordering.
http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order
:param seq: The sequence to be processed
:return... |
def find_subscript_name(subscript_dict, element, avoid=[]):
"""
Given a subscript dictionary, and a member of a subscript family,
return the first key of which the member is within the value list.
If element is already a subscript name, return that.
Parameters
----------
subscript_dict: dic... |
def get_toks(seg_str):
"""Extract list of tokens from segmented string
Args:
seg_str (str): segmented string which can be by human or botok
Returns:
list: list of tokens
"""
tokens = [token for token in seg_str.split(' ') if token]
return tokens |
def check_for_filetype(line):
"""
Check the current line for whether it reveals the current file's type or not.
:param srtr line: the line to check
:return: None or the string associated with this filetype's key ('Cantrips', 'Epherma'...)
"""
if line == 'EPHEMERA OBJECTS':
return "Ephem... |
def gf_neg(f, p):
"""Negate a polynomial over GF(p)[x]. """
return [ -coeff % p for coeff in f ] |
def is_false(value):
"""
Return ``True`` if the input value is ``'0'``, ``'false'`` or ``'no'`` (case insensitive)
:param str value: value to be evaluated
:returns: bool
Example
_______
>>> is_false('0')
True
>>> is_false('1')
False
"""
return str(value).lower() in ['fa... |
def _parent_data_to_dict(parent_data):
"""Make a dict out of the column names and values for the parent data, discarding any unused rows"""
parent_dict = {}
for (col, val) in parent_data:
if col:
parent_dict[col] = val
return parent_dict |
def analyze_time_diff(diff, device_id):
"""Analyze and return assessement of diff."""
if diff is 0:
return "{} last reported {}".format(device_id, 'moments ago')
return "{} last reported {} minutes ago".format(device_id, diff) |
def DictFromLast(seq):
"""Returns dict mapping each item to index of its last occurrence in seq.
WARNING: will fail if items in seq are unhashable, e.g. if seq is a list of
lists.
"""
return dict([(item, index) for index, item in enumerate(seq)]) |
def non_shorthand_keys(py_to_cpp_map):
"""Retrieve the keys but ignore all shorthand forms, i.e., ignore keys
that would translate a value like TRANSPARENT to a short form like
't'
"""
return [key for key in py_to_cpp_map.keys()
if py_to_cpp_map[key].__class__ == "".__class__] |
def FindNextMultiLineCommentEnd(lines, lineix):
"""We are inside a comment, find the end marker."""
while lineix < len(lines):
if lines[lineix].strip().endswith('*/'):
return lineix
lineix += 1
return len(lines) |
def get_drive_by_mountpoint(mountpoint):
"""
This accepts a mountpoint ('/mnt/enclosure0/rear/column2/drive32') and returns the drive:
drive32
"""
return (mountpoint.split("/")[5]) |
def parse_playlist_uri(uri):
"""
Takes a playlist uri and splits it to (user_id, playlist_id)
"""
playlistparts = uri.split(':')
# Sample: spotify:user:lmljoe:playlist:0DXoY83tBvgWkd8QH49yAI
if len(playlistparts) != 5:
print('Invalid playlist id')
exit()
user_id = playlistpar... |
def insertion_sort(array : list) -> list:
"""
This function sorts an array of numbers using the insertion sort algorithm
Parameters
----------
array : list
List containing numbers
Returns
-------
list
The sorted list
"""
for i in range(1, len(array)):
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.