content stringlengths 42 6.51k |
|---|
def curly(content):
"""
Generate LaTeX code for data within curly braces.
Parameters
----------
content : str
String to be encapsulated within the curly braces.
Returns
-------
str
LaTeX code for data within curly braces.
"""
return "\\{" + content + "\\}" |
def having_sum_recursive(number: int) -> int:
"""Returns all elements of the sum are the results of integer division.
Args:
number (int): a number to get divisible from
Examples:
>>> assert having_sum_recursive(25) == 47
"""
if number == 1:
return 1
return number + havi... |
def bearer_token(token):
"""
Returns content of authorization header to be provided on all non-auth
API calls.
:param token: access_token returned from authorization call.
:return: Formatted header.
"""
return 'Bearer {}'.format(token) |
def is_null(content, nulls=None, blanks_as_nulls=False):
"""Determines whether or not content can be converted into a null
Args:
content (scalar): the content to analyze
nulls (Seq[str]): Values to consider null.
blanks_as_nulls (bool): Treat empty strings as null (default: False).
... |
def is_karpekar(n):
"""
defines wheter given number is karpekar number or not.
"""
n_square = n**2
len_of_n = len(str(n))
l = str(n_square)[-(len_of_n):]
r = str(n_square)[:-(len_of_n)]
if r == '':
r = 0
if (int(l) + int(r) == n):
return True
return False |
def csum2(numlist):
"""
3. Write a Python program of recursion list sum. Go to the editor
Test Data: [1, 2, [3,4], [5,6]]
Expected Result: 21
"""
if len(numlist) == 1:
return numlist[0]
if isinstance(numlist[0], list):
return csum2(numlist[0]) + csum2(numlist[1:])
else:
... |
def get_output_file_name(infile_name):
"""Parse input file name to replace text after first dot with 'nc'"""
split_str = infile_name.split('.')
return split_str[0] + '.nc' |
def get_sub_vs_list_from_data(response_data):
"""Get Sub VS IDs and the "Rs" data portion of the Sub VSs as a tuple
:param response_data: Data portion of LM API response
:return: Tuple of list of sub VS IDs and a dict of full RS sub VS data
"""
subvs_entries = []
full_data = {}
for key, val... |
def first_non_null(*iterable):
"""
Returns the first element from the iterable which is not None.
If all the elements are 'None', 'None' is returned.
:param iterable: Iterable containing list of elements.
:return: First non-null element, or None if all elements are 'None'.
"""
return next((i... |
def _get_id2line(team_stats):
"""
team_stats: {
'headers':[],
'data': [[],[]] # two teams, don't know which is home/away
}
"""
headers = team_stats['headers']
id_loc = headers.index('TEAM_ID')
data0 = team_stats['data'][0]
data1 = team_stats['data'][1]
... |
def floats_equal(x, y):
"""A deeply inadequate floating point comparison."""
small = 0.0001
if x == y or x < small and y < small:
return True
epsilon = max(abs(x), abs(y)) * small
return abs(x - y) < epsilon |
def overlay_line(base, line):
"""Overlay a line over a base line
' World ' overlayed over 'Hello ! ! !'
would result in 'Hello World!'
"""
escapes = [('', 0)]
if '\x1b' in line: # handling ANSI codes
nl = ""
while '\x1b' in line:
i = line.index('\x1b')
... |
def is_number(n):
"""
This function checks if n can be coerced to a floating point.
Args:
n (str): Possibly a number string
"""
try:
float(n)
return True
except:
return False |
def _synda_search_cmd(variable):
"""Create a synda command for searching for variable."""
project = variable.get('project', '')
if project == 'CMIP5':
query = {
'project': 'CMIP5',
'cmor_table': variable.get('mip'),
'variable': variable.get('short_name'),
... |
def _pop_rotation_kwargs(kwargs):
"""Pop the keys responsible for text rotation from `kwargs`."""
ROTATION_ARGS = {"ha", "rotation_mode"}
rotation = kwargs.pop("rotation", None)
rotation_kwargs = {arg: kwargs.pop(arg) for arg in ROTATION_ARGS if arg in kwargs}
if rotation is not None:
rotati... |
def valid_index(index, shape):
"""Get a valid index for a broadcastable shape.
Parameters
----------
index : tuple
Given index.
shape : tuple of int
Shape.
Returns
-------
tuple
Valid index.
"""
# append slices to index
index = list(index)
while ... |
def conv_connected_inputs(input_shape,
kernel_shape,
output_position,
strides,
padding):
"""Return locations of the input connected to an output position.
Assume a convolution with given parameters is applied to... |
def _varbase(values, period=None, population=False):
"""
Returns final variance.
:param values: list of values to iterate and compute stat.
:param period: (optional) # of values included in computation.
* None - includes all values in computation.
:param population:
* True - entire ... |
def correctHeading(x, headingCorrection):
"""
corrects a given column of directional data with the given headingCorrection
"""
if x + headingCorrection > 360:
return (x + headingCorrection) - 360
else:
return x + headingCorrection |
def hermiteInterpolate(v0, v1, v2, v3, alpha, tension, bias):
"""
Hermite interpolator. Allows better control of the bends in the spline by providing two
parameters to adjust them:
* tension: 1 for high tension, 0 for normal tension and -1 for low tension.
* bias: 1 for bias towards the n... |
def _lt_from_gt(self, other):
"""Return a < b. Computed by @total_ordering from (not a > b) and (a != b)."""
op_result = self.__gt__(other)
if op_result is NotImplemented:
return NotImplemented
return not op_result and self != other |
def abbreviate_str(string, max_len=80, indicator="..."):
"""
Abbreviate a string, adding an indicator like an ellipsis if required.
"""
if not string or not max_len or len(string) <= max_len:
return string
elif max_len <= len(indicator):
return string[0:max_len]
else:
return string[0:max_len - l... |
def check_int(value: int) -> bool:
"""Check whether value can be written as 2^p * 5^q where p and q are
natural numbers."""
if value == 1:
return True
else:
if value % 2 == 0:
return check_int(value//2)
if value % 5 == 0:
return check_int(value//5)
ret... |
def get_app_details_hr(app_dict):
"""
Prepare application detail dictionary for human readable in 'risksense-get-app-detail' command.
:param app_dict: Dictionary containing application detail.
:return: List containing application detail dictionary.
"""
return [{
'Address': app_dict.get(... |
def convert_dict_to_list(dictionary):
"""
Accepts a dictionary and return a list of lists.
@example: input : { "python" : 50, "json": 100, "text" : 20}
output : [['python', 50], ['json', 100], ['text', 20]]
"""
output_list = []
for k in dictionary.keys():
output_list.ap... |
def _inc_time(t: int, type_str: str = 'nano') -> int:
"""Increment time at aprrox rate of 10Hz."""
return int(t + 1e8) if type_str == 'nano' else t + 100 |
def single_to_list(recipients):
""" Ensure recipients are always passed as a list """
if isinstance(recipients, str):
return [recipients]
return recipients |
def check_stc_order(order, symbol):
"""Return order id if order has an in-effect STC order
for input symbol, else return None"""
if order["status"] in ["WORKING", "QUEUED", "ACCEPTED"]:
if len(order["orderLegCollection"]) == 1: # no multi-leg orders
instruct = order["orderLegCollection"... |
def clean_depparse(dep):
"""
Given a dependency dictionary, return a formatted string representation.
"""
return str(dep['dep'] + "(" + dep['governorGloss'].lower() + "-" +
str(dep['governor']) + ", " + dep['dependentGloss'] + "-" +
str(dep['dependent']) + ")") |
def version_string(version):
"""
Converts a version number into a version string
:param version: The version number from the firmware
:returns str -- The version string
"""
major_version = version >> 0x10
minor_version = version & 0xFFFF
return '%d.%d' % (major_version, minor_version) |
def coor(n,a,b):
"""
Calculates a list of coordinates using a for loop
Parameters
----------
n: integer
number of coordinates to use between endpoints
a: float
starting point
b: float
ending point
Returns
-------
coordinates: ... |
def sort_range(lines, r=None):
"""
>>> a = sorted(range(10), reverse=True)
>>> sort_range(a, (1, 1))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> sort_range(a, (1, 2))
[9, 7, 8, 6, 5, 4, 3, 2, 1, 0]
>>> sort_range(a, (0, 2))
[7, 8, 9, 6, 5, 4, 3, 2, 1, 0]
>>> sort_range(a)
[0, 1, 2, 3, 4, ... |
def dunder_to_chained_attrs(value, key):
"""
If key is of the form "foo__bar__baz", then return value.foo.bar.baz
"""
if '__' not in key:
return getattr(value, key)
first_key, rest_of_keys = key.split('__', 1)
first_val = getattr(value, first_key)
return dunder_to_chained_attrs(first... |
def string_for_attrs(attrs):
"""Returns string describing tag attributes in the order given."""
if not attrs: return ''
return ''.join(' %s="%s"' % (attr, value) for attr, value in attrs) |
def heatcap(x, T):
"""
Calculate heat capacity of wood at temperature and moisture content.
Example:
cp = heatcap(12, 300)
Inputs:
x = moisture content, %
T = temperature, K
Output:
cp_wet = heat capacity wet wood, kJ/(kg*K)
Reference:
Glass and Zelinka,... |
def _getReadHitsSep(cells, readCol, hitCol, hitSep):
"""
use hitSep to divide hit cell in to multipl hits
"""
read = cells[readCol]
hitCell = cells[hitCol]
hits = hitCell.strip().split(hitSep)
return (read, hits) |
def fibonacciRecursion(sequenceNumber):
"""
A recursive Algorithm that gets a number from fibonacci sequence at certain point in sequence
Args:
sequenceNumber {integer} the place in the sequence to get the number from
Return:
{integer} the number from fibonacci sequence
"""
... |
def groupID_callback(x):
"""
image_name = 1_1-1256_1264_2461_2455-12003110450161(_1).jpg
big_image_name = 12003110450161
"""
img_path = x['info']['image_path']
big_img_name = img_path.split('.')[-2]
big_img_name = big_img_name.split('-')[-1].split('_')[0]
return big_img_name |
def r(x, y, Xi, Yi):
""" Return the distance between (x, y) and (Xi, Yi) """
return ((x-Xi)**2 + (y - Yi)**2)**0.5 |
def fatorial(num,show=False):
"""
-> CALCULA O FATORIAL DE UM NUMERO
:param num: o numero a ser calculado
:param show: mostra ou nao calculo
:return: retorna o resultado
"""
f = 1
for c in range(num,0, -1):
if show :
print(c, end='')
if c > 1:
... |
def _is_number(x):
""" True if x is numeric i.e. int or float """
from numbers import Number
return isinstance(x, Number) |
def csv_list(string):
"""Helper method for having CSV argparse types.
Args:
string(str): Comma separated string to parse.
Returns:
list[str]: The parsed strings.
"""
return string.split(',') |
def is_pattern(s):
"""
Returns *True* if the string *s* represents a pattern, i.e., if it contains characters such as
``"*"`` or ``"?"``.
"""
return "*" in s or "?" in s |
def _get_path_on_disk(inputs, properties):
"""Returns the path as defined in the volume definition """
disk_path = ""
for search in inputs.values():
try:
if isinstance(search["path"], str):
disk_path = search["path"]
break
except (KeyError, TypeEr... |
def nullBasedArray(length):
"""
Returns an array with the given length filled with zeros
"""
array = []
for i in range (0,length):
array.append(0)
return array |
def infer_type(value, variable=None):
"""
Tries to infer the type of a variable, based on the default value if given.
"""
if value in ['T', 'F']:
return 'bool'
try:
throwaway = int(value)
return 'int'
except ValueError:
pass
try:
throwaway = float(... |
def clean_leetcode(tree: str) -> str:
"""
>>> clean_leetcode("[1,2,3,null,4]")
'1,2,3,None,4,None,None'
"""
arr = tree[1:-1].replace("null", "None").split(",")
height, max_nodes = 0, 1
while len(arr) > max_nodes:
height += 1
max_nodes = 2 ** (height + 1) - 1
w... |
def sanitize(sinput):
"""Sanitize `sinput`."""
return " ".join(sinput.split()) |
def uniquify(l):
"""Takes a list `l` and returns a list of the unique elements in `l`
in the order in which they appeared.
"""
mem = set([])
out = []
for e in l:
if e not in mem:
mem.add(e)
out.append(e)
return out |
def producer(number, fib_list):
"""
Returns the #num fibonacci number using recursion
:param number: current number
:param fib_list: pointer to shared list of fibonacci numbers
"""
# If the number has already been computed
if fib_list[number] != -1:
return fib_list[number]
if n... |
def complement(i,j,k):
"""
Input:
i,j elements of {1,2,3,4}
returns the only element of (1,2,3,4) not in the SET {i,j}
"""
list=[1,2,3,4]
list.remove(i)
list.remove(j)
list.remove(k)
return list[0] |
def check_present_students(students, k):
"""
:type students: list[int]
:type k: int
:rtype: str
"""
present_students = sum(1 for x in students if x < 0)
return "YES" if present_students >= k else "NO" |
def compact_values(lst):
"""..."""
assert all(x.validate() for x in lst), lst
# params_lst = [tuple(x.params.values()) for x in lst]
# assert all(len(x) == 1 for x in params_lst), [lst, params_lst]
# params = sorted(set(tuple(sorted(x[0])) for x in params_lst))
# return params
def trim_str(... |
def testAssociate(id_, key, requestor):
"""Test that keepass has the given identifier and key"""
input_data = {
'RequestType': 'test-associate',
}
return requestor(key, input_data, id_) |
def expand_transition(transition, input_list):
"""Add new (partially) expanded state transition.
Parameters
----------
transition: list
Specifies a state transition.
input_list: list
List of inputs, where each input is a string.
Returns
-------
list
New (partial... |
def generate_custom_inputs(desc_inputs):
"""
Generates a bunch of custom input dictionaries in order to generate
as many outputs as possible (to get their path templates).
Currently only works with flag inputs and inputs with defined value
choices.
"""
custom_input_dicts = []
for desc_in... |
def lastchange(pyccd_result, ordinal):
"""
Number of days since last detected change.
Defaults to 0 in cases where the given ordinal day to calculate from
is either < 1 or no change was detected before it.
Args:
pyccd_result: dict return from pyccd
ordinal: ordinal day to calculate... |
def stops(a,b):
"""
Tell if the games with the pair (a,b) will stop at a pair of the form (x,x).
"""
n = a+b
while not bool(n&1):
n >>= 1
return (a%n)==0 |
def render_warning(s) :
""" Make rst code for a warning. Nothing if empty """
return """
.. warning::
%s"""%(s) if s else '' |
def _create_appconfig_props(config_props, prop_list):
"""A helper function for mk-appconfig and ch-appconfig that creates the config properties dictionary
Arguments:
config_props {Dictionary} -- A dictionary with key-value pairs that gives the properties in an appconfig
prop_list {List} -- A li... |
def valid_version(parameter, min=0, max=100):
"""
Summary.
User input validation. Validates version string made up of integers.
Example: '1.6.2'. Each integer in the version sequence must be in
a range of > 0 and < 100. Maximum version string digits is 3
(Example: 0.2.3 )
... |
def update_cluster_node_map(cluster_node_map, cluster, max_node_id):
"""
Updates 'cluster_node_map' which is in format of
<cluster name> => <node id>
by adding 'cluster' to 'cluster_node_map' if it does not
exist
:param cluster_node_map: map of cluster names to node ids
:type cluster_node... |
def upperwhite(safe_string):
"""Return a username as full name."""
return safe_string.replace("_", " ").title() |
def filter_dict_by_keys(dict_, field_names):
""" Returns a copy of `dict_` with only the fields in `field_names`"""
return {key: value for (key, value) in dict_.items()
if key in field_names} |
def value_in(value, choices):
"""Raise an exception if a value doesn't match one of the given choices."""
if value not in choices:
raise ValueError("Expected one of %s, received %r." % (", ".join([repr(choice) for choice in choices]), value)) # pragma: no cover
return value |
def linearSearch(num :int, minimum :int, maximum :int) ->int:
"""linearly search the num in the range of minimum-maximum
Args:
num (int): the target number to find
minimum (int): the minimum limit of the num
maximum (int): the maximum limit of the num
Returns:
the se... |
def get_timeout(run_type):
"""Get timeout for a each run type - daily, hourly etc
:param run_type: Run type
:type run_type: str
:return: Number of seconds the tool allowed to wait until other instances
finish
:rtype: int
"""
timeouts = {
'hourly': 3600 / 2,
'daily': 24... |
def _parse_endpoint_url(urlish):
"""
If given a URL, return the URL and None. If given a URL with a string and
"::" prepended to it, return the URL and the prepended string. This is
meant to give one a means to supply a region name via arguments and
variables that normally only accept URLs.
""... |
def removesuffix(s: str, suffix:str) -> str:
"""Removes the suffix from s."""
if s.endswith(suffix):
return s[:-len(suffix)]
return s |
def bioconductor_annotation_data_url(package, pkg_version, bioc_version):
"""
Constructs a url for an annotation package tarball
Parameters
----------
package : str
Case-sensitive Bioconductor package name
pkg_version : str
Bioconductor package version
bioc_version : str
... |
def ERR_NOSUCHSERVICE(sender, receipient, message):
""" Error Code 408 """
return "ERROR from <" + sender + ">: " + message |
def strictwwid(wwid):
"""Validity checks WWID for invalid format using strict rules - must be Brocade format"""
if len(wwid) != 23: # WWPN must be 23 characters long
print("WWID has invalid length " + wwid)
return None
# Colon separators must be in the correct place
if wwid[2:3] !... |
def _str_to_int(string, exception=None):
"""Convert string to integer. Return `exception_value` if failed.
Args:
string (str): Input string.
exception (): Exceptional value returned if failed.
Returns:
int:
"""
try:
return int(string)
except:
return exce... |
def filter_by_year(statistics, year, yearid):
"""
Inputs:
statistics - List of batting statistics dictionaries
year - Year to filter by
yearid - Year ID field in statistics
Outputs:
Returns a list of batting statistics dictionaries that
are from the input year.
""... |
def validate_dialog(dialog, max_turns):
""" Check if the dialog consists of multiple turns with equal or
less than max_turns by two users without truncated tweets.
Args:
dialog: target dialog
max_turns: upper bound of #turns per dialog
Return:
True if the... |
def hamming_distance(str1, str2, capdistance=None):
"""Count the # of differences between equal length strings str1 and str2. Max diff can be capped using capdistance to short-circuit full calculation when only care about a range of distances."""
diffs = 0
if len(str1) != len(str2):
raise ValueErro... |
def _getitem_list_tuple(items, keys):
"""Ugly but efficient extraction of multiple values from a list of
items.
Keys are contained in a tuple.
"""
filtered = []
for item in items:
row = ()
do_append = True
for key in keys:
try:
row += (item[k... |
def checksum(sentence):
"""Calculate and return checsum for given NMEA sentence"""
crc = 0
for c in sentence:
crc = crc ^ ord(c)
crc = crc & 0xFF
return crc |
def number_is_within_bit_limit(number, bit_width=8):
"""
Check if a number can be stored in the number of bits given.
Negative numbers are stored in 2's compliment binary.
Args:
number (int): The number to check.
bit_width (int, optional): The number of bits available.
Returns:
... |
def next_bet(current, strategy):
"""Returns the next bet based on the current bet and betting strategy.
Standard increases by AUD denominations until reaching 100. Non standard
betting strategy doubles each time
Parameters:
current (int): The current bet to be increased for the next roll
strate... |
def term_printable(ch):
"""Return a char if printable, else, a dot."""
if (33 <= ch <= 126):
return ch
return ord(".") |
def max_or_none(iterable):
"""
Returns the max of some iterable, or None if the iterable has no items
Args:
iterable (iterable): Some iterable
Returns:
max item or None
"""
try:
return max(iterable)
except ValueError:
return None |
def replace_last(string, old, new):
"""
Replace the last occurrence of a pattern in a string
:param string:
string
:type string: ``str``
:param old:
string to find
:type old: ``str``
:param new:
string to replace
:type new: ``str``
:returns: ``str``
""... |
def list_type_check(lst, data_type):
"""
Checks if each element of lst has a given type.
:param lst: List = list of objects
:param data_type: type = estimated type for the objects
:return: bool = true if all objects in list have the type data_type
"""
return all([type(e) == data_type for e i... |
def frac(x, d):
"""
Utility func -- Works like fractional div, but returns ceiling
rather than floor
"""
return (x + (d-1)) // d |
def addtup(sttup, ndtup):
"""
Take two tuple as its parameter, where the different
length of both tuples is allowed, then return a list of
a tuple. How this function
work is as follows: sttup:= 4A, ndtup:= 5B, then
it will return 4A + 5B or 9 A-B. In this case,
it will return [(A, B, ... |
def fix_btwoc(value):
"""
Utility function to ensure the output conforms the `btwoc` function output.
See http://openid.net/specs/openid-authentication-2_0.html#btwoc for details.
@type value: bytes or bytearray
@rtype: bytes
"""
# Conversion to bytearray is python 2/3 compatible
array... |
def wf_mutation_rate_from_theta(popsize, theta):
"""
Given a value for theta (the population-level dimensionless innovation rate, returns the actual probability
of mutation per locus per tick. This is a *per locus* innovation rate, however,
so if you are using this in code which randomly selects one of... |
def startswith(value, arg):
"""Usage {% if value|startswith:"arg" %}"""
if value:
return value.startswith(arg)
return False |
def bin_to_dec(l):
"""Converts a list "l" of 1s and 0s into a decimal"""
return int(''.join(map(str, l)), 2) |
def check_eye_colour(val):
"""ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth."""
return val in {"amb", "blu", "brn", "gry", "grn", "hzl", "oth"} |
def standardize_breaks(text):
"""
Converting line endings to the Unix style.
The Windows and the old Mac line breaks have been observed in Twitter
profiles. These are best replaced with the standard form to make printing
and text file handling easier. Especially since "\r" in an unquoted field
... |
def isPotentialMatch(candidate: str, hints: str, guessedLetter: str) -> bool:
"""Given candidate string, string of hints in form of 011010 and guessed letter decide whether given candidate matches hint"""
for serv_let, cand_let in zip(hints, candidate):
if serv_let == "0" and cand_let == guessedLetter:
... |
def SfromL( L, nmax=25, epsilon= 2**(-50) ):
"""
Compute sequence of generalized inverses from given Schroder value L.
Args:
L (real): main arg, range 0.0 to 1.0
nmax (integer): default 22. Max length to allow for S.
epsilon (real): smallest change in L you don't care about.
Returns:... |
def get_organic_aerosols_keys(chem_opt):
"""
Return the anthropogenic and biogenic keys
"""
asoa_keys = None
bsoa_keys = None
if chem_opt == 106:
asoa_keys = ('orgaro1i', 'orgaro1j', 'orgaro2i', 'orgaro2j', 'orgalk1i', 'orgalk1j', 'orgole1i', 'orgole1j') # SOA Anth
bsoa_keys = ... |
def getfilename(path):
"""This function extracts the file name without file path or extension
Args:
path (file):
full path and file (including extension of file)
Returns:
name of file as string
"""
return path.split('\\').pop().split('/').pop().rsplit('.', 1)[... |
def factorial(n):
"""returns n!"""
return 1 if n < 2 else n * factorial(n-1) |
def zero_insert(input_string):
"""
Get a string as input if input is one digit add a zero.
:param input_string: input digit az string
:type input_string:str
:return: modified output as str
"""
if len(input_string) == 1:
return "0" + input_string
return input_string |
def process(data):
"""
Lower cases and reverses a string
Arguments:
data (str): The string to transform
Returns:
result (str): The lower cased, reversed string
"""
return data.lower()[::-1] |
def unstitch_strip(strip):
"""Revert stitched strip back to a set of strips without stitches.
>>> strip = [0,1,2,2,3,3,4,5,6,7,8]
>>> triangles = triangulate([strip])
>>> strips = unstitch_strip(strip)
>>> _check_strips(triangles, strips)
>>> strips
[[0, 1, 2], [3, 3, 4, 5, 6, 7, 8]]
>>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.