content stringlengths 42 6.51k |
|---|
def make_signal_header(label, dimension='uV', sample_rate=256,
physical_min=-200, physical_max=200, digital_min=-32768,
digital_max=32767, transducer='', prefiler=''):
"""
A convenience function that creates a signal header for a given signal.
This can be used t... |
def copyList(A):
"""
This function just copies a list. It was written before the original author
realized that the copy module had a deepcopy function.
Parameters
---------------------------------------------------------------------------
A: list
A list of values
Returns
-----... |
def train_params(max_episodes=1000,
max_steps_per_episode=1000,
stop_value=100,
avg_window=100,
render=False,
verbose=True,
save_agent=True,
save_file='checkpoint_dqn.pth'):
"""
Parameters
... |
def replace(param, index=None):
"""
Optionally used by the preload generator to wrap items in the preload
that need to be replaced by end users
:param param: parameter name
:param index: optional index (int or str) of the parameter
"""
if (param.endswith("_names") or param.endswith("_ips")) ... |
def nextpow2(i):
"""
Find 2^n that is equal to or greater than.
"""
n = 0
while (2**n) < i:
n += 1
return n |
def check_pem_files(keys_path):
"""Check *_public.pem and *_private.pem is exist."""
from pathlib import Path
pub_file = Path(keys_path + "_public.pem")
pri_file = Path(keys_path + "_private.pem")
return bool(pub_file.is_file() and pri_file.is_file()) |
def parse_cron_options(argstring):
"""
Parse periodic task options.
Obtains configuration value, returns dictionary.
Example::
my_periodic_task = 60; now=true
"""
parts = argstring.split(';')
options = {'interval': float(parts[0].strip())}
for part in parts[1:]:
name, ... |
def TSKVsPartGetStartSector(tsk_vs_part):
"""Retrieves the start sector of a TSK volume system part object.
Args:
tsk_vs_part (pytsk3.TSK_VS_PART_INFO): TSK volume system part information.
Returns:
int: start sector or None.
"""
# Note that because pytsk3.TSK_VS_PART_INFO does not explicitly defines... |
def _latency_label_customers(avg_latency, std_latency, recency):
"""Add a label to describe a customer's latency metric.
Args:
avg_latency (float): Average latency in days
std_latency (float): Standard deviation of latency in days
recency (float): Recency in days
Returns:
... |
def headers(auth_token=None):
"""
Generate an appropriate set of headers given an auth_token.
:param str auth_token: The auth_token or None.
:return: A dict of common headers.
"""
h = {'content-type': ['application/json'],
'accept': ['application/json']}
if auth_token is not None:... |
def ver_tuple_to_str(req_ver):
"""Converts a requirement version tuple into a version string."""
return ".".join(str(x) for x in req_ver) |
def fib_recursive(n):
""" return the n th fibonacci number recursive """
if n <= 2:
return 1
else:
return fib_recursive(n - 1) + fib_recursive(n - 2) |
def isnum(n):
""" Return True if n is a number, else False """
try:
y = n+1
return True
except:
return False |
def ext_valid_update_path(cursor, ext, current_version, version):
"""
Check to see if the installed extension version has a valid update
path to the given version. A version of 'latest' is always a valid path.
Return True if a valid path exists. Otherwise return False.
Args:
cursor (cursor) ... |
def mean(lst):
"""Return the average of a float list."""
length = len(lst)
return sum(lst)/float(length) if length != 0 else None |
def key_at_depth(dic, dpt):
""" From koffein
http://stackoverflow.com/questions/20425886/python-how-do-i-get-a-list-of-all-keys-in-a-dictionary-of-dictionaries-at-a-gi
"""
if dpt > 0:
return [key for subdic in dic.values() if isinstance(subdic,dict)
for key in key_a... |
def bfs(graph, start):
"""Visits all the nodes of a graph using BFS
Args:
graph (dict): Search space represented by a graph
start (str): Starting state
Returns:
explored (list): List of the explored nodes
"""
# list to keep track of all visited nodes
explored = []
... |
def GetChangePageUrl(host, change_number):
"""Given a gerrit host name and change number, return change page url."""
return 'https://%s/#/c/%d/' % (host, change_number) |
def _list_diff(a, b):
"""
Get the difference between two lists.
:param a: The first list.
:param b: The second list.
:return: A list of items that are in the first list but not in the second \
list.
"""
# Return the difference between two lists
return [x for x in a if x not in... |
def rfib2(n):
"""With functools.lru_cache"""
return rfib2(n - 1) + rfib2(n - 2) if n > 2 else 1 |
def bytechr(i):
"""Return bytestring of one character with ordinal i; 0 <= i < 256."""
if not 0 <= i < 256:
if not isinstance(i, int):
raise TypeError('an integer is required')
else:
raise ValueError('bytechr() arg not in range(256)')
return chr(i).encode('latin1') |
def _find_pk(pk, queryset):
"""Find a PK in a queryset in memory"""
found = None
try:
pk = int(pk)
found = next(obj for obj in queryset if obj.pk == pk)
except (ValueError, StopIteration):
pass
return found |
def IterWrapper(value):
""" Return an iterable for the value """
if type(value) is tuple:
return value
else:
return (value,) |
def get_int(string):
"""return the int value of a binary string"""
return int(string, 2) |
def split(value: str) -> list:
"""
Splits string and returns as list
:param value: required, string. bash command.
:returns: list. List of separated arguments.
"""
return value.split() |
def _set_gps_from_zone(kwargs, location, zone):
"""Set the see parameters from the zone parameters.
Async friendly.
"""
if zone is not None:
kwargs['gps'] = (
zone.attributes['latitude'],
zone.attributes['longitude'])
kwargs['gps_accuracy'] = zone.attributes['rad... |
def nick(raw_nick):
"""
Split nick into constituent parts.
Nicks with an ident are in the following format:
nick!ident@hostname
When they don't have an ident, they have a leading tilde instead:
~nick@hostname
"""
if '!' in raw_nick:
nick, _rest = raw_nick.split('!')
... |
def get_process_output(cmd_stdout, cmd_stderr):
"""Get task process log output."""
text = ''
if cmd_stdout:
text += cmd_stdout.decode(errors='ignore').replace('\r', '')
if cmd_stderr:
text += cmd_stderr.decode(errors='ignore').replace('\r', '')
return text.rstrip('\n\r') |
def queue_suffix_for_platform(platform):
"""Get the queue suffix for a platform."""
return '-' + platform.lower().replace('_', '-') |
def color565(r, g, b):
"""Convert red, green, blue components to a 16-bit 565 RGB value. Components
should be values 0 to 255.
"""
return ((r & 0xF0) << 8) | ((g & 0xFC) << 3) | (b >> 3) |
def validate_input(self,user_input):
"""check some edge cases"""
#check if len of input is equal to or less than amount of frames
#return if this is the case, no simulation needed here
#user must enter jobs before submitting
if(len(user_input) <= 0):
return -1
#user must ... |
def check_days_to_check(days_to_check: int):
"""
days_to_check has to be 0 or bigger.
"""
if days_to_check < 0:
return (False)
return (True) |
def get_last_version(documents):
"""
Helper function to get the last version of the list of documents provided.
:param documents: List of documents to check.
:type documents: [cla.models.model_interfaces.Document]
:return: 2-item tuple containing (major, minor) version number.
:rtype: tuple
... |
def long_to_bytes(val, expect_byte_count=None, endianness='big'):
"""
Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
convert ``val``, a :func:`long`, to a byte :func:`str`.
:param expect_byte_count:
:param long val: The value to pack
:param str endianness: The endianness of th... |
def return_union_item(item):
"""union of statements, next statement"""
return " __result.update({0})".format(item) |
def count_line_length(file_contents):
"""
The function count line length
Parameters
----------
file_contents : str
file contents
Returns
-------
: list[int]
list of line length
"""
return [len(line) for line in file_contents.splitlines()] |
def extract_property_class(prop):
"""
This function extracts the property class from the property string.
Property strings have the format of -([<function>.]<property_class_id>.<counter>)
"""
prop_class = prop["property"].rsplit(".", 3)
# Do nothing if prop_class is diff than cbmc's convention
... |
def with_previous_s1(iterable):
"""Provide each sequence item with item before it
Comments:
This is an improvement over the previous solution:
1. We are now keeping track of the previous item
2. We are avoiding indexes.
Solution passes 1 bonus
"""
prev = None... |
def get_attachment_path(problem_number):
"""
Given a problem number, return the path of the attachment file.
"""
import os
# hard-coded configs
attachment_dir = "attachments"
attachment_filenames = {
22: "p022_names.txt",
42: "p042_words.txt",
54: "p054_poker.txt",
... |
def find_unordered_cfg_lines(intended_cfg, actual_cfg):
"""Check if config lines are miss-ordered, i.e in ACL-s.
Args:
intended_cfg (str): Feature intended configuration.
actual_cfg: (str): Feature actual configuration.
Returns:
list: List of tuples with unordered_compliant cfg lin... |
def calculate_kinetic_energy(mass, velocity):
"""Returns kinetic energy of mass [kg] with velocity [ms]."""
return 0.5 * mass * velocity ** 2 |
def partition(array: list, low: int, high: int, pivot: int) -> int:
"""
>>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
>>> partition(array, 0, len(array), 12)
8
"""
i = low
j = high
while True:
while array[i] < pivot:
i += 1
j -= 1
... |
def reformat_for_export(parsed_note_data):
"""
Format a parsed note into an understandable
plain text version for later download
"""
export_string = "================================================================\n"
export_string += "Title: " + parsed_note_data["title"] + "\n"
export_strin... |
def format_3(value):
"""Round a number to 3 digits after the dot."""
return "{:.3f}".format(value) |
def format_image_bboxes(bboxes_on_image, class_dict, crop_size=512):
"""Convert ImageAug BoundingBoxOnImage object to YOLO fmt labels
Parameters
----------
bboxes_on_image: imgaug.imgaug.BoundingBoxexOnImage
ImgAug object containing all bboxes
class_dict: dict
Dictionary containing ... |
def id_is_int(patient_id):
""" Check if patient id is integer
Check if the patient's id is a integer
Args:
patient_id (int): id number of the patient
Returns:
True or str: indicate if the input patient id is an integer
"""
try:
int(patient_id)
return True
... |
def norm_aplha(alpha):
""" normalise alpha in range (0, 1)
:param float alpha:
:return float:
>>> norm_aplha(0.5)
0.5
>>> norm_aplha(255)
1.0
>>> norm_aplha(-1)
0
"""
alpha = alpha / 255. if alpha > 1. else alpha
alpha = 0 if alpha < 0. else alpha
alpha = 1. if alph... |
def try_divide(x, y, val=0.0):
"""
try to divide two numbers
"""
if y != 0.0:
val = float(x) / y
return val |
def rational_lcm(*args):
"""Least common multiple of rationals"""
# Handle the case that a list is provided
if len(args) == 1 and type(args[0]) is list:
return sum(*args[0])
return sum(args) |
def search_by_id(target_book_id = ""):
"""
this function takes in a book id and returns a list of possible matches
"""
# do nothing if no name given
if target_book_id == "":
# [] represents not found
return []
# open file and load file contents to an array
f = open("database... |
def euclid_alg (a, b):
""" Euclidean algorithm for gcd.
Finds the greatest common divisor of
two integers.
"""
a, b = abs(a), abs(b)
while b != 0:
r = a % b
a, b = b, r
return a |
def getItemNames(fullname):
"""Split a fullname in the 3 parts that compose it
Args:
fullname(str): Fullname
Returns:
tuple with the names of each item in the hierarchy or None
for the items that are not present
"""
n = fullname.split(':')
if len(n) == 1:
return... |
def single_line(line, report_errors=True, joiner='+'):
"""Force a string to be a single line with no carriage returns, and report
a warning if there was more than one line."""
lines = line.strip().splitlines()
if report_errors and len(lines) > 1:
print('multiline result:', lines)
return joiner... |
def longest_in_list( l:list ) ->str:
"""
Returns the longest item's string inside a list
"""
longest :str = ''
for i in range( len(l) ):
if len( str(l[i]) ) > len(longest):
longest = l[i]
return longest |
def item_empty_filter(d):
"""return a dict with only nonempty values"""
pairs = [(k, v) for (k, v) in d.items() if v]
return dict(pairs) |
def replace_at(string,old,new,indices):
"""Replace the substring "old" by "new" in a string at specific locations
only.
indices: starting indices of the occurences of "old" where to perform the
replacement
return value: string with replacements done"""
if len(indices) == 0: return string
ind... |
def twos_complement(dec):
"""
Convert decimal integer number to U2
:param dec: Number to change
:type dec: int
:return: Number in U2
:rtype: string
"""
if dec >= 0:
binint = "{0:b}".format(dec)
if binint[0] == "1": binint = "0" + binint
else:
dec2 = abs(dec ... |
def _label(label: str) -> str:
"""
Returns a query term matching a label.
Args:
label: The label the message must have applied.
Returns:
The query string.
"""
return f'label:{label}' |
def get_input_data(input_section):
"""
Gets playbook single input item - support simple and complex input.
:param input_section: playbook input item.
:return: The input default value(accessor) and the input source(root).
"""
default_value = input_section.get('value')
if isinstance(default_va... |
def reverse(x):
"""
:type x: int
:rtype: int
"""
lower = -(2 ** 31)
upper = (2 ** 31) - 1
if x < 0:
neg = True
else:
neg = False
x = abs(x)
answer = 0
while (x // 10) >= 0:
answer = (answer * 10) + x % 10
x //= 10
if x == 0:
... |
def split_component_view(arg):
"""
Split the input to data or subset.__getitem__ into its pieces.
Parameters
----------
arg
The input passed to ``data`` or ``subset.__getitem__``. Assumed to be
either a scalar or tuple
Returns
-------
selection
The Component sel... |
def stable_unique(items):
"""
Return a copy of ``items`` without duplicates. The order of other items is
unchanged.
>>> stable_unique([1,4,6,4,6,5,7])
[1, 4, 6, 5, 7]
"""
result = []
seen = set()
for item in items:
if item in seen:
continue
seen.add(... |
def _trim_pandas_styles(styles):
"""Trim pandas styles dict.
Parameters
----------
styles : dict
pandas.Styler translated styles.
"""
# Filter out empty styles, as every cell will have a class
# but the list of props may just be [['', '']].
return [x for x in styles if any(any(... |
def is_valid_aspect_target(target):
"""Returns whether the target has had the aspect run on it."""
return hasattr(target, "intellij_info") |
def force_iterator(mixed):
"""Sudo make me an iterator.
Deprecated?
:param mixed:
:return: Iterator, baby.
"""
if isinstance(mixed, str):
return [mixed]
try:
return iter(mixed)
except TypeError:
return [mixed] if mixed else [] |
def extract_types_from_response(response_data):
"""
This function extracts the list of types found by code_inspector from the response.
:param response_data json response from code_inspector
"""
types = []
software_info = {}
if "software_invocation" in response_data:
software_info = ... |
def macaddr_pack(data, bytes = bytes):
"""
Pack a MAC address
Format found in PGSQL src/backend/utils/adt/mac.c, and PGSQL Manual types
"""
# Accept all possible PGSQL Macaddr formats as in manual
# Oh for sscanf() as we could just copy PGSQL C in src/util/adt/mac.c
colon_parts = data.split(':')
dash_parts = d... |
def print_float(value): # sInt #string_float_value
"""int represented as a short float"""
value = "%f" % value
return value.rstrip('0') |
def coalesce(*args):
"""return first non-None arg or None if none"""
for arg in args:
if arg is not None:
return arg
return None |
def read_labels(labels_file):
"""
Returns a list of strings
Arguments:
labels_file -- path to a .txt file
"""
if not labels_file:
print('WARNING: No labels file provided. Results will be difficult to interpret.')
return None
labels = []
with open(labels_file) as infile:... |
def get_available_resources(threshold, usage, total):
""" Get a map of the available resource capacity.
:param threshold: A threshold on the maximum allowed resource usage.
:type threshold: float,>=0
:param usage: A map of hosts to the resource usage.
:type usage: dict(str: number)
:param t... |
def length_vector_sqrd(vector):
"""Compute the squared length of a vector.
Parameters
----------
vector : list
XYZ components of the vector.
Returns
-------
float
The squared length.
Examples
--------
>>> length_vector_sqrd([1.0, 1.0, 0.0])
2.0
"""
... |
def superpack_name(pyver, numver):
"""Return the filename of the superpack installer."""
return 'numpy-%s-win32-superpack-python%s.exe' % (numver, pyver) |
def _coord(x):
"""String representation for coordinate"""
return ("%.4f" % x).rstrip("0").rstrip(".") |
def verifica_participante(s):
"""
"""
return "Participants" in s |
def sign_to_int(signs):
"""
Convert a list to an integer.
[-1, 1, 1, -1], -> 0b0110 -> 6
"""
return int("".join('0' if x == -1 else '1' for x in signs),2) |
def det2(a, b, c, d):
"""Determinant of 2x2 matrix"""
return a * d - b * c |
def name_spin_sym(nElec: int) -> str:
"""Finds the suitable name (or more general: string representation) for the given amount of unpaired
electrons. For instance 2 unpaired electrons represent a "Triplet"."""
names = ["Singlet", "Doublet", "Triplet", "Quartet",
"Quintet", "Sextet", "Septet", "... |
def client_registration_supported_to_gui(config_file_dict,
config_gui_structure):
"""
Converts a required information from config file to a config GUI structure
:param config_gui_structure: Data structure used to hold and show
configuration information in the Gui... |
def get_color(val, trendType):
"""Determine if evolution is positive or negative.
From trend type - determined in config.toml for each KPIs,
picking right color to return
"""
if(val > 0):
if(trendType == 'normal'):
color = 'red'
else:
color = 'green'
elif... |
def _pf1c(val1, val2):
"""
Returns
-------
Description for the return statement
"""
return int(val1 + int(val2[0])) |
def LineRamp(t, duration, Initial, Final):
"""Creates a linear ramp from A to B"""
f = t / duration
return (1 - f) * Initial + f * Final |
def parse_dimension(string):
"""Parses a dimension string to a tuple (key, value, expiration_secs)."""
key, value = string.split(':', 1)
expiration_secs = 0
try:
expiration_secs = int(key)
except ValueError:
pass
else:
key, value = value.split(':', 1)
return key, value, expiration_secs |
def sanitize_field(value):
"""Clean field used in the payment request form
:param string value:
:return: A sanitized value
Adyen suggest to remove all new-line, so we do.
"""
if value is None:
return value
return str(value).replace('\n', ' ').replace('\r', ' ').strip() |
def lettergrade(value):
"""
Maps grade point average to letter grade.
"""
if value > 3.85:
return 'A'
elif value > 3.5:
return 'A-'
elif value > 3.15:
return 'B+'
elif value > 2.85:
return 'B'
elif value > 2.5:
return 'B-'
elif value > 2.15:
... |
def trapped_rainwater(arr_tank):
"""
The elements of the array are heights of walls.
If it rains, how much rain water will be trapped?
I will answer this question for any array you give me.
"""
prev_ht = arr_tank[0]
drops = []
goingdown=True
area = 0
for ht in arr_tank[1:]:
... |
def score_discrete(tabcode_a, tabcode_b):
"""
Return the tableau matching score between the two tableaux entries
tabcode_a amd tabcode_b, as per Kamat et al (2008) (s5.1).
This score is 2 if the tableau entries are equal, 1 if they are equal
in only one position, else -2.
"""
if tabcode_a[0]... |
def mean(x: list) -> float:
"""given x can be an array or list output is the mean value"""
mean_x = sum(x)/len(x)
return mean_x |
def reverseStrA(s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
if len(s) <=k:
return s[::-1]
elif k<=len(s)<2*k:
return s[:k][::-1]+s[k:]
else:
result=""
start=0
value=len(s) % (2 * k)
if value != 0:
s+=" "*(2*k-value)
for i in range(2*k-1,len(s),2*k):
string=s[start:i+1]
substring=... |
def _get_keys(response):
"""
return lists of strings that are the keys from a client.list_objects() response
"""
keys = []
if 'Contents' in response:
objects_list = response['Contents']
keys = [obj['Key'] for obj in objects_list]
return keys |
def extract(predicate, iterable):
"""Separates the wheat from the shaft (`predicate` defines what's the wheat), and returns both.
"""
wheat = []
shaft = []
for item in iterable:
if predicate(item):
wheat.append(item)
else:
shaft.append(item)
return wheat, ... |
def get_horizontal_radius(res):
"""Returns half the width of the input rectangle."""
return round(res[0] / 2) |
def get_aa_using_name_gct(gct=None, aa=None):
"""
This function returns a dictionary object containing
:param gct: dictionary object containing gc table data.
:param aa: amino acid notation/ name (String) e.g. Full name e.g. Alanine or
3-letter notation e.g. Ala or single letter notation e.g. A
... |
def sinal(u):
""" Retorna a classe baseada no valor de u. """
return 1 if u >= 0 else -1 |
def sol(a, b):
"""
Take an XOR, so 1 will be set whereever there is bit diff.
Keep doing AND with the number to check if the last bit is set
"""
c = a^b
count=0
while c:
if c&1:
count+=1
c=c>>1
return count |
def RPL_UNIQOPIS(sender, receipient, message):
""" Reply Code 325 """
return "<" + sender + ">: " + message |
def poisson_lambda_mle(d):
"""
Computes the Maximum Likelihood Estimate for a given 1D training
dataset from a Poisson distribution.
"""
return sum(d) / len(d) |
def vis444(n):
"""
O OO OOO OOOO
O O O
O O
O
"""
result = ''
for i in range(n):
result = 'O' + 'O' * (n - 1)
result += '\nO' * (n - 1)
return result |
def limit_lines(lines, N=32):
""" When number of lines > 2*N, reduce to N.
"""
if len(lines) > 2 * N:
lines = [b"... showing only last few lines ..."] + lines[-N:]
return lines |
def place_equiv(y, y_hat):
"""
Checks if two cvs have equivalent place.
"""
if ((y%19 in [0, 2, 10, 1, 11, 6, 3, 17]) and
(y_hat%19 in [0, 2, 10, 1, 11, 6, 3, 17])):
if (y%19 in [0, 2, 10]) and (y_hat%19 in [0, 2, 10]):
# b, f, r
return True
elif (y%19 in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.