content stringlengths 42 6.51k |
|---|
def get_condition_label(condition_id: str) -> str:
"""Convert a condition ID to a label.
Labels for conditions are used at different locations (e.g. ensemble
prediction code, and visualization code). This method ensures that the same
condition is labeled identically everywhere.
Parameters
----... |
def normalize_str(input_str):
""" Normalize an input string """
return input_str.strip().lower().replace(" ", " ") |
def list_from_i_to_n(i,n):
"""
make list [i,i+1,...,n]
for example:
list_from_i_to_n(3,7) => [3,4,5,6,7]
list_from_i_to_n(4,6) => [4,5,6]
"""
result = []
for j in range(i,n+1):
result = result + [j]
return result |
def subexpr_from_unbalanced(expr, ltok, rtok):
"""Attempts to pull out a valid subexpression for unbalanced grouping,
based on opening tokens, eg. '(', and closing tokens, eg. ')'. This
does not do full tokenization, but should be good enough for tab
completion.
"""
lcnt = expr.count(ltok)
... |
def binary_search_two_pointers_recur(sorted_nums, target, left, right):
"""Util for binary_search_feast_recur()."""
# Edge case.
if left > right:
return False
# Compare middle number and recursively search left or right part.
mid = left + (right - left) // 2
if sorted_nums[mid] == targ... |
def up_to_unmatched_closing_paren(s):
"""Splits a string into two parts up to first unmatched ')'.
Args:
s: a string which is a substring of line after '('
(e.g., "a == (b + c))").
Returns:
A pair of strings (prefix before first unmatched ')',
remainder of s after first unmatched '... |
def on_square(number: int) -> int:
"""Return the number of grains on a given square."""
return 1 << (number - 1) |
def is_alnum_or_in_str(c, s):
"""
checks if a character is a-z, A-Z, 0-9, or in the string s.
:return: True if c is alphanumaric or in s.
"""
return c.isalnum() or c in s |
def stringbytes(elems: list) -> list:
"""Chain bytes() instances next to each other in elems together.
"""
out = []
while len(elems) > 0:
elem = elems.pop(0)
while isinstance(elem, bytes) and len(elems) > 0 and isinstance(elems[0], bytes):
elem += elems.pop(0)
out.app... |
def export_data(processed_data, all_drugs_sorted, export_path, cost_usd):
"""
Formats and writes all entries to export file.
Args:
processed_data (dictionary): contains all analyzed data. Primary key
is drug name (string), and primary value is tuple containing
number of pres... |
def get_computer_move_history(piece, board_state):
"""Get the move history of the computer"""
move_history = []
for move in board_state:
if move[0] == piece:
move_history.append(int(move[1]))
return move_history |
def lstrip(s):
"""lstrip(s) -> string
Return a copy of the string s with leading whitespace removed.
"""
return s.lstrip() |
def str2colour(colstr = None):
"""Return a valid colour from supplied string."""
ret = [0.0, 0.0, 0.0]
if colstr:
cvec = colstr.split(',')
if len(cvec) == 3:
try:
for c in range(0,3):
ret[c] = float(cvec[c])
if ret[c] < 0.0:... |
def get_completions(text, options):
"""
Returns a list of options, which could be used to complete provided text.
"""
completions = []
l = len(text)
for x in options:
if len(x) < l:
continue
if x.startswith(text):
completions.append(x)
return completio... |
def safe_equals(x,y):
"""Handle "x = y" where x and y could be some combination of ints and
strs.
@param x (any) LHS of the equality check.
@param y (any) RHS of the equality check.
@return (boolean) The result of the equality check, taking into
account the implicit type conversions VB perform... |
def _parse_node_to_coords(element):
"""
Parse coordinates from a node in the overpass response.
The coords are only used to create LineStrings and Polygons.
Parameters
----------
element : dict
element type "node" from overpass response JSON
Returns
-------
coords : dict
... |
def create_reference(obj) -> str:
"""Return a ``module:varname`` reference to the given object."""
obj_name = obj.__qualname__
if '<locals>' in obj_name:
raise ValueError('cannot create a reproducible reference to a nested function')
return '%s:%s' % (obj.__module__, obj_name) |
def _getColor(color, ref):
""" _getColor(color, reference)
Get the real color as a 4 element tuple, using the reference
color if the given color is a scalar.
"""
if isinstance(color, float):
return (color*ref[0], color*ref[1], color*ref[2], ref[3])
else:
return color |
def get_doc_changes(original, new, base_prefix=()):
"""
Return a list of changed fields between
two dict structures.
:type original: dict
:rtype: list[(tuple, object, object)]
>>> get_doc_changes({}, {})
[]
>>> get_doc_changes({'a': 1}, {'a': 1})
[]
>>> get_doc_changes({'a': {... |
def _merge_general_metadata(meta_list):
""" Combine list of "general" metadata dicts into
a single dict
"""
if not meta_list:
return {}
meta = None
for md in meta_list:
if meta:
meta["data_paths"] += md["data_paths"]
meta["file_stats"] += md["file_stat... |
def calculate_average_price_sl_percentage_short(sl_price, average_price):
"""Calculate the SL percentage based on the average price for a short deal"""
return round(
100.0 - ((sl_price / average_price) * 100.0),
2
) |
def err(ranking, max=10, max_grade=2):
"""
todo
"""
if max is None:
max = len(ranking)
ranking = ranking[:min(len(ranking), max)]
ranking = map(float, ranking)
result = 0.0
prob_step_down = 1.0
for rank, rel in enumerate(ranking):
rank += 1
utility = (pow(2... |
def is_subset(subset, settt):
"""
Determines if 'subset' is a subset of 'set'
:param subset: The subset
:param set: The set
:return: True if 'subset' is a subset of 'set, False otherwise
"""
cpos = 0
for c in settt:
""" too slow
if c > subset[cpos]:
return False
"""
cpos += c == subset[cpos] # Found... |
def capitalize_header(key):
""" Returns a capitalized version of the header line such as
'content-type' -> 'Content-Type'.
"""
return "-".join([
item if item[0].isupper() else item[0].upper() + item[1:]
for item in key.split("-")
]) |
def extract_bibtex_key(system_control_numbers):
"""Get bibtex key from 'system_control_numbers' field
Unfortunately, this seems to be the only way to get the bibtex key. I have
seen suggestions around the github issues for inspirehep/invenio that this
should always be present
"""
if isins... |
def add_the_commas_diy(i):
"""
Most complex method using my own implementation.
:param i: Integer value to format.
:return: Value with thousands separated with commas.
"""
number = str(i)
# Simple case 1: no commas required
if len(number) < 4:
return number
decimal_part = F... |
def parse_paid(value):
"""
Parses a specific portuguese word "Sim"(=Yes) to a bool.
"""
if value == 'Sim':
return True
else:
return False |
def extender (l, tail) :
"""Return list `l` extended by `tail` (`l` is changed in place!)
>>> extender ([1, 2, 3], (4, 5))
[1, 2, 3, 4, 5]
>>> extender ([], [1])
[1]
"""
xtend = l.extend if isinstance (tail, (list, tuple)) else l.append
xtend (tail)
return l |
def matches(expanded_solution, constraints):
"""
solution is a tuple of spaces, the output of solve1
constraints is a tuple of values from 1, 0 and -1, that
mean:
0 -> OFF
1 -> ON
-1 -> not constrained
"""
for s, c in zip(expanded_solution, constraints):
if c ==... |
def check_index(index, valid_min, valid_max):
"""Check that an index doesn't exceed the valid bounds."""
if index >= valid_max:
index = index - valid_max
if index < valid_min:
index = index + valid_max
return index |
def get_trader_scada_ramp_rate(trader_id, ramp_rates):
"""
Extract SCADA ramp rate for a given trader. If the SCADA ramp rate is 0
or missing return None.
"""
if (trader_id in ramp_rates.keys()) and (ramp_rates[trader_id] > 0):
return ramp_rates[trader_id]
else:
return None |
def _split_channels(num_chan, num_groups):
"""Split range(num_chan) in num_groups intervals. The first one is larger if num_chan is not a multiple of num_groups"""
split = [num_chan // num_groups for _ in range(num_groups)]
# add the remaining channels to the first group
split[0] += num_chan - sum(split... |
def song_text(string_num=3, la_num=3, last_symbol=1):
"""
The method generates strings which consist of 1 same word with separator "-".
Takes 3 params:
:param string_num: - number of lines
:param la_num: - number of words
:param last_symbol: - the last symbol for the last line. 1 == !, 0 == .
... |
def stirling(n_items, k_sets):
"""
Takes as its inputs two positive integers of which the first is the
number of items and the second is the number of sets into which those
items will be split. Returns total number of k_sets created from
n_items.
"""
if n_items < k_sets:
return 0
... |
def str2hex(s):
"""Convert string to hex-encoded string."""
res = ["'"]
for c in s:
res.append("\\x%02x" % ord(c))
res.append("'")
return "".join(res) |
def _serialize_rules(rules):
"""Serialize all the Rule object as string."""
result = [(rule_name, str(rule))
for rule_name, rule in rules.items()]
return sorted(result, key=lambda rule: rule[0]) |
def _parse_auth(auth):
"""
Parse auth string and return dict.
>>> _parse_auth('login:user,password:secret')
{'login': 'user', 'password': 'secret'}
>>> _parse_auth('name:user, token:top:secret')
{'name': 'user', 'token': 'top:secret'}
"""
if not auth:
return None
items = au... |
def find_job_debug_data(job_name, tasks):
"""Find the stack analysis debug data for given job."""
for task in tasks:
if task["task_name"] == job_name:
return task
return None |
def pre_process(line):
"""
Return a ``line`` cleaned from comments markers and space.
"""
if '#' in line:
line = line[:line.index('#')]
return line.strip() |
def pathjoin(*args):
"""Join a /-delimited path.
"""
return "/".join([p for p in args if p]) |
def complete_sulci_name(sulci_list, side):
"""Function gathering sulci and side to obtain full name of sulci
It reads suli prefixes from a list and adds a suffix depending on a given
side.
Args:
sulci_list: a list of sulci
side: a string corresponding to the hemisphere, whether 'L' or ... |
def _list_to_dict(artifact_list):
"""Returns a dict of artifact name to version."""
tuples = [tuple(item.rsplit(":", 1)) for item in artifact_list]
return {name: version for (name, version) in tuples} |
def flatten(List):
"""
Make a list of nested lists a simple list
Doesn't seem to work or else I don't recall what it should do.
"""
if type(List[0]) == list:
newlist = sum(List, [])
else:
newlist = List
return newlist |
def get_multiples(n):
"""Returns 2,3,4,5,6x multiples on n"""
return [i*n for i in range(2, 7)] |
def contains_digit(s):
"""Find all files that contain a number and store their patterns.
"""
isdigit = str.isdigit
return any(map(isdigit, s)) |
def clamp(num, smallest, largest):
"""
Propose a number and a range (smallest, largest) to receive a number that is clamped within that range.
:param num: a number to propose
:param smallest: minimum of range
:param largest: maximum of range
:return: number in range
"""
return max(smalle... |
def DFS_cycle(graph, start, path = []):
""" Detect Cycles with a Depth First Search """
# append to path
path = path + [start]
# graph start
for node in graph[start]:
# check if node != path init
if node not in path:
# return true after... |
def relative_viewname(viewname, resolver):
"""
Helper for building a fully namespaced `viewname` given a URL resolver.
(This is typically from the current request.)
"""
if resolver is None:
return viewname
return ':'.join(
[_f for _f in [
resolver.app_name, resolver.... |
def is_scalar(vect_array):
"""Test if a "fully-vectorized" array represents a scalar.
Parameters
----------
vect_array : array-like
Array to be tested.
Returns
-------
is_scalar : bool
Boolean determining if vect_array is a fully-vectorized scalar.
"""
if isinstanc... |
def mpd_duration(timespec):
""" return duration string. """
try:
timespec = int(timespec)
except ValueError:
return 'unknown'
timestr = ''
m = 60
h = m * 60
d = h * 24
w = d * 7
if timespec > w:
w, timespec = divmod(timespec, w)
timestr = timestr + '%... |
def mm2ns(distance, velocity):
"""Return the time (ns) from distance (mm) and signal velcity (m/ns).
Attributes:
distance <float>: travel distance (ns) of radio signal;
velocity <float>: travel velocity (m/ns) of radio signal.
"""
d, v = distance / 1000, velocity
t... |
def inch_to_canvas(value,x):
"""returns the cm value in the correct needed value for canvas"""
value = value*72
if(x == False):
value = 11.7*72-value
return value |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary. Structured data to conform to the schema.
"""
#
# process the data here
# rebuild output for added semanti... |
def kronecker_delta(i, j):
"""
kronecker_delta Delta function: \delta_{i, j}
Parameters
----------
i: tensor index
j: tensor index
Returns
-------
1 if i==j, 0 otherwise
"""
if i == j:
return 1
else:
return 0 |
def from_text(text):
"""Convert text into a Name object"""
if not text.endswith('.'):
text += '.'
return text |
def sort_probs(probs_list):
"""Sort probabilities list for consistent comparison."""
return sorted(probs_list, key=lambda x: x[1]) |
def GetNestedAttr(content, nested_attr, default=None):
"""Get the (nested) attribuite from content.
Get the (nested) attribute from the content dict.
E.X. content is {key1: {key2: {key3: value3}}, key4: value4}
nested_attr = [key1] gets {key2: value2, {key3: value3}}
nested_attr = [key1, key2] gets {key3: va... |
def fibonacci(n: int) -> int:
"""Compute the N-th fibonacci number."""
if n in (0, 1):
return 1
return fibonacci(n - 1) + fibonacci(n - 2) |
def match_piecewise(candidates: set, symbol: str, sep: str='::') -> set:
"""
Match the requested symbol reverse piecewise (split on ``::``) against the candidates.
This allows you to under-specify the base namespace so that ``"MyClass"`` can match ``my_namespace::MyClass``
Args:
candidates: set... |
def get_names( keys):
""" Transforms full classifier strings into names"""
names = []
# shorten keys to names
for k in keys:
if k.startswith( "OneVsRestClassifier(estimator="):
k = k[30:]
if k.find("(") > 0:
k = k[:k.find("(")]
if k.endswith( "Classifier")... |
def dequote(s):
"""
If a string has single or double quotes around it, remove them.
Make sure the pair of quotes match.
If a matching pair of quotes is not found, return the string unchanged.
"""
if (s[0] == s[-1]) and s.startswith(("'", '"')):
return s[1:-1]
return s |
def heap_parent(d, i):
"""Parent in d-ary heap of element at position i in list."""
return (i-1)//d |
def build_response_card(title, subtitle, options):
"""
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
"""
buttons = None
if options is not None:
buttons = []
for i in range(min(5, len(options))):
buttons.a... |
def sv_length(pos, end, chrom, end_chrom, svlen=None):
"""Return the length of a structural variant
Args:
pos(int)
end(int)
chrom(str)
end_chrom(str)
svlen(int)
Returns:
length(int)
"""
if chrom != end_chrom:
return int(10e10)
if svlen:
... |
def parse_list(list_str):
"""Parse comma-separated list"""
if list_str.strip():
return [t.strip() for t in list_str.split(',') if t.strip()]
else:
return [] |
def mock_input_default(prompt, choices="", clear=False):
"""Enter default choice at prompts"""
res = [x for x in choices if x.isupper()]
return res[0] if res else "" |
def _GetModuleOrNone(module_name):
"""Returns a module if it exists or None."""
module = None
if module_name:
try:
module = __import__(module_name)
except ImportError:
pass
else:
for name in module_name.split('.')[1:]:
module = getattr(module, name)
return module |
def rayleigh_coefficients(zeta, omega_1, omega_2):
"""
Compute the coefficients for rayleigh damping such, that the modal damping
for the given two eigenfrequencies is zeta.
Parameters
----------
zeta : float
modal damping for modes 1 and 2
omega_1 : float
first eigenfrequen... |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
if len(input_list) == 0: return []
if len(input_list) == 1: return input_list
index = 0
# skip 0 at the... |
def round_down(i: float, k: int) -> int:
"""Round down an integer."""
return int(k * (i // k)) |
def iShiftRows(state):
"""Performs inverse shiftRows operation on the state."""
# put your code here
newstate = bytearray(16)
newstate[0] = state[0]
newstate[4] = state[4]
newstate[8] = state[8]
newstate[12] = state[12]
newstate[1] = st... |
def rgb_to_int(x):
"""Converts an rgb/rgba tuple into an int"""
r = x[0]
g = x[1]
b = x[2]
return (r * 0x10000) + (g * 0x100) + b |
def FormatNameToPython(i):
"""
Transform a (method) name into a form which can be used as a python
attribute
example::
>>> FormatNameToPython('<clinit>')
'clinit'
:param i: name to transform
:rtype: str
"""
i = i.replace("<", "")
i = i.replace(">", "")
i = i.r... |
def cleanGender(x):
"""
This is a helper funciton that will help cleanup the gender variable.
"""
if x in ['female', 'mostly_female']:
return 'female'
if x in ['male', 'mostly_male']:
return 'male'
if x in ['couple'] :
return 'couple'
else:
return 'unknownGe... |
def parse_header(line):
"""Parse output of tcpdump of pcap file, extract:
time
date
ethernet_type
protocol
source ip
source port (if it exists)
destination ip
destination port (if it exists)
length of the data
"""
ret_dict = {}
... |
def removePOS(sentence):
"""
Removes the part of speech from a string sentence.
"""
cleansentence = []
for word in sentence.split():
cleansentence.append(word.split('/')[0])
return ' '.join(cleansentence) |
def stringify_tuple(tup, sep=","):
"""
Takes in a tuple and concatante its elements as string seperated by a given char.
Parameters
----------
tup: tuple
Tuple to make string
sep: str, default ","
Seperator between tuple elements in the concataned string
""... |
def NameAndAttribute(line):
"""
Split name and attribute.
:param line: DOT file name
:return: name string and attribute string
"""
split_index = line.index("[")
name = line[:split_index]
attr = line[split_index:]
return name, attr |
def merge_sort(array):
"""
### Merge sort
Implementation of one of the most powerful sorting algorithms algorithms.\n
Return a sorted array,
"""
def merge(L, R):
res = []
left_ind = right_ind = 0
while left_ind < len(L) and right_ind < len(R):
... |
def sched_exp(start, end, pos):
"""Exponential scheduler."""
return start * (end / start) ** pos |
def make_list(unused_s, unused_l, toks):
"""Makes a list out of a token tuple holding a list."""
result = []
for item in toks:
result.append(item.asList())
return result |
def bterm(f,p,pv0,e,B,R,eta):
"""
For the cubic equation for nu in the four-variable model with CRISPR,
this is the coefficient of nu^2
"""
return -(e*f*pv0*(pv0*(f + R) + p*(1 + f*(-1 + B*(-eta + (1 + e + eta)*pv0)) -
R + B*(eta + pv0*(-1 - e - eta + 2*R))))) |
def get_value_from_tuple_list(list_of_tuples, search_key, value_index):
"""
Find "value" from list of tuples by using the other value in tuple as a
search key and other as a returned value
:param list_of_tuples: tuples to be searched
:param search_key: search key used to find right tuple
:param ... |
def ping(host):
"""
Returns True if host responds to a ping request
"""
import subprocess, platform, os
# Ping parameters as function of OS
ping_str = "-n1" if platform.system().lower()=="windows" else "-c1"
args = ["ping", ping_str, host]
# Ping
return subprocess.call(args, stdou... |
def html_title(title):
"""Generates an HTML-formatted title.
"""
return '<center><h1>%s</h1></center>' % (title) |
def constrain(value, min_value, max_value):
"""
Constrains the `value` to the specified range `[min_value, max_value]`
Parameters
----------
`value` : The value to be constrained
`min_value` : The lower limit of range (inclusive)
`max_value` : The upper limit of range (inclusive)
Ret... |
def b36encode(number: int) -> str:
"""Convert the number to base36."""
alphabet, base36 = ["0123456789abcdefghijklmnopqrstuvwxyz", ""]
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0] |
def is_serialised(serialised):
"""
Detects whether some bytes represent a real number.
:param serialised: A ``bytes`` object which must be identified as being a
real number or not.
:return: ``True`` if the ``bytes`` likely represent a real number, or
``False`` if it does not.
"""
#This works with a simple finit... |
def compare_fingerprints(fp1, fp2):
"""
compute the 'distance' between two fingerprints.
it consists of the sum of the distance of each frame
of fp1 from the frame at the same index in fp2.
since each frame is a sorted list of frequencies, the
distance between two frames is the sum of the |diffe... |
def upper(_, text):
""" Convert all letters in content to uppercase. """
return text.upper() |
def cubic_bezier_point(p0, p1, p2, p3, t):
"""
https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves
"""
a = (1.0 - t)**3
b = 3.0 * t * (1.0 - t)**2
c = 3.0 * t**2 * (1.0 - t)
d = t**3
return {
"x": a * p0["x"] + b * p1["x"] + c * p2["x"] + d * p3["x"],
... |
def dictitems(d):
""" A pickleable version of dict.items
>>> dictitems({'x': 1})
[('x', 1)]
"""
return list(d.items()) |
def hashtable(l, tablesize):
"""
http://interactivepython.org/courselib/static/pythonds/SortSearch/Hashing.html
hash table, linear probing implementation
"""
ht = {}
for i in range(tablesize):
ht[i] = None
for i, v in enumerate(l):
idx = v % tablesize
while ht[id... |
def _is_class(s):
"""Imports from a class/object like import DefaultJsonProtocol._"""
return s.startswith('import ') and len(s) > 7 and s[7].isupper() |
def number_equal(element, value, score):
"""Check if element equals config value
Args:
element (float) : Usually vcf record
value (float) : Config value
score (integer) : config score
Return:
Float: Score
"""
if element == value:
return score |
def check_ch(row: str) -> bool:
"""
This function will check if the input is legal or illegal.
"""
row_lst = row.lower().split()
ans = True
if len(row_lst) == 4:
for i in range(4):
if row_lst[i].isalpha() is False or len(row_lst[i]) != 1:
ans = False
else:
ans = False
return ans |
def pg_connect_bits(meta):
"""Turn the url into connection bits."""
bits = []
if meta['username']:
bits.extend(['-U', meta['username']])
if meta['hostname']:
bits.extend(['-h', meta['hostname']])
if meta['port']:
bits.extend(['-p', str(meta['port'])])
return bits |
def get_grant_key(grant_statement):
"""
Create the key from the grant statement.
The key will be used as the dictionnary key.
:param grant_statement: The grant statement
:return: The key
"""
splitted_statement = grant_statement.split()
grant_privilege = splitted_statement[1]
if "."... |
def str_format(s, *args, **kwargs):
"""Return a formatted version of S, using substitutions from args and kwargs.
(Roughly matches the functionality of str.format but ensures compatibility with Python 2.5)
"""
args = list(args)
x = 0
while x < len(s):
# Skip non-start token characters... |
def is_sns_event(event):
"""
Determine if the event we just received is an SNS event
"""
if "Records" in event:
return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.