content stringlengths 42 6.51k |
|---|
def is_callable(func):
"""Determines if func is a callable function or not"""
return True if hasattr(func, "__call__") else False |
def getVerbosityLevel(verbosity_count):
"""Set verbosity level by how many --vvv were passed
Arguments:
verboisty_count {int} -- how many v's were passed
50 - critical
40 - error
30 - warning
20 - info
10 -debug
0 - notset
"""
# If 5, we want 10 debug level logging
... |
def lmhash_locked(password=b""):
"""
Generates a lanman password hash that matches no password.
Note that the author thinks LanMan hashes should be banished from
the face of the earth.
"""
return 32 * b"X" |
def get_mixture_weights_index_tuples(n_mixtures):
"""Index tuples for mixture_weight.
Args:
n_mixtures (int): Number of elements in the mixture distribution of the factors.
Returns:
ind_tups (list)
"""
ind_tups = []
for emf in range(n_mixtures):
ind_tups.append(("mixtu... |
def IsInverse(a, b) -> bool:
"""Checks if two provided directions are the opposites of each other.
"""
if (a == 2 and b == 3) or (a == 3 and b == 2):
return True
if (a == 0 and b == 1) or (a == 1 and b == 0):
return True
return False |
def _remove_dot_segments(path):
"""
Remove . and .. segments from path.
Implements 5.2.4. Remove Dot Segments.
"""
input = path
output = []
while input:
# A
if input.startswith("./"):
input = input[2:]
elif input.startswith("../"):
input = in... |
def _process_how_args(merge, how, how_subds):
"""Resolve how-related arguments into `how` and `how_subds` values.
"""
# Translate old --merge value onto --how
if merge and (how or how_subds):
raise ValueError("`merge` is incompatible with `how` and `how_subds`")
elif merge == "ff-only":
... |
def round_to_factor(value, factor):
"""
Round value to nearest multiple of factor. Factor can be a float
:param value: float
:param factor: float
:return: float
"""
return factor * round(value / factor) |
def cif2float(cifnum):
"""
Convert a cif-floating point number that may include an uncertainty
indication to a proper floating point number.
In a .cif file the value "0.4254(4)" is a floating point number where
the digit in brackets gives the uncertainty. To convert this number to
a regular Pyt... |
def corsikaRunScriptFileName(arrayName, site, primary, run, label=None):
"""
Corsika script file path.
Parameters
----------
arrayName: str
Array name.
site: str
Paranal or LaPalma.
run: int
RUn number.
label: str
Instance label.
Returns
-------
... |
def invert_dict(original):
"""
Produce a dictionary with the keys and values
inverted, relative to the dict passed in.
Args:
original dict: The dict like object to invert
Returns:
dict
"""
return {value: key for key, value in original.items()} |
def fatorial(numero, show=False):
"""
Calcula o fatorial de um numero.
:param numero: O numero pelo qual o fatorial vai ser calculado [Obrigatorio].
:param show: Mostra o calculo do fatorial [Opcional], Padrao: "False".
:return: Retorna o resultado do fatorial (numero inteiro).
"""
fatorial = 1
... |
def camelize(string):
"""Returns a copy of `string` where first letter of each item in `string`
are capitalized and leaves the rest unchanged.
:param strin: string to camelcase
"""
return ' '.join(s[0].upper() + s[1:] for s in string.split()) |
def make_doc1_url(court_id, pacer_doc_id, skip_attachment_page):
"""Make a doc1 URL.
If skip_attachment_page is True, we replace the fourth digit with a 1
instead of a zero, which bypasses the attachment page.
"""
if skip_attachment_page and pacer_doc_id[3] == '0':
# If the fourth digit is ... |
def extract_preference(prefer):
"""Extracts the parameters from a Prefer header's value
>>> extract_preferences('return=representation;include="http://www.w3.org/ns/ldp#PreferMinimalContainer http://www.w3.org/ns/oa#PreferContainedIRIs"')
{"return": "representation", "include": ["http://www.w3.org/ns/ldp#Pr... |
def _cross_exec(set_tuple):
"""
Function used by cross() to generate the cross-product of a tuple
"""
resulting_set = []
if len(set_tuple) == 1:
for val in set_tuple[0]:
resulting_set.append([val])
else:
tmp_set = _cross_exec(set_tuple[1:])
for val in set_tupl... |
def rgb_from_hexstr(hexstr: str):
"""Create a Color instance from a hex string like #ffaa22 or #11aa88ff.
Supports both long and short form (i.e. #ffffff is the same as #fff), and also an optional
alpha value (e.g. #112233ff or #123f).
"""
if hexstr[0] == "#": # get rid of leading #
hexstr = hexstr[1:]
... |
def hello(name: str) -> str:
"""Test function that prints hello world
:param name: name to be displayed
:type name: str, optional
:return: hello world string
:rtype: str
"""
return f'Hello World! My name is {name}' |
def get_samples_from_file(f, leading_str):
"""Return a list of ordered samples from file.
f --- iterate over lines of a file or strings
...doctest:
>>> f = '#abc\\tsample0\\tsample1'
>>> get_samples_from_file([f], '#abc')
['sample0', 'sample1']
"""
for line in f:
line... |
def get_top_fitness(dirty_values):
"""Return top fitness value.
Returns the top fitness values of a
:class:`~paddy.Paddy_Runner.PFARunner`, solely, for each iteration as a
list when passed a dictionary with the structure type of
:attr:`~paddy.Paddy_Runner.PFARunner.top_values`.
Parameters
... |
def estimation_formula_bg_dynamic(growth, eps, pe):
"""
BG formula, integrate with the normal pe (based on Gaussian Distribution)
"""
return (2*growth+pe)*eps |
def list_to_dict(lst):
"""
Converts an input list with mapped characters (every
odd entry is the key of the dictionary and every
even entry adjacent to the odd entry is its correponding
value) to a dictionary.
Parameters
----------
lst : list
Input list.
Returns
-----... |
def contains_all_required_firewalls(firewall, topology):
"""
Check that the list of firewall settings contains all necessary firewall settings
"""
for src, row in enumerate(topology):
for dest, col in enumerate(row):
if src == dest:
continue
if col == 1 an... |
def _get_union_type_name(type_names_to_union):
"""Construct a unique union type name based on the type names being unioned."""
if not type_names_to_union:
raise AssertionError(
"Expected a non-empty list of type names to union, received: "
"{}".format(type_names_to_union)
... |
def _default_metric_compare_fn(last_metrics, new_metrics):
"""Compare two metrics
Args:
last_metrics: previous metrics. A comparable object.
new_metrics: new metrics. A comparable object.
Returns:
True if new_metrics is equal to or better than the last_metrics.
False, o... |
def r_min_KimKim(T_sat, sigma, h_fg, rho, deltaT_sub):
""" minimum droplet radius """
r_min = 2*T_sat*sigma / (h_fg * rho * deltaT_sub)
return r_min |
def format_message_list(message_list):
"""
question = message_list[-1]
if len(question) > 160:
return question[0:157] + "..."
else:
extra_space = 160 - len(question)
message_start = ""
if extra_space > 3:
for msg in message_list[0:-1]:
message_... |
def get_sprint_number(current_sprint_name):
""" current_sprint_name format: "Sprint 56: Browser testet". """
return current_sprint_name.split()[1][:-1] |
def clean_string(str):
"""
Removes tabs and newlines from the given string
"""
if str is None:
return None
else:
return str.replace('\r', '').replace('\n','') |
def ERR_NICKNAMEINUSE(sender, receipient, message):
""" Error Code 433 """
return "ERROR from <" + sender + ">: " + message |
def perc_bounds(perc):
"""
perc_flt : float or tuple, default None
Percentage or tuple of percentages used to filter around reporting
irradiance in the irrRC_balanced function. Required argument when
irr_bal is True.
"""
if isinstance(perc, tuple):
perc_low = perc[0]... |
def unique_regions(R):
"""removed duplicated regions"""
return list(set(R)) |
def validate_username(username):
"""Check that username meets all requirements."""
errors = []
if len(username) < 3 or len(username) > 20:
errors.append("Username should be 3-20 characters long")
if any(character.isspace() for character in username):
errors.append("Username should not co... |
def add_eprint_to_bib(bib, eprint):
"""
Insert the eprint information in a given bibtex string
Parameters
----------
bib: str
The bibtex string without the arxiv number
eprint: str
The arxiv number
Returns
-------
bib: str
The bibtex ... |
def _apply_link(input, link, ln_title="Link"):
"""input[0]: mol_img_tag
input[1]: link_col value"""
link_str = link.format(input[1])
result = '<a target="_blank" href="{}" title="{}">{}</a>'.format(
link_str, ln_title, input[0]
)
return result |
def _interleave(x, y):
"""combine 2 32 bit integers to a 64 bit integer"""
c = 0
for i in range(31, 0, -1):
c = (c << 1) | ((x >> i) & 1)
c = (c << 1) | ((y >> i) & 1)
return c |
def vec_add(a, b):
"""
Add two vectors or a vector and a scalar element-wise
Parameters
----------
a: list[]
A vector of scalar values
b: list[]
A vector of scalar values or a scalar value.
Returns
-------
list[]
A vector sum of a and b
"""
if type(... |
def fix_timestamp(timestamp):
"""
Fix timestamp values, due to a len issue when posting them to Zipkin.
:param timestamp: The unix timestamp format.
"""
default_timestamp_len = 16
if len(str(timestamp)) < default_timestamp_len:
miss_len = default_timestamp_len - len(str(timestamp))
... |
def set_buildoverrides_facts(facts):
""" Set build overrides
Args:
facts(dict): existing facts
Returns:
facts(dict): Updated facts with missing values
"""
if 'buildoverrides' in facts:
buildoverrides = facts['buildoverrides']
# If we're actually defin... |
def fit_in_range(min, max, x):
"""fits a number(x) within a specified range between min and max"""
return (x - min) / (max - min) |
def bubbleSort_inc(array):
"""
It repeatedly swaps adjacent elements that are out of order
it has O(n2) time complexity
larger numbers are sorted first
"""
for i in range(len(array)):
for j in range(len(array)-i-1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array |
def hasManyOccurencies(elt, listx):
"""Find if a point has many similar occurences in a list.
This function is based on a threshold by default it is 80%.
Args:
elt: One element of the list.
listx: The list of elements
Returns:
True if it is a very frequent element, False other... |
def get_header(token):
""" Return a header with authorization info, given the token. """
return {
'Authorization': 'token %s' % token,
'Content-Type': 'application/json; charset=UTF-8'
} |
def binaryToDotted(binaryString):
""" This function takes the 32 bit long string and returns the IP in dotted notation)
"""
return '.'.join([ str(int(binaryString[0:8],2)), str(int(binaryString[8:16],2)), str(int(binaryString[16:24],2)), str(int(binaryString[24:32],2))]) |
def parse_argparse_boolstring(value: str) -> bool:
"""Return True or False given the provided string. If the string is actually not a boolean, raise a TypeError.
:param value: the argument to test
:return: the parsed boolean as type bool
"""
if value.lower() in ("yes", "true", "t", "1"):
re... |
def _IsExpectedErrorLine(line):
"""Returns whether or not the given line was expected from the Docker client.
Args:
line: The line received in stderr from Docker
Returns:
True if the line was expected, False otherwise.
"""
expected_line_substrs = [
# --email is deprecated
'--email',
... |
def get_value(str_):
"""
Helper function to store formatted string. Will replace '\x00' characters in string with ''.
:param str_: <str> to be formatted
:return:
"""
if not str_:
return None
else:
return str_.strip().replace('\x00', '') |
def mock_listdir(dir_map, dir):
""" mock os.listdir() """
return dir_map.get(dir, []) |
def indent(text, times=1, tab=' '):
""" Returns indented text
Inserts times number of tabs for each line and at the beginning
"""
if not text:
return ''
tabs = tab * times
return tabs + text.replace('\n', "\n%s" % tabs) |
def str2int(s):
"""return the int value of string, handles strings like 1e6 too"""
rv = None
try:
rv = int(s)
except ValueError:
rv = int(float(s))
return rv |
def address_for_puzzle_hash(puzzle_hash):
"""
Turn the puzzle hash into a human-readable address.
Eventually this will use BECH32.
"""
return puzzle_hash.hex() |
def serialize_proto(proto):
"""Serialize the protocol buffer object."""
if proto is None:
return b''
elif isinstance(proto, bytes):
return proto
elif (hasattr(proto, 'SerializeToString') and
callable(proto.SerializeToString)):
result = proto.SerializeToString()
... |
def replace_morph_breaks(gloss):
"""
If the stem or its gloss contains several parts separated by a & sign,
replace it with a hyphen.
"""
gloss = gloss.replace('&', '-')
return gloss |
def person(author):
"""Any text. Returns the name before an email address,
interpreting it as per RFC 5322.
>>> person('foo@bar')
'foo'
>>> person('Foo Bar <foo@bar>')
'Foo Bar'
>>> person('"Foo Bar" <foo@bar>')
'Foo Bar'
>>> person('"Foo \"buz\" Bar" <foo@bar>')
'Foo "buz" Bar'... |
def get_close_icon(x1, y1, height, width):
"""percentage = 0.1
height = -1
while height < 15 and percentage < 1.0:
height = int((y2 - y1) * percentage)
percentage += 0.1
return (x2 - height), y1, x2, (y1 + height)"""
return x1, y1, x1 + 15, y1 + 15 |
def is_curry_func(f):
"""
Checks if f is a toolz or cytoolz function by inspecting the available attributes.
Avoids explicit type checking to accommodate all versions of the curry fn.
"""
return hasattr(f, 'func') and hasattr(f, 'args') and hasattr(f, 'keywords') |
def kClosest2(points, K):
"""
Find k closest points to original point
:type points: List[List[int]]
:type K: int
:rtype: List[List[int]] k closest points to original point
"""
dist_points = [[p[0] ** 2 + p[1] ** 2, p[0], p[1]] for p in points]
dist_points.sort(key=lambda x: x[0])
ret... |
def get_data_from_context(context):
"""Get the django paginator data object from the given *context*.
The context is a dict-like object. If the context key ``endless``
is not found, a *PaginationError* is raised.
"""
try:
return context['endless']
except KeyError:
raise Exception... |
def json_validator(json_object):
""" json validator
"""
# Reference: https://stackoverflow.com/questions/5508509/how-do-i-check-if-a-string-is-valid-json-in-python
import json
try:
json.loads(json_object)
except ValueError:
return False
return True |
def enable_pause_data_button(n, interval_disabled):
"""
Enable the play button when data has been loaded and data *is* currently streaming
"""
if n and n[0] < 1: return True
if interval_disabled:
return True
return False |
def format_project(prj_id, name, extid, team_id, prv_id):
"""
Helper for project row formatting
"""
data_point = {}
data_point["ID"] = prj_id
data_point["ExtName"] = name
data_point["ExtID"] = extid
data_point["TeamID"] = team_id
data_point["ProviderID"] = prv_id
return data_poin... |
def make_connections_from_connect_streams(connect_streams):
"""
Converts from the format of connect_streams to the format of
connections.
connect_streams is a list of 4-tuples:
sender_process, out_stream, receiver_process, in_stream
connections is a dict where
connections[sender_proc... |
def find_build_dirs(tests):
""" given the list of test objects, find the set of UNIQUE build
directories. Note if we have the useExtraBuildDir flag set """
build_dirs = []
reClean = []
for obj in tests:
# keep track of the build directory and which source tree it is
... |
def add_previous_and_next_labels(docs):
"""
Assuming that labels docs are sorted, this method identifies all
previous and next labels and add the following fields to each label doc:
previous_label_published_date
previous_label_spl_id
previous_label_spl_version
next_label_publ... |
def first_half(dayinput):
"""
first half solver:
An opening parenthesis, (, means he should go up one floor
and a closing parenthesis, ), means he should go down one floor.
"""
result = dayinput.count('(') - dayinput.count(')')
return result |
def size(default_chunk_size, response_time_max, response_time_actual):
"""Determines the chunk size based on response times."""
if response_time_actual == 0:
response_time_actual = 1
scale = 1 / (response_time_actual / response_time_max)
size = int(default_chunk_size * scale)
return min(max(... |
def render_tab_content(active_reactor, active_tab):
"""
This callback takes the 'active_tab' property as input, as well as the
stored graphs, and renders the tab content depending on what the value of
'active_tab' is.
"""
on = {"display": "inline-block"}
off = {"display": "none"}
input_c... |
def _platform(platform, *args):
"""
Helper for platform()
"""
ret = False
for arg in args:
if arg[0] == '!':
arg = arg[1:]
if platform != arg:
ret = True
break
elif platform == arg:
ret = True
break
return ret |
def palindromePermutation(str): #Here we just check that string should not contain more than one odd character.
"""Return True if string is permutation of palindrome"""
import string
str = str.replace(' ', '').lower()
d = dict.fromkeys(string.ascii_lowercase, False) #Hash Table from a to z.
count = 0
for char i... |
def str2_bool(str):
"""Convert a str to bool"""
return True if str.lower() == 'true' else False |
def optimize(f, g, c, x0, n, count, prob):
"""
Args:
f (function): Function to be optimized
g (function): Gradient function for `f`
c (function): Function evaluating constraints
x0 (np.array): Initial position to start from
n (int): Number of evaluations allowed. Remember... |
def is_first_bag_missing_words(bag1, bag2):
""" If bag2 contains words that are not in bag1,
return True
"""
return len(set(bag2.keys()).difference(bag1.keys())) > 0 |
def decode(param):
"""Decodes the given param when it is bytes."""
if isinstance(param, (float, int)):
return param
return param.decode("utf-8") |
def make_postback_action(data, label=None, i18n_labels=None,
display_text=None, i18n_display_texts=None):
"""
make post back action.
reference
- `Common Message Property <https://developers.worksmobile.com/jp/document/1005050?lang=en>`_
:param data: post back strin... |
def get_filename_suffix_by_framework(framework: str):
"""
Return the file extension of framework.
@param framework: (str)
@return: (str) the suffix for the specific framework
"""
frameworks_dict = \
{
'TENSORFLOW1': '.pb',
'TENSORFLOW2': '.zip',
'PYTO... |
def convert_bit_reprentation_into_int_minutes(list):
"""
Return the list of minutes ranges from the bit representation.
>>> convert_bit_reprentation_into_int_minutes(A list of minutes ranges from the bit representation)
[[540, 600], [720, 780]]
"""
result = []
flag = False
idx ... |
def RGBToHTMLColor(rgb_tuple):
""" convert an (R, G, B) tuple to #RRGGBB """
hexcolor = '%02x%02x%02xff' % (int(rgb_tuple[0]*256), int(rgb_tuple[1]*256), int(rgb_tuple[2]*256))
# that's it! '%02x' means zero-padded, 2-digit hex values
return hexcolor |
def vals_are_0_1(vlist):
"""determine whether every value in vlist is either 0 or 1"""
for val in vlist:
if val != 0 and val != 1: return 0
return 1 |
def data_type(value):
"""A function called data_type, that takes one argument,
compares and returns results, based on the argument supplied to the function.
"""
# check if it is a string, return the length of that string
if isinstance(value, str):
return len(value)
# check there is no va... |
def safe_print_division(a, b):
"""
divides two integers and prints the result
catches divide by zero exception
"""
try:
res = a / b
except:
res = None
finally:
print("Inside result: {}".format(res))
return res |
def _scan(r, cols, name, rest):
"""Generate all possible combinations of values. Each set of values is
stored in a list and each value is repeated as many times so that if taking
one row in all value lists, I will get one unique combination of values
between all input keys.
@param r request as a... |
def arrangements(ns):
"""
prime factors of 19208 lead to the "tribonacci" dict;
only needed up to trib(4)
"""
trib = {0: 1, 1: 1, 2: 2, 3: 4, 4: 7}
count = 1
one_seq = 0
for n in ns:
if n == 1:
one_seq += 1
if n == 3:
count *= trib[one_seq]
one_seq = 0
return count
# # one-liner...
# return r... |
def getfullURL(date):
"""Returns Congressional Record URL (of PDF record) for a given date."""
base_url = "https://www.gpo.gov/fdsys/pkg/CREC-"+date+"/pdf/CREC-"+date+".pdf"
return base_url |
def get_acoem(core_data):
""" gets the ac oem from core data children """
if core_data != 'error':
data = core_data[1]
try:
for i, child in enumerate(data.children):
# find the aircraft model name in parse tree for reference
if child.name == ... |
def decode_uint256(s: bytes) -> int:
"""Decode 256-bit integer from little-endian buffer."""
assert len(s) == 32
return int.from_bytes(s, 'little') |
def unique(seq):
"""List of elements of a sequence 'seq' with duplicates removed, order preserved. (from: http://stackoverflow.com/a/480227/1202674)"""
if not seq: return []
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)] |
def java_type_boxed(typ):
"""Returns the java boxed type."""
boxed_map = {
'boolean': 'Boolean',
'byte': 'Byte',
'char': 'Character',
'float': 'Float',
'int': 'Integer',
'long': 'Long',
'short': 'Short',
'double': 'Double'
}
if typ in boxed_map:
return boxed_... |
def parse_resource_path(path):
"""Split the path to its elements.
:param path: URL path
:type path: str
:return: name and rest of the path
:rtype: tuple(str, list(str))
"""
splits = path.split('/')
return splits[0], splits[1:] |
def module_exists(module_name):
"""Check if module exists."""
try:
__import__(module_name)
except ImportError:
return False
else:
return True |
def humanize_path(path: str) -> str:
""" Replace python dotted path to directory-like one.
ex. foo.bar.baz -> foo/bar/baz
:param str path: path to humanize
:return str: humanized path
"""
return path.replace(".", "/") |
def howIndent(s):
"""returs indentation depth."""
s=s.replace("\t"," "*2)
indent=0
while len(s) and s[0]==" ":
indent+=1
s=s[1:]
return indent |
def fn_GetNumValues(d_Dict: dict) -> int:
"""
:
: Gets the total number of unique values from the given mapping.
:
:
: Args:
: dict d_Luminosity :
:
: Returns:
: Number of unique values
:
:
"""
return len(list(set(d_Dict.values()))) |
def build_graph(order, edges):
"""
Builds an adjacency list for a directed graph with the given number of
vertices (order) and directed edges u -> v represented (u, v).
"""
adj = [[] for _ in range(order)]
for src, dest in edges:
adj[src].append(dest)
return adj |
def get_predictor_cost(x, y, rho, sens, spec, cov):
"""
Calculate the predictor's cost on a point (x, y) based on the rho and its sensitivity, specificity and coverage
"""
return x * ((rho * cov * (1 - sens)) + cov - 1) + y * (((1 - rho) * cov * (1 - spec)) + cov - 1) + 1 - cov |
def makePrefixForLap(lap):
""" Get string prefix for saving lap-specific info to disk.
Returns
-----
s : str
"""
return 'Lap%08.3f' % (lap) |
def phoneCall(min1, min2_10, min11, s):
"""
You have s cents on your account before the call.
What is the duration of the longest call (in minutes
rounded down to the nearest integer) you can have?
Time Complexity: O(1)
Space Complexity: O(1)
"""
# Check if there is enough cents t... |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
Use method of bisection while keeping track of computations
using Python's integer division yields O(log n)//
"""
... |
def _rstrip(string: str) -> str:
"""find the rightmost non-whitespace character and rstrip and pad to that index"""
rstrip_list = [x for x in string.splitlines() if not len(x.strip()) == 0]
end_points = (len(x.rstrip()) for x in rstrip_list)
max_point = max(end_points)
new_rstrip_list = ((x + ' ' * ... |
def make_hash(o):
"""
Returns a hash number for an object, which can also be a dict or a list
>>> make_hash(range(10))
-6299899980521991026
>>> make_hash(list(range(10)))
-4181190870548101704
>>> a = make_hash({'a': 1, 'b': 2, 'c': 3})
>>> b = make_hash({'c': 3, 'a': 1, 'b': 2})
>>>... |
def n_states_of_vec(l, nval):
""" Returns the amount of different states a vector of length 'l' can be
in, given that each index can be in 'nval' different configurations.
"""
if type(l) != int or type(nval) != int or l < 1 or nval < 1:
raise ValueError("Both arguments must be positive integ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.