content stringlengths 42 6.51k |
|---|
def isiterable(p_object):
"""
Test if the parameter is an iterable (not a string or a dict) or a file
Parameters
___________
p_object: object
Any object
Returns
_______
True: bool
Returns true if the conditions are met
"""
if type(p_object) == str ... |
def _normalize_names(name):
"""Normalize column names."""
name = name.strip()
name = name.strip("*")
return name |
def make_normal_initializer(mean, std):
"""make normal initializer param of make_table_options
Args:
mean (float): A python scalar. Mean of the random values to generate.
std (float): A python scalar. Standard deviation of the random values to generate.
Returns:
dict: initializer p... |
def returnBaseK(n, k):
"""Given base 10 number n and base k, return n converted to base k as a string"""
s = ""
while n > 0:
s = s + str(n % k)
n = int(round(n // k))
return s[::-1] |
def is_list(object):
"""RETURN : True/False """
return isinstance(object, list) |
def dedup_and_title_case_names(names):
"""Should return a list of names, each name appears only once"""
return list({name.title() for name in names}) |
def time_checked_cell(i):
"""Make and return the time_checked aka now_status cell at Column D."""
return "D{}".format(str(i)) |
def createAltitudeStr(altitudeLow, altitudeHigh, altitudeType):
"""Create a string out of a low altitude, high altitude, and altitude type.
Return value will look something like: ``8000-20000 MSL``. If the
low altitude is 0, it will be noted as ``SFC``.
Args:
altitudeLow (int): Low altitud... |
def get_object(context):
"""
Get an object from the context or view.
"""
object = None
view = context.get("view")
if view:
# View is more reliable then an 'object' variable in the context.
# Works if this is a SingleObjectMixin
object = getattr(view, "object", None)
... |
def climb_stairs(stair_count, max_steps):
"""
Given n number of stairs, you can climb at most m stairs at a time.
For instance, for m=3, you can climb 1, 2, or 3 stairs at a time.
Count the number of different ways that you can reach the top.
:param stair_count: No of stairs to climb.
:param ma... |
def filter_doc_list_through_topics(frequent_topics, docs):
"""
Reads all of the documents and creates a new list of two-tuples
that contain a single feature entry and the body text, instead of
a list of topics. It removes all geographic features and only
retains those documents which have at least o... |
def convert_xywh_to_xyxy(api_bbox):
"""
Converts an xywh bounding box to an xyxy bounding box.
Note that this is also different from the TensorFlow Object Detection API coords format.
Args:
api_bbox: bbox output by the batch processing API [x_min, y_min, width_of_box, height_of_box]
Re... |
def get_table_type(filename):
""" Accepted filenames:
device-<device_id>.csv,
user.csv,
session-<time_iso>.csv,
trials-<time_iso>-Block_<n>.csv
:param filename: name of uploaded file.
:type filename: str
:return: Name of table type.
:rtype: str|None
"""
basename, ext = f... |
def match_regexes(regexes, string):
"""
Given a string, determine if it matches any of a list of regular
expressions. Returns True if it does, False if it doesn't.
"""
match = [regex.search(string) for regex in regexes if regex.search(string)]
if match:
return True
else:
ret... |
def is_int(value):
"""
Try to parse the value to int.
Return True if can and False if cannot.
"""
try:
num = int(value)
except ValueError:
return False
return True |
def remove_duplicates(seq):
"""
Removes duplicates from a list.
This is the fastest solution, source:
http://www.peterbe.com/plog/uniqifiers-benchmark
Input arguments:
seq -- list from which we are removing duplicates
Output:
List without duplicates.
Example:
... |
def pl_true_int_repr(clause, model={}):
"""
Lightweight version of pl_true.
Argument clause represents the set of args of an Or clause. This is used
inside dpll_int_repr, it is not meant to be used directly.
>>> from sympy.logic.algorithms.dpll import pl_true_int_repr
>>> pl_true_int_repr(set([... |
def cleanup_packing_list(doc, parent_items):
"""Remove all those child items which are no longer present in main item table"""
delete_list = []
for d in doc.get("packed_items"):
if [d.parent_item, d.parent_detail_docname] not in parent_items:
# mark for deletion from doclist
delete_list.append(d)
if not de... |
def FindMid(list1):
"""integer division to find "mid" value of list or string"""
length = len(list1)
mid = length//2
return mid |
def list2string(lt, dy):
"""
:param list lt: list of nonnegative integers from some set {0,1,...,q-1}
:param dict dy: mapping from {0,1,...,q-1} to some alphabet symbols
:return: string of symbols corresponding to the integers in lt
:rtype: str"""
return "".join([dy[i] for i in lt]) |
def verify_data_fields(payload, data_fields):
"""This function checks a dictionary of data fields and values to ensure they match what is in the payload.
:param payload: The payload for a new board
:type payload: dict
:param data_fields: The data fields and corresponding values to check
:type data_... |
def reward_straight_track(params):
""" Determines if a track is going straight for the next x waypoints """
waypoints = params['waypoints']
closest_waypoints = params['closest_waypoints']
# Make sure we dont go out of bounds for our waypoints array
if closest_waypoints[1] + 1 < len(waypoints):
... |
def validate_package_name(name):
"""
Check if the given name is compliant to Keypirinha's package naming rules
and return a boolean.
**CAUTION:** this function should just serve an informational purpose as it
may not be up-to-date with current Keypirinha release.
"""
ascii_alnum = "... |
def repeat(f, x, n):
""" Repeat Function
>>> list(repeat(flatten, [1, 2, [3, [4]], 5], 2))
[1, 2, 3, 4, 5]
"""
if n == 0: return x
return repeat(f, f(x), n - 1) |
def gpu_requested(resources):
"""
Check whether the requested resources contains GPU.
Here resources is a dict like {"cpu": 1, "memory": 2,...}.
"""
if resources is None:
return False
if not isinstance(resources, dict):
raise TypeError("Parameter resources is required to be a dic... |
def hexColorToInt(rgb):
"""Convert rgb color string to STK integer color code."""
r = int(rgb[0:2],16)
g = int(rgb[2:4],16)
b = int(rgb[4:6],16)
color = format(b, '02X') + format(g, '02X') + format(r, '02X')
return int(color,16) |
def name_combine(prod_list):
"""breaking off names to combine them per instructions"""
names_list = [item[0] for item in prod_list]
return names_list |
def _compute_qset_filters(req_params, translation_dict):
"""
_compute_qset_filters translates the keys of req_params to the keys of translation_dict.
If the key isn't present in filters_dict, it is discarded.
"""
return {
translation_dict[rp]: req_params[rp]
for rp in filter(lambda ... |
def relative_points(points):
"""Convert point sequence in absolute coordinate to xdwapi-style."""
if len(points) < 2:
return points
p0 = points[0]
return tuple([p0] + [p - p0 for p in points[1:]]) |
def v6_multimax(iterable):
"""Return a list of all maximum values.
Bonus 2: Make the function works with lazy iterables.
Our current solutions fail this requirement because they loop through
our iterable twice and generators can only be looped over one time only.
We could keep track of the maximu... |
def fromOpt(object, default):
"""
Given an object, return it if not None. Otherwise return default
"""
return object if object is not None else default |
def array(string):
"""Converts string to a list, split on whitespace
:param:
string(str): The string to split
:return
string.split()(list): The string split into a list on the white space."""
return string.split() |
def sum_of_digits(number):
""" A function that takes an integer and
calculates the sum of n's digits """
summ = 0
p = 0
if number < 9:
return number
while number > 0:
p = number % 10
summ += p
number = number // 10
return summ |
def _get_value_simple(doc, key):
"""
Extracts a value from a nested set of dictionaries 'doc' based on
a 'key' string.
The key string is expected to be of the format 'x.y.z'
where each component in the string is a key in a dictionary separated
by '.' to denote the next key is in a nested diction... |
def _generate_size(number_bytes: int) -> str:
"""Convert count of bytest to human readable for with dimension"""
dimensions = ["B", "KiB", "Mib", "GiB", "TiB"]
current_dim = 0
size = float(number_bytes)
while size > 1024:
size /= 1024
current_dim += 1
return f"{size:.3f} {dimen... |
def strong(line):
""" Check if strong words exist, if exist, change them into html format
:param line: str, the line in markdown format
:return: str, the line in html format with strong style
"""
if line.count('**') >= 2:
for i in range(0, line.count('**') - line.count('**') % 2):
... |
def _conflict_update(x, y):
"""
Merge dictionaries x and y, check if conflict key-value pair exists, return
False if has conflict.
"""
for key, value in y.items():
ori_value = x.setdefault(key, value)
if ori_value != value:
return False
return True |
def check_subgraph(subgraph):
"""Check subgraph."""
if subgraph in ("all", "Default", "Gradients"):
return subgraph
raise ValueError("subgraph must be all or Default or Gradients, but got {}.".format(subgraph)) |
def gt(s,t):
"""Semantically equivalent to python's >"""
return (s > t) |
def _produce_axis(low, high, bins):
""" This method produces an array that represents the axis between low and
high with bins.
Args:
low (float): Low edge of the axis
high (float): High edge of the axis
bins (int): Number of bins
"""
return [low + x * (high - low) / bins for x in ... |
def preconvert_snowflake(snowflake, name):
"""
Converts the given `snowflake` to an acceptable value by the wrapper.
Parameters
----------
snowflake : `str` or `int`
The snowflake to convert.
name : `str`
The name of the snowflake.
Returns
-------
snowflake ... |
def calculate_profit(price_ago, current_price):
"""
Calculates the profit of a price regarding a previous one.
:param price_ago: First price.
:param current_price: Last price.
:return: Profit in percentage.
"""
profit = (current_price - price_ago) / float(price_ago) * 100
return ... |
def convertListOfSentenceTokensToListOfWords(matrix_of_tokens):
"""
Given a 2-D matrix of tokens with each 1-D list in the matrix representing a list of tokens of a single sentence,
this function converts it to a flattened 1-D representation of all the tokens in the matrix.
:param matrix_of_tokens: 2-D... |
def check_grades_list(unchecked_list, max_grade):
"""
This function checks that the given list contains elements with the
accepted format and rules.
:param unchecked_list: the list that is generated after parsing the given
file of grades or the list that is given directly as a string input by the
... |
def getMeshIndex(gltf, idname):
"""
Return the mesh index in the gltf array.
"""
if gltf.get('meshes') is None:
return -1
index = 0
for mesh in gltf['meshes']:
key = 'id' if mesh.get('id') != None else 'name'
if mesh.get(key) == idname:
return index
... |
def SplitPatch(data):
"""Splits a patch into separate pieces for each file.
Args:
data: A string containing the output of svn diff.
Returns:
A list of 2-tuple (filename, text) where text is the svn diff output
pertaining to filename.
"""
patches = []
filename = None
diff = []
for line in... |
def suck_out_formats(reporters):
"""Builds a dictionary mapping edition keys to their cite_format if any.
The dictionary takes the form of:
{
'T.C. Summary Opinion': '{reporter} {volume}-{page}',
'T.C. Memo.': '{reporter} {volume}-{page}'
...
}
In other ... |
def reverse_compliment(sequence):
"""
Given a sequence consists of A, T, C and G, find reverse compliment of the sequence.
"""
reference = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C', 'N': 'N'}
reversecompliment = ''.join(reference[x] for x in sequence[::-1])
return reversecompliment |
def time2mass(t, sf, k0):
"""
Here the time t is actually the number of channels.
To convert a real time to the number of channel t, you should divide the real time by the Time Resolution which can be obtained by pySPM.ITM.get_value("Registration.TimeResolution")
"""
return ((t-k0)/sf)**2 |
def plain_text_to_html(string):
"""Convert plain text to HTML markup."""
string = string.replace("&", "&")
return string |
def get_class_plural_name(cls):
"""Convert class name to it's plural form"""
base = cls.__name__.lower()
for ending in ('s', 'z', 'x', 'ch', 'sh'):
if base.endswith(ending):
return base + 'es'
if base.endswith('y'):
return base[:-1] + 'ies'
else:
return base + 's' |
def read_color(input_func):
"""
Reads input color and lower cases it
"""
user_supplied_color = input_func()
return user_supplied_color.casefold() |
def remove_strings(string, strings_to_remove):
"""Replace an iterable of strings in removables
if removables is a string, each character is removed """
for r in strings_to_remove:
try:
string = string.replace(r, "")
except TypeError:
raise TypeError("Strings_to_rem... |
def parse_results(f):
"""
returns a dict sending the property to the result string
input is a list of strings, one per line.
"""
d = {}
prop = None
for line in f:
line = line.strip()
if not line:
continue # skip empty lines
if prop is None:
pro... |
def get_all_non_none_parsed_value(parsed_values):
"""
Gets all the non-`None` parsed values.
Parameters
----------
parsed_values : `None`, `list` of `Any`
The parsed value.
Returns
-------
values : `None`, `Any`
The parsed value if any.
"""
values = []
i... |
def green(text):
""" Return this text formatted green """
return '\x0303%s\x03' % text |
def simulate_one(chain, state={}, config={}):
"""
Simulate a chain once
Args:
- chain: an iterable with functions of type
f(state, log) -> new_state
- state (default: {}): initial state to apply chain to
- config (default: {}): pass configuration parameters in a dictiona... |
def NORMAG(LX, X):
"""
NORMAG: NORmalizes an array by the magnitude of the element which is greates in MAGnitude.
p.23
"""
B = 0.0
for I in range(LX):
# print(B)
B = max(abs(X[I]), B)
for I in range(LX):
X[I] /= B
return X |
def _get_failure_context(result):
"""
Get the logging context from a failed slack call.
"""
ret = {}
for attr in ['error', 'needed', 'provided']:
if attr in result:
ret[attr] = result[attr]
return ret |
def change_gates(gates, qubits):
"""
Modifies the gates outputted from decompose_state so that they
apply to the qubits in the list qubits
Specifically, a gate applied to (i, j) will now apply to
(qubits[i], qubits[j]
"""
return [(gate, qubits[i], qubits[j]) if j is not None else
... |
def sort_query_ids_numerically(ids):
"""
Returns query ids in the format "R1_10" sorted
ascending by the numerical part of the id
(1 in this example).
"""
return sorted(
ids, key=lambda x: int(x.split("_")[0].lstrip("R"))) |
def is_package_in_package_list(package_name, package_list):
"""
:returns true if package_name exists in package_list
"""
package_found_in_list = False
for item in package_list:
versions = item["latest_versions"]
for version in versions:
file_name = version["file"]
... |
def format_bytes(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
Code from: https://www.thepythoncode.com/article/get-hardware-system-information-python
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
... |
def get_unused_options_ls(cfg_dict, options_ls):
"""
Returns the unused keys in a configuration dictionary. An unused key
is a key that is not seen in any *options_ls* item.
Parameters
----------
cfg_dict : dict
options_ls : list
list of :py:class:`~enrich2.plugins.options.Options` ... |
def _serialize_notes(notes):
"""Compile the notes dictionary into a string format.
Returns a multi-line string where each line corresponds to a key-value pair in the
format: '{key}: {value}'
"""
note_lines = [f"{key}: {value}" for key, value in notes.items()]
return "\n".join(note_lines) |
def db_error_needs_new_session(driver, code):
"""some errors justify a new database connection. In that case return true
mostly due to strange issues
added 1000 (open_cursors exceeded) after adding a test over dg4odbc
added 55524 (Too many recursive autonomous transactions for temporary
... |
def fuel_used(distance_km: float, litres_per_100km: float):
"""
Calculates the amount of fuel used for a given number of kilometers and fuel efficiency.
Args:
distance_km (float): Distance driven in km.
litres_per_100km (float): Fuel efficiency in litres per 100km.
Returns:
flo... |
def clean_domain(listing: dict) -> dict:
"""Extracts key listing details for API return.
Args:
listing (dict): Domain listing object
Returns:
dict: Address, property details, price & some ID info
"""
address = {
"displayable_address": listing.get("property_details", {}).get... |
def _GetDeviceIncrementalDir(package):
"""Returns the device path to put incremental files for the given package."""
return '/data/local/tmp/incremental-app-%s' % package |
def digits(number, base=10):
"""
Determines the number of digits of a number in a specific base.
Args:
number(int): An integer number represented in base 10.
base(int): The base to find the number of digits.
Returns:
Number of digits when represented in a particular ba... |
def non_empty_keys(data):
"""Strip out empty keys from a dict.
:param dict data: the dict to copy
:return:
"""
non_empty = {}
for (key, val) in data.items():
if isinstance(val, dict):
data = non_empty_keys(val)
if data:
non_empty[key] = data
... |
def parse_pubsub_numpat(command, res, **options):
"""
Result callback, handles different return types
switchable by the `aggregate` flag.
"""
aggregate = options.get('aggregate', True)
if not aggregate:
return res
numpat = 0
for node, node_numpat in res.items():
numpat +... |
def ee_bands_rgb(collection):
"""
Earth Engine rgb band names
"""
dic = {
'Sentinel2_TOA': ['B4','B3','B2'],
'Landsat7_SR': ['B3','B2','B1'],
'Landsat8_SR': ['B4', 'B3', 'B2'],
'CroplandDataLayers': ['landcover'],
'NationalLandCoverDatabase': ['impervious']
... |
def append_step_to_route(route_with_distance, distances, next_step):
"""Append step to route_with_distance and update distance."""
distance, route = route_with_distance
return (distance + distances[route[-1]][next_step],
route + [next_step]) |
def validate_ascii_domain(domain_str):
"""
Validates ASCII domain str is compliant
:param domain_str:
:return: True for Compliant, False for non-compliant.
"""
domain_chars = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.')
return set(domain_str).issubset(domain_char... |
def _get_contents_between(string, opener, closer):
"""
Get the contents of a string between two characters
"""
opener_location = string.index(opener)
closer_location = string.index(closer)
content = string[opener_location + 1:closer_location]
return content |
def compose_select(table, fields):
"""Compose select query string.
Arguments
---------
table : str
Real table name.
fields : str
List of table fields.
Returns
-------
str
Query string with real table name. However, it can contain placeholders
for query p... |
def INT_NPURE(am):
"""Gives the number of spherical functions for an angular momentum.
#define INT_NPURE(am) (2*(am)+1)
"""
return 2 * abs(am) + 1 |
def no_limits(nparams, npeaks):
"""
No limits on nparameters for npeaks.
"""
return [[(None, None)] * npeaks] * nparams |
def software_fibonacci(n):
""" A normal old Python function to return the Nth Fibonacci number. """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a |
def square_rect_unknoll(dx, dy, rect_x, rect_y, width, height):
"""Given a co-ordinate pair and a rectangle, reverses square_rect_knoll"""
return (dx + rect_x, dy + rect_y) |
def url_avatar(hashed, quality='full'):
"""Provides the full URL for a steam avatar.
Parameters
----------
hashed : str
The avatar hash.
quality : str, optional
The quality to use; may be any of:
- icon
- medium
- full
Returns
-------
... |
def floatStr(n, l):
"""
Return a string representing the number n in a maximum of l characters,
left-padded with spaces.
"""
s = str(n)
if len(s) == l:
return s
if len(s) < l:
s = " " * (l - len(s)) + s
return s
if len(s) > l:
i = s.find(".")
... |
def approx_first_derivative(fun, x, h):
"""
Function to approximate the first derivative through central differences
args:
fun (function): function that will be approximated
x (float): value where the function will be centered
h (float): finite step that will be taken... |
def egcd(a, b):
"""
Calculate the extended Euclidean algorithm. ax + by = gcd(a,b)
Args:
a (int): An integer.
b (int): Another integer.
Returns:
int: Greatest common denominator.
int: x coefficient of Bezout's identity.
int: y coefficient of Bezout's identity.
... |
def parse_txt(data):
"""Parse txt data, returns list of lines"""
return data.splitlines() |
def concat(text):
""" turns white space into underscore """
return str(text).replace(' ', '_') |
def create_search_context_from_results(results):
"""Converts SQL query results to dictionary for HTML template.
"""
search_results = {}
if results:
search_results['search_results'] = []
search_results['script_hits'] = len(results)
search_results['snippet_hits'] = 0
for result in results:
... |
def create_url(config):
"""Create github api url."""
return '{base_url}/repos/{repo_owner}/{repo_name}/issues'.format(**config) |
def list_to_streamdict(list):
"""creates a dictionary out of a list
assuming the list is written in kwarg, arg,...
the dictionary will be written as {kwarg:[arg], }"""
dictio = {}
for i in range(1,len(list),2):
list[i] = [list[i]]
print(list[i])
# print("List[1]", li... |
def to_camel_case(name):
"""Convert a name from snake_case to camelCase. Names that already are
camelCase remain the same.
"""
is_capital = False
name2 = ""
for c in name:
if c == "_" and name2:
is_capital = True
elif is_capital:
name2 += c.upper()
... |
def subsetdict(d, dkeys, default=0):
"""Subset of dictionary d: only the keys in dkeys. If you plan on omitting
keys, make sure you like the default."""
newd = {} # dirty variables!
for k in dkeys:
newd[k] = d.get(k, default)
return newd |
def __prepare_to_write_reg(t_res):
"""
Returns in order user's infomation for a registration.
:param t_res: dict, contains the info for a user registration
:return: tuple, ordered tuple with user's data
"""
return t_res['ter_id'], t_res['operation'], t_res['pin'], t_res['name'], t_res['surname... |
def getDate(timestamp):
"""
Extracts the date from a timestamp.
:param timestamp: The timestamp from which the date should be obtained. \t
:type timestamp: string \n
:returns: The date info of the timestamp. \t
:rtype: string \n
"""
return timestamp.split('T')[0] |
def get_nested_key(d: dict, key_path: str):
"""
Get a value from a dictionary using nested key names.
:param d: A dictionary
:param key_path: A path to a key. E.g., "environment.username"
:return: value in key_path
"""
keys = key_path.split('.')
d0 = d
while len(keys) > 1:
d0... |
def get_response_ids_submitdates(resp_meta, debug=False):
"""
Return a dict mapping response ids to submitdates.
response ids are of type int, submitdates of type str.
:param resp_meta: dict mapping response ids to a dict
with meta information,
cf. :func:`ge... |
def parse_class(class_path):
"""Attempts to import a class at the given path and return it."""
parts = class_path.split('.')
module = '.'.join(parts[:-1])
class_name = parts[-1]
if len(parts) < 2:
raise Exception(
'Invalid path "%s". Must be of the form "x.Y".' % class_path)
... |
def time_slice_zip(number_of_samples, samples_per_time_slice):
"""Create a zipped list of tuples for time slicing a numpy array
When dealing with large numpy arrays containing time series data, it is
often desirable to time slice the data on a fixed duration, such as one
minute. This function creates a... |
def func(x):
"""
>>> func(2)
32
>>> func(0)
1
>>> func(-1)
1.25
"""
return x**4 + 4**x |
def get_navigation_offsets(offset1, offset2, increment):
"""Calculate offsets for fetching lists of flights from MongoDB"""
offsets = {}
offsets['Next'] = {'top_offset': offset2 + increment, 'bottom_offset':
offset1 + increment}
offsets['Previous'] = {'top_offset': max(offset2 - increment, 0),
'bottom_offset... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.