content stringlengths 42 6.51k |
|---|
def aec_value (val=None):
""" Set or get automatic exposure control value """
global _aec_value
if val is not None:
_aec_value = val
return _aec_value |
def strip_comments_count(text):
"""
strip "comments and comment strings"
"""
result = text.strip(" comments")
return "0" if result == "" else result |
def _infer_length(iterable):
"""
Try and infer the length using the PEP 424 length hint if available.
adapted from click implementation
"""
try:
return len(iterable)
except (AttributeError, TypeError): # nocover
try:
get_hint = type(iterable).__length_hint__
... |
def listify(obj):
"""
makes sure that the obj is a list
"""
if isinstance(obj, list):
return obj
elif isinstance(obj, tuple):
return list(obj)
else:
return [obj] |
def parse_modified(full_dict, ignored_keys=('#', '?')):
"""
Extract 'staged' and 'modified' counts from Git status lines.
Arguments
---------
full_dict: dict
full meta data dictionary
ignored_keys: iterable
keys that should not contribute towards the staged and modified counts
... |
def contains(n, L):
"""
n: an int or a str of int
L: a list of int w/ len = 1
output: True if n contains at least one elem in L
"""
numStrList = list(str(n))
for num in L:
if num in numStrList:
return True
return False |
def address_fixup(a):
""" Add missing zip codes """
a = a.replace(
"2542 Monterey Highway, Gate D, San Jose, CA",
"2542 Monterey Highway, Gate D, San Jose, CA 95111",
)
return a |
def sortdictionary(dic):
"""Returns a dictionary sorted on keys"""
keys = sorted(dic)
sorteddict = {}
for k in keys:
sorteddict[k] = dic[k]
return sorteddict |
def is_letter(s):
"""
Return True if the given str is a alphabet, which
means it is in 'a-z,A-Z', False otherwise.
@param
---
`s` A symbol in string
"""
return s.isalpha() |
def _list_common_process_exact_filter(model, query, filters, legal_keys):
"""Applies exact match filtering to a query.
:param model: model to apply filters to
:param query: query to apply filters to
:param filters: dictionary of filters; values that are lists,
tuples, sets, or froze... |
def eval_pfile(pfile):
"""
Appropriately type-cast paramters from parameter file.
"""
def eval_element(element):
try:
element = eval(element)
except (NameError, SyntaxError):
pass
return element
for key in pfile:
if key in locals():
... |
def fib_bottom_up(n):
""" the bottom up algorithm """
fib_pp = 1
fib_p = 1
fib_cur = 1
for _ in range(3, n + 1):
fib_cur = fib_pp + fib_p
fib_pp = fib_p
fib_p = fib_cur
return fib_cur |
def time_converter(seconds: float) -> str:
"""Modifies seconds to appropriate days/hours/minutes/seconds.
Args:
seconds: Takes number of seconds as argument.
Returns:
str:
Seconds converted to days or hours or minutes or seconds.
"""
days = round(seconds // 86400)
secon... |
def escape_yaml(raw_str: str) -> str:
"""
Shell-Escape a yaml input string.
Args:
raw_str: The unescaped string.
"""
escape_list = [char for char in raw_str if char in ['!', '{', '[']]
if len(escape_list) == 0:
return raw_str
str_quotes = '"'
i_str_quotes = "'"
if s... |
def _bruteforce(triple_sum):
"""Run through all possible combinations of a, b, c such that
a^2 + b^2 = c^2 and a + b + c = triple_sum.
Parameters:
triple_sum The sum a + b + c
Return:
The triplet (a, b, c). None if the triple does not exist.
"""
# The largest possible value of... |
def ganeti_host_to_netbox(ganeti_dict, additional_fields):
"""Takes a single entry from the Ganeti host list and returns just the fields pertinent to Netbox
along with any additional fields that need to be added"""
shortname = ganeti_dict["name"].split(".")[0]
output = {
"name": shortname,
... |
def _norm2x(xp, xrange, xcenter):
""" Convert normalized x in (-1, 1) back to data x unit
Arguments
xp: float | np1darray in (-1, 1)
xrange: float MHz
xcenter: float MHz
Returns
x: float | np1darray
"""
return xp / 2 * x... |
def get_new_path(path, post):
"""
A function to get a new path with given postfix
:param path: A directory path
:param post: A postfix
:return: A new path with postfix added
"""
main_dir = path.split("/")[1]
new_path = path.replace(main_dir, main_dir + post)
return new_path |
def converttabs(text, spaces=4):
"""
Convert all the tabs to a specific amount of spaces
text:
The text to convert tabs to spaces on
spaces:
The amount of spaces to replace tabs to. Default is 4.
"""
return text.replace('\t', ' ' * spaces) |
def clamp(n, min_value, max_value):
"""Restricts a number to a certain range of values,
returning the min or max value if the value is too small or large, respectively
:param n: The value to clamp
:param min_value: The minimum possible value
:param max_value: The maximum possible value
:return: ... |
def get_feeds_config(full_config):
"""
Returns the feeds-specifc portion of the global config. To centralized this logic.
:param full_config:
:return: dict that is the feeds configuration
"""
return full_config.get('feeds',{}) |
def gettypes(*a):
"""
Convert a list of objects to their types
"""
return list(map(type, a)) |
def calculate_manhattan_dist(idx, value, n):
"""calculate the manhattan distance of a tile"""
if idx == value:
return 0
# zero is not a tile
elif value == 0:
return 0
else:
term1 = divmod(value, n)
term2 = divmod(idx, n)
return sum(abs(x - y) for x, y in zip(t... |
def create_user(first_name, last_name, email, phone_number, dob, address_id):
"""
Creates immutable user data structure
:param first_name: user's first name (string)
:param last_name: user's last name (string)
:param email: user's email (string)
:param phone_number: user's phone number (... |
def getCurrentJobs(jobs):
"""
Gets all current running jobs
"""
current_jobs = []
for job in jobs:
if 'result' not in job:
current_jobs.append(job)
return current_jobs |
def reduce_to_unit(divider):
"""
Reduce a repeating divider to the smallest repeating unit possible.
Note: this function is used by make-div
:param divider: the divider
:return: smallest repeating unit possible
:rtype: str
:Example:
'XxXxXxX' -> 'Xx'
"""
for unit_size in range(... |
def get_regions(ref_seq):
"""
ref_seq is a string containing gaps '-'
This function returns a list of lists (legnth two)
with the start and stop (python) of the non gapped regions.
"""
gap=True
gene = []
region = []
for i in range(0,len(ref_seq)):
if ref_seq[i]!='-' and gap=... |
def __or__(self,other): # supports syntax S | T
"""Return a new set that is the union of two existing sets."""
result = type(self)() # create new instance of concrete class
for e in self:
result.add(e)
for e in other:
result.add(e)
return result |
def _get_buildlogger_handler_info(logger_info):
"""Return the buildlogger handler information if it exists, and None otherwise."""
for handler_info in logger_info["handlers"]:
handler_info = handler_info.copy()
if handler_info.pop("class") == "buildlogger":
return handler_info
re... |
def transpose(data, length):
"""
takes a 3d list and the length of the 3d list.
transposes the columns of each of the 2d lists within this list
"""
for i in range(length):
data[i] = list(zip(*data[i]))
return data |
def doc_enumerate(items, connect_with='and', map_using=str, default='<null>'):
"""Enumerates a list of items using natural English. That is, `'[0]'`,
`'[0] and [1]'`, , `'[0], [1] and [2]'`, and so on. The connecting word is
specified using `connect_with` and defaults to `'and'`. Optionally, objects
can... |
def get_extension(file_name):
"""
Returns the file extension without 'dot'
"""
return file_name.rsplit('.', 1)[1].lower() |
def set_cache_env(host, port, db):
"""Set basic cache config parameters to environment variables.
Functions using Redis to access the pickled config need to be able
to access Redis without reading the config.
"""
import os
os.environ["HYPERGLASS_CACHE_HOST"] = str(host)
os.environ["HYPERGL... |
def ascii_symbol_to_integer(character):
"""Convert ascii symbol to integer."""
if(character == ' '):
return 0
elif(character == '+'):
return 1
elif(character == '#'):
return 2 |
def militarytime(time, separator=':'):
"""Converts simple AM/PM time strings from 12 hr to 24hr format
Example
input: 9:30 pm
output: 2130
Does not handle
"""
if time is None:
return '0000'
elif time.lower().endswith('am'):
hours, minutes = time.lower().rstrip('... |
def make_diagnostic_string(diagnostic: str):
"""Returns the diagnostic as a nice string"""
diagnostic_rename = {
"LFS-LP": "Low-field-side target",
"LFS-IR": "Low-field-side target",
"HFS-LP": "High-field-side target",
"TS": "Divertor Thomson",
"RDPA": "Divertor volume",
... |
def compute_volume(celldms,ibrav=4):
"""
Compute the volume given the *celldms*. Only for ibrav=4 for now, else
returns 0.
"""
if ibrav==4:
return 0.866025404*celldms[0]*celldms[0]*celldms[2]
return 0 |
def find_next_multi_line_comment_end(lines, line_index):
"""We are inside a comment, find the end marker."""
while line_index < len(lines):
if lines[line_index].strip().endswith('*/'):
return line_index
line_index += 1
return len(lines) |
def build_output_type_set(output_type_list, config):
"""Builds set of output types.
Args:
output_type_list: list, possible output image types.
config: dict, user passed parameters.
Returns:
Set of requested output image types.
"""
output_types = set()
for output_type in... |
def is_list_of_str_or_num(value):
"""
Check if an object is string, integer or float
:param value:
:return:
"""
return bool(value) and isinstance(value, list) and all(isinstance(elem, (str, int, float)) for elem in value) |
def unescapeDoubleQuotes(strPattern):
"""Convert any \" to ".
This is the primary difference between Rust string literals and raw string literals.
If anyone is using the "end of line escape followed by a newline", however,
we won't notice that.
We have a similar problem with the Perl /x extended mode."""
... |
def get_progress(processed, total):
"""
Based on how many items were processed and how many items are there in total
return string representing progress (e.g. "Progress: 54%")
:param processed: number of already processed items
:param total: total number of items to be processed
:return: string ... |
def _hasprefix(line, prefixes):
""" helper prefix test """
# if not isinstance(prefixes, tuple):
# prefixes = [prefixes]
return any(line == p or line.startswith(p + ' ') for p in prefixes) |
def slices(series, length):
"""
Return list of slices of len "length" from series"
"""
if length < 0:
raise ValueError("slice length cannot be negative")
if length == 0:
raise ValueError("slice length cannot be zero")
if series == "":
raise ValueError("series cannot ... |
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item |
def linear_interpolation(y1, y2, weight):
"""
Perform linear interpolation
Perform the linear interpolation between two equally space values (y1, y2)
and apply the weighting -> [0..1]: 0 = 100%y1, 1 = 100%y2.
Args:
y1: (float) first data value
y1: (float) second dat... |
def _extract_spotinst_access_token(definition: dict):
"""
extract the provided access token
"""
return definition["Mappings"]["Senza"]["Info"]["SpotinstAccessToken"] |
def rgb_hex_to_rgb_list(hex_string):
"""Return an RGB color value list from a hex color string."""
return [int(hex_string[i:i + len(hex_string) // 3], 16)
for i in range(0,
len(hex_string),
len(hex_string) // 3)] |
def _get_server_info(metadata=None, created=None):
"""
Creates a fake server config to be used when testing creating servers
(either as the config to use when creating, or as the config to return as
a response).
:param ``dict`` metadata: metadata to include in the server config
:param ``created... |
def e_timeToString(dateString):
"""
input: string
output: string
description: format dateString to yyyymmddHHMM
example: Wed Aug 29 07:23:03 CST 2018 ->> 201808290723
"""
# define month list for get digital
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
... |
def get_plugin_option(name, options):
"""
Retrieve option name from options dict.
:param options:
:return:
"""
for o in options:
if o.get("name") == name:
return o.get("value", o.get("default")) |
def procedure_coding_system(input_dict, field="m_procedure_code_oid"):
"""Determine from the OID in procedure coding system"""
coding_system_oid = input_dict[field]
if coding_system_oid == '2.16.840.1.113883.6.104':
return 'ICD9 Procedure Codes'
elif coding_system_oid == '2.16.840.1.113883.6.12... |
def check(in_str):
"""Checks whether the string consists of a's and b's
without more than 3 consecutive a's"""
accept=True #flag for accept/reject status
a_count = 0 #counter for cons a's
for c in in_str:
if c == 'a':
a_count += 1
elif c == 'b':
a_count = 0
else:
#reject if any sym not a or b
a... |
def to_hrs(mins=0, secs=0, time_format=False) -> str:
"""
Convert the given minutes or seconds into hours.
@params mins time in minus.
@params secs time in secs.
@params time_format is to return the time format.
"""
assert not (mins > 0 and secs > 0), (
"Both the mins and secs as ar... |
def add_members_to_policy(role: str, iam_policy: list, members: list, command_name: str) -> list:
"""
Append members to policy role members.
Args:
role (str): The name of policy role.
iam_policy (list): IAM policies.
members (list): Members to append to policy.
command_name (... |
def _convert_type(typename, obj):
"""Converts the specified object to the corresponding type
denoted by the specified type name."""
if obj == "null":
return None
if typename == "byte":
return int(obj)
elif typename == "short":
return int(obj)
elif typename in ("int", "in... |
def make_list(strings, delimiter='or'):
"""
Take a list of strings and a string.
If the length of the string is 1 return its element.
If it's 2, return its elements joined by the delimeter.
Otherwise, return its elements joined by commas (',') with
the delimeter before the final element.
Def... |
def concatenate_rounds(rounds_1: list, rounds_2):
"""Concatenate two lists of round numbers.
:param rounds_1: list - first rounds played.
:param rounds_2: list - second set of rounds played.
:return: list - all rounds played.
"""
rounds_1.extend(rounds_2)
return rounds_1 |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
answerlist = [ ]
for n in range(1,num+1):
if num % n == 0:
answerlist.append(n)
return answerlist |
def commonprefix(m):
"""Return the longest prefix of all list elements."""
if not m: return ''
prefix = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0: return ''
break
... |
def client_host(server_host):
"""Return the host on which a client can connect to the given listener."""
if server_host == '0.0.0.0':
# 0.0.0.0 is INADDR_ANY, which should answer on localhost.
return '127.0.0.1'
if server_host == '::':
# :: is IN6ADDR_ANY, which should answer on loca... |
def parse_string(my_str):
"""
Param my_str (str)
Removes line-breaks for cleaner CSV storage
Handles string or null value
Returns string or null value
"""
try:
my_str = my_str.replace("\n", " ")
my_str = my_str.replace("\r", " ")
my_str = my_str.strip()
except Att... |
def get_position_right(original_position):
"""
Given a position (x,y) returns the position to the right of the original position, defined as (x+1,y)
"""
(x,y) = original_position
return(x+1,y) |
def depth_first_traverse_postorder(root):
"""
Traverse a binary tree in postorder
:param root: root node of the binary tree
:type root: TreeNode
:return: traversed list
:rtype: list[TreeNode]
"""
node_list = []
if root is not None:
node_list.extend(depth_first_traverse_posto... |
def build_annotation_list_from_iters(annotation_iterators):
"""
Build the annotations dataframe
"""
annotation_lists = [list(iterator) for iterator in annotation_iterators]
return list(annotation_lists) |
def is_float(s):
""" Checks whether string s is a number"""
try:
float(s)
return True
except ValueError:
return False |
def rshift(val, n):
"""
Arithmetic right shift, preserves sign bit.
https://stackoverflow.com/a/5833119 .
"""
return (val % 0x100000000) >> n |
def get_style_message(output):
"""
Given a terminal output, wrap in a message
"""
# The output is limited to what GitHub can store in comments, 65,536 4-byte unicode
# total rounded down -300 for text below
if len(output) >= 64700:
output = output[:64682] + "\n... truncated ..."
ret... |
def get_timestamp(secs, divider='-'):
"""
Convert seconds into timestamp
:param secs: seconds
:type secs: int
:param divider: divider between minute and second, default "-"
:type divider: str
:return: timestamp
:rtype: str
"""
minutes = int(secs/60)
seconds = round(secs%60,... |
def is_prime(n):
"""
>>> is_prime(10)
False
>>> is_prime(7)
True
"""
factor = n - 1
while factor > 1:
if n % factor == 0:
return False
factor -= 1
return True |
def convert_children_to_list(taxa_tree):
"""Convert a dictionary of children to a list, recursively."""
children = taxa_tree['children']
taxa_tree['children'] = [convert_children_to_list(child)
for child in children.values()]
return taxa_tree |
def is_valid_RGB(r, g, b):
"""
check that an RGB color is valid
:params r,g,b: (0,255) range floats
:return: True if valid, otherwise False
"""
return all([0 <= x <= 255 for x in (r, g, b)]) |
def write_binary_file(filename, binary_data):
"""Write binary_data to filename and return number of bytes written."""
with open(filename, 'wb') as file:
file.write(binary_data)
return len(binary_data) |
def bytes_from_hex(value):
"""There are many ways to convert hex to binary in python.
This function is here to attempt to standardize on a single method.
Additionally, it will return None of None is passed to it
instead of throwing an expected string exception
"""
if not value:
return No... |
def dotjoin(*args):
""" string arguments joined by '.' unless empty string """
return ".".join(arg for arg in args if not arg=="") |
def create_gzip(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a GZIP archive."""
cmdlist = [cmd, 'a']
if not interactive:
cmdlist.append('-y')
cmdlist.extend(['-tgzip', '-mx=9', '--', archive])
cmdlist.extend(filenames)
return cmdlist |
def escape_chars(string):
"""
escape common shell special characters
"""
string = string.replace("\\", "\\\\\\")
string = string.replace("*", "\*")
string = string.replace('"', '\\"')
return string |
def _process_x(dtype, data):
"""Returns the MPL encoding equivalent for Altair x channel
"""
return ('x', data) |
def is_subset(a, b):
"""
a = [1,2], b = [[2,4], [2,1], [3,9,10], ]
is `a a subset of `b? Yes
Order of elements in a list DOES NOT matter
"""
iok = False
for si in b:
if set(si) == set(a):
iok = True
break
return iok |
def clip(s):
"""
Return a shortened version of the string, or a placeholder message if empty
"""
if not s:
return "No description available..."
if len(s) > 200:
s = s[:200].strip() + "..."
return s |
def encrypt(plaintext, n, key1, key2):
"""Encrypt the string and return the ciphertext"""
result = ''
for l in plaintext[:int(len(plaintext)/2)]:
try:
i = (key1.index(l) + n) % len(key1)
result += key1[i]
except ValueError:
result += l
for l in plainte... |
def month_num_to_string(number):
"""
Convert number to three-letter month.
Args:
number: Month in number format.
"""
m = {
1: 'jan',
2: 'feb',
3: 'mar',
4: 'apr',
5: 'may',
6: 'jun',
7: 'jul',
8: 'aug',
9: ... |
def gCallbackCov(dataset, colors):
"""Callback to set initial value of green slider from dict.
Positional arguments:
dataset -- Currently selected dataset.
colors -- Dictionary containing the color values.
"""
colorsDict = colors
try:
colorVal = colorsDict[dataset][4:-1].split(',')[... |
def add(data, params=None):
"""
Add function aggregation.
Example config:
.. code-block:: python
config = {
...
'fields': ['timestamp', 'x'],
'aggregations': [
{
'func': 'add',
'field': 'x',
... |
def playback_state(state):
"""Generate user-friendly playback states.
Args:
state (str): The Sonos-supplied state string.
Returns:
str: A user-friendly playback state description.
"""
playback_mapping = {
"STOPPED": "stopped",
"PAUSED_PLAYBACK": "paused",
"P... |
def get_formatted_wwn(wwn_str):
"""Utility API that formats WWN to insert ':'."""
if (len(wwn_str) != 16):
return wwn_str.lower()
else:
return (':'.join([wwn_str[i:i + 2]
for i in range(0, len(wwn_str), 2)])).lower() |
def preparePandas(timeData, sampleSizes, name):
"""Create DF for sns-plots"""
preparePd = list()
for time, sample in zip(timeData, sampleSizes):
preparePd.append([str(name),time, sample])
return preparePd |
def _get_column_nums_from_args(columns):
"""Turn column inputs from user into list of simple numbers.
Inputs can be:
- individual number: 1
- range: 1-3
- comma separated list: 1,2,3,4-6
"""
nums = []
for c in columns:
for p in c.split(','):
p = p.strip()
... |
def format_cpu_memory(container_group):
"""Format CPU and memory. """
containers = container_group.get('containers')
if containers is not None and containers:
total_cpu = 0
total_memory = 0
for container in containers:
resources = container.get('resources')
if... |
def to_lower(text):
"""
Custom to lower method that should not lowercase abbreviations
"""
return text if text.isupper() else text.lower() |
def _project_point_onto_cone(x_val, y_val, z_val, w_val):
"""
Try to find a point on the cone x0, y0, z0, w0 such that
z0 = z_val
w0 = w_val
x0, y0 lie on the circle x**2 + y**2 == z_val*w_val and are as close as possible to x_val, y_val
In order to find such a point, we can require that x0 an... |
def euclid(x, y):
""" Return the greatest common divisor of two integers. """
if not isinstance(x, int) or not isinstance(y, int):
raise TypeError("arguments must be integers")
if (x < 1) or (y < 1):
raise ValueError("arguments must be natural numbers")
# Make sure x is the largest.
... |
def get_comma_separated_values(values):
"""Return the values as a comma-separated string"""
# Make sure values is a list or tuple
if not isinstance(values, list) and not isinstance(values, tuple):
values = [values]
return ','.join(values) |
def append_tensors_to_lists(list_of_lists, list_of_tensors):
"""Appends tensors in a list to a list after converting tensors to numpy arrays
Args:
list_of_lists (list[lists]): List of lists, each of which holds arrays
list_of_tensors (list[torch.tensorFloat]): List of Pytorch tensors
Retur... |
def as_list(x):
"""Convert ``x`` to a list.
It performs the following conversion:
.. code-block:: python
None => []
list => x
tuple => list(x)
other => [x]
Args:
x (any): the object to be converted
Returns:
list:
"""
if x is None:
r... |
def update_project_settings(window, filename, settings):
"""Update the settings associated with a specific project folder."""
if window is None:
return None
projects = window.project_data()
if type(projects) != dict or projects.get("folders", None) is None:
return None
for folder... |
def digits(n, base, alphabet=None, pad=0, big_endian=True):
"""
Returns `n` as a sequence of indexes into an alphabet.
Parameters
----------
n : int
The number to convert into a sequence of indexes.
base : int
The desired base of the sequence representation. The base must be
... |
def is_local_filename(url):
"""
Whether a url is a local filename.
"""
return url.startswith('file://') or not('://' in url) |
def length_rating(pw):
"""
Takes in the password and returns a length-score dependent on its length.
Parameters:
pw (str): the password string
Returns:
(float): the length score [Maximum val- 5.0]
"""
length = len(pw)
if length > 17:
return 5.0
el... |
def ElementAttributes(attributes):
"""
Pretty much assumes one or more attr/val pairs.
Args:
attributes: list of (attrname, attrval) tuples
Returns:
string: xml formatted string attr="attrval"...
"""
attrs = []
for pair in attributes:
attrs.append(' ')
attrs.append('%s=\"%s\"' % (pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.