content stringlengths 42 6.51k |
|---|
def list_as_comma_sep(lst: list) -> str:
"""Gets a list and returns one single string with elements separated by a comma"""
return ",".join(lst) |
def mysql_connection(run_services, mysql_socket):
"""The connection string to the local mysql instance."""
if run_services:
return 'mysql://root@localhost/?unix_socket={0}&charset=utf8'.format(mysql_socket) |
def uniform_cdf(x: float) -> float:
"""Uniform cumulative distribution function (CDF)"""
"""Returns the probability that a uniform random variable is <= x"""
if x < 0:
return 0 # Uniform random is never less than 0
elif x < 1:
return x # e.g. P(X <= 0.4) = 0.4
else:
return 1 |
def _rgb_to_hex(tup):
"""Convert RGBA to #AARRGGBB
"""
tup = tuple(tup)
if len(tup) == 3:
return '#%02x%02x%02x' % tup
elif len(tup) == 4:
return '#%02x%02x%02x%02x' % (tup[3], tup[0], tup[1], tup[2])
else:
raise ValueError("Array or tuple for RGB or RGBA should be given.... |
def binary_digits_to_places(binary_string):
"""Given a string representing a binary value, return a list of the
decimal values of the places for which the bit is on.
0011 -> [1, 2]"""
reversed_bits = reversed(binary_string)
place_values = [
2**exp for exp, digit in enumerate(reversed_bits) i... |
def from_iob_to_io(sentences):
"""
Transforms the IOB tags in sentences (output of create_sentences_out_of_dataframe) to IO tags
:param sentences: (list of list of tuples)
:return: (list of list of tuples)
"""
clean_sentences=[]
for desc in sentences:
sublist=[]
for x in desc... |
def quaternion_to_xaxis_yaxis(q):
"""Return the (xaxis, yaxis) unit vectors representing the orientation specified by a quaternion in x,y,z,w format."""
x = q[0]
y = q[1]
z = q[2]
w = q[3]
xaxis = [ w*w + x*x - y*y - z*z, 2*(x*y + w*z), 2*(x*z - w*y) ]
yaxis = [ 2*(x*y - ... |
def repeat(phrase, num):
"""Return phrase, repeated num times.
>>> repeat('*', 3)
'***'
>>> repeat('abc', 2)
'abcabc'
>>> repeat('abc', 0)
''
Ignore illegal values of num and return None:
>>> repeat('abc', -1) is None
True
>>> repeat(... |
def product(xs):
"""Return the product of the elements in an iterable."""
accumulator = 1
for x in xs:
accumulator *= x
return accumulator |
def r(n):
"""venn2 can't show specified values, so round the values instead"""
return round(n, 3) |
def escape_suite_name(g: str) -> str:
""" format benchmark suite name for display """
c = g.split('-')
if c[0] == "amd" or c[0] == "nvidia":
return c[0].upper() + " SDK"
if c[0] == "npb" or c[0] == "shoc":
return c[0].upper()
elif c[0] == "parboil" or c[0] == "polybench" or c[0] == "... |
def long2str(x):
""" Convert long integer x to a bytes string.
"""
l = ( x & 0xff,
(x >> 8) & 0xff,
(x >> 16) & 0xff,
(x >> 24) & 0xff)
return ''.join([chr(x) for x in l]) |
def uniform(n: int) -> int:
"""Generates a binary number with alternating ones and zeros in decimal format"""
# input: 1, 2, 3, 4, 5, ...
# output: 2, 5, 10, 21, 42, ...
bits = 2
for i in range(n - 1):
bits *= 2
if not i % 2:
bits += 1
return bits |
def _from_url(url: str):
"""
Returns data from paste url.
"""
server = url.split('?')[0]
paste_id, key = (url.split('?')[1]).split('#')
return server, paste_id, key.encode('utf-8') |
def toggle_trigger_measure_button_label(measure_triggered, mode_val, btn_text):
"""change the label of the trigger button"""
if mode_val == "single":
return "Single measure"
else:
if measure_triggered:
if btn_text == "Start sweep":
return "Stop sweep"
... |
def validPalindrome(s):
"""
:type s: str
:rtype: bool
"""
if s[::-1]==s:
return True
i=0
j=len(s)-1
while(i<j):
if s[i] != s[j]:
sA=s[:i]+s[i+1:]
sB=s[:j]+s[j+1:]
if sA==sA[::-1] or sB==sB[::-1]:
return True
else:
return False
i+=1
j-=1 |
def _qtp_ids(tests):
"""Return IDs for QueryTime params tests."""
return ["-".join(item[0].keys()) for item in tests] |
def best_model(vals):
"""Decide on the best model according to an Information Criterion."""
if vals[0] is not None and vals[0] == min(x for x in vals if x is not None):
return 1
elif vals[1] is not None and vals[1] == min(x for x in vals if x is not None):
return 2
elif vals[2] is not N... |
def swap_http_https(url):
"""Get the url with the other of http/https to start"""
for (one, other) in [("https:", "http:"),
("http:", "https:")]:
if url.startswith(one):
return other+url[len(one):]
raise ValueError("URL doesn't start with http: or https: ({0})".f... |
def add(*args):
"""
:param args: This represents the group of ints that are to be added
:return: This returns the total sum of all numbers that were added
"""
total = 0
for arg in args:
if type(arg) is int:
total += arg
return total |
def compute_energy_from_density(density, x_dimension, y_dimension, chemical_potential):
"""Computes energy from energy density."""
return (x_dimension * y_dimension) * (density - chemical_potential) |
def to_arg(flag_str: str) -> str:
"""
Utility method to convert from an argparse flag name to the name of the corresponding attribute
in the argparse Namespace (which often is adopted elsewhere in this code, as well)
:param flag_str: Name of the flag (sans "--")
:return: The name of the argparse a... |
def wrap(item):
"""Wrap a string with `` characters for SQL queries."""
return '`' + str(item) + '`' |
def calculate_i(condition) -> int:
"""Return 0 or 1 based on the truth of the condition."""
if condition():
return 1
return 0 |
def make_sentiment(value):
"""Return a sentiment, which represents a value that may not exist.
>>> positive = make_sentiment(0.2)
>>> neutral = make_sentiment(0)
>>> unknown = make_sentiment(None)
>>> has_sentiment(positive)
True
>>> has_sentiment(neutral)
True
>>> has_sentiment(unk... |
def nulls(data):
"""Returns keys of values that are null (but not bool)"""
return [k for k in data.keys()
if not isinstance(data[k], bool) and not data[k]] |
def delegate(session_attributes, fulfillment_state, message):
"""Build a slot to delegate the intent"""
response = {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Delegate'
}
}
return response |
def tuple_cont_to_cont_tuple(tuples):
"""Converts a tuple of containers (list, tuple, dict) to a container of tuples."""
if isinstance(tuples[0], dict):
# assumes keys are correct
return {k: tuple(dic[k] for dic in tuples) for k in tuples[0].keys()}
elif isinstance(tuples[0], list):
... |
def get_area_from_bbox(bbox):
"""
bbox: [x1,y1,x2,y2]
return: area of bbox
"""
assert bbox[2] > bbox[0]
assert bbox[3] > bbox[1]
return int(bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) |
def encode(number, base):
"""Encode given number in base 10 to digits in given base.
number: int -- integer representation of number (in base 10)
base: int -- base to convert to
return: str -- string representation of number (in given base)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base <= ... |
def _decimal_to_binary(decimal):
"""Convert decimal to binary"""
return int("{0:b}".format(decimal)) |
def skip_chars(chars, text, i):
""" syntax
"""
while i < len(text):
if text[i] not in chars: return i
i += 1
return None |
def get_dataset_json(met, version):
"""Generated HySDS dataset JSON from met JSON."""
return {
"version": version,
"label": met['id'],
"location": met['location'],
"starttime": met['sensingStart'],
"endtime": met['sensingStop'],
} |
def _legacy_mergeOrderings(orderings):
"""Merge multiple orderings so that within-ordering order is preserved
Orderings are constrained in such a way that if an object appears
in two or more orderings, then the suffix that begins with the
object must be in both orderings.
For example:
>>> _me... |
def build_grid_refs(lats, lons):
"""
This function takes latitude and longitude values and returns
grid reference IDs that are used as keys for raster grid files
Parameters:
Two iterables containing float values. The first containing
latitudes, and the second containing longitudes.
Return... |
def yaml_formatter(data, **kwargs):
"""Method returns parsing results in yaml format."""
try:
from yaml import dump
except ImportError:
import logging
log = logging.getLogger(__name__)
log.critical(
"output.yaml_formatter: yaml not installed, install: 'python -m ... |
def get_first_k_words(text: str, num_words: int) -> str:
"""
Returns the given text with only the first k words. If k >= len(text), returns the entire text.
:param text: The text to be limited in the number of words (String).
:param num_words: The value of k (int). Should be >= 0.
:return: The give... |
def test_deprecated_args(a, b, c=3, d=4):
"""
Here we test deprecation on a function with arguments.
Parameters
----------
a : int
This is the first argument.
b : int
This is the second argument.
c : int, optional
This is the third argument.
d : int, optional
... |
def escape(c):
"""Convert a character to an escape sequence according to spec"""
return "&#{};".format(ord(c)) |
def jaccard(a, b):
"""Compute the jaccard index between two feature sets
"""
return 1.*len(set(a).intersection(set(b)))/len(set(a).union(set(b))) |
def add(*args):
"""Add a list of numbers"""
sum = 0.0
for arg in args:
sum += arg
return sum |
def _default_list(length: int) -> list:
""" Returns a list filled with None values. """
return [None for _ in range(length)] |
def check_deceased(path, name):
"""Check if the patient at the given path is deceased"""
return "In Memoriam" in path |
def validate_window_size(s):
"""Check if s is integer or string 'adaptive'."""
try:
return int(s)
except ValueError:
if s.lower() == "adaptive":
return s.lower()
else:
raise ValueError(f'String {s} must be integer or string "adaptive".') |
def ngramsplit(word, length):
"""
ngramsplit("google", 2) => {'go':1, 'oo':1, 'og':1, 'gl':1, 'le':1}
"""
grams = {}
for i in range(0, len(word) - length + 1):
g = word[i:i + length]
if not g in grams:
grams[g] = 0
grams[g] += 1
return grams |
def trim_and_lower(string):
"""Trims and lowers a string."""
return string.strip().lower() |
def make_device(**kwargs):
"""fixture factory for mocking a device
for current tests we only need the fields below and we can add more as needed
"""
device_data = {"id": 5883496, "is_running__release": {"__id": 1234}}
device_data.update(kwargs)
return device_data |
def insertion_sort(array, begin=1, end=None):
""" Sorting is done by splitting the array into a sorted and
an unsorted part. Values from the unsorted part are selected
and moved to their correct position in the sorted part. """
# None is initiated to be used in Introsort implementatio... |
def names_cleaner(name):
"""
Helper function to clean up string from 'thml' symbols
"""
# pylint: disable=W1402
return name.replace('\u202a', '').replace('\u202c', '').strip() |
def _make_header_wsgi_env_key(http_header: str) -> str:
"""Convert HTTP header to WSGI environ key format.
HTTP_ Variables corresponding to the client-supplied HTTP request
headers (i.e., variables whose names begin with "HTTP_").
See https://www.python.org/dev/peps/pep-3333/ for more details
>>> ... |
def formatNumber(number, billions="B", spacer=" ", isMoney = False):
"""
Format the number to a string with max 3 sig figs, and appropriate unit multipliers
Args:
number (float or int): The number to format.
billions (str): Default "G". The unit multiplier to use for bi... |
def _is_composite(b, d, s, n):
"""_is_composite(b, d, s, n) -> True|False
Tests base b to see if it is a witness for n being composite. Returns
True if n is definitely composite, otherwise False if it *may* be prime.
>>> _is_composite(4, 3, 7, 385)
True
>>> _is_composite(221, 3, 7, 385)
Fa... |
def not_empty_string(s):
"""A string that can't be empty."""
return isinstance(s, str) and len(s) > 0 |
def unique (inn):
"""
Removes duplicate entries from an array of strings. Returns an array of
strings, also removes null and blank strings as well as leading or trailing
blanks.
* inn = list of strings with possible redundancies
"""
# Make local working copy and blank redundant entri... |
def format(message):
"""Formats the message into bytes"""
return bytes(message, "utf-8") |
def htons(x):
"""Convert 16-bit positive integers from host to network byte order."""
return (((x) << 8) & 0xFF00) | (((x) >> 8) & 0xFF) |
def get_ws_url_private(account_id: int) -> str:
"""
Builds a private websocket URL
:param account_id: account ID
:return: a complete private websocket URL
"""
return f"wss://ascendex.com:443/{account_id}/api/pro/v1/websocket-for-hummingbot-liq-mining" |
def dec_to_bin(n):
"""
:param n: decimal number
:return: decimal converted to binary
"""
return bin(int(n)).replace("0b", "") |
def isqrt(n):
"""Calculate the floor of the square root of n, using Newton's
method.
Args
----
n : int
Integer to use.
Returns
-------
n_isqrt : int
Floor of the square root of n.
"""
n_isqrt = n
y = (n_isqrt + 1) // 2
while y < n_isqrt:
n_isqrt = y
y = (n_isqrt + n // n_isq... |
def calculate_speed_of_sound(t, h, p):
"""
Compute the speed of sound as a function of
temperature, humidity and pressure
Parameters
----------
t: float
temperature [Celsius]
h: float
relative humidity [%]
p: float
atmospheric pressure [kpa]
Returns
----... |
def frequency(lst, search_term):
"""Return frequency of term in lst.
>>> frequency([1, 4, 3, 4, 4], 4)
3
>>> frequency([1, 4, 3], 7)
0
"""
return lst.count(search_term) |
def canonify_slice(s, n):
"""
Convert a slice object into a canonical form
to simplify treatment in histogram bin content
and edge slicing.
"""
if isinstance(s, int):
return canonify_slice(slice(s, s + 1, None), n)
start = s.start % n if s.start is not None else 0
stop = s.stop %... |
def raw(string):
"""
Escapes a string into a form which won't be colorized by the ansi parser.
"""
return string.replace('{', '{{') |
def none2empty_filter(val):
"""Jinja2 template to convert None value to empty string."""
if not val is None:
return val
else:
return '' |
def is_percent(val):
"""Checks that value is a percent.
Args:
val (str): number string to verify.
Returns:
bool: True if 0<=value<=100, False otherwise.
"""
return int(val) >= 0 and int(val) <= 100 |
def calculate_enrichment_score(gene_set, expressions, omega):
"""
Given a gene set, a map of gene names to expression levels, and a weight omega, returns the ssGSEA
enrichment score for the gene set as described by *D. Barbie et al 2009*
:requires: every member of gene_set is a key in expressions
:p... |
def lintrans(x,inboundtuple,outboundtuple):
"""
Purpose: make a linear transformation of data for enhancing contrast.
Suppose, the input data is x which lies in [x1,x2], we want to transform it into range [y1,y2] by a linear way.
Arguments:
inboundtuple --> the original bound tuple (x1,... |
def left_top_of_center(angle):
"""
True, if angle leads to point left top of center
"""
return True if 180 <= angle < 270 else False |
def race_transform(input_str):
"""Reduce values to White, Black and Other."""
result = "Other"
if input_str == "White" or input_str == "Black":
result = input_str
return result |
def create_group_name(permissions):
"""Create group name based on permissions."""
formatted_names = [perm.name.rstrip(".").lower() for perm in permissions]
group_name = ", ".join(formatted_names).capitalize()
return group_name |
def _get_sources_with_sink(node_str, connections):
"""Returns the source nodes that are connected to the sink node with the
given string representation.
Args:
node_str: a string representation of a PipelineNode
connections: a list of PipelineConnection instances
Returns:
a list... |
def geo_db_path(type):
"""
Returns the full path of a specific GeoLite2 database
Args:
type (str): The type of database path to retrieve (ASN, City, Country)
Raises:
ValueError: An invalid database type has been provided
Returns:
str: The absolute path to the specified dat... |
def strip_qualifiers(typename):
"""Remove const/volatile qualifiers, references, and pointers of a type"""
qps = []
try:
while True:
typename = typename.rstrip()
qual = next(q for q in ['&', '*', 'const', 'volatile'] if typename.endswith(q))
typename = typename[:... |
def pack_bitflags(*values):
# type: (*bool) -> int
"""
Pack separate booleans back into a bit field.
"""
result = 0
for i, val in enumerate(values):
if val:
result |= (1 << i)
return result |
def _allocation_type(action) -> tuple:
"""Get details of child policy"""
allocation = '---'
action_type = '---'
if action.get("action-type",{}) == 'shape':
if 'bit-rate' in action.get('shape',{}).get('average',{}):
allocation = str(round(int(action.get("shape",{}).get("average",{})... |
def dtrunc (x: float) -> float:
""" Truncar un numero float """
k = int(x)
x = float(k) # numero float sin parte decimal
return x |
def format_smashgg_url(url):
"""Converts bracket url to api url, if necessary."""
if "api.smash.gg" not in url:
url = "http://api.smash.gg/phase_group/" + url.split("/")[-1]
api_string = "?expand[0]=sets&expand[1]=entrants"
if api_string not in url:
url += api_string
return url |
def climbing_stairs(n):
"""
n, the number of stairs
O(2**n) time and space
"""
if n < 2:
return 1
if n == 2:
return 2
return climbing_stairs(n-1) + climbing_stairs(n-2) |
def list_to_scalar(input_list):
"""
This is a helper function, that turns a list into a scalar if its length is 1.
"""
if len(input_list) == 1:
return input_list[0]
else:
return input_list |
def _fabric_xmlrpc_uri(host, port):
"""Create an XMLRPC URI for connecting to Fabric
This method will create a URI using the host and TCP/IP
port suitable for connecting to a MySQL Fabric instance.
Returns a URI.
"""
return 'http://{host}:{port}'.format(host=host, port=port) |
def sequence_of_bst(postorder):
"""
:param postorder: LRD of binary search tree
:return: bool
"""
if len(postorder) <= 1:
return True
root = postorder[-1]
# right_child = postorder.filter(lambda x: x > root, postorder)
# left_child = postorder.filter(lambda x: x < root, postorde... |
def bitwise_list_comparator(x, y):
""" Uses the first element in the list for comparison """
return (1 - x[0]) * y[0] |
def UnionFindSet(m, edges):
"""
:param m:
:param edges:
:return: union number in a graph
"""
roots = [i for i in range(m)]
rank = [0 for i in range(m)]
count = m
def find(member):
tmp = []
while member != roots[member]:
tmp.append(member)
mem... |
def equal(a: int, b: int, c: int):
"""Return the number of equal values in (a,b,c)."""
test_equality = set([a, b, c])
length = len(test_equality)
count = int(length % 3)
number_of_equal_values = 3 if count is 1 else count
return number_of_equal_values |
def get_prompt_save_file_name(name: str) -> str:
"""
Derives a file name to use for storing default prompt values.
Args:
name (str): The unique identifier of the file-name.
Returns:
str: The file name.
"""
return f"{name}.sav" |
def get_image_details(dynamodb_obj, image_id_list):
"""Get the image details of all the images provided by the image ID list"""
try:
image_id_list = list(set(image_id_list))
image_id_query = [{ 'id': item } for item in image_id_list]
response = dynamodb_obj.batch_get_item(
R... |
def compute_avg_headway(headways):
"""
Compute the average headways from the sum of all trips with the
specified headways.
:param headways: (list of int) list of headways
"""
if not headways:
return 0
frequency = sum([1 / headway for headway in headways])
return 1 / frequency |
def _xList(l):
"""
"""
if l is None:
return []
return l |
def _is_string_like(obj):
"""
Check whether obj behaves like a string.
"""
try:
obj + ""
except (TypeError, ValueError):
return False
return True |
def not_in_dict_or_none(dict, key):
"""
Check if a key exists in a map and if it's not None
:param dict: map to look for key
:param key: key to find
:return: true if key is in dict and not None
"""
if key not in dict or dict[key] is None:
return True
else:
return False |
def str_to_bool(value: str):
"""Convert a string to bool.
Arguments
---------
value : str
A string representation of a boolean.
Returns
-------
A bool.
Exceptions
----------
Raise a ValueError if the string is not recognized as a boolean's string representation.
""... |
def return_operations(*sets):
"""Sa se scrie o functie care primeste un numar variabil de seturi.
Returneaza un dictionar cu urmatoarele operatii dintre toate seturile doua cate doua:
reuniune, intersectie, a-b, b-a.
Cheia va avea urmatoarea forma: "a op b".
"""
output = {}
for i in range(0... |
def get_groupers(groupers):
""" Get default groupers if the input is None
Args:
groupers (sequence of str or None): groupers for calc and plot functions
Returns:
list: groupers for calc and plot functions
"""
if groupers is None:
groupers = ["ALL", "time.season", "time.mont... |
def to_list(value):
"""
Returns ``value`` as a list if it is iterable and not a string,
otherwise returns ``value`` in a list.
>>> to_list(('foo', 'bar', 'baz'))
['foo', 'bar', 'baz']
>>> to_list('foo bar baz')
['foo bar baz']
"""
if hasattr(value, '__iter__') and not isinstance(va... |
def largest_divisor_five(x=120):
"""Find which is the largest divisor of x among 2,3,4,5."""
largest = 0
if x % 5 == 0:
largest = 5
elif x % 4 == 0: #means "else, if"
largest = 4
elif x % 3 == 0:
largest = 3
elif x % 2 == 0:
largest = 2
else: # When all other ... |
def recursive_circus_v1(circuits):
"""Recursive Circus."""
programs = {}
for name in circuits.keys():
programs[name] = 0
for circuit in circuits.values():
if 'children' in circuit:
for child in circuit['children']:
programs[child] += 1
for name, count in ... |
def rivers_with_station(stations):
"""Returns a set of names of rivers with a monotoring station"""
rivers = []
for x in stations:
if x.river not in rivers:
rivers += [x.river]
return sorted(rivers) |
def get_line_ending(line: bytes) -> bytes:
"""
Return line ending.
Note: this function should be somewhere else.
"""
non_whitespace_index = len(line.rstrip()) - len(line)
if not non_whitespace_index:
return b""
else:
return line[non_whitespace_index:] |
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""
Updates the learning rate using inverse time decay in numpy
alpha is the original learning rate
decay_rate is the weight used to determine the rate at which alpha will
decay
global_step is the number of passes of gradien... |
def pop_path_info(environ):
"""Removes and returns the next segment of `PATH_INFO`, pushing it onto
`SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`.
If there are empty segments (``'/foo//bar``) these are ignored but
properly pushed to the `SCRIPT_NAME`:
>>> env = {'SCRIPT_NA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.