content stringlengths 42 6.51k |
|---|
def to_base36(value):
"""Returns a base36 version of an integer"""
buf = []
while value:
value, i = divmod(value, 36)
buf.append(u'0123456789abcdefghijklmnopqrstuvwxyz'[i])
return u''.join(reversed(buf)) or u'0' |
def type_to_str(t, separator=":"):
"""convert a type, e.g. a class to its unique module name.
Constructed by default as:
PATH_TO_MODULE:CLASS_NAME
"""
return f"{t.__module__}{separator}{t.__name__}" |
def _fullname_to_url(fullname):
"""For forked projects, fullname is 'forks/user/...' but URL is
'fork/user/...'. This is why we can't have nice things.
"""
if fullname.startswith("forks/"):
fullname = fullname.replace("forks", "fork", 1)
return fullname |
def normalize_config(config, prefix='boto3.', **kwargs):
"""
:type config: dict
:type prefix: str
:rtype: dict
"""
prefix_len = len(prefix)
normalized = dict([(k[prefix_len:], v) for k, v in config.items()
if k.startswith(prefix) and v])
normalized.update(kwargs)
... |
def columns(expansion='') -> tuple:
"""
Column information for the parser to
use when deciding how to split and
structure the incoming data.
Returns:
tuple: Number of channels + column name pairs, otherwise ()
"""
mapping = {
'2a03': (5, ['pulse1', 'pulse2', 'triangle', 'noi... |
def ParetoCdf(x, alpha, xmin):
"""Evaluates CDF of the Pareto distribution with parameters alpha, xmin."""
if x < xmin:
return 0
return 1 - pow(x / xmin, -alpha) |
def float_to_htk_int(string):
""" Converts a string representing a floating point number to an
integer (time in 100ns units)...
"""
try:
return int(round(float(string)*10000000))
except:
print(string)
raise |
def flatten_dict(obj, previous_key=None):
"""Flatten a nested dictionary with keys as obj1.obj2... and so on"""
result = {}
for k, v in obj.items():
if not isinstance(v, dict):
key = f"{previous_key}.{k}" if previous_key is not None else k
result.update({key: v})
else... |
def _make_cmd(*args):
"""Normalize args list that may contain empty values or tuples.
Flatten tuples and lists in the args list and remove any values that are
None or the empty string.
:param args:
:return: processed list of command arguments
"""
cmd = []
for a in args:
if type... |
def time_(milliseconds: int) -> str:
"""Inputs time in milliseconds, to get beautified time,
as string"""
seconds, milliseconds = divmod(int(milliseconds), 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = ((str(days) + " ... |
def lstdct2dctlst(lst):
"""List of dictionaries -> dict of lists."""
keys = lst[0].keys()
result = {k: [] for k in keys}
for item in lst:
for k, v in item.items():
result[k].append(v)
return result |
def format_title(title):
"""
Format title for reST.
reST requires header text to have an underline at least as long as the text.
"""
underline = "=" * len(title)
return f"{title}\n{underline}" |
def sort_dict(item):
"""
Sort nested dict
https://gist.github.com/gyli/f60f0374defc383aa098d44cfbd318eb
"""
return {
k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())
} |
def derive_fabs_awarding_sub_tier(row, office_list):
""" Derives the awarding sub tier agency code if it wasn't provided and can be derived from the office code.
Args:
row: the dataframe row to derive the awarding sub tier agency code for
office_list: A dictionary of sub tier codes ... |
def multiplication(a, b):
""" Multiplication modulo 2^16 + 1 ,
where tha all-zero word (0x0000) in inputs is interpreted as 2^16,
and 2^16 in output is interpreted as the all-zero word (0x0000)
:param a: <int>
:param b: <int>
:return: result: <int>
"""
# Assert statements are a... |
def _range_string_to_set(range_str):
"""Convert a range encoding in a string to a set."""
if '..' in range_str:
range_start, range_end = range_str.split('..')
range_start = int(range_start, 16)
range_end = int(range_end, 16)
return set(range(range_start, range_end+1))
else:
... |
def set_rc_params(usetex=False):
"""
Set the rcParams that will be used in all the plots.
"""
rc_params = {
#"axes.prop_cycle": cycler('color',
# ['#1b9e77','#d95f02','#7570b3',
# '#e7298a','#66a61e','#e6ab02',
# '#a6761d','#666666']),
"axes.labelsize"... |
def bin2str(s1):
"""
Convert a binary string to corresponding ASCII string
"""
for i in s1:
assert i == "0" or i == "1"
bin_list = [int(s1[i:i+8], 2) for i in range(0, len(s1), 8)]
for i in bin_list:
assert i < 256
bin_list = [chr(i) for i in bin_list]
return "".join(bin_list) |
def nested_get(dic, keys):
"""
Address a nested dict with a list of keys to fetch a value.
This is functionaly similar to the standard functools.reduce()
method employing dict.get, but this returns 'bad_path' if the path
does not exist. This is because we need to differentiate between
an existin... |
def _to_int(string):
"""Convert a one element byte string to int for python 2 support."""
if isinstance(string, str):
return ord(string[0])
else:
return string |
def lerp(a, b, i):
"""Linearly interpolates from a to b
Args:
a: (float) The value to interpolate from
b: (float) The value to interpolate to
i: (float) Interpolation factor
Returns:
float: Interpolation result
"""
return a + (b-a)*i |
def _get_upload_headers(user_agent):
"""Get the headers for an upload request.
:type user_agent: str
:param user_agent: The user-agent for requests.
:rtype: dict
:returns: The headers to be used for the request.
"""
return {
'Accept': 'application/json',
'Accept-Encoding': ... |
def desc(x):
"""Transform Data Helper Function."""
return " ".join([i["value"] for i in x]) |
def flatten(d, parent_key='', sep='$'):
""" Flattens a nested dict.
Source: http://stackoverflow.com/questions/6027558/
>>> d = {'id':1, 'pre':{'ogg':'x', 'mp3':'y'}}
>>> sorted(flatten(d).items())
[('id', 1), ('pre$mp3', 'y'), ('pre$ogg', 'x')]
"""
items = []
for k, v in d.items():
... |
def fchr(char):
""" Print a fancy character
:param char: the shorthand character key
:type char: str
:return: a fancy character
:rtype: str
"""
return {
'PP': chr(10003),
'FF': chr(10005),
'SK': chr(10073),
'>>': chr(12299)
}.get(char, '... |
def get_max_values(iterable):
"""Return the max values of the iterable."""
max_values = []
max_v = max(iterable)
ACCEPTABLE_DIFFERENCE = 1 # hyperparameter
for iter in iterable:
difference = max_v - iter
squared_difference = difference*difference
if squared_difference < ACC... |
def normURL(path):
"""Normalizes a URL path, like os.path.normpath.
Acts on a URL independent of operating system environment.
"""
if not path:
return
initialslash = path[0] == '/'
lastslash = path[-1] == '/'
comps = path.split('/')
newcomps = []
for comp in comps:
i... |
def database_info(connection):
"""
Parse an SQL string of the format:
database_type://user:password@address:/database
mysql://dbadmin:password@10.0.0.1/nova
"""
db = {}
conn = connection.partition(':')
if conn[1] != ':':
return None
db['type'] = conn[0]
conn = con... |
def _nav_conf(lst, bp=None):
"""
Shortcut for configuration navigation bars.
Parameters
----------
lst : list
List of tuples like (Display name, route name, {url arguments}).
bp : str, optional
The name of blueprint that the routes passed belong to. If omitted,
a bluepr... |
def translate(parsed):
"""
translate a tuple (mod, args) to a string
"""
if isinstance(parsed, tuple):
return '%s(%s)' % (parsed[0], ', '.join(map(translate, parsed[1])))
else:
return parsed |
def clip(value, minimum=-float("inf"), maximum=float("inf")):
"""Clips a value to a certain range
Arguments:
value {float} -- Value to clip
Keyword Arguments:
minimum {float} -- Minimum value output can take
(default: {-float("inf")})
maximum {fl... |
def coding_problem_04(array):
"""
Given an array of integers, find the first missing positive integer in linear time and constant space.
You can modify the input array in-place.
Example:
>>> coding_problem_04([3, 4, -1, 1])
2
>>> coding_problem_04([1, 2, 0])
3
>>> coding_problem_04(... |
def temperature_over_total_temperature(
mach,
gamma=1.4
):
"""
Gives T/T_t, the ratio of static temperature to total temperature.
Args:
mach: Mach number [-]
gamma: The ratio of specific heats. 1.4 for air across most temperature ranges of interest.
"""
return (1 + (... |
def _mode_array_map(mode_key, approx):
"""Return the mode_array in pycbc format for requested mode
Parameters
----------
mode_key: int/str
Mode key e.g. 22/'22'.
approx: str
Waveform approximant.
Returns
-------
mode_array: list
pesummary.gw.waveform.fd_waveform... |
def sexToDec (sexv, ra = False, delimiter = ':'):
"""sexToDec.
Args:
sexv:
ra:
delimiter:
"""
# Note that the approach below only works because there are only two colons
# in a sexagesimal representation.
degrees = 0
minutes = 0
seconds = 0
decimalDegrees = None
sg... |
def _format_value(value):
"""Convert to a string or be very visibly wrong.
"""
try:
val_str = repr(value)
except Exception:
val_str = "<could not convert to string>"
return val_str |
def cast(val):
"""
Cast a value from a string to one of:
[int, float, str, List[int], List[float], List[str]]
Args:
val (str): The value to cast.
Returns:
object: The casted value.
"""
val = str(val.strip())
if val.strip("[]") != val:
return [cast(elem) for ele... |
def _n2x(n):
"""
convert decimal into base 26 number-character
:param n:
:return:
"""
numerals='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
b=26
if n<=b:
return numerals[n-1]
else:
pre=_n2x((n-1)//b)
return pre+numerals[n%b-1] |
def curve_area(x_array, y_array, switch_idx, switch_state):
"""
It truncates the curve space according the current switch_state.
"""
if switch_state == 0:
x_array_reduced = x_array[:switch_idx]
y_array_reduced = y_array[:switch_idx]
else:
x_array_reduced = x_array[switch_idx ... |
def add_stub2connaddr(pack, stub):
"""
add stub into connaddr
"""
return pack | (stub << 32) |
def _parse_style_str(s):
"""
Take an SVG 'style' attribute string like 'stroke:none;fill:black'
and parse it into a dictionary like {'stroke' : 'none', 'fill' : 'black'}.
"""
styledict = {}
if s :
# parses L -> R so later keys overwrite earlier ones
for keyval in s.split(';'):
... |
def mean(numbers):
"""
Returns the arithmetic mean of a numeric list.
see: http://mail.python.org/pipermail/python-list/2004-December/294990.html
"""
return float(sum(numbers)) / float(len(numbers)) |
def get_result_item(data, fields, fields_dict: dict = {}, filter_isset: bool = False) -> dict:
"""
:param data: dict or object withs function get(field_name)
:param fields: list or set
:param fields_dict: dict { alias: field_name }
:return: dict
"""
result = {}
# function getter field fr... |
def yaml_padding_from_line(line: str) -> int:
"""Calculate number of spaces required to create a YAML multiline string.
eg:
line='foo: bar' -> 2
line=' foo: bar' -> 4
"""
last_c = None
padding = 0
for i, c in enumerate(line):
if i == 0 and c != ' ':
padding ... |
def get_lat_long(row):
"""Get latitude and longitude."""
return row["coordinates"] |
def cipher(text, shift, encrypt=True):
"""
Encrypts or decrypts a text using Caesar cipher.
Parameters
----------
text: str
A string that is to be encrypted or decrypted
shift: int
The number of positions that the text is shifted by
encrypt: bool
A boolean that state... |
def intersection(list1, list2):
"""Intersection of two lists, returns the common elements in both lists.
Args:
list1 (list): A list of elements.
list2 (list): A list of elements.
Returns:
result_list (list): A list with the common elements.
Examples:
>>> intersection([1,2... |
def mod_inverse(a, n):
"""Return the inverse of a mod b
>>> mod_inverse(42, 2017)
1969
"""
b = n
if abs(b) == 0:
return (1, 0, a)
x1, x2, y1, y2 = 0, 1, 1, 0
while abs(b) > 0:
q, r = divmod(a, b)
x = x2 - q * x1
y = y2 - q * y1
a, b, x2, x1, y2,... |
def read_parameters(job):
"""Return the parameters of the job in a format that is valid for using as ``**kwargs``"""
parameters = job["parameters"] or {}
py_parameters = {k.replace("-", "_"): v for k, v in parameters.items()}
return py_parameters |
def _exists(index, nx, ny):
"""
Checks whether an index exists an array
:param index: 2D index tuple
:return: true if lower than tuple, false otherwise
"""
return (0 <= index[0] < nx) and (0 <= index[1] < ny) |
def _labels_to_reverse_name(labels, ip_type):
"""
Convert a list of octets (IPv4) or nibbles (IPv6) to a reverse domain name
"""
name = '.'.join(list(reversed(labels)))
name += '.in-addr.arpa' if ip_type == '4' else '.ip6.arpa'
return name |
def is_set(val):
"""
Returns True iff this is a "set-like" type
"""
return isinstance(val, (frozenset, set)) |
def charidx(c):
"""Return the array index of the given letter.
Assumes 'A' <= c <= 'Z'
"""
return ord(c) - ord('A') |
def flop_bothtrsm(n, k):
"""# of + and * for both lower and upper trsms, one with unit diag, of nxn
matrix with k vectors."""
return (2*n**2 - n)*k |
def _apply(func, *args, **kwargs):
"""
Apply a maybe-function to positional and named arguments.
The result is ``func(*args, **kwargs)`` if ``callable(func)``, otherwise ``func``.
:param func: A value that is optionally callable.
:param args: The positional arguments passed to ``func``, if it is c... |
def reverse_commits(fuchsia_commits_for_integration):
"""
Convert a map of "integration_revs -> [fuchsia_revs]" to
"fuchsia_revs -> integration_revs".
"""
fuchsia_rev_to_integration = {}
for integ, fuch_revs in fuchsia_commits_for_integration.items():
for f in fuch_revs:
fuch... |
def split_labels(labels):
"""Just split a string of labels into a list."""
return labels.split(",") |
def two_fer(name=None) -> str:
"""
Return specific formatted information string based on presence
of parameter.
:param name: String (name) to format new returned string with.
:return: Formatted string.
"""
return f"One for {name if name else 'you'}, one for me." |
def adjustNumberInRange(x: float) -> float:
"""Adjust number into range (0,100)"""
if x <= 0:
return 1e-12
if x >= 100:
return 100 - 1e-12
return x |
def fx(vx0, n):
"""
Computed by hand
"""
if n>= vx0:
return vx0*(vx0+1)/2
else:
return n*(2*vx0 + 1 -n) / 2 |
def get_volumes(raw_input):
""" Parse the sizes of storage volume 'volume' """
volumes = raw_input.strip().split("\n")
volumes.pop(0) # delete the header
output = {}
for volume in volumes:
device, size, used, available, percent, mountpoint = \
volume.split()
output[mountp... |
def largest_number_possible(iterable):
"""
Largest_number is defined as the largest number formed by arranging the elements of the iterable
:param iterable: It is of type list or tuple accepting only non-negative integers
:return: The largest number possibly formed from the given iterable
... |
def value_of_card(card: str) -> int:
"""Determine the scoring value of a card.
:param card: str - given card.
:return: int - value of a given card. 'J', 'Q', 'K' = 10; 'A' = 1; numerical value otherwise.
"""
if card in ("J", "Q", "K"):
return 10
if card == "A":
return 1
re... |
def reveal(ch, answer):
"""
This function will reveal the positions of the letter that
is in the answer.
:param ch: str, the characters that are in the answer
:param answer: str, the word to be guessed
:return: str, the revealed word after each guessing
"""
ans = ''
for i in range(le... |
def parse_scoped_selector(scoped_selector):
"""Parse scoped selector."""
# Conver Macro (%scope/name) to (scope/name/macro.value)
if scoped_selector[0] == '%':
if scoped_selector.endswith('.value'):
err_str = '{} is invalid cannot use % and end with .value'
raise ValueError(err_str.format(scoped_s... |
def main( argv ):
""" Script execution entry point """
# return success
return 0 |
def fscore(precision, recall, beta=1):
"""Computes the F score.
The F score is the weighted harmonic mean of precision and recall.
This is useful for multi-label classification, where input samples can be
classified as sets of labels. By only using accuracy (precision) a model
would achiev... |
def _create_edge_label(v1_label: str, v2_label: str, is_directed: bool) -> str:
"""Creates a consistent string representation of an :term:`edge`.
This function is used instead of `edge.create_edge_label` to avoid circular dependencies.
Args:
v1_label: The first vertex label of the edge.
... |
def _(text):
"""
AllanC
OH MY GOD!!!!!!!!!
I PRAY THIS IS SHORT TERM!!!!! REALLY!!!!
This is copy and pasted from the admin_scripts translation - it cant be imported because it is outside the lib folder
REMOVE THIS HACK!! PLEASE!! PLEASE!!!
"""
words = [
("contents", "content")... |
def _joinregexes(regexps):
"""gather multiple regular expressions into a single one"""
return b'|'.join(regexps) |
def second_smallest(numbers):
"""Find second smallest element of numbers."""
m1, m2 = float('inf'), float('inf')
for x in numbers:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2 |
def ensure_list(v):
""" Returns v if v is list; returns [v] otherwise """
if type(v) == list: return v
return [v] |
def testCaseStatusToBootstrapClass(value, arg):
"""
Translates the test case status value to the appropriate class to trigger the right color highlighting
:param arg: the boolean value of test_case_include_flag
"""
if not arg:
return 'info'
else:
translations = {
'NE... |
def magic(target, actual, passed):
"""Wanna some magics?"""
target_to_date = int(passed * target)
return [
target,
actual,
target - actual, # Actual remain
target_to_date,
target - target_to_date, # Target to date remain
target_to_date - actual... |
def dedent(line, indent):
"""Dedents a line by specified amount.
Args:
line (str): The line to check.
indent (int): The length of indent to remove.
Returns:
str: The dedented line.
"""
return line[indent:] |
def is_nat_f(n):
"""Predicate determining if a string is a natural number"""
return str.isdigit(n) |
def get_launch_args(argv, separator=':='):
"""
Get the list of launch arguments passed on the command line.
Return a dictionary of key value pairs for launch arguments passed
on the command line using the format 'key{separator}value'. This will
process every string in the argv list.
NOTE: all ... |
def remove_empty_values(list_with_empty_values: list) -> list:
"""
Remove empty values from list:
.. code-block:: python
>>> lst = ["A", "T", "R", "", 3, None]
>>> list_to_dict(lst)
["A", "T", "R", 3]
Args:
list_with_empty_values (list): List with empty values
Retu... |
def _resolve_dotted_attribute(obj, attr):
"""Resolves a dotted attribute name to an object. Raises
an AttributeError if any attribute in the chain starts with a '_'.
"""
for i in attr.split('.'):
if i.startswith('_'):
raise AttributeError(
'attempt to access private ... |
def decibels_to_gain(decibels: float):
"""
Change unit from decibels to gains.
Args:
decibels: value in decibels.
Returns:
value in gains.
"""
return 10 ** (decibels / 20) |
def remove_debian_default_epoch(version):
"""
Remove the default epoch from a Debian ``version`` string.
"""
return version and version.replace("0:", "") |
def return_scalar(string):
"""
Return scalar if input string can transform to a scalar
Can not deal with too large number (float)
"""
try:
scalar = float(string)
return scalar
except ValueError:
return string |
def crc(line):
"""Calculate the cyclic redundancy check (CRC) for a string
Parameters
----------
line : str, characters to calculate crc
Returns
-------
crc : str, in hex notation
"""
crc = ord(line[0:1])
for n in range(1, len(line)-1):
crc = crc ^ ord(line[n:n+1])
r... |
def remap_vertex(vertex, symmetry):
"""
Remap a go board coordinate according to a symmetry.
"""
assert vertex >= 0 and vertex < 361
x = vertex % 19
y = vertex // 19
if symmetry >= 4:
x, y = y, x
symmetry -= 4
if symmetry == 1 or symmetry == 3:
x = 19 - x - 1
... |
def distance ( a , b ) :
"""
Distance in ULPS between two (floating point) numbers.
It is assumed here that size(long)==size(double) for underlying C-library!
Example
-------
>>> a = ...
>>> b = ...
>>> print distance ( a , b )
"""
if a == b : return 0
elif a > b : retu... |
def get_filename(fh):
"""Try to get the `name` attribute from file-like objects. If it fails
(fh=cStringIO.StringIO(), fh=StringIO.StringIO(), fh=gzip.open(), ...),
then return a dummy name."""
try:
name = fh.name
except AttributeError:
name = 'object_%s_pwtools_dummy_filename' %str(... |
def add_names_to_metadata_dict(metadata_dictionary, list_of_area_names):
"""Adds area names to metadata dictionary"""
for image_name in metadata_dictionary.keys():
for area_name in list_of_area_names:
if area_name in image_name:
metadata_dictionary[image_name]['area_name'] = ... |
def to_proper_degrees(theta):
"""
Converts theta (degrees) to be within -180 and 180.
"""
if theta > 180 or theta < -180:
theta = theta % 180
return theta |
def MI(n: int):
"""nxn identity matrix"""
return [[1 if i==j else 0 for i in range(n)] for j in range(n)] |
def get_y(pair):
"""Gets y in a pair."""
y = pair[1]
return y |
def shell_escape_single_quote (command):
"""Escape single quotes for use in a shell single quoted string
Explanation:
(1) End first quotation which uses single quotes.
(2) Start second quotation, using double-quotes.
(3) Quoted character.
(4) End second quotation, using double-quotes.
(5) S... |
def elemental_index_to_nodal_index(index):
"""
elemental_index_to_nodal_index converts an elemental index to a nodal one -
elements exist in centroids formed by the nodal mesh
:param index: elemental index
:return: nodal index
"""
return tuple(i + 0.5 for i in index) |
def get_width_and_height_from_size(x):
"""Obtain height and width from x.
Args:
x (int, tuple or list): Data size.
Returns:
size: A tuple or list (H,W).
"""
if isinstance(x, int):
return x, x
if isinstance(x, list) or isinstance(x, tuple):
return x
else:
... |
def preprocess(x, LPAREN="(", RPAREN=")"):
"""
Parameters
----------
x: str or list[str]
LPAREN: str, default "("
RPAREN: str, default ")"
Returns
-------
list[str]
"""
if isinstance(x, list):
x = " ".join(x)
sexp = x.replace(LPAREN, " %s " % LPAREN).replace(RPAR... |
def read_file(path):
"""Reads a file and returns the data as a string."""
output = ""
try:
# If we could not open then we simply return "" as the output
with open(path, "r") as content:
output = content.read()
except:
pass
return output |
def format_input(string: str) -> str:
"""Format input to be used."""
return string.replace("r/", "").lower() |
def get_age_breakdown(members):
"""This function will retrieve all the ages of the members, and return the
number of adults, seniors, children, infants, and the total number of
family members.
"""
infants = 0
children = 0
adults = 0
seniors = 0
for member in members:
if member.age < 2:
infants = inf... |
def is_collection(v):
"""
Decide if a variable contains multiple values and therefore can be
iterated, discarding strings (single strings can also be iterated, but
shouldn't qualify)
"""
# The 2nd clause is superfluous in Python 2, but (maybe) not in Python 3
# Therefore we use 'str' instead... |
def _glue_prefix_box(prefix, box, indent_width=None):
"""Concatenate strings with proper indentation."""
lines = box.split("\n")
if indent_width is None:
prefix_lines = prefix.split("\n")
indent_width = len(prefix_lines[-1])
indent = indent_width * " "
res_lines = [prefix + lines[0]]... |
def _validate_data_format(data_format):
"""Verify correctness of `data_format` argument."""
data_format_ = str(data_format).upper()
if data_format_ in {'NHWC', 'NCHW'}:
return data_format_
raise ValueError(
'Argument data_format="{}" not recognized; must be one of '
'{{"NHWC", "NCHW"}} (case ins... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.