content stringlengths 42 6.51k |
|---|
def make_label(label_text):
"""
returns a label object
conforming to api specs
given a name
"""
return {'messageListVisibility': 'show',
'name': label_text,
'labelListVisibility': 'labelShow'} |
def sort_mappers(classes):
"""
try to put mapper objects into an insert order which will allow foreign key constraints to be satisfied
"""
order = []
#iterate over a copy of the list so we dont modify the original
classlist = dict(classes)
# not sure what it is but it mucks things up
... |
def permute_point(p, permutation=None):
"""
Permutes the point according to the permutation keyword argument. The
default permutation is "012" which does not change the order of the
coordinate. To rotate counterclockwise, use "120" and to rotate clockwise
use "201"."""
if not permutation:
... |
def pack_numbers(numbers):
"""Packs a list of numbers into bins with a maxmimum sum of 100"""
bins = [[]]
for n in numbers:
# if current bin would be too full after adding n, create new bin first
if sum(bins[-1]) + n > 100:
bins.append([])
# add n to current bin
... |
def is_number(s):
"""This is used to check if the input string can be used as a number"""
try:
float(s)
return True
except ValueError:
return False |
def to_bytes( arg ):
"""Converts arg to a 'bytes' object."""
return bytes( bytearray( arg )) # if python2, 'bytes' is synonym for 'str' |
def restructure_day_array(day):
"""Restructures day array into start times and end times.
Will be used to fill the editable profile form with correct
values.
"""
# day is received as a list [{starttime, endtime}, {startime, endtime}]
# all are in 1-hour blocks. Only need first and last.
# if... |
def extract_token(auth_response):
"""
Extract an auth token from an authentication response.
:param dict auth_response: A dictionary containing the decoded response
from the authentication API.
:rtype: str
"""
return auth_response['access']['token']['id'].encode('ascii') |
def stomp_subscribe(topic):
""" Return a javascript callback that subscribes to a given topic,
or a list of topics.
"""
sub = "stomp.subscribe('%s');"
if isinstance(topic, list):
sub = ''.join([sub % t for t in topic])
else:
sub = sub % topic
return sub |
def chunk_string(in_s, n):
"""Chunk string to max length of n"""
return "\n".join(
"{}\\".format(in_s[i : i + n]) for i in range(0, len(in_s), n)
).rstrip("\\") |
def list_to_str(value):
"""
Converts list objects to string objects.
Exception used to handle NaN values.
"""
try:
aux = ';'.join(value)
return aux
except TypeError:
return value |
def flattening(rad):
"""Flattening of a spheroid
Arguments
---------
rad : dict
{'a', 'b', 'c'} Equatorial1, Equatorial2, and polar radius
"""
a, b, c = rad['a'], rad['b'], rad['c']
return (a-c)/a |
def check_one_liners(docstring, context, is_script):
"""One-liner docstrings should fit on one line with quotes.
The closing quotes are on the same line as the opening quotes.
This looks better for one-liners.
"""
if not docstring:
return
lines = docstring.split('\n')
if len(lines)... |
def ConvertToABMag(mag: float, band: str) -> float:
"""Converts a magnitude to the AB system.
Args:
mag: The magnitude to convert.
band: The band of the magnitude.
Returns:
The magnitude converted to the AB system.
Raises:
ValueError: If the band is not 'R' or 'V'.
... |
def prox_laplacian(a, lamda):
"""Prox for l_2 square norm, Laplacian regularisation."""
return a / (1 + 2.0 * lamda) |
def replace_invalid_path_chars(path, replacement='-'):
"""
Replace invalid path character with a different, acceptable, character
"""
exclude = set('\\/"?<>|*:-')
path = ''.join(ch if ch not in exclude else replacement for ch in path)
return path |
def _obtain_input_shape(input_shape, default_size, min_size, data_format):
"""Internal utility to compute/validate an ImageNet model's input shape.
# Arguments
input_shape: either None (will return the default network input shape),
or a user-provided shape to be validated.
default_si... |
def top_files(query, files, idfs, n):
"""
Given a `query` (a set of words), `files` (a dictionary mapping names of
files to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the filenames of the the `n` top
files that match the query, ranked accord... |
def get_cell_description(cell_input):
"""Gets cell description
Cell description is the first line of a cell,
in one of this formats:
* single line docstring
* single line comment
* function definition
"""
try:
first_line = cell_input.split("\n")[0]
if first_line.startsw... |
def search_codetree_hasleftsub(tword,codetree):
""" Stored in codetree with non-zero value in any except the terminal node
"""
pos = 0
while True:
s = tword[pos]
if s not in codetree:
return 0
elif codetree[s][0]>0:
return codetree[s][0]
elif pos==... |
def indexof(needle, haystack):
"""
Find an index of ``needle`` in ``haystack`` by looking for exact same item by pointer ids
vs usual ``list.index()`` which finds by object comparison.
For example::
>>> a = {}
>>> b = {}
>>> haystack = [1, a, 2, b]
>>> indexof(b, haysta... |
def factorial(n):
"""
What comes in: The sole argument is a non-negative integer n.
What goes out: Returns n!, that is, n x (n-1) x (n-2) x ... x 1.
Side effects: None.
Examples:
factorial(5) returns 5 x 4 x 3 x 2 x 1, that is, 120.
factorial(0) returns 1 (by definition).
"""... |
def drop_duplicates(bq_client, table_id, field_name, ids):
"""
Drop ids from table_id that will be updated to avoid duplicates
bq_client: BigQuery Client
table_id: Table to affect
field_name: name of te "primary_key" field
ids: list of ids to drop
return: Nothing, resulting call to bq
"""
... |
def get_from_dict(dictionary, key, default_value):
"""
Gets value from dict, if it does not exist, returns default_value
:param dictionary: dict, which we want to retrieve value of key from
:param key: key, which value we are looking for
:param default_value: if key does not exists in dictionary, t... |
def f(n):
"""
n: integer, n >= 0.
"""
if n == 0:
# Problem is here, where n is equal to zero
# Gets multiplied by previous results gving us 0
# Need to return 1 instea
return 1
else:
return n * f(n-1) |
def ros_publish_cmd(topic, _msg, _id=None):
"""
create a rosbridge publish command object
:param topic: the string name of the topic to publish to
:param _msg: ROS msg as dict
:param _id: optional
"""
command = {
"op": "publish",
"topic": topic,
"msg": _msg
}
... |
def jp_server_config(jp_unix_socket_file):
"""Configure the serverapp fixture with the unix socket."""
return {"ServerApp": {"sock": jp_unix_socket_file, "allow_remote_access": True}} |
def annuity(A, r, g, t):
"""
A = annual payment
r = discount rate
t = time periods
returns present value
"""
return((A/r) * (1 - 1/((1+r)**t))) |
def build_histogram(text):
"""Builds a distribution of the word types and numbers of word tokens."""
histogram = {}
words = text.split()
# make a distribution of word types and count of tokens
for word in words:
word = word.lower()
if word not in histogram:
histogram[word... |
def format_baseline_list(baseline_list):
"""Format the list of baseline information from the loaded files into a
cohesive, informative string
Parameters
------------
baseline_list : (list)
List of strings specifying the baseline information for each
SuperMAG file
Returns
--... |
def checkInstance(ids, claims):
"""
Check the value of an instance (example: Q5) of an item.
if the value is in the list of `ids`, return True
otherwise return False
@param ids: list|string of ids
@param claims: pywikibot.page._collections.ClaimCollection
@return bool
"""
ids = ids... |
def check_sample_filters(sample, project):
"""
:param sample:
:param project:
:return:
"""
if project == 'ENCODE':
bt = sample['biosample_type']
if bt.startswith('immortal') or bt.startswith('in vitro'):
return False
btn = (sample['biosample_term_name']).lower... |
def validate_codons(starts,stops):
"""
Check if codons are valid
Parameters
----------
starts : list
List of start codons.
stops : list
List of stop codons.
Returns
-------
bool
True is codons are fine.
"""
validalphabets=['A','C','T','G']
if no... |
def map_keys_with_obj(f, dct):
"""
Calls f with each key and value of dct, possibly returning a modified key. Values are unchanged
:param f: Called with each key and value and returns the same key or a modified key
:param dct:
:return: A dct with keys possibly modifed but values unchanged
""... |
def boolToInt(boolean):
"""Returns 1 if boolean is True, else returns 0"""
if boolean == True:
return 1
return 0 |
def filter_comics(comics):
"""Filter comics based on (hardcoded) criterias.
On the long run, I'd like the criteria to be provided via command-line
arguments."""
comics = list(comics)
initial_len = len(comics)
filtered_comics = [c for c in comics if "new" in c]
filtered_len = len(filtered_co... |
def cotain_chinese(text):
"""
check if the input text contains Chinese
"""
for char in text:
if '\u4e00' <= char <= '\u9fa5':
return True
return False |
def extended_euclidean_algorithm(m, n):
"""
Extended Euclidean Algorithm.
Finds 2 numbers a and b such that it satisfies
the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity)
"""
a = 0
a_prime = 1
b = 1
b_prime = 0
q = 0
r = 0
if m > n:
c = m
d = n
... |
def opposite_bearing(bearing1:float) -> float:
"""Return the oppisite bearing, e.g. 90 -> 270
Parameters
----------
bearing1 : float
Bearing in degrees.
Returns
-------
bearing : float
Opposite bearing in degrees.
"""
return bearing1 - 180*(bearing1 > 180) + 180... |
def output(theta,final_list):
"""Function takes each point and returns the x,y,z coordinates in three lists.
Input: theta (for testing), final sides dictionary
Output: three lists of x,y,z
"""
#create 3 empty lists for the x,y,z coordinate values
x = list()
y = list()
z = list()
final_coordinates = []
#ite... |
def get_business_obj_dict(business_obj_list):
""" Convert business_obj_list to business_obj_dict, with key: business_id, V: business_obj
"""
business_obj_dict = {}
for w in business_obj_list:
business_obj_dict[w['business_id']] = w
return business_obj_dict |
def chunks(iterable: list, amount: int):
"""
Split a list into x chunks
:param iterable: List of stuff to chunk
:param amount: How many chunks?
:return: List of lists
"""
avg = len(iterable) / float(amount)
out = []
last = 0.0
while last < len(iterable):
out.append(itera... |
def lists_match(list_data, item_data):
"""
Returns True if the two list items are of the same type,
with the same delimiter and bullet character. This is used
in agglomerating list items into lists.
"""
return list_data.get('type') == item_data.get('type') and \
list_data.get('delimiter... |
def getFuncName(sig):
"""Get the function name from a signature or '', if signature is not a function."""
sig = sig.strip()
pos1 = sig.rfind('(')
if pos1 < 0:
return ""
else:
pos1 -= 1
while (pos1 >= 0) and (sig[pos1] == ' '):
pos1 -= 1
pos2 =... |
def league_stats(n_clicks):
"""
This function just returns a sentence to update the tab h2 element
pretty much an initial test to see how updating the tab works
:param n_clicks:
:return: string
"""
if n_clicks == 0:
return None
return str("Overall League Statistics.") |
def trapezoid_area(base_minor, base_major, height):
"""Returns the area of a trapezoid"""
# You have to code here
# REMEMBER: Tests first!!!
return (1/2) * (base_minor + base_major) * height |
def get_possible_successors_set_present_in_node_ids(possible_successors, nodes_ids):
"""
:param possible_successors:
:param nodes_ids:
:return:
"""
return set(possible_successors).intersection(set(nodes_ids)) |
def handler_mergeList(a, b):
"""List merger"""
#FIXME : there is certainly a better python way !
for p in b :
if p not in a:
a.append(p)
return a |
def difference(d1, d2):
"""Difference of two dicts.
Return elements of the first dict not existing in the second dict."""
ret = {}
for k in d1:
if k not in d2:
ret[k] = d1[k]
return ret |
def get_chain(value, key_chain, default=None):
"""Gets a value in a chain of nested dictionaries, with a default if any
point in the chain does not exist. """
for key in key_chain:
if value is None:
return default
value = value.get(key)
return value |
def format_tweet(tweet):
"""
Basic output formatting of the tweet (dict)
"""
buffer = ""
buffer += "@" + tweet['user']['screen_name'] + ": "
buffer += tweet['text'] + "\n"
try:
if len(tweet['entities']['media']) > 0:
buffer += "media: " + tweet['entities']['media'][0]['m... |
def read_dbxrefs(entry):
"""Parse db_links and return a list of dbxrefs"""
# expected input (example):
# kegg_information["DBLINKS"] = [
# 'DBLINKS PubChem: 4509',
# 'ChEBI: 17950',
# 'LIPIDMAPS: LMS... |
def df(*v):
"""Return a path to a test data file"""
from os.path import dirname, join
return join(dirname(__file__), 'test_data', *v) |
def usd(value):
"""Formats value as USD."""
if value < 0:
return f"-${value*-1:,.2f}"
else:
return f"${value:,.2f}" |
def removeUnicodeIdentifiers(s):
"""
Removes the u infrount of a unicode string: u'string' -> 'string'
Note that this also removes a u at the end of string 'stru' -> 'str'
which is not intended.
@ In, s, string, string to remove characters from
@ Out, s, string, cleaned string
"""
s = s.repl... |
def lustre_string2index(index_string):
"""
Transfer string to index number, e.g.
"000e" -> 14
"""
index_number = int(index_string, 16)
if index_number > 0xffff:
return -1, ""
return 0, index_number |
def dedup(dict, to_match):
"""Quick and dirty function to deduplicate the lists of dictionaries based
on an id to determine whether or not an item has been 'seen'
"""
seen = set()
dlist = []
for d in dict:
if d[to_match] not in seen:
seen.add(d[to_match])
dlist.a... |
def preparse_address(addr_spec):
"""
Preparses email addresses. Used to handle odd behavior by ESPs.
"""
# sanity check, ensure we have both local-part and domain
parts = addr_spec.split('@')
if len(parts) < 2:
return None
# if we add more esp specific checks, they should be done
... |
def get_slack_current_subgraph_notification_message(subgraph_name: str, subgraph_version: str,
subgraph_network: str, subgraph_last_block_number: str,
infura_last_block_number: str):
"""
Get slack message tem... |
def prefix_average3(S):
"""Return list such that, for all j, A[j] equals average of S[0], ..., S[j]."""
n = len(S)
A = [0] * n
total = 0
for j in range(n):
total += S[j] # update prefix sum to include S[j]
A[j] = total / (j+1)
return A |
def _canonical_name(name):
""" Replace aliases to the corresponding type. """
if name.startswith('int['):
return 'uint256' + name[3:]
if name == 'int':
return 'uint256'
if name.startswith('real['):
return 'real128x128' + name[4:]
if name == 'real':
return 'real128... |
def not_preceded_by(pattern):
""" matches if the current position is not preceded by the pattern
:param pattern: an `re` pattern
:type pattern: str
:rtype: str
"""
return r'(?<!{:s})'.format(pattern) |
def makeaxisstep(start=0, step=1.00, length=1000, adjust=False, rounded=-1):
"""
Creates an axis, or vector, from 'start' with bins of length 'step'
for a distance of 'length'.
:type start: float
:param start: first value of the axis. Default is 0.
:type step: float
:param st... |
def _get_loc2(area_val, near_val):
"""
Handle location string, variant 2.
:param area_val: value of the 'area' field.
:param near_val: value of the 'near' field.
:return:
"""
if area_val:
s = " located in the %s area" % area_val
if near_val:
s += ", near %s." % ne... |
def sign(x: float) -> float:
"""Return the sign of the argument. Zero returns zero."""
if x > 0:
return 1.0
elif x < 0:
return -1.0
else:
return 0.0 |
def find_volume(r):
"""Returns the volume of a sphere with a given radius
"""
from math import pi
return (4/3)*pi*(r**3) |
def is_sequence_match(pattern: list, instruction_list: list, index: int) -> bool:
"""Checks if the instructions starting at index follow a pattern.
:param pattern: List of lists describing a pattern, e.g. [["PUSH1", "PUSH2"], ["EQ"]] where ["PUSH1", "EQ"] satisfies pattern
:param instruction_list: List of ... |
def overlapping_intervals(intervals: list) -> list:
"""
O(n*log(n))
"""
length = len(intervals)
if length < 2:
return intervals
intervals.sort(key=lambda _: _[0]) # sort by starting interval
return_list = [intervals[0]]
for i in range(1, length):
if return_list[-1][1... |
def sanitize_int(value):
"""
Sanitize an input value to an integer.
:param value: Input value to be sanitized to an integer
:return: Integer, or None of the value cannot be sanitized
:rtype: int or None
"""
if isinstance(value, str):
try:
return int(value)
except... |
def vector_columna(matriz, columna):
"""
(list of list, int) -> list
Obtiene el vector columna para la posicion de la matriz
>>> vector_columna([[1,2],[1,2]],0)
[1, 1]
>>> vector_columna([[1,2],[1,2]],1)
[2, 2]
:param matriz: la matriz que contiene nuestro vector
:param columna: ... |
def sort_player_scores(unsorted_scores, highest_possible_score):
"""Takes in a list of unsorted scores and the highest possible scores and returns a list of sorted scores"""
tracker = {}
sorted_scores = []
if type(unsorted_scores) != list:
raise TypeError(
"The first argument for so... |
def convert_v4_address_bits_to_string(ip_address_bits):
"""
return v4 address bits to string
for example: '11111111111111110000000000000000' -> '255.255.0.0'
"""
ip_address_octets = [int(ip_address_bits[i:i + 8], 2) for i in range(0, len(ip_address_bits), 8)]
ip_address = '.'.join([str(octet) ... |
def classesByDepartment (theDictionary, department):
"""Lists the courses being taken from specific department.
:param dict[str, int] theDictionary: The student's class information
with the class as the key and the number or credits as the value
:param str department: The department in question
... |
def path_to_obj(root_obj, attr_path):
"""Get an object from a root object and "attribute path" specification.
>>> class A:
... def foo(self, x): ...
... foo.x = 3
... class B:
... def bar(self, x): ...
...
>>> obj = path_to_obj(A, ('foo',))
>>> assert callable(ob... |
def is_integer(s: str) -> bool:
"""Return True if the text is an integer"""
return s.isdigit() |
def extract(input_data: str) -> list:
"""take input data and return the appropriate data structure"""
lines = input_data.split('\n')
return list(list(map(int, row)) for row in lines) |
def zoom_to_roi(zoom, resolution):
"""Gets region of interest coordinates from x,y,w,h zoom parameters"""
x1 = int(zoom[0] * resolution[0])
x2 = int((zoom[0]+zoom[2]) * resolution[0])
y1 = int(zoom[1] * resolution[1])
y2 = int((zoom[1]+zoom[3]) * resolution[1])
return ((x1,y1),(x2,y2)) |
def hexdump(data):
"""Pretty print a hex dump of data, similar to xxd"""
lines = []
offset = 0
while offset < len(data):
piece = data[offset:offset + 16]
bytes = ''.join([('%02x ' % ord(x)) for x in piece])
chars = ''.join([(x if 0x20 < ord(x) < 0x7f else '.') for x in piece])
... |
def generate_seqmining_dataset(patterns):
"""This function generates a sequence database to mine n-grams from.
Parameters
----------
patterns : List of Textual Patterns
Returns
-------
type List of Sequences
"""
smining_dataset = []
for pattern in patterns:
words = pat... |
def _underline(text: str, line_symbol: str):
"""
Add a line made of `line_symbol` after given `text`,
and return new text.
"""
return text + "\n" + line_symbol * len(text) |
def is_set(obj):
"""Helper method to see if the object is a Python set.
>>> is_set(set())
True
"""
return type(obj) is set |
def get_filter_in(filters):
"""Recuperar filtros de una lista"""
filter_in = {}
for filter_index, value in list(filters.items()):
if isinstance(value, list):
filter_in.update({filter_index: value})
del filters[filter_index]
return filter_in |
def to_right(d):
"""return direction as vector, rotated 90 degrees right"""
return d[1], -d[0] |
def evaluate_cv_total_accuracy(val_beauty_acc, val_fashion_acc, val_mobile_acc, kaggle_public_acc=None):
"""Utility function to evaluate results, pass kaggle_public_acc=False to evaluate local CV score"""
if kaggle_public_acc:
total_examples = 57317 + 43941 + 32065 + 172402*0.3
num_correct = 573... |
def identity(arg, **kwargs):
"""The identity function returns the input."""
# pylint: disable=unused-argument
return arg |
def shift_row(ns):
"""
ns -> States of nibbles
Predict the states of nibbles after passing through ShiftRow in SomeCipher.
"""
assert len(ns) == 12
n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11 = ns
return [n0, n1, n10, n7, n4, n5, n2, n11, n8, n9, n6, n3] |
def substr_enclosed_in_seq(data, initial_seq, terminal_seq, from_index=0, to_index=-1,
include_trailing_newline=False):
"""
Get first substring between initial and terminal key sequence if present in data,
e.g. if data is '[[my_val]]', initial_seq is '[[', and terminal_seq is ']]'... |
def get_airflow_version(ac_version):
"""Get Airflow Version from the string containing AC Version"""
return ac_version.split('-')[0] |
def del_null(num):
""" replace null string with zero
"""
return 0 if num is None else num |
def abbr(label):
"""Gets a better visualization with abbreviations of long attribute names."""
if label == "fuel_economy":
return "fuel"
# publication_date and date_posted do not appear in the same vertical.
elif label == "publication_date":
return "date"
elif label == "date_posted":
return "date... |
def ContainsString(field, value):
"""
A criterion used to search for objects having a text field's value like the specified `value`.
It's a wildcard operator that wraps the searched value with asteriscs. It operates the same way a the `Like` criterion For example:
* search for cases where title is lik... |
def listToIndiceString(my_list):
"""
for example:
turns [[1,2,63,7], [5,2,986], [305,3], []]
into 1,2,63,7;5,2,986;305,3;
"""
output = ";".join([",".join([str(int(item)) for item in row]) for row in my_list])
return output |
def hamming(set1, set2):
"""Hamming distance between sets `a` and `b`.
The Hamming distance for sets is the size of their symmetric difference,
or, equivalently, the usual Hamming distance when sets are viewed as 0-1-strings.
Parameters
----------
set1, set2 : iterable of int
The two s... |
def get_fill(st, starttime=None, endtime=None):
"""
Subroutine to get data fill
@rtype: float
"""
if len(st) == 0:
# no trace
return 0.0
ststart = min(tr.stats.starttime for tr in st)
stend = max(tr.stats.endtime for tr in st)
dttot = (stend if not endtime else endtime) ... |
def by_locale(value_for_us, value_for_international):
""" Return a dictionary mapping "us" and "international" to the two values.
This is used to create locale-specific values within our UNITS.
"""
return {"us" : value_for_us,
"international" : value_for_international} |
def flatten_list(a, result=None):
"""Flattens a nested list.
>>> flatten_list([[1, 2, [3, 4]], [5, 6], 7])
[1, 2, 3, 4, 5, 6, 7]
"""
if result is None:
result = []
for x in a:
if isinstance(x, list):
flatten_list(x, result)
else:
result.append(x)... |
def validateFilename(value):
"""
Validate filename.
"""
if 0 == len(value):
raise ValueError("Name of SimpleGridDB file must be specified.")
return value |
def data_has_value(data, search_value):
"""Recursively search for a given value.
Args:
data (dict, list, primitive)
search_value (string)
Returns:
(bool) True or False if found
"""
if isinstance(data, list):
return any(data_has_value(item, search_value) for item in ... |
def getParameter(parameter, key, default = None):
"""Gets a parameter from a dict, returns default value if not defined
Arguments:
parameter (dict): parameter dictionary
key (object): key
default (object): deault return value if parameter not defined
Returns:
object... |
def decode_csv(csv_string, column_names):
"""Parse a csv line into a dict.
Args:
csv_string: a csv string. May contain missing values "a,,c"
column_names: list of column names
Returns:
Dict of {column_name, value_from_csv}. If there are missing values,
value_from_csv will be ''.
"""
import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.