content stringlengths 42 6.51k |
|---|
def extend_padding(ls_of_ls, padding=''):
"""
Takes in a lists of lists, returns a new list of lists
where each list is padded up to the length of the longest
list by [padding] (defaults to the empty string)
"""
maxlen = max(map(len, ls_of_ls))
newls = []
for ls in ls_of_ls:
if len(ls) != maxlen:
ls.extend([padding]*(maxlen - len(ls)))
newls.append(ls)
return newls |
def haxelib_homepage_url(name, baseurl='https://lib.haxe.org/p/'):
"""
Return an haxelib package homepage URL given a name and a base registry web
interface URL.
For example:
>>> assert haxelib_homepage_url('format') == u'https://lib.haxe.org/p/format'
"""
baseurl = baseurl.rstrip('/')
return '{baseurl}/{name}'.format(**locals()) |
def get_pattern_precise(guess: str, solution: str):
"""generates the patterns for a guess"""
hint = ""
for index, letter in enumerate(guess):
if not letter in solution:
hint += "b"
else:
if letter == solution[index]:
hint += "g"
else:
# only color yellow if not already marked in other yellow or any green
letter_solution = solution.count(letter)
letter_green = sum([l == letter and l == solution[i] for i, l in enumerate(guess)])
letter_yellow_already = sum([l == letter and l != solution[i] for i, l in enumerate(guess[:index])])
if letter_solution - letter_green - letter_yellow_already > 0:
hint += "y"
else:
hint += "b"
return hint |
def format_settings(file_rows):
"""
Takes a list of settings (as written in config files) and
formats it to a dictionary.
Returns a dictionary with all settings as keys.
"""
SETTING_PART_LENGTH = 2
settings = {}
for row in file_rows:
row = row.strip("\n")
parts = row.split("=", 1)
if len(parts) == SETTING_PART_LENGTH:
# Strip to remove whitespace at end and beginning
settings[parts[0].strip()] = parts[1].strip()
return settings |
def has_wiki_desc(resp: dict) -> bool:
"""
Check if a POI response contains a Wikipedia description.
"""
return any(b["type"] == "description" and b["source"] == "wikipedia" for b in resp["blocks"]) |
def reward_clipping(rew):
"""
Sets positive rewards to +1 and negative rewards to -1.
Args:
rew: A scalar reward signal.
Returns:
+1. if the scalar is positive, -1. if is negative and 0 otherwise.
"""
if rew > 0:
return 1.
if rew < 0:
return -1.
return 0. |
def find_output_processes(process_id, connections):
"""
Finds all the processes that this process outputs to
"""
me = connections[process_id]
outputs_to = []
for proc_id in connections:
if proc_id == process_id:
# Don't look at our own process
continue
proc = connections[proc_id]
for input_id in proc.input_ids:
if input_id in me.output_ids:
outputs_to.append(proc)
break
return outputs_to |
def snake(s):
"""Convert from title or camelCase to snake_case."""
if len(s) < 2:
return s.lower()
out = s[0].lower()
for c in s[1:]:
if c.isupper():
out += "_"
c = c.lower()
out += c
return out |
def put_items_to_boxes(items, weights, n, cutoff):
"""Put seqs into n boxes, where stop to put more items when sum of weight in a box is greater than or equal to a cutoff
items --- a list of strings
weights --- item weights
n --- number of boxes
cutoff --- sum of weight cutoff to stop putting items to a box
..doctest::
>>> put_items_to_boxes(['1', '2'], [1, 3], 1, 100)
[['1', '2']]
>>> put_items_to_boxes(['1', '2'], [1, 3], 2, 100)
[['1', '2']]
>>> put_items_to_boxes(['2', '2'], [1, 3], 2, 2)
[['2'], ['2']]
>>> put_items_to_boxes(['1', '2'], [1, 3], 100, 1)
[['1'], ['2']]
"""
weight_d = dict(zip(items, weights))
assert sum(weights) <= n * cutoff
boxes = [[] for dummpy in range(n)]
idx = 0
for item in items:
if sum([weight_d[i] for i in boxes[idx]]) >= cutoff:
idx += 1
boxes[idx].append(item)
return [box for box in boxes if len(box) != 0] |
def clean(text):
"""cleans text string by removing (date), - company"""
# re.sub(r'\s*\(\d{4}\)\s*', '', "text")
return text |
def __create_gh_repo_url(account: str, repo: str) -> str:
"""
Given an account name and a repo name, returns a cloneable
gh repo url.
"""
return 'https://github.com/' + account + '/' + repo + '.git' |
def one_space(value):
""""Removes empty spaces, tabs and new lines from a string and adds a space between words when necessary.
Example:
>>> from phanterpwa.tools import one_space
>>> one_space(" My long \r\n text. \tTabulation, spaces, spaces. ")
'My long text. Tabulation, spaces, spaces.'
"""
result = ""
if isinstance(value, str):
value = value.strip()
value = value.replace("\n", " ").replace("\t", " ").replace("\r", " ")
spl = value.split(" ")
result = " ".join([x for x in spl if x])
return result |
def splitChunkAndSignature(chunk):
"""Simple wrapper method to separate the signature from the rest of the chunk.
Arguments:
chunk {bytes} -- Everything inside the message field of an IOTA tx.
Returns:
bytes -- Everything except the trailing 64 bytes.
bytes -- 64 bytes long signature.
"""
signature = chunk[-64:]
data = chunk[0:-64]
return data, signature |
def ssn_checksum(number):
"""
Calculate the checksum for the romanian SSN (CNP).
"""
weights = (2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9)
check = sum(w * int(n) for w, n in zip(weights, number)) % 11
return 1 if check == 10 else check |
def limits(centre, out, valid):
""" Calculate matrix borders with limits """
bottom = max(valid[0], centre-out)
top = min(valid[1], centre+out)
return bottom, top |
def int_2_bool(value):
"""Converts an integer, eg. 0, 1, 11, 123 to boolean
Args:
value (int)
Returns:
False for value: 0
True otherwise
"""
if isinstance(value, int):
return (bool(value))
else:
return False |
def len_str_list(lis):
"""returns sum of lengths of strings in list()"""
res = 0
for x in lis:
res += len(x)
return res |
def fib_nr(n):
"""Fibonacci:
fib(n) = fib(n-1) + fib(n-2) se n > 1
fib(n) = 1 se n <= 1
"""
#
seq = [1,1]
#calculando os outros
for i in range(2, n + 1):
seq.append(seq[i-1] + seq[i-2])
return seq[n] |
def is_nan_numeric(value) -> bool:
"""
Check for nan and inf
"""
try:
value = str(value)
value = float(value)
except Exception:
return False
try:
if isinstance(value, float):
a = int(value) # noqa
isnan = False
except Exception:
isnan = True
return isnan |
def get_length(alt_len, ref_len, category, pos, end, svtype=None, svlen=None):
"""Return the length of a variant
Args:
alt_len(int)
ref_len(int)
category(str)
svtype(str)
svlen(int)
"""
# -1 would indicate uncertain length
length = -1
if category in ('snv', 'indel', 'cancer'):
if ref_len == alt_len:
length = alt_len
else:
length = abs(ref_len - alt_len)
elif category == 'sv':
if svtype == 'bnd':
length = int(10e10)
else:
if svlen:
length = abs(int(svlen))
# Some software does not give a length but they give END
elif end:
if end != pos:
length = end - pos
return length |
def deduplicate_dicts(l: list) -> list:
"""
Removes duplicate dicts from a list of dicts, preserving order
"""
seen = set()
new_l = []
for d in l:
t = tuple(d.items())
if t not in seen:
seen.add(t)
new_l.append(d)
return new_l |
def is_permutation_palindrome(string):
"""Returns True if a permutation is a variation of a palindrome or False otherwise"""
if type(string) != str:
raise TypeError(
"The argument for is_permutation_palindrome must be of type string.")
tracker = set()
for char in string:
if char in tracker:
tracker.remove(char)
else:
tracker.add(char)
return len(tracker) <= 1 |
def spd_units_string(units, units_only=False):
"""
Return string describing particle data units for labels
Input:
units: str
String describing units
Returns:
String containing full units string
"""
out = ['', 'Unknown', '']
units = units.lower()
if units == 'counts':
out = ['', 'Counts', '']
elif units == 'rate':
out = ['Rate (', '#/sec', ')']
elif units == 'eflux':
out = ['Energy Flux (', 'eV / sec / cm^2 / ster / eV', ')']
elif units == 'flux':
out = ['Flux (', '# / sec / cm^2 / ster / eV', ')']
elif units == 'df':
out = ['f (', 's^3 / cm^3 / km^3', ')']
elif units == 'df_cm':
out = ['f (', 's^3 / cm^6', ')']
elif units == 'df_km':
out = ['f (', 's^3 / km^6', ')']
elif units == 'e2flux':
out = ['Energy^2 Flux (', 'eV^2 / sec / cm^2 / ster /eV', ')']
elif units == 'e3flux':
out = ['Energy^3 Flux (', 'eV^3 / sec / cm^2 / ster /eV', ')']
if units_only:
return out[1]
return ''.join(out) |
def length_palindrome(full_string, center, odd=True):
"""
Helper function that returns the length of the palindrome centered at
position center in full_string. If the palidrome has even length, set
odd=False, otherwise set odd=True.
"""
# We will increase the palindrom simultaneously in both directions from the
# center. If the two end-points stop being equal to each other, we stop
# growing the palindrome. We are only given palindromes of a certain minmum
# length, so we may begin by growing by 2 steps from the center instead of
# 1.
steps = 2
# If we have an even palindrome, we need to shift positions by 1 in order
# to account for the double-letter at the center of this palindrome.
if odd:
shift = 0
else:
shift = 1
# We will look to see whether the letter at position min_pos is equal to
# that at position max_pos
min_pos = center - steps + shift
max_pos = center + steps
# We grow the palindrome as long as our minimum and maximum don't go out of
# range for the string
while ((min_pos >= 0) and
(max_pos <= len(full_string) - 1) and
(full_string[min_pos] == full_string[max_pos])):
steps += 1
min_pos = center - steps + shift
max_pos = center + steps
# Now we know how many steps we have grown our palindrome. The total length
# is returned
length = (steps - 1) * 2 + 1 - shift
return length |
def refresh_token_as_str(refresh_token):
"""Convert refresh token settings (set/not set) into string."""
return "set" if refresh_token else "not set" |
def bits_to_int(bits: list, base: int = 2) -> int:
"""Converts a list of "bits" to an integer"""
return int("".join(bits), base) |
def sort_list(lst, index2sorton, type='asc'):
"""
"""
if type=='asc':
return sorted(lst, key=lambda x: x[index2sorton])
elif type=='des':
return sorted(lst, key=lambda x: x[index2sorton], reverse=True) |
def prt_bytes(bytes, human_flag):
"""
convert a number > 1024 to printable format, either in 4 char -h format as
with ls -lh or return as 12 char right justified string
"""
if human_flag:
suffix = ''
mods = list('KMGTPEZY')
temp = float(bytes)
if temp > 0:
while (temp > 1023):
try:
suffix = mods.pop(0)
except IndexError:
break
temp /= 1024.0
if suffix != '':
if temp >= 10:
bytes = '%3d%s' % (temp, suffix)
else:
bytes = '%.1f%s' % (temp, suffix)
if suffix == '': # must be < 1024
bytes = '%4s' % bytes
else:
bytes = '%12s' % bytes
return(bytes) |
def flatten(items):
"""Convert a sequence of sequences to a single flat sequence.
Works on dictionaries, tuples, lists.
"""
result = []
for item in items:
if isinstance(item, list):
result += flatten(item)
else:
result.append(item)
return result |
def get_input_words(word_counts, reserved_tokens, max_token_length):
"""Filters out words that are longer than max_token_length or are reserved.
Args:
word_counts: list of (string, int) tuples
reserved_tokens: list of strings
max_token_length: int, maximum length of a token
Returns:
list of (string, int) tuples of filtered wordcounts
"""
all_counts = []
for word, count in word_counts:
if len(word) > max_token_length or word in reserved_tokens:
continue
all_counts.append((word, count))
return all_counts |
def extend_sequence(sequence, item):
""" Simply add a new item to the given sequence.
Simple version of extend_distribution_sequence, since not using distributions here makes
the equalization of distributions in sequence irrelevant.
"""
sequence.append(item)
return sequence |
def calculate_satoshis(my_list_of_outputs):
"""Calculate satoshis."""
result = 0
for output in my_list_of_outputs:
result += output.satoshis
return result |
def checkValues_coordinate0(coordinate0, reference_point):
"""Function that check the range of the input coordinates to be rigth"""
# AP
if 90 > coordinate0[0] > -90:
pass # Entry in correct range
else:
raise Exception(
"Coordinate AP ({}) out of range for lambda, should be between -90mm and 90mm: "
.format(len(coordinate0)))
# ML
if 90 > coordinate0[1] > -90:
pass # Entry in correct range
else:
raise Exception(
"Coordinate ML ({}) out of range, should be between -90mm and 90mm: "
.format(len(coordinate0)))
# DV
if 90 > coordinate0[2] > -90:
pass # Entry in correct range
else:
raise Exception(
"Coordinate DV ({}) out of range, should be between -90mm and 90mm: "
.format(len(coordinate0)))
return True |
def environment_tag_targets_for_instances(ilist):
"""
Generate List of possible targets ordered by environment key.
"""
env_nodes = {}
for i in ilist:
if i.tags is None:
continue
for tag in i.tags:
if tag['Key'] == 'environment' or tag['Key'] == 'Environment':
name = tag['Value']
if name not in env_nodes:
env_nodes[name] = []
env_nodes[name].append(i.private_ip_address)
return [('env:{}'.format(env), ips) for env, ips in env_nodes.items()] |
def decode_textfield_quoted_printable(content):
"""
Decodes the contents for CIF textfield from quoted-printable encoding.
:param content: a string with contents
:return: decoded string
"""
import quopri
return quopri.decodestring(content) |
def convert_single_value_to_tuple(value):
"""This function converts a single value of nearly any type into a tuple.
.. versionchanged:: 3.2.0
The function has been aesthetically updated to be more PEP8 compliant.
.. versionadded:: 2.3.0
:param value: The value to convert into a tuple
"""
value = (value,)
return value |
def vowels(value):
"""Count the number of vowels in a string."""
return sum(1 for char in value.lower() if char in "aeiou") |
def get_direction(start, finish):
"""Return left right up or down, dependent on dir between start finish (x,y) coordinate pairs"""
if start[1] > finish[1]:
dir = "up"
elif start[1] < finish[1]:
dir = "down"
elif start[0] > finish[0]:
dir = "left"
elif start[0] < finish[0]:
dir = "right"
else:
dir = "down"
return dir |
def make_node_pairs_along_route(route):
"""Converts a list of nodes into a list of tuples for indexing edges along a route.
"""
return list(zip(route[:-1], route[1:])) |
def parse_auth_response(text):
"""Parse received auth response."""
response_data = {}
for line in text.split("\n"):
if not line:
continue
key, _, val = line.partition("=")
response_data[key] = val
return response_data |
def _IsValidComposerUpgrade(cur_version, candidate_version):
"""Validates that only MINOR and PATCH-level version increments are attempted.
(For Composer upgrades)
Checks that major-level remains the same, minor-level ramains same or higher,
and patch-level is same or higher (if it's the only change)
Args:
cur_version: current 'a.b.c' Composer version
candidate_version: candidate 'a.b.d' Composer version
Returns:
boolean value whether Composer candidate is valid
"""
curr_parts = list(map(int, cur_version.split('.', 3)))
cand_parts = list(map(int, candidate_version.split('.', 3)))
if (curr_parts[0] == cand_parts[0] and
(curr_parts[1] < cand_parts[1] or
(curr_parts[1] <= cand_parts[1] and curr_parts[2] <= cand_parts[2]))):
return True
return False |
def _test_jpeg(h):
"""JPEG data with JFIF or Exif markers; and raw JPEG"""
if h[6:10] in (b'JFIF', b'Exif'):
return 'jpeg'
elif h[:4] == b'\xff\xd8\xff\xdb':
return 'jpeg' |
def db2dbm(quality):
"""
Converts the Radio (Received) Signal Strength Indicator (in db) to a dBm
value. Please see http://stackoverflow.com/a/15798024/1013960
"""
dbm = int((quality / 2) - 100)
return min(max(dbm, -100), -50) |
def recurse_while(predicate, f, *args):
"""
Accumulate value by executing recursively function `f`.
The function `f` is executed with starting arguments. While the
predicate for the result is true, the result is fed into function `f`.
If predicate is never true then starting arguments are returned.
:param predicate: Predicate function guarding execution.
:param f: Function to execute.
:param *args: Starting arguments.
"""
result = f(*args)
result = result if type(result) == tuple else (result, )
while predicate(*result):
args = result # predicate(args) is always true
result = f(*args)
result = result if type(result) == tuple else (result, )
return args if len(args) > 1 else args[0] |
def ppm_to_freq(ppm, water_hz=0.0, water_ppm=4.7, hz_per_ppm=127.680):
"""
Convert an array from chemical shift to Hz
"""
return water_hz + (ppm - water_ppm) * hz_per_ppm |
def api_full_name(api_name, api_version, organization_name):
"""Canonical full name for an API; used to generate output directories and
package name"""
if api_version:
return '-'.join([organization_name, api_name, api_version])
else:
return '-'.join([organization_name, api_name]) |
def filter_interface_conf(c):
"""Determine if an interface configuration string is relevant."""
c = c.strip()
if c.startswith("!"):
return False
if c.startswith("version "):
return False
if c.startswith("interface"):
return False
if not c:
return False
return True |
def colorscale_to_colors(colorscale):
"""
Converts a colorscale into a list of colors
"""
color_list = []
for color in colorscale:
color_list.append(color[1])
return color_list |
def _get_marker_style(obs_stat, p, one_sided_lower):
"""Returns matplotlib marker style as fmt string"""
if obs_stat < p[0] or obs_stat > p[1]:
# red circle
fmt = 'ro'
else:
# green square
fmt = 'gs'
if one_sided_lower:
if obs_stat < p[0]:
fmt = 'ro'
else:
fmt = 'gs'
return fmt |
def ease_out_quad(n: float) -> float:
"""A quadratic tween function that begins fast and then decelerates."""
return -n * (n - 2) |
def cap_digit(digit):
"""
This function will ensure that entered digit doesnt go above 9 to represent all single digits.
Also due to Exixe SPI technical details the 10th slot in the bytes array controls the 0 digit.
Here is where we will convert the 0 digit to 10 to represent this correctly.
More info here: https://github.com/dekuNukem/exixe/blob/master/technical_details.md
"""
digit = digit % 10
if digit == 0:
digit = 10
return digit |
def seq3(seq):
"""Turn a one letter code protein sequence into one with three letter codes.
The single input argument 'seq' should be a protein sequence using single
letter codes, either as a python string or as a Seq or MutableSeq object.
This function returns the amino acid sequence as a string using the three
letter amino acid codes. Output follows the IUPAC standard (including
ambiguous characters B for "Asx", J for "Xle" and X for "Xaa", and also U
for "Sel" and O for "Pyl") plus "Ter" for a terminator given as an asterisk.
Any unknown character (including possible gap characters), is changed into
'Xaa'.
e.g.
>>> from Bio.SeqUtils import seq3
>>> seq3("MAIVMGRWKGAR*")
'MetAlaIleValMetGlyArgTrpLysGlyAlaArgTer'
This function was inspired by BioPerl's seq3.
"""
threecode = {'A':'Ala', 'B':'Asx', 'C':'Cys', 'D':'Asp',
'E':'Glu', 'F':'Phe', 'G':'Gly', 'H':'His',
'I':'Ile', 'K':'Lys', 'L':'Leu', 'M':'Met',
'N':'Asn', 'P':'Pro', 'Q':'Gln', 'R':'Arg',
'S':'Ser', 'T':'Thr', 'V':'Val', 'W':'Trp',
'Y':'Tyr', 'Z':'Glx', 'X':'Xaa', '*':'Ter',
'U':'Sel', 'O':'Pyl', 'J':'Xle',
}
#We use a default of 'Xaa' for undefined letters
#Note this will map '-' to 'Xaa' which may be undesirable!
return ''.join([threecode.get(aa,'Xaa') for aa in seq]) |
def is_numeric(x):
"""Returns whether the given string can be interpreted as a number."""
try:
float(x)
return True
except:
return False |
def _maxdiff(xlist, ylist):
"""Maximum of absolute value of difference between values in two lists.
"""
return(max(abs(x-y) for x, y in zip(xlist, ylist))) |
def parents(digraph, nodes):
"""
"""
nodes = set(nodes)
parents = set()
for parent, children in digraph.items():
if nodes & set(children):
parents.add(parent)
return parents |
def uniqlist(l):
""" return unique elements in a list (as list). """
result = []
for i in l:
if i not in result: result.append(i)
return result |
def toNumber(s):
"""Tries to convert string 's' into a number."""
try:
return int(s)
except ValueError:
return float(s) |
def get_digit(unit: int, number: int) -> int:
"""
Finds the digit on the given unit
"""
# Gets the number to have the desired
# digit on the last unit
while unit > 0:
number //= 10
unit -= 1
return number % 10 |
def clip_bedfile_name(bedfile):
"""
clip bed file name for table/plotting purposes; assumes file
naming system matches that of Pipeliner
"""
toolused = bedfile.split("/")[-3]
sample = bedfile.split("/")[-2]
return( toolused, sample ) |
def get_heading_level(heading):
"""Returns the level of a given Markdown heading
Arguments:
heading -- Markdown title
"""
i = 0
while( i < len(heading) and heading[i] == '#' ):
i += 1
return i |
def generate_master(playlists):
"""Generate master playlist. Playlists arg should be a map {name: url}.
Little validation or encoding is done - please try to keep the names valid
without escaping.
"""
lines = ["#EXTM3U"]
for name, url in playlists.items():
lines += [
# We name each variant with a VIDEO rendition with no url
'#EXT-X-MEDIA:TYPE=VIDEO,GROUP-ID="{name}",NAME="{name}",AUTOSELECT=YES,DEFAULT=YES'.format(name=name),
'#EXT-X-STREAM-INF:VIDEO="{name}",NAME="{name}"'.format(name=name),
url,
]
return "\n".join(lines) + '\n' |
def get_digits(value: float) -> int:
"""
Get number of digits after decimal point.
"""
value_str: str = str(value)
if "e-" in value_str:
_, buf = value_str.split("e-")
return int(buf)
elif "." in value_str:
_, buf = value_str.split(".")
return len(buf)
else:
return 0 |
def grep(pattern, filename):
"""Very simple grep that returns the first matching line in a file.
String matching only, does not do REs as currently implemented.
"""
try:
# for line in file
# if line matches pattern:
# return line
return next((L for L in open(filename) if L.find(pattern) >= 0))
except StopIteration:
return '' |
def binary_search_recur(arr, low, high, num):
"""
recursive variant of binary search
"""
if low > high: # error case
return -1
mid = (low + high) // 2
if num < arr[mid]:
return binary_search_recur(arr, low, mid - 1, num)
if num > arr[mid]:
return binary_search_recur(arr, mid + 1, high, num)
return mid |
def check_bibtex_entry(entry, fix = False):
"""
Check whether an entry is suitable for the database. Returns None if all is ok, else
returns a user-readable string describing the error.
If fix is set to true then will 'fix' any problems by replacing errors with dummy values.
This is only useful during testing and development.
"""
errors = []
mandatory = ['id', 'title', 'author', 'year']
for f in mandatory:
if not f in entry:
errors.append("The entry did not include the '" + f + "' field.")
if fix:
if f == "year":
entry['year'] = "2000"
else:
entry[f] = "No" + f
if 'year' in entry:
yearstr = entry['year']
try:
year = int(yearstr)
except ValueError:
errors.append("The year field should be a single integer year, i.e. '2001'.")
if fix:
entry['year'] = "2000"
if len(errors) == 0:
return None
else:
rv = ""
for e in errors:
rv += e + " "
return rv |
def dot_notation(dict_like, dot_spec):
"""Return the value corresponding to the dot_spec from a dict_like object
:param dict_like: dictionary, JSON, etc.
:param dot_spec: a dot notation (e.g. a1.b1.c1.d1 => a1["b1"]["c1"]["d1"])
:return: the value referenced by the dot_spec
"""
attrs = dot_spec.split(".") # we split the path
parent = dict_like.get(attrs[0])
children = ".".join(attrs[1:])
if not (parent and children): # if no children or no parent, bail out
return parent
if isinstance(parent, list): # here, we apply remaining path spec to all children
return [dot_notation(j, children) for j in parent]
elif isinstance(parent, dict):
return dot_notation(parent, children)
else:
return None |
def parse_anno(text):
"""Convert text with layer annotation to data structure"""
return eval(text) if text else None |
def default_pretransform(sample, values):
"""Returns the image sample without transforming it at all
Args:
sample: Loaded image data
values: Tuple such that the 1th arguement is the target (defined by default)
Returns:
var: The loaded sample image
int: Value representing the image class (label for data)
"""
target = values[1]
return sample, target |
def predict_four(student):
""" Predicts four year retention of a student
>>> predict_four({
... 'hs_grade':7,
... 'sat_verbal':600,
... 'sat_math':600,
... 'gender':1,
... 'white':2,
... 'native_american':1,
... 'black':1,
... 'mexican_american':1,
... })
0.6618
"""
return (
-.2004 +\
.0554 * float(student['hs_grade']) +\
.000408 * float(student['sat_verbal']) +\
.000546 * float(student['sat_math']) +\
.0803 * float(student['gender']) +\
.0378 * float(student['white']) +\
-.1403 * float(student['native_american']) +\
-.0570 * float(student['black']) +\
-.0566 * float(student['mexican_american'])
) |
def _contains_edge(edges_set, vertex1, vertex2):
"""
Check if the container has an edge between the given vertices.
The edge can be (vertex1, vertex2) or (vertex2, vertex1).
"""
return (vertex1, vertex2) in edges_set or (vertex2, vertex1) in edges_set |
def parse_hpo_disease(hpo_line):
"""Parse hpo disease line
Args:
hpo_line(str)
"""
hpo_line = hpo_line.rstrip().split('\t')
hpo_info = {}
disease = hpo_line[0].split(':')
hpo_info['source'] = disease[0]
hpo_info['disease_nr'] = int(disease[1])
hpo_info['hgnc_symbol'] = None
hpo_info['hpo_term'] = None
if len(hpo_line) >= 3:
hpo_info['hgnc_symbol'] = hpo_line[2]
if len(hpo_line) >= 4:
hpo_info['hpo_term'] = hpo_line[3]
return hpo_info |
def parse_indexes(x):
"""parse a string into a set of indexes"""
# verify the quality of the input
ok = [str(_) for _ in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ",", "-"]]
for d in x:
if d not in ok:
raise Exception("unacceptable index string")
result = set()
for xpart in x.split(","):
xrange = xpart.split("-")
if len(xrange) > 2:
raise Exception("unacceptable index string")
elif len(xrange)==1:
result.add(int(xrange[0]))
else:
for _ in range(int(xrange[0]), int(xrange[1])+1):
result.add(_)
return sorted(list(result)) |
def average(data):
"""
Calculate the average of values of the data.
Args:
data (list): values.
Returns the average of values of the data.
"""
return 1.0*sum(data)/len(data) |
def wheel(wheel_pos):
"""Color wheel to allow for cycling through the rainbow of RGB colors."""
wheel_pos = wheel_pos % 256
if wheel_pos < 85:
return 255 - wheel_pos * 3, 0, wheel_pos * 3
elif wheel_pos < 170:
wheel_pos -= 85
return 0, wheel_pos * 3, 255 - wheel_pos * 3
else:
wheel_pos -= 170
return wheel_pos * 3, 255 - wheel_pos * 3, 0 |
def get_fsubmission_obj(parent, obj_id):
""" Inverse of id() function. But only works if the object is not garbage collected"""
print("get_fsubmission_obj parent: ", parent)
if parent:
return parent.find_obj_by_id(parent, obj_id)
print("cannot find obj") |
def letters_in(string):
"""Return sorted list of letters in given string."""
return sorted(
char
for char in string.lower()
if char.isalpha()
) |
def shift_backward(text, spaces):
""" Shifts the given string or list the given number of spaces backward
:param str text: Text to shift
:param int spaces: Number of spaces to shift the text backwards by
:return: Backward-shifted string
:rtype: str
"""
output = text[spaces::]
if type(text) == str:
output += text[:spaces:]
elif type(text) == list:
output.extend(text[:spaces:])
else:
output = text
return output |
def fatorial(numero, show=False):
"""
Funcao que recebe um numero e devolve seu fatorial.
:param numero: numero a se calcular.
:param show: (opcional) mostrar o calculo.
:return: resultado do calculo fatorial.
"""
fatorial = 1
for counter in range(numero, 0, -1):
fatorial *= counter
if show:
if counter > 1:
print(counter, end=' x ')
else:
print(counter, end=' = ')
return fatorial |
def filter_nodes(nodes_list, ids=None, subtree=True):
"""Filters the contents of a nodes_list. If any of the nodes is in the
ids list, the rest of nodes are removed. If none is in the ids list
we include or exclude the nodes depending on the subtree flag.
"""
if not nodes_list:
return None
nodes = nodes_list[:]
if ids is not None:
for node in nodes:
if node.id in ids:
nodes = [node]
return nodes
if not subtree:
nodes = []
return nodes |
def mimebundle_to_html(bundle):
"""
Converts a MIME bundle into HTML.
"""
if isinstance(bundle, tuple):
data, metadata = bundle
else:
data = bundle
html = data.get('text/html', '')
if 'application/javascript' in data:
js = data['application/javascript']
html += '\n<script type="application/javascript">{js}</script>'.format(js=js)
return html |
def epiweek_to_month(ew):
"""
Convert an epiweek to a month.
"""
return (((ew - 40) + 52) % 52) // 4 + 1 |
def _get_table_to_primary_key_columns(
table_to_column_metadata, table_to_explicit_primary_key_columns, primary_key_selector
):
"""Return the set of primary key columns for each table."""
table_to_primary_key_columns = {}
for table_name in table_to_column_metadata:
if table_name in table_to_explicit_primary_key_columns:
table_to_primary_key_columns[table_name] = table_to_explicit_primary_key_columns[
table_name
]
else:
if primary_key_selector is None:
raise AssertionError(
"Table {} does not have a primary key nor a primary key "
"selector".format(table_name)
)
table_to_primary_key_columns[table_name] = primary_key_selector(
table_name, table_to_column_metadata[table_name]
)
return table_to_primary_key_columns |
def _null_to_empty(val):
"""Convert to empty string if the value is currently null."""
if not val:
return ""
return val |
def in_cksum_add(s, buf):
"""in_cksum_add(cksum, buf) -> cksum
Return accumulated Internet checksum.
"""
nleft = len(buf)
i = 0
while nleft > 1:
s += ord(buf[i]) * 256 + ord(buf[i+1])
i += 2
nleft -= 2
if nleft:
s += ord(buf[i]) * 256
return s |
def _get_c_string(data, position):
"""Decode a BSON 'C' string to python unicode string."""
end = data.index(b"\x00", position)
return data[position:end].decode('utf8'), end + 1 |
def _parse_line_remove_comment(line):
"""Parses line from config, removes comments and trailing spaces.
Lines starting with "#" are skipped entirely. Lines with comments after
the parameter retain their parameter.
Parameters
--------------
line : str
Returns
--------------
line : str
"""
i = line.find('#')
if i >= 0:
line = line[:i]
return line.strip() |
def index_of_opening_parenthesis(words, start, left_enc ='(', right_enc =')'):
"""Returns index of the opening parenthesis of the parenthesis indicated by start."""
num_opened = -1
i = start-1
while i >= 0:
if words[i] == left_enc:
num_opened += 1
elif words[i] == right_enc:
num_opened -= 1
if num_opened == 0:
return i
i -= 1
return -1 |
def unquote(string):
"""stripped down implementation of urllib.parse unquote_to_bytes"""
if not string:
return b''
if isinstance(string, str):
string = string.encode('utf-8')
# split into substrings on each escape character
bits = string.split(b'%')
if len(bits) == 1:
return string # there was no escape character
res = [bits[0]] # everything before the first escape character
# for each escape character, get the next two digits and convert to
for item in bits[1:]:
code = item[:2]
char = bytes([int(code, 16)]) # convert to utf-8-encoded byte
res.append(char) # append the converted character
res.append(item[2:]) # append anything else that occurred before the next escape character
return b''.join(res) |
def gateway_options(gateway_options):
"""Deploy template apicast staging gateway."""
gateway_options["path_routing"] = True
return gateway_options |
def php_str_noquotes(data):
"""
Convert string to chr(xx).chr(xx) for use in php
"""
encoded = ""
for char in data:
encoded += "chr({0}).".format(ord(char))
return encoded[:-1] |
def do(func, x):
""" Runs ``func`` on ``x``, returns ``x``
Because the results of ``func`` are not returned, only the side
effects of ``func`` are relevant.
Logging functions can be made by composing ``do`` with a storage function
like ``list.append`` or ``file.write``
>>> from toolz import compose
>>> from toolz.curried import do
>>> log = []
>>> inc = lambda x: x + 1
>>> inc = compose(inc, do(log.append))
>>> inc(1)
2
>>> inc(11)
12
>>> log
[1, 11]
"""
func(x)
return x |
def get_start_timestamp(start_time):
"""
get start timestamp to use in datasetname
It removes the hyphens and colons from the timestamp
:param start_time:
:return:
"""
start_time = start_time.replace("-","")
start_time = start_time.replace(":","")
return start_time |
def defined_or_defaut_dir(default, directory):
"""
if given a directory it will return that directory, otherwise it returns the default
"""
if directory:
return directory
else:
return default |
def mdce(aa, bb, __verbose = False):
"""
Algoritmo euclideano estendido, utilizado para calcular os
valores das constantes alfa e beta que satifazem equacoes
da forma
a * alfa + b * beta = mdc(a,b)
r | q | x | y
a | * | 1 | 0
b | * | 0 | 1
(...)
"""
a = aa
b = bb
swap = False
# Garante que o primeiro parametro seja maior que o segundo
if (a < b):
a, b = b, a
swap = True
x = [1, 0]
y = [0, 1]
if __verbose:
print("%d\t*\t%d\t%d" % (a, x[0], y[0]))
print("%d\t*\t%d\t%d" % (b, x[1], y[1]))
while a % b != 0:
q, r = a // b, a % b
"""
Calculo dos novos valores para x e y
x0 <- x1
x1 <- Ultimo valor de x0 - x1 * q
(Processo analogo para y)
"""
x[0], x[1] = x[1], x[0] - x[1] * q
y[0], y[1] = y[1], y[0] - y[1] * q
if __verbose:
print("%d\t%d\t%d\t%d" % (r, q, x[1], y[1]))
a, b = b, r
"""
Caso os parametros 'a' e 'b' tenham sido trocados, vamos
inverter os respectivos valores de 'alfa' e 'beta'
"""
if swap == False:
if __verbose:
print("\n%d * (%d) + %d * (%d) = %d\n" % \
(aa, x[1], bb, y[1], b))
return b, x[1], y[1]
else:
if __verbose:
print("\n%d * (%d) + %d * (%d) = %d\n" % \
(aa, y[1], bb, x[1], b))
return b, y[1], x[1] |
def remove_trailing_whitespace(line):
"""Removes trailing whitespace, but preserves the newline if present.
"""
if line.endswith("\n"):
return "{}\n".format(remove_trailing_whitespace(line[:-1]))
return line.rstrip() |
def merge_dict(data, *override):
"""
Merges any number of dictionaries together, and returns a single dictionary
"""
result = {}
for current_dict in (data,) + override:
result.update(current_dict)
return result |
def compare_dictionaries(dict_1, dict_2, dict_1_name, dict_2_name, path=""):
"""Compare two dictionaries recursively to find non mathcing elements
Args:
dict_1: dictionary 1
dict_2: dictionary 2
Returns:
"""
err = ''
key_err = ''
value_err = ''
old_path = path
for k in dict_1.keys():
path = old_path + "[%s]" % k
if not k in dict_2:
key_err += "Key %s%s not in %s\n" % (dict_1_name, path, dict_2_name)
else:
if isinstance(dict_1[k], dict) and isinstance(dict_2[k], dict):
err += compare_dictionaries(dict_1[k],dict_2[k], dict_1_name, dict_2_name, path)
else:
if dict_1[k] != dict_2[k]:
value_err += "Value of %s%s (%s) not same as %s%s (%s)\n"\
% (dict_1_name, path, dict_1[k], dict_2_name, path, dict_2[k])
for k in dict_2.keys():
path = old_path + "[%s]" % k
if not k in dict_1:
key_err += "Key %s%s not in %s\n" % (dict_2_name, path, dict_1_name)
return key_err + value_err + err |
def get_room_media(roomid,rooms_media):
"""Get all room media."""
media = []
for i in rooms_media:
if i[0] == roomid:
media.append(i[1])
return media |
def makeVector(dim, initValue):
"""
Return a list of dim copies of initValue
"""
return [initValue]*dim |
def _unflatten(mapping):
"""Converts a flat tuple => object mapping to hierarchical one"""
result = {}
for path, value in mapping.items():
parents, leaf = path[:-1], path[-1]
# create the hierarchy until we reach the leaf value
temp = result
for parent in parents:
temp.setdefault(parent, {})
temp = temp[parent]
# set the leaf value
temp[leaf] = value
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.