content stringlengths 42 6.51k |
|---|
def smallestRangeI(A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
A.sort()
if A[len(A)-1] - A[0] - 2 * K > 0:
return A[len(A)-1] - A[0] - 2 * K
else:
return 0 |
def padded_num_to_str(num, characters):
"""Return a string of the number, left-padded with zeros up to characters
num: number to convert
characters: number of total characters in resultant string, zero-padded
"""
word = str(num)
padded_word = (characters-len(word))*'0' + word
return padded_w... |
def nd_cross_variogram(x1, y2, x2, y1):
"""
Inner most calculation step of cross-variogram
This function is used in the inner most loop of `neighbour_diff_squared`.
Parameters
----------
x, y : np.array
Returns
-------
np.array
"""
res = (x1 - x2) * (y1 - y2)
return ... |
def _get_used_ports(vms):
"""
Return a set of ports in use by the ``vms``.
:param vms: list of virtual machines
:type vms: list(:class:`~.vm.VM`)
:return: set of ports
:rtype: set(int)
"""
used_ports = set()
for vm in vms:
ip, port = vm.get_ssh_info()
... |
def create_indexed_tag(key, value):
"""
Creates a tag for the api.
"""
key = key.upper()
key = key.replace("INDEXED_", "")
key = key.replace("UNINDEXED_", "")
return "->".join([key, value]).upper() |
def sxs_id_from_alt_names(alt_names):
"""Takes an array of alternative names from an SXS metadata.json file
and returns the SXS ID of the simulation."""
pattern = 'SXS'
if not isinstance(alt_names, (list, tuple)):
alt_names = [alt_names]
sxs_id = str(next((ss for ss in alt_names if pattern i... |
def construct_publish_comands(additional_steps=None):
"""Get the shell commands we'll use to actually build and publish a package to PyPI.
Returns:
List[str]: List of shell commands needed to publish a module.
"""
return (additional_steps or []) + [
"python setup.py sdist bdist_wheel",... |
def test_for_symbolic_cell(raw_python_source: str) -> bool:
"""
Returns True if the text "# Long" is in the first line of
`raw_python_source`. False otherwise.
"""
first_element = raw_python_source.split("\n")[0]
if "#" in first_element and "symbolic" in first_element.lower():
return Tru... |
def check_ends_with_period(docstring, context, is_script):
"""First line should end with a period.
The [first line of a] docstring is a phrase ending in a period.
"""
if docstring and not eval(docstring).split('\n')[0].strip().endswith('.'):
return True |
def line1(lines):
""" convert a string with newlines to a single line with ; separating lines
"""
return lines.replace('\n',';') |
def separate_units_by_type(all_units):
"""Separate all_units to their respective unit type group."""
immune = {}
infection = {}
unit_type_to_group = {
'immune': immune,
'infection': infection,
}
for unit_no, unit in all_units.items():
group = unit_type_to_group[unit['type... |
def _get_target_column_list(market: str) -> list:
"""Generate a column list according to the ``market``.
Each market has its own column list. This function generates the corresponding list
of column qualifiers in terms of the given ``market``.
Args:
market (str): The given market such as `1x2... |
def remove_duplicates(aList : list) -> list:
"""
Returns a list without duplicates
Parameters:
aList (list): A list.
Returns:
result (list): The given list without duplicates.
"""
result = list(dict.fromkeys(aList))
return result |
def getSqlServerNameFromJDBCUrl(jdbcURL):
"""Returns the Azure SQL Server name from given Hive, Oozie or Ranger JDBC URL"""
return jdbcURL[17:].split(";")[0] |
def get_dict_from_list(smu_info_list):
"""
Given a SMUInfo array, returns a dictionary keyed by the SMU name with SMUInfo as the value.
"""
smu_info_dict = {}
for smu_info in smu_info_list:
smu_info_dict[smu_info.name] = smu_info
return smu_info_dict |
def get_polygon(annotation):
"""
Extracts a polygon from an annotation
Parameters
----------
- annotation : Kili annotation
"""
try:
return annotation['boundingPoly'][0]['normalizedVertices']
except KeyError:
return None |
def check_variable_list_are_valid(variable_type_dict):
"""
Checks that the provided variable_type_dict is valid, by:
- Confirming there is no overlap between all variable lists
:param variable_type_dict: A dictionary, with keys describing variables types, and values listing particular
variabl... |
def timeout(func, args=(), timeout_duration=2, default=None, **kwargs):
"""This will spwan a thread and run the given function using the args, kwargs and
return the given default value if the timeout_duration is exceeded
"""
import threading
class InterruptableThread(threading.Thread):
def ... |
def hhmmss_to_seconds(hhmmss: str) -> int: #need more doc
"""Converts time from 24 hour to seconds elapsed from 00:00
This function assumes 24 hour input format, but can take time in forma
hh, hh:mm or hh:mm:ss
"""
power = 2
seconds = 0
for num in hhmmss.split(':'):
seconds... |
def get_block_string_indentation(value: str) -> int:
"""Get the amount of indentation for the given block string.
For internal use only.
"""
is_first_line = is_empty_line = True
indent = 0
common_indent = None
for c in value:
if c in "\r\n":
is_first_line = False
... |
def specificrulevalue(ruleset, summary, default=None):
"""
Determine the most specific policy for a system with the given multiattractor summary.
The ruleset is a dict of rules, where each key is an aspect of varying specificity:
- 2-tuples are the most specific and match systems with that summary.
... |
def get_prob_current(psi, psi_diff):
"""
Calculates the probability current Im{psi d/dx psi^*}.
"""
print("Calculating probability current")
curr = psi*psi_diff
return -curr.imag |
def textbar(maximum, value, fill="-", length=20):
"""print a text bar scaled to length with value relative to maximum"""
percent = value / maximum
num = int(round(length * percent))
ret = ""
for x in range(num):
ret += fill
return ret |
def get_diff_between_groups(group1, group2):
"""
Get difference between groups as a set.
"""
return set(group1).difference(set(group2)) |
def splitActionOwnerName(action) :
"""Takes the name of an action that may include both owner and action
name, and splits it.
Keyword arguments:
action - Name of action, possibly including both owner and name.
"""
s = action.split("/")
return (s[0], s[1]) if len(s) > 1 else ("", s[0]) |
def _find_from_file(full_doc, from_file_keyword):
"""
Finds a line in <full_doc> like
<from_file_keyword> <colon> <path>
and return path
"""
path = None
for line in full_doc.splitlines():
if from_file_keyword in line:
parts = line.strip().split(':')
if ... |
def render_docstr(func, indent_str='', closing_str=''):
""" Render a docstring as a string of lines.
The argument is either a docstring or an object.
Note that we don't use a sequence, since we want
the docstring to line up left, regardless of
indentation. The shorter triple quotes a... |
def error_match(actual, expected):
"""Check that an actual error message matches a template."""
return actual.split(":")[0] == expected.split(":")[0] |
def pop_type(args, ptype):
""" Reads argument of type from args """
if len(args) > 0 and isinstance(args[0], ptype):
return args.pop(0)
return None |
def unpack_bool(data):
"""Extract list of boolean from integer
Args:
data (int)
Return:
list: in bool
"""
return [bool(int(i)) for i in '{:016b}'.format(data)] |
def replace_iterable_params(args, kwargs, iterable_params):
"""Returns (args, kwargs) with any iterable parameters converted to lists.
Args:
args: Positional rguments to a function
kwargs: Keyword arguments to a function.
iterable_params: A list of (name, index) tuples for iterable parameters.
Retur... |
def test_wsgi_app(environ, start_response):
"""just a test app"""
status = '200 OK'
response_headers = [('Content-type','text/plain'),('Content-Length','13')]
start_response(status, response_headers)
return ['hello world!\n'] |
def close(conn):
"""This closes the database connection. Note that this does not
automatically call commit(). If you just close your database connection
without calling commit() first, your changes will be lost.
"""
try:
conn.close()
except:
pass
return True |
def copy_send(src_feat, dst_feat, edge_feat):
"""doc"""
return src_feat["h"] |
def get_current_step(t, t0, sequence):
""" returns i, (period, color) """
period = sum(s[0] for s in sequence)
tau = t - t0
while tau - period > 0:
tau -= period
i = 0
while True:
current = sequence[i][0]
if tau < current:
break
else:
i += 1
tau -= current
return i, sequence[i] |
def simplify_postags(tagged_words):
"""
Convert part-of-speech tags (Penn Treebank tagset) to the 4 tags {_N, _V, _J, _X} for
nounds, verbs, adjectives/adverbs, and others.
Beware that this method takes a list of tuples and returns a list of strings.
:param tagged_words: [(str,str)] -- words and the... |
def clap_convert(txt):
"""convert string of clap values on medium to actualy number
Args:
txt (str): claps values
Returns:
number on claps (int)
"""
# Medium annotation
if txt[-1] == "K":
output = int(float(txt[:-1]) * 1000)
return output
else:
return int(txt) |
def divide(x, y):
"""Divide value x by value y and convert values to integer.
Args:
x (any): dividend
y (any): divisor
Raises:
ZeroDivisionError: divisor can't be 0
Returns:
[integer]: An integer holding the result
"""
if y != 0:
return int(x) / int... |
def code_to_omz(_code_points):
""" Returns a ZSH-compatible Unicode string from the code point(s) """
return r'\U' + r'\U'.join(_code_points.split(' ')) |
def _get_input_tensor(input_tensors, input_details, i):
"""Gets input tensor in `input_tensors` that maps `input_detail[i]`."""
if isinstance(input_tensors, dict):
# Gets the mapped input tensor.
input_detail = input_details[i]
for input_tensor_name, input_tensor in input_tensors.items():
if input... |
def interpolate(l, r, t0, dt, t):
"""
this is a poorly written function that linearly interpolates
l and r based on the position of t between tl and tr
"""
p = (t-t0)/dt
return [p*(j-i) + i for i, j in zip(l, r)] |
def parse_location(d):
""" Used to parse name of location where match is played.
"""
return str(d.get("accNaam", "")) |
def indentLevel(line):
"""Returns the indentation level of a line, defined in Piklisp as the number of leading tabs."""
for i in range(len(line)):
if line[i] != "\t":
return i # i characters were "\t" before lines[i]
return None |
def _idivup(a, b):
"""
return the integer division, plus one if `a` is not a multiple of `b`
"""
return (a + (b - 1)) // b |
def chk_chng(src_flist,dst_flist):
""" Returns unchanged file list and changed file list
Accepts source file list and dsetination file list"""
uc_flist = []
c_flist = []
for files in src_flist:
if files in dst_flist:
uc_flist.append(files)
else:
c_flist.ap... |
def breakSuffix(glyphname):
"""
Breaks the glyphname into a two item list
0: glyphname
1: suffix
if a suffix is not found it returns None
"""
if glyphname.find('.') != -1:
split = glyphname.split('.')
return split
else:
return None |
def JoinWords(Words, Delimiter, Quote = False):
"""Join words in a list using specified delimiter with optional quotes around words.
Arguments:
Words (list): List containing words to join.
Delimiter (string): Delimiter for joining words.
Quote (boolean): Put quotes around words.
... |
def decode(e):
"""
Decode a run-length encoded list, returning the original time series (opposite of 'encode' function).
Parameters
----------
e : list
Encoded list consisting of 2-tuples of (length, element)
Returns
-------
list
Decoded time series.
"""
return ... |
def decode(bp_sp: str):
""" Return (row, column) tuple from string. The string is binary encoded, not by 0 and 1, but by F&B and L&R
Therefore we convert it to binary and use pythons int() function to convert it to decimal
"""
row = ''
col = ''
for x in range(0, 7):
if bp_sp[x] == 'F... |
def prepare_prefix(url_prefix):
"""Check if the url_prefix is set and is in correct form.
Output is None when prefix is empty or "/".
:param url_prefix: Registered prefix of registered callback.
:type url_prefix: str, list, None
:return: Url prefix of registered callback
:rtype: str, None
... |
def clean_metadata(metadata):
"""
Transform metadata to cleaner version.
"""
metadata = metadata.copy()
# Fix missing metadata fields
metadata['description'] = metadata['description'] or metadata['summary']
metadata['summary'] = metadata['summary'] or metadata['description']
return ... |
def optimal_merge_pattern(files: list) -> float:
"""Function to merge all the files with optimum cost
Args:
files [list]: A list of sizes of different files to be merged
Returns:
optimal_merge_cost [int]: Optimal cost to merge all those files
Examples:
>>> optimal_merge_pattern([2... |
def inlineKBRow(*argv) -> list:
"""
Row of inline Keyboard buttons
- *`argv` (`list`): Pass InlineKeyboardButton objects to generate a list (This is unuseful, you an use [button1,button2] with the same result)
"""
result = list()
for arg in argv:
result.append(arg)
return result |
def add_alternatives(status, unsure, names, name):
"""
Add alternative dependencies to either the list of dependencies
for the current package, or to a list of unused dependencies.
Parameters
status : dict, main package contents
unsure : dict, alternative dependencies
names : list, package ... |
def _init_data(data, key, init_data):
"""Initialize the data at specified key, if needed"""
if isinstance(key, int):
try:
data[key]
except IndexError:
data.append(init_data)
else:
data[key] = data.get(key, init_data)
return data |
def prod(F, E):
"""Check that the factorization of P-1 is correct. F is the list of
factors of P-1, E lists the number of occurrences of each factor."""
x = 1
for y, z in zip(F, E):
x *= y**z
return x |
def singleton_bound_asymp(delta,q):
"""
Computes the asymptotic Singleton bound for the information rate.
EXAMPLES::
sage: singleton_bound_asymp(1/4,2)
3/4
sage: f = lambda x: singleton_bound_asymp(x,2)
sage: plot(f,0,1)
"""
return (1-delta) |
def rivers_with_station(stations):
"""returns a list, from a given list of station objects, of river names with a monitoring station"""
rivers = set() # build an empty set
for station in stations:
river = station.river
rivers.add(river)
return sorted(rivers) |
def remove_parenthesis(dictionary):
""" remove () from the value"""
for key in dictionary:
value = dictionary[key]
if type(value) == str:
new_value = value.replace('(', '')
new_value = new_value.replace(')', '')
dictionary[key] = new_value
else:
... |
def select_transect(shore_pts, i_start, j_start, i_end, j_end):
"""Select transect position among shore points, by avoiding positions
on the bufferred parts of the transect. Buffers overlap between up to
4 tiles, and cause the same positions to be selected multiple times.
Inputs:
... |
def _bin(x):
"""
>>> _bin(0)
[]
>>> _bin(1)
[1]
>>> _bin(5)
[1, 0, 1]
"""
def f(x):
while x>0:
yield x % 2
x = x // 2
return list(f(x)) |
def api_upload_text(body): # noqa: E501
"""upload text data on Bitcoin SV.
upload text data on Bitcoin SV. # noqa: E501
:param body: upload text data on Bitcoin SV.
:type body: dict | bytes
:rtype: ResponseUploadTextModel
"""
# if connexion.request.is_json:
# body = RequestUpload... |
def _parse_cisco_mac_address(cisco_hardware_addr):
"""
Parse a Cisco formatted HW address to normal MAC.
e.g. convert
001d.ec02.07ab
to:
00:1D:EC:02:07:AB
Takes in cisco_hwaddr: HWAddr String from Cisco ARP table
Returns a regular standard MAC address
"""
cisco_hardware_addr =... |
def find_destination_containers(
container_wrapper, target_container, exclude_containers=None
):
"""Search through a collection of containers and return all containers
other than the given container
:param container_wrapper: A collection of containers in the Google Tag Manager
... |
def adjacent_sents(a, b, th):
"""
DESCRIPTION: Define if two sentences are adjacent measured in sentences
INPUT: a <int> - Sentence a index,
b <int> - Sentence b index
th <int> - maximum gap between indexes
OUTPUT: True if the two sentences are adjacents, False otherwise
"""
... |
def pad_data(value, width, fillbyte):
"""Append the fill byte to the end of the value until it has the
requested width.
"""
return value.ljust(width, fillbyte) |
def get_intron_exon_border_coords(ex_s, ex_e,
us_intron_len=False,
ds_intron_len=False,
eib_width=20):
"""
Get intron-exon border region coordinates surrounding one exon.
ex_s:
Genomic exon start (... |
def filter_orders_violating_max_xrate(xrate, b_orders, s_orders, fee):
"""Remove orders that violate the maximum exchange rate (considering the fee)."""
# For b_orders: xrate <= max_xrate * (1 - fee)
b_orders = [
order for order in b_orders
if xrate <= order.max_xrate * (1 - fee.value)
... |
def get_files_preview(thepath=".", preview_size=40):
"""Returns a tuple containing the file name and the first 40 characters of the file for each file in a given directory. Includes gzip files. Excludes .tar files.
Examples:
>>> from pprint import pprint\n
>>> pprint( previewgzipfiles() )\n
... |
def sentence_to_allen_format(sentence, sign_to_id, usingRealSigns):
"""
Transform the sentence to AllenNLP format
:param sentence: the sentence to transform
:param sign_to_id: dictionary of sign to id
:param usingRealSigns: whether using the signs as is
:return: the AllenNLP format for BiLSTM
... |
def removeSlash(p):
"""
If string p does not end with character '/', it is added.
"""
if p.endswith('/'):
return p[:-1]
else:
return p |
def transform(seq):
"""
Transforms "U" to "T" for the processing is done on DNA alphabet
"""
S = ""
for s in seq:
if s == "T":
S += "U"
else:
S += s
return S |
def bounds_to_space(bounds):
"""
Takes as input a list of tuples with bounds, and create a dictionary to be processed by the class Design_space. This function
us used to keep the compatibility with previous versions of GPyOpt in which only bounded continuous optimization was possible
(and the optimizati... |
def local_coord_to_global(in_coord, center_coord, max_x, max_y):
""" Converts a coordinate from a 3x3 grid into coordinate from large grid
Args:
:in_coord: tuple of local coordinates to convert to global
:center:coord: center coordinate of 3x3 grid cell in global coordinate system
... |
def parse_result_format(result_format):
"""This is a simple helper utility that can be used to parse a string result_format into the dict format used
internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where
there is no need to specify a custom partial_unexp... |
def dayOfWeek(dayInt):
"""
Takes the day of the week as integar and returns the
name of the day as a string
"""
if dayInt == 0:
return "Monday"
elif dayInt == 1:
return "Tuesday"
elif dayInt == 2:
return "Wednesday"
elif dayInt == 3:
return "Thursday"
... |
def complementray_filter(one_gyro_angle, one_accel_angle, alpha=0.96):
""" docstring """
#http://www.geekmomprojects.com/gyroscopes-and-accelerometers-on-a-chip/
return alpha*one_gyro_angle + (1.0 - alpha)*one_accel_angle |
def first_lower(string):
"""
Return a string with the first character uncapitalized.
Empty strings are supported. The original string is not changed.
"""
return string[:1].lower() + string[1:] |
def azure_translation_format(sentence):
"""
Puts an individual sentence into the required format for the Azure Translation API.
azure_translation_format(sentence)
sentence: str
The sentence to be formated
Returns: dict; The dict-format accepted by the Azure Translation API.
"""
r... |
def merge_intervals(indexes, length):
"""Merges overlapping intervals of matches for given indexes and generic
lzngth. This function assume the indexes are allready sorted in ascending
order.
:param indexes: the list of indexes acs sorted to merge
:param length: the length of the generic
:type... |
def reverse_comp(DNA):
"""returns a string with reverse complement of the string argument DNA
sequence"""
rev_dna = DNA[::-1]
new_dna = []
for i, element in enumerate(rev_dna):
if element in 'Gg':
new_dna.extend('c')
elif element in 'Cc':
new_dna.extend('g')
... |
def units_decoder(units):
"""
https://darksky.net/dev/docs has lists out what each
unit is. The method below is just a codified version
of what is on that page.
"""
si_dict = {
'nearestStormDistance': 'Kilometers',
'precipIntensity': 'Millimeters per hour',
'precipIntensi... |
def _leaky_relu_not_vect(x, derivative=False):
"""Non vectorized LeakyReLU activation function.
Args:
x (list): Vector with input values.
derivative (bool, optional): Whether the derivative should be returned instead. Defaults to False.
"""
a = 0.02
if x > 0:
if derivative:
... |
def format_exc(exc):
""" format the exception for printing """
try:
return f"<{exc.__class__.__name__}>: {exc}"
except:
return "<Non-recognized Exception>" |
def pad(tokens, length, pad_value=1):
"""add padding 1s to a sequence to that it has the desired length"""
return tokens + [pad_value] * (length - len(tokens)) |
def hide_tokens(request):
""" Hide tokens in a request """
if 'context' in request:
[request['context']['tokens'].update({key: '*****'})
for key in (request['context']['tokens'] if 'tokens' in request['context'] else [])]
return request |
def cross(v1, v2):
"""
Returns the cross product of the given two vectors
using the formulaic definition
"""
i = v1[1] * v2[2] - v2[1] * v1[2]
j = v1[0] * v2[2] - v2[0] * v1[2]
k = v1[0] * v2[1] - v2[0] * v1[1]
return [i, -j, k] |
def encode_ip_addr(address_octets):
"""encodes IP octets into a 32-bit int (for DCC use)"""
ip_int = 0
octets = address_octets.split('.')
if(len(octets) == 4):
ip_int += int(octets[0]) << 24
ip_int += int(octets[1]) << 16
ip_int += int(octets[2]) << 8
ip_int += int(octets[3])
return str(ip_int) |
def natural_size(num: float, unit: str = "B", sep: bool = True) -> str:
"""
Convert number to a human readable string with decimal prefix.
:param float num: Value in given unit.
:param unit: Unit suffix.
:param sep: Whether to separate unit and value with a space.
:returns: Human readable strin... |
def render_vextab(vextab: str, show_source: bool = False) -> str:
"""Create Javascript code for rendering VExflow music notation
:param vextab: The Vexflow source code to render into music notation
:param show_source: ``True`` to include the original Vexflow music notation
source cod... |
def total_chars(transcript: str) -> int:
"""
Sums the total amount of characters in the transcript.
:param transcript: A string containing the contents of the transcribed audio file.
:return: Returns the number of characters in the file.
"""
counter = 0
for i in transcript:
counter +... |
def traffic_data_maxmin_unnormalize(data, max_value=100, min_value=0):
"""
maxmin_unnormalize data.
:param data: ndarray, data.
:return: ndarray
"""
if max_value > 0:
scaler = max_value - min_value
data = data * scaler + min_value
return data |
def rho_beta(levels , ps, check=False):
"""
This function returns the Boer beta field, given the levels in G and the ps (hPa)
uses xarray
returns:
xr.DataArray in the same dimension as ps levels
"""
aa= (levels < ps)
if check is True:
print('ratio ' + str( aa.sum()/float(aa.size... |
def get_patched_apps(themes, plugins, apps):
"""
Patches in the active themes and plugins to the installed apps list provided by settings.py
"""
return plugins['active'] + [
# Theme first so it has template priority!
themes['active']
] + apps |
def to_string(obj, last_comma=False):
"""Convert to string in one line.
Args:
obj(list, tuple or dict): a list, tuple or dict to convert.
last_comma(bool): add a comma at last.
Returns:
(str) string.
Example:
>>> to_string([1, 2, 3, 4], last_comma=True)
>>> # 1... |
def split_namespace(tag):
"""returns a tuple of (namespace,name) removing any fragment id
from namespace"""
if tag[0] == "{":
namespace, name = tag[1:].split("}", 1)
return namespace.split("#")[0], name
else:
return (None, tag) |
def fitsum(list):
"""Sum of fitnesses in the list, needed to build
wheel of fortune."""
sum=0.0
for i in range(0,len(list)):
sum+=list[i]
return sum |
def _border_color_from_bin(bin, n_bins):
""" Return border color for bin."""
if n_bins <= 0:
return 'grey'
ratio = bin/float(n_bins)
if ratio <= 0.3:
return 'grey'
elif ratio <= 0.5:
return 'black'
return 'black' |
def split_on_uppercase(s, keep_contiguous=False):
"""
>>> split_on_uppercase('theLongWindingRoad')
['the', 'Long', 'Winding', 'Road']
>>> split_on_uppercase('TheLongWindingRoad')
['The', 'Long', 'Winding', 'Road']
>>> split_on_uppercase('TheLongWINDINGRoadT', True)
['The', 'Long', 'WINDING',... |
def find_res(line: str):
"""Find video resolution"""
lines = [
le.rstrip()
for le in line.split()
if not le.startswith("(") and not le.endswith(")")
]
lines = [le for le in lines if not le.startswith("[") and not le.endswith("]")]
res = None
for le in lines:
if le... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.