content stringlengths 42 6.51k |
|---|
def none_or_str(x):
"""Cast X to a str if it is not None"""
if x is not None and not isinstance(x, str):
return str(x)
return x |
def bubble_sort(marks):
"""Function to return a sorted list using the bubble sort algorithm."""
for i in range(len(marks)):
for j in range(len(marks)-i-1):
if marks[j] > marks[j+1]:
marks[j], marks[j+1] = marks[j+1], marks[j]
return marks |
def is_list(a):
"""Check if argument is a list"""
return isinstance(a, list) |
def indexOfSortedSuffix(doc, max_word_len):
"""
Treat a suffix as an index where the suffix begins.
Then sort these indexes by the suffixes.
"""
indexes = []
length = len(doc)
indexes = [(i,j) for i in range(0, length)
for j in range(i + 1, min(i + 1 + max_word_len, length + 1... |
def any_(*rules):
"""
Returns list of rules which can be used in HANDLER_MODULE_ALLOWLIST
or HANDLER_MODULE_BLOCKLIST and is later evaluated as "matched" if *any*
rule from the `rules` matches.
:param rules: Each rule is a dict in the same format as other
dicts in the HANDLER_MODULE_ALLOWLI... |
def normalized(expression):
"""Converts the expression to the syntax necessary for Pandas'
DataFrame.eval method.
Args:
expression: The expression to normalize
Returns:
A normalized version of the expression usable in Pandas' DataFrame.eval
method.
"""
return expression... |
def clamp(value: float, min_value: float, max_value: float) -> float:
"""Ensures the **value** is contained within bounds (a minimum and a maximum).
:param value: The value to *clamp*
:param min_value: The lower bound
:param max_value: The upper bound
:type value: float
:type min_value: ... |
def is_ascii(s):
"""
Check if a "bytes" contains all ascii characters
:param s: the string to check
:return: true if the string is entirely ascii characters
"""
try:
s.decode('ascii')
except UnicodeDecodeError:
return False
return True |
def decide_operation(left, right, operation):
"""
input operations is as string representing a built-in operation
"""
if operation == '+':
return left + right
if operation == '-':
return left - right
if operation == '*':
return left * right
if operation == '/':
... |
def get_closest_targets(targets_with_distances, min_distance):
"""Get closest targets with min_distance from targets_with_distances."""
return [
(target_row, target_col)
for distance, (target_row, target_col) in targets_with_distances
if distance == min_distance] |
def get_circle_shell_for_given_radius(radius, dimension=3):
"""
:param radius: radius of the circle.
:param dimension: must be 2 or 3.
:return: matrix coordinate values for a circle of given input radius and dimension centered at the origin.
E.G.
>> get_circle_shell_for_given_radius(3,2)
[(-... |
def get_next_chunk(sliceable, start_position, chunk_size, down):
"""includes start_position, of size chunk_size"""
if not down:
chunk_beg = max(0, start_position - chunk_size + 1)
# print('yielding chunk upwards from ', chunk_beg, 'to', start_position + 1)
return sliceable[chunk_beg:star... |
def name_from_title(title):
""" convert a title into an acceptable directory name """
txt = title.strip() # strip off lealding & trailing blanks
chars = list(txt) # atomize the title
for ndx, char in enumerate(chars):
if char == ' ':
chars[ndx] = '_'
eli... |
def correlate_objects(objects, attr):
"""Correlate several objects under one dict.
If you have several objects each with a 'name' attribute, this
puts them in a dict keyed by name.
Example::
>>> class Flintstone(DumbObject):
... pass
...
>>> fred = Flintstone(name="... |
def add_prices(basket):
"""The add_prices function returns the total price of all of the groceries in
the dictionary."""
total = 0
for product, prices in basket.items():
total += prices
return round(total, 2) |
def incremental_version(old, new):
"""Determine if version label has changed."""
return False if old == new else True |
def encode_byte_array(value: bytes) -> bytes:
"""Encodes a byte array.
"""
return bytes([]) if isinstance(value, type(None)) else value |
def psmid_to_run(psmid):
"""
Extract run from Percolator PSMId.
Expects the following formatted PSMId:
`run` _ `SII` _ `MSGFPlus spectrum index` _ `PSM rank` _ `scan number` _ `MSGFPlus-assigned charge` _ `rank`
See https://github.com/percolator/percolator/issues/147
"""
psmid = psmid.... |
def decoder(address: str) -> list:
"""For a parm address (that may contain floating bits), return the list of decoded addresses (floating bits
expanded out to their options."""
if 'X' not in address: # Base case,
return [address] # Return list with a singl... |
def temp_file(filename):
"""creates a temp file copy to work with without editing original"""
with open('temp.txt', 'wt', encoding='utf-8') as temp:
for i in filename:
temp.write(i)
# print('in temp file test')
return 'temp.txt' |
def list_to_indices(index_string):
"""
Return an integer list from a string representing indices.
e.g. index_string = '1-3, 5-6, 8-13, 15, 20'
indices = [1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 13, 15, 20]
Args:
index_string (string): condensed string representation of integer list.
Retu... |
def format_date(datestring):
"""Convert a long iso date to the day date.
input: 2014-05-01T02:26:28Z
output: 2014-05-01
"""
return datestring[0:10] |
def which_prize(points):
"""
Notifies a competitor of the prize they have won in a game,
depending on the number of points they've scored
"""
prize = None
if points <= 50:
prize = "wooden rabbit"
elif points <= 150:
prize = None
elif points <= 180:
prize = "wafer-... |
def _get_uid(context):
"""Returns a unique context identifier for logging purposes for a plugin.
"""
if 'uid' in context:
return context['uid']
return context.get('ip', '') |
def _contains_lines(haystack, needle, ignore_whitespace=True):
"""
>>> _contains_lines(range(4), range(1,2))
True
>>> _contains_lines(range(4), range(1,5))
False
"""
if isinstance(haystack, str):
haystack = haystack.split('\n')
if isinstance(needle, str):
needle = needle.... |
def to_string(number):
""" Convert float/int to string
>>> to_string(13)
'13'
"""
return str(int(number)) |
def vsbyfmt(val):
"""Tricky formatting of vis"""
val = round(val, 3)
if val == 0:
return 0
if val <= 0.125:
return "1/8"
if val <= 0.25:
return "1/4"
if val <= 0.375:
return "3/8"
if val <= 0.5:
return "1/2"
if val <= 1.1:
return "1"
if... |
def _pluralize(wordlist):
"""Take a list of words and return a list of their plurals"""
return [i + 's' for i in wordlist] |
def vaultRequestHeaderFromSessionId(sessionId, clientId):
"""
Return the Vault Authorization Header from the Vault SessionID.
:param sessionId: vault sessionId
:param vaultClientId: client ID to track REST API Calls in logs
:return: headers: Vault Authorization Header
"""
headers = {'Autho... |
def diff_one_dimension(a1: int, a2: int, b1: int, b2: int):
"""
Perform A - B on two 1-dimensional segments,
where A is given by range (a1,a2) and B by (b1,b2).
Return a tuple of:
* First element: list of 0, one, or two segments that remain after diff operation
* second element: the cut segment... |
def n_palavras_diferentes(lista_palavras):
"""
This function receives a list of words and returns the
number of different words used.
"""
freq = dict()
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
freq[p] += 1
else:
fre... |
def get_dtype(max_value):
"""
Calculate the appropriate dtype that will contain the max value
Parameters
----------
max_value : number
max encoded value
Returns
-------
numpy dtype string
"""
if max_value <= 255:
return "uint8"
if max_value <= 65535:
... |
def is_even(x):
"""
takes an integer input
outputs true if int is even
else outputs false
"""
return x%2==0 |
def format_time( t ):
""" format seconds as mm:ss """
m,s = divmod(t,60)
if m > 59:
h,m = divmod(m,60)
return "%d:%02d:%02d"%(h,m,s)
else:
return "%d:%02d"%(m,s) |
def _dict_mixed_empty_parser(v, v_delimiter):
"""
Parse a value into the appropriate form, for a mixed value based column.
Args:
v: The raw string value parsed from a column.
v_delimiter: The delimiter between components of the value.
Returns:
The parsed value, which can either... |
def is_ogc(name):
"""Checks if name is a valid ogc entity type"""
return name in ["Things", "Sensors", "Locations", "HystoricalLocations", "Datastreams", "ObservedProperties",
"Observations", "FeaturesOfInterest"] |
def _warning(msg, *a, **kwargs):
"""Improve the printing of user warnings."""
return str(msg) + "\n" |
def getCountDict( inlist ):
"""list -> count dict"""
outCD = {}
for element in inlist:
if element in outCD:
outCD[element] += 1
else:
outCD[element] = 1
return outCD |
def _CanonicalizeJoinCond(join_cond):
"""join_cond: 4-tuple"""
t1, c1, t2, c2 = join_cond
if t1 < t2:
return join_cond
return t2, c2, t1, c1 |
def set_bit(n, i, x):
"""Set the i-th bit of n to 1 if x is truthy, else to 0,"""
m = 1 << i # mask with bit i set.
return n | m if x else n & ~m |
def _thunkByte(c, mask=0xff, shift=0):
"""extract an integer from a byte applying a mask and a bit shift
@c character byte
@mask the AND mask to get the desired bits
@shift negative to shift right, positive to shift left, zero for no shift
"""
val = c & mask
if shift < 0:
val = val >... |
def flipDP(directionPointer: int) -> int:
"""
Cycles the directionpointer 0 -> 1, 1 -> 2, 2 -> 3, 3 -> 0
:param directionPointer: unflipped directionPointer
:return: new DirectionPointer
"""
if directionPointer != 3:
return directionPointer + 1
return 0 |
def count_multiples(start, end, divisor):
"""Returns the number of multiples of divisor between start and end."""
counter = start
num_multiples = 0
while counter <= end:
if counter % divisor == 0:
num_multiples += 1
counter += 1
return num_multiples |
def is_indented(text):
""" Simple check to see if a line is indented
For now, a line that starts with ANY whitespace is indented
"""
return bool(len(text) - len(text.lstrip())) |
def bytes2human(n, format='%(value).1f %(symbol)sB'):
"""
Convert n bytes into a human readable string based on format.
symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
see: http://goo.gl/kTQMs
>>> from datalad.utils import bytes2human
>>> bytes2human(1)
'1.0 B'... |
def tanhDerivative(x):
""" This function computes the tanh derivative of x"""
return 1.0 - x**2 |
def choice_name(choice):
"""
Returns Choice type field's choice Name (Text) for form rendering
"""
try:
resp = choice[1]
except IndexError:
resp = ''
pass
return resp |
def hex_to_bin(hex_str: str, width: int = 32) -> str:
"""Converts hex string to binary string
Parameters
----------
hex_str : str
hexadecimal string to convert
width : int, optional
width of binary output (used for zero padding), default=32
Returns
-------
str
... |
def getMissedAnnoIds(missed_annotations):
"""
Extract oid from annotations
Parameters
----------------
missed_annotations: list of dict
Returns
----------------
missedAnnoIds: list of ints
"""
missedAnnoIds = []
for anno in missed_annotations:
missedAnnoIds.append(an... |
def repl_whites(name):
"""Replace whitespace in names."""
return '_'.join(name.split()) |
def bytecount_scoredistance(first_data, memento_data):
"""Calculate the distance between byte counts given the content in
`first_data` and `memento_data`.
"""
score = None
if type(first_data) == type(memento_data):
if type(first_data) == list:
first_data = ''.join(first_data)... |
def caps_from_underscores(string):
"""Converts words_with_underscores to CapWords."""
words = string.split('_')
return ''.join([w.title() for w in words]) |
def N_HTELTF_from_N_ESS(N_ESS):
"""Number of HT Extension LTFs from number of extension spatial streams"""
table_20_14 = {0: 0,
1: 1,
2: 2,
3: 4}
return table_20_14[N_ESS] |
def pintensity(policies, weights):
"""Get the total intensity of a given bin of policies"""
total = 0
for p in policies:
if p == "nan":
continue
if p not in weights.keys():
raise ValueError(f"Missing intensity group: {p}")
else:
total += weights[... |
def roi_center(roi):
""" Return center point of roi
"""
def slice_center(s):
return (s.start + s.stop)*0.5
if isinstance(roi, slice):
return slice_center(roi)
return tuple(slice_center(s) for s in roi) |
def check_positives(lst, idx):
"""Binary array of positive values given value and index list """
return not [x for i,x in enumerate(lst) if (i in idx) and int(x)<1] |
def first(xs):
"""
Get the first item in a sequence
Example:
assert first([1,2,3]) == 1
"""
return next(iter(xs)) |
def make_tuple(input):
"""
returns the input as a tuple. if a string is
passed, returns (input, ). if a tupple is
passed, returns the tupple unmodified
"""
if not isinstance(input, (tuple, list)):
input = (input,)
return input |
def partial_product(start, stop):
"""Product of integers in range(start, stop, 2), computed recursively.
start and stop should both be odd, with start <= stop.
"""
numfactors = (stop - start) >> 1
if not numfactors:
return 1
elif numfactors == 1:
return start
else:... |
def _getDct(dct, frame):
"""
Gets the dictionary for the frame.
Parameters
----------
dct: dictionary to use if non-None
frame: stack frame
Returns
-------
dict
"""
if dct is None:
#dct = frame.f_back.f_locals
dct = frame.f_back.f_globals
return dct |
def fibonacci_recursive(nth_nmb: int) -> int:
"""An recursive approach to find Fibonacci sequence value.
YOU MAY NOT MODIFY ANYTHING IN THIS FUNCTION!!"""
cache = {0: 0, 1: 1}
def fib(_n):
return _n if _n in cache else fib(_n - 1) + fib(_n - 2)
return fib(nth_nmb) |
def factor(n):
"""Factor n."""
l = []
while n != 1:
for i in range(2, n+1):
if n % i == 0:
n //= i
l.append(i)
break
return l |
def human_readable_filesize(size):
"""Convert file size in bytes to human readable format
Args:
size (int): Size in bytes
Returns:
str: Human readable file-size, i.e. 567.4 KB (580984 bytes)
"""
if size < 1024:
return "{} bytes".format(size)
remain = float(size)
fo... |
def to_float_hours(hours, minutes, seconds):
""" (int, int, int) -> float
Return the total number of hours in the specified number
of hours, minutes, and seconds.
Precondition: 0 <= minutes < 60 and 0 <= seconds < 60
>>> to_float_hours(0, 15, 0)
0.25
>>> to_float_hours(2, 45, 9)
2.7... |
def dbw_to_watts(dbw):
"""
Convert dBW to Watts.
Given the power in the decibel scale, this function will evaluate the
power in Watts.
Parameters
----------
dbw: float
Power in the decibel scale (dBW)
Returns
-------
watts float
Pow... |
def xnor(a, b):
"""xnor bits together.
>>> assert xnor(0, 0) == 1
>>> assert xnor(0, 1) == 0
>>> assert xnor(1, 0) == 0
>>> assert xnor(1, 1) == 1
"""
assert a in (0, 1)
assert b in (0, 1)
if a == b:
return 1
else:
return 0 |
def ml_mean(values):
"""
Given a list of values assumed to come from a normal distribution,
return the maximum likelihood estimate of mean of that distribution.
There are many libraries that do this, but do not use any functions
outside core Python (sum and len are fine).
"""
# Your code he... |
def get_ukb_sumstats_mt_path(reference: str = 'GRCh37', sex: str = 'both_sexes'):
"""
Get UKB sumstats MatrixTable path
:param str reference: Which reference to use (one of "GRCh37" or "GRCh38")
:param str sex: Which sex to return results for (one of "both_sexes" (default), "female", "male")
:retur... |
def get_rev_strand(strand):
"""
Get reverse strand.
>>> get_rev_strand("-")
'+'
"""
if strand == "+":
return "-"
elif strand == "-":
return "+"
else:
assert False, "invalid strand information given (%s)" %(strand) |
def one_group(named_parameters):
"""All parameters in all group."""
return [{"params": [p for (_, p) in named_parameters]}] |
def sanitize_value(string):
"""Sanitize string of tags value and source.
@oaram string: Input String
@return: Sanitized String
"""
res = string.strip()
res = res.replace("\"", "\\\"")
return "\"" + res.replace("\n", "\\n") + "\"" |
def filter_styles(style, group, other_groups, blacklist=[]):
"""
Filters styles which are specific to a particular artist, e.g.
for a GraphPlot this will filter options specific to the nodes and
edges.
Arguments
---------
style: dict
Dictionary of styles and values
group: str
... |
def safe_int(value):
"""Returns an int object, suppressing all errors, default to 0"""
try:
return int(value)
except:
return 0 |
def parse_return(data):
"""
Returns the data portion of a string that is colon separated.
:param str data: The string that contains the data to be parsed. Usually the
standard out from a command
For example:
``Time Zone: America/Denver``
will return:
``America/Denver``
"""
if ... |
def extract_user(event):
"""
:param event: (required) the event from the request
:return: The username of the user who made the request
"""
return event["requestContext"]["authorizer"]["claims"]["cognito:username"] |
def _suffix(d):
"""
Determine the suffix for a date
:param d: day to determine suffix of
:return: string of suffix
"""
return 'th' if 11 <= d <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(d % 10, 'th') |
def _ConvertFormatToQmark(statement, args):
"""Replaces '%s' with '?'.
The server actually supports '?' for bind parameters, but the
MySQLdb implementation of PEP 249 uses '%s'. Most clients don't
bother checking the paramstyle member and just hardcode '%s' in
their statements. This function converts a for... |
def human_readable(value):
"""
Returns the number in a human readable format; for example 1048576 = "1Mi".
"""
value = float(value)
index = -1
suffixes = 'KMGTPEZY'
while value >= 1024 and index + 1 < len(suffixes):
index += 1
value = round(value / 1024)
if index == -1:
... |
def courant(dx, dt, v_max, **kwargs):
"""
Calculate the Courant's number describing
stability of the numerical scheme.
Parameters
----------
dx : float
Size of the spatial grid cell [m].
dt : float
Time step [s].
v_max : float
Max. velocity of the model.
Returns
-------
C : flo... |
def getGroups(zNum, zCond, edata, events):
"""
Extract and construct the groups for the given event.
"""
groups = []
if ('groups' in edata) and (edata['groups'] is not None):
for eGroups in edata['groups']:
if ('zone_conditions' in eGroups) and \
(eGroups['zone_con... |
def is_divisible(n, x, y):
"""
checks if a number n is divisible by two numbers x AND y.
:param n: positive, non negative integer.
:param x: positive, non negative integer.
:param y: positive, non negative integer.
:return: if n is divisible by x and y.
"""
return n % x == 0 and n % y ==... |
def get_filepath(video_id):
"""
Returns the filepath of the video in the clevrer directory
Args:
video_id(int): The id of the video obtained from the json
Returns:
filepath(string): the path from the dataset directory to the video
Ex: image_00000-01000/video_00428
"""
... |
def parse_result(line):
"""
Parse the result line of a phenomizer request.
Arguments:
line (str): A raw output line from phenomizer
Returns:
result (dict): A dictionary with the phenomizer info:
{
'p_value': float,
'gene_symbols': l... |
def break_list_into_parts(LIST, parts):
"""For example:
.. doctest::
>>> break_list_into_parts([1,2,3,4,5], [3,2])
([1, 2, 3], [4, 5])
:param LIST:
:param parts:
:return:
"""
start = 0
RET = tuple()
for p in parts:
RET += (LIST[start:start+p],)
star... |
def paddingBase64(length, bit, sym='='):
"""Base64 Padding"""
_length = length % bit
return (8-_length) * sym if _length > 0 else "" |
def con_kwh_to_joule(energy_kwh):
"""
Converts energy value from kWh to Joule
Parameters
----------
energy_kwh : float
Energy demand value in kWh
Returns
-------
energy_joule : float
Energy demand value in Joule
"""
energy_joule = energy_kwh * 1000 * 3600
re... |
def alphabet_values(L):
"""Create a list containing all alphabet values of the words in L."""
alphabet = { 'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9,
'j':10, 'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16, 'q':17, 'r':18,
's':19, 't':20, 'u':21, 'v':22, 'w':23, 'x':24, 'y':25... |
def convert_bool_args(args: dict) -> dict:
"""Convert boolean CLI arguments from string to bool.
Args:
args: a mapping from CLI argument names to values
Returns:
copy of args with boolean string values convert to bool
"""
new_args = {}
for k, v in args.items():
if v.low... |
def encode(line):
"""
INPUT: A line of ASCII String.
OUTPUT: A List of Run-Length Encoded of the input string.
"""
if not line:
return [""]
else:
last_char = line[0]
length = len(line)
i = 1
while i < length and last_char == line[i]:
i += 1
... |
def get_whole_number_or_float(number):
""" Get whole number of input or keep as float. """
if number % 1 == 0:
return int(number)
return number |
def my_quad(y,x):
"""quadratic integration on given grids
I = Sum (y[i+1]+y[i])*(x[i+1]-x[i])/2
"""
I = 0.
for i in range(len(x)-1):
I += (y[i+1]+y[i])*(x[i+1]-x[i])/2.
return I |
def get_words(data, letters):
"""Get all words in the data that can be made with the provided letters and have all capitalized letters."""
all_letters = {letter.lower() for letter in letters}
required_letters = {
letter.lower() for letter in letters if letter == letter.upper()
}
return [
... |
def positive(number: int) -> int:
"""
:return: Number, or 1 if number is negative or 0
"""
return max(1, number) |
def conv_to_zerofill(param):
"""
User to convert single int to double: 1 -> 01
"""
return str(param).zfill(2) |
def r_in(td, r_0):
"""Calculate incident countrate given dead time and detected countrate."""
tau = 1 / r_0
return 1. / (tau - td) |
def _filter_token(dict_dirty: dict, token: list):
"""Remove token fields from resultset."""
return dict(filter(lambda elem: elem[0] not in token, dict_dirty.items())) |
def addMiddlePoints(p1, p2, n ):
""" Function to calculate the middle point between two points
@ params:
p1 - Required: set of coordinates of first point
p2 - Required: set of coordinates of second point
n - Required: number of divisions"""
x_1 = p1[0]
y_1 = p1[1]
x_2 = p2[0]
y_2 ... |
def get_dp_logs(logs):
"""Get only the list of data point logs, filter out the rest."""
filtered = []
compute_bias_for_types = [
"mouseout",
"add_to_list_via_card_click",
"add_to_list_via_scatterplot_click",
"select_from_list",
"remove_from_list",
]
for log in... |
def fibList(n):
"""
returns first n fibonacci suequence as list
"""
fibs = [1, 1]
for i in range(2, n):
fibs.append(fibs[-1]+fibs[-2])
return fibs |
def collection_to_dict(collection):
"""Utility function to construct collection dict with names."""
return {v.name[:v.name.rfind(':')]: v for v in collection} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.