content stringlengths 42 6.51k |
|---|
def std_float(number, num_decimals=2):
"""
Print a number to string with n digits after the decimal point
(default = 2)
"""
return "{0:.{1:}f}".format(float(number), num_decimals) |
def ensure_dir(file_path):
"""
Guarantees the existance on the directory given by the (relative) file_path
Args:
file_path (str): path of the directory to be created
Returns:
bool: True if the directory needed to be created, False if it existed already
"""
import os
directory... |
def convertTimeToTimeString(time):
"""
Convert a time (float) to string --- [hh:mm:ss.ssss]
"""
hours = int(time // (60 * 60))
if hours > 23 or hours < 0:
return ""
time -= hours * 60 * 60
minutes = int(time // 60)
time -= minutes * 60
seconds = time
timeStr = '[{:02d}:{:... |
def validate_spec(index, spec):
""" Validate the value for a parameter specialization.
This validator ensures that the value is hashable and not None.
Parameters
----------
index : int
The integer index of the parameter being specialized.
spec : object
The parameter specializa... |
def flatten(iterable, types=(tuple, list), initial=None):
"""Collapse nested iterables into one flat :class:`list`.
Args:
iterable:
Nested container.
types:
Type(s) to be collapsed. This argument is passed directly to
:func:`isinstance`.
initial:
... |
def torusF2(x,y,z,rin,rout):
"""Return the Torus surface function with the origin
tangent to the outer surface.
"""
return ((z+rin+rout)**2+y**2+x**2+rout**2-rin**2)**2 - \
4*rout**2*((z+rin+rout)**2+y**2) |
def find_outputs(graph):
"""Return a list of the different outputs"""
outputs = []
for node, value in graph.items():
if value['data']['title'] == 'Output':
outputs += [node]
return outputs |
def encode_string(s):
"""
Simple utility function to make sure a string is proper
to be used in a SQLite query
(different than posgtresql, no N to specify unicode)
EXAMPLE:
That's my boy! -> 'That''s my boy!'
"""
return "'" + s.replace("'", "''") + "'" |
def unsort_to_tensors(tensors, sorted_indices):
"""Get original tensors from sorted tensors.
Args:
tensor: sorted tensors.
sorted_indices: indices of sorted tensors.
Returns:
original tensors.
"""
return list(zip(*sorted(zip(sorted_indices, tensors))))[1] |
def fix_macro_int(lines, key, value):
"""
Fix lines to have new value for a given key
lines: array of strings
where key to be found
key: string
key
value: int
set to be for a given key
returns: bool
True on success, False otherwise
"""
l = -1
k = ... |
def plus_one(digits):
"""
Given a non-empty array of digits representing a non-negative integer,
plus one to the integer.
:param digits: list of digits of a non-negative integer,
:type digits: list[int]
:return: digits of operated integer
:rtype: list[int]
"""
result = []
carry ... |
def _strip_quotes(x):
"""Strip quotes from the channel name"""
return x.strip('"') |
def range_t(listp1, listc1, listc2, listp2, precision):
""" this function calculates the range of t
Keyword arguments:
listp1 -- Punkt 1
listc1 -- Punkt 2
listc2 -- Punkt 3
listp2 -- Punkt 4
precision -- Genauigkeit
"""
max_distance_1 = max(abs(listc1[0] - listp1[0]), abs(listc... |
def generate_sequencer_program(num_measurements, task, waveform_slot=0):
"""Generates sequencer code for a given task.
Arguments:
num_measurements (int): number of measurements per qubit
task (string): specifies the task the sequencer program will do
"dig_trigger_play_s... |
def cmp(a, b): # pragma: no cover
"""
Replacement for built-in function ``cmp`` that was removed in Python 3.
Note: Mainly used for comparison during sorting.
"""
if a is None and b is None:
return 0
elif a is None:
return -1
elif b is None:
return 1
return (a >... |
def parse_response(response):
"""
function to parse response and
return intent and its parameters
"""
result = response['result']
params = result.get('parameters')
intent = result['metadata'].get('intentName')
return intent, params |
def get_cluster_sizes(connections):
"""
Returns a dictionary mapping clusters of servers (given
by their naming scheme) and the number of connections in
that cluster.
"""
import re
expr = re.compile(r'.*\.shard\d+$')
clusters = {}
for conn in connections:
if not expr.match(co... |
def filter_dict_non_intersection_key_to_value(d1, d2):
"""
Filters recursively from dictionary (d1) all keys that do not appear in d2
"""
if isinstance(d1, list):
return [filter_dict_non_intersection_key_to_value(x, d2) for x in d1]
elif isinstance(d1, dict) and isinstance(d2, dict):
... |
def find_star_info(line, column):
""" For a given .STAR file line entry, extract the data at the given column index.
If the column does not exist (e.g. for a header line read in), return 'False'
"""
# break an input line into a list data type for column-by-column indexing
line_to_list = line.spl... |
def conj(z):
"""
Conjugate of a complex number.
.. math::
\\begin{align*}
(a + ib)^* &= a - ib\\\\
a, b &\\in \\mathbb{R}
\\end{align*}
Parameters
----------
z : :class:`numpy.cdouble`
The complex number to take the conjugate of.
Returns
--... |
def default_pylogger_config(name="ctl"):
"""
The defauly python logging setup to use when no `log` config
is provided via the ctl config file
"""
return {
"version": 1,
"formatters": {"default": {"format": "[%(asctime)s] %(message)s"}},
"handlers": {
"console": {
... |
def get_phrases(entities):
"""
Args:
entities (Iterable[Entity]):
Returns:
Set[Tuple[str]]
"""
return {entity.words for entity in entities} |
def get_frame_name(frame_index: int) -> str:
"""
Get frame name from frame index.
"""
return f"{frame_index:07d}.jpg" |
def mean(num_list):
"""
Calculate the mean/average of a list of numbers
Parameters
----------
num_list : list
The list to take the average of
Returns
-------
ret: float
The mean of a list
Examples
--------
>>> mean([1, 2, 3, 4, 5])
3.0
... |
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
return (list(name_or_flags), kwargs) |
def get_overlapping_timestamps(timestamps: list, starttime: int, endtime: int):
"""
Find the timestamps in the provided list of timestamps that fall between starttime/endtime. Return these timestamps
as a list. First timestamp in the list is always the nearest to the starttime without going over.
Par... |
def max_subsequent_sum(the_list):
"""
Function that returns the maximum sum of consecutive numbers in a list.
@param the_list: an array with integers
@return: maximum sum of consecutive numbers in the list
"""
memory = [0] * len(the_list)
memory[0] = the_list[0]
for i in range(1, len(the_list)):
memory[i]... |
def sanitize_data(value: str) -> str:
"""Returns given string with problematic removed"""
sanitizes = ["\\", "/", ":", "*", "?", "'", "<", ">", '"']
for i in sanitizes:
value = value.replace(i, "")
return value.replace("|", "-") |
def radixsort(lst):
""" Implementation of radix sort algorithm """
# number system
r = 10
maxLen = 11
for x in range(maxLen):
# initialize bins
bins = [[] for i in range(r + 9)]
for y in lst:
# more or equal zero
if y >= 0:
bins[int(y... |
def calc_even_parity(data, size=8):
"""Calc even parity bit of given data"""
parity = 0
for i in range(size):
parity = parity ^ ((data >> i) & 1)
return parity |
def clean_borough(row : str) -> str:
"""
Removes the trailing space afer some boroughs.
:param: row (str): row in the the Pandas series
:rvalue: string
:returns: removed trailing space from the row
"""
if row == 'Manhattan ':
return 'Manhattan'
elif row == 'Brooklyn ':
... |
def quote(string):
"""
Utility function to put quotes around var names in string.
"""
return'\'{}\''.format(string) |
def is_json_valid(json_data):
""" Check if the .json file contains valid syntax for a survey """
try:
if json_data is None:
return False
for channel_key in json_data:
if json_data[channel_key] is None:
return False
for question_key in json_data... |
def total_fluorescence_from_intensity(I_par, I_per):
"""
Calculate total fluorescence from crossed intensities.
"""
return I_par + 2 * I_per |
def group_modes(modes):
""" Groups consecutive transportation modes with same label, into one
Args:
modes (:obj:`list` of :obj:`dict`)
Returns:
:obj:`list` of :obj:`dict`
"""
if len(modes) > 0:
previous = modes[0]
grouped = []
for changep in modes[1:]:
... |
def first(iterable, default=None):
"""
Returns the first item or a default value
>>> first(x for x in [1, 2, 3] if x % 2 == 0)
2
>>> first((x for x in [1, 2, 3] if x > 42), -1)
-1
"""
return next(iter(iterable), default) |
def get_count_of_increased_sequent(measurements) -> int:
"""
Count how many sequent increases are in a list of measurements
Args:
measurements (List[int]): list of measurements
Returns:
int: number of sequent increases
"""
if len(measurements) < 2:
ra... |
def RestrictDict( aDict, restrictSet ):
"""Return a dict which has the mappings from the original dict only for keys in the given set"""
return dict( [ ( k, aDict[k] ) for k in frozenset( restrictSet ) & frozenset( aDict.keys() ) ] ) |
def prepare_wiki_content(content, indented=True):
"""
Set wiki page content
"""
if indented:
lines = content.split("\n")
content = " ".join(i + "\n" for i in lines)
return content |
def get_object_from_string(string):
"""
Given a string identifying an object (as returned by the get_class_string
method) load and return the actual object.
"""
import importlib
the_module, _, the_name = string.rpartition('.')
return getattr(importlib.import_module(the_module), the_nam... |
def create_abstract_insert(table_name, row_json, return_field=None):
"""Create an abstracted raw insert psql statement for inserting a single
row of data
:param table_name: String of a table_name
:param row_json: dictionary of ingestion data
:param return_field: String of the column name to RETURNI... |
def get_ibit(num: int, index: int, length: int = 1) -> int:
"""Returns a slice of a binary integer
Parameters
----------
num : int
The binary integer.
index : int
The index of the slice (start).
length : int
The length of the slice. The default is `1`.
Returns
-... |
def get_supported_pythons(classifiers):
"""Return min and max supported Python version from meta as tuples."""
PY_VER_CLASSIFIER = 'Programming Language :: Python :: '
vers = filter(lambda c: c.startswith(PY_VER_CLASSIFIER), classifiers)
vers = map(lambda c: c[len(PY_VER_CLASSIFIER):], vers)
vers = ... |
def filter_unique_config_flags(node_config_params):
"""filters out the always unique config params from configuration comparision"""
always_unique_conf = ['node_configuration', 'listen_address', \
'rpc_address', 'broadcast_rpc_address', \
'broadcast_address', \
'native_transp... |
def reverse_lookup(d, v):
"""
Reverse lookup all corresponding keys of a given value.
Return a lisy containing all the keys.
Raise and exception if the list is empty.
"""
l = []
for k in d:
if d[k] == v:
l.append(k)
if l == []:
raise ValueError
else:
... |
def valid_filename(filename:str) -> bool:
"""
Fungsi yang melakukan validasi filename, di mana filename harus berekstensi .ps atau .eps dan filename tidak boleh mengandung illegal characters.
"""
ILLEGAL_CHARACTERS = '<>:"/\\|?*'
# Menyimpan filename dalam bentuk upper sementara (hanya untuk pengece... |
def pipe_to_underscore(pipelist):
"""Converts an AFF pipe-seperated list to a CEDSCI underscore-seperated list"""
return pipelist.replace("|", "_") |
def get_comparative_word_freq(freqs):
"""
Returns a dictionary of the frequency of words counted relative to each other.
If frequency passed in is zero, returns zero
:param freqs: dictionary in the form {'word':overall_frequency}
:return: dictionary in the form {'word':relative_frequency}
>>> ... |
def indent(indentation: int, line: str) -> str:
"""
Add indentation to the line.
"""
return " " * indentation + line |
def get_lang(repo):
"""
Return name of output language folder
"""
if isinstance(repo["language"], str):
return repo["language"]
elif isinstance(repo["language"], list):
if repo["language"]:
return repo["language"][0]
return "Without language" |
def isIn(obj, objs):
"""
Checks if the object is in the list of objects safely.
"""
for o in objs:
if o is obj:
return True
try:
if o == obj:
return True
except Exception:
pass
return False |
def check_passthrough_query(params):
"""
returns True if params is:
{
"from": "passthrough",
"name": "query"
}
"""
for param in params:
if param['from'] == 'passthrough' and param['name'] == 'query':
return True
return False |
def compute_chi_squared(data):
"""
Calculate Chi-Squared value for a given byte array.
Keyword arguments:
data -- data bytes
"""
if len(data) == 0:
return 0
expected = float(len(data)) / 256.
observed = [0] * 256
for b in data:
observed[b] += 1
chi_squared = 0
... |
def center_text(baseline, text):
"""Return a string with the centered text over a baseline"""
gap = len(baseline) - (len(text) + 2)
a1 = int(gap / 2)
a2 = gap - a1
return '{} {} {}'.format(baseline[:a1], text, baseline[-a2:]) |
def get_config_list(log, config, key):
"""
Return value of a key in config
"""
if key not in config:
return None
list_config = config[key]
if not isinstance(list_config, list):
log.cl_error("field [%s] is not a list",
key)
return None
return list_... |
def get_device_type(uid):
"""
The top 16 bits of UID.
"""
return int(uid >> 72) |
def isSeason_(mmm, ismmm_=True):
"""
... if input string is a season named with 1st letters of composing
months ...
"""
mns = 'jfmamjjasond' * 2
n = mns.find(mmm.lower())
s4 = {'spring', 'summer', 'autumn', 'winter'}
if ismmm_:
return (1 < len(mmm) < 12 and n != -1)
els... |
def factI(n):
"""Assumes n an int > 0
Returns n!"""
result = 1
while n > 1:
result = result * n
n -= 1
return result |
def _bit_length(n):
"""Return the number of bits necessary to store the number in binary."""
try:
return n.bit_length()
except AttributeError: # pragma: no cover (Python 2.6 only)
import math
return int(math.log(n, 2)) + 1 |
def convert_system_name_for_file(system_name: str) -> str:
"""Convert ship name to match file name criteria"""
return system_name.replace(" ", "_").replace("*", "") |
def getOneHotEncodingFromValues(values):
"""Creates one hot mapping"""
# Literally creates an identity matrix at the moment.
# In the future, may switch this infrastructure to
# numpy vectorizer + numpy onehot encoding
oneHotArr = [[1 if j == i else 0 for j in range(len(values))]
fo... |
def is_class_name(class_name):
"""
Check if the given string is a python class.
The criteria to use is the convention that Python classes start with uppercase
:param class_name: The name of class candidate
:type class_name: str
:return: True whether the class_name is a python class otherwise Fa... |
def get_suffix(filename):
"""a.jpg -> jpg"""
pos = filename.rfind('.')
if pos == -1:
return ''
return filename[pos:] |
def parse_redlion(info):
"""
Manufacturer: Red Lion Controls
Model: MC6B
"""
infos = info.split('\n')
data = {}
for info in infos:
if ':' not in info:
continue
k, v = info.split(':', 1)
if '.' in k:
continue
data[k] = v.strip()
retu... |
def dialog(questions, answerfunc):
"""
Create a dialog made of:
- questions asked by a so-called "customer",
- and answers given by a so-called "owner".
Parameters:
-----------
- questions: strings iterable
- answerfunc: function
Return an answer (i.e.: a string) for each elemen... |
def suffix(day_of_month):
"""
Returns suffix for day of the month to make
dates look pretty for eventual plotting
"""
if day_of_month in [1,21,31]:
ending = 'st'
elif day_of_month in [2,22]:
ending = 'nd'
elif day_of_month in [3,23]:
ending = 'rd'
else:
... |
def _add(*dictionaries):
"""Returns a new `dict` that has all the entries of the given dictionaries.
If the same key is present in more than one of the input dictionaries, the
last of them in the argument list overrides any earlier ones.
This function is designed to take zero or one arguments as well as multi... |
def breakable_path(path):
"""Make a path breakable after path separators, and conversely, avoid
breaking at spaces.
"""
if not path:
return path
prefix = ''
if path.startswith('/'): # Avoid breaking after a leading /
prefix = '/'
path = path[1:]
return pr... |
def get_mode(filename):
"""Returns the mode of a file, which can be used to determine if a file
exists, if a file is a file or a directory.
"""
import os
try:
# Since this function runs remotely, it can't depend on other functions,
# so we can't call stat_mode.
return os.s... |
def inconsistent_typical_range_stations(stations):
"""Returns a list of stations that have inconsistent data given a list of station objects"""
# Create list of stations with inconsistent data
inconsistent_stations = []
for station in stations:
if not station.typical_range_consistent():
... |
def folder_name_func(dirpath, name_list):
"""
This function isolates the name of the folder from the directory path obtained from the initial input function (model_input_func).
This allows to name each model within the code based on the name of the directory.
Parameters
----------
dirpath ... |
def define_result(result: str, index: int) -> str:
"""
Rather than having the Team decode this, what if we just told it
whether it had a win, loss, or draw? Then it wouldn't matter how
we came to know this, we would just have to inform the team.
The less that the Team knows about how we determine th... |
def flatten_record_actions(a):
"""Flatten the records list generated from `record_actions`
Parameters
-----------
a : list
Attribute created by decorator `record_actions`
Returns
--------
out : dict
Dictionary of record, hopefully easier to read.
ke... |
def _by_weight_then_from_protocol_specificity(edge_1, edge_2):
""" Comparison function for graph edges.
Each edge is of the form (mro distance, adaptation offer).
Comparison is done by mro distance first, and by offer's from_protocol
issubclass next.
If two edges have the same mro distance, and t... |
def is_relative_url(url):
""" simple method to determine if a url is relative or absolute """
if url.startswith("#"):
return None
if url.find("://") > 0 or url.startswith("//"):
# either 'http(s)://...' or '//cdn...' and therefore absolute
return False
return True |
def daysinmonths(month):
"""
outputs number of days in a given month without leap
year days
"""
import numpy as np
temp = np.array([31,28,31,30,31,30,31,31,30,31,30,31])
return temp... |
def is_ascii(string):
"""Indicates whether a string contains only ASCII characters.
:param string: The string to be evaluated.
:type string: str
:rtype: bool
.. note::
As of Python 3.7, strings provide the ``isascii()`` method. See the discussions at:
https://stackoverflow.com/q/1... |
def get_label_from_strat_profile(num_populations, strat_profile, strat_labels):
"""Returns a human-readable label corresponding to the strategy profile.
E.g., for Rock-Paper-Scissors, strategies 0,1,2 have labels "R","P","S".
For strat_profile (1,2,0,1), this returns "(P,S,R,P)". If strat_profile is a
single s... |
def check_data_in_evidence(evid_dict, dict_unique_vals):
"""
Ensure variables you will condition on existed during traning.
"""
for k,v in evid_dict.items():
if v not in dict_unique_vals[k]:
return False
return True |
def box_at(row, col, width=3, height=3):
"""Return the box index of the field at (row, col)
Args:
row (int): The row of the field.
col (int): The column of the field.
width (int): The width of the sudoku.
height (int): The height of the sudoku.
Returns:
int: The ind... |
def _merge_dict(*d_li: dict) -> dict:
"""Merge dict.
Returns:
dict: Merged dict.
"""
result: dict = {}
for d in d_li:
result = {**result, **d}
return result |
def create_dico(item_list):
#{{{
"""
Create a dictionary of items from a list of list of items.
"""
assert type(item_list) is list
dico = {}
for items in item_list:
for item in items:
if item not in dico:
dico[item] = 1
else:
dico[i... |
def bprop_scalar_log(x, out, dout):
"""Backpropagator for `scalar_log`."""
return (dout / x,) |
def iob_ranges(tags):
"""
IOB -> Ranges
"""
ranges = []
def check_if_closing_range():
if i == len(tags)-1 or tags[i+1].split('-')[0] == 'O':
ranges.append((begin, i, type))
for i, tag in enumerate(tags):
if tag.split('-')[0] == 'O':
pass
elif ... |
def sanitize_string_to_filename(value):
"""
Best-effort attempt to remove blatantly poor characters from a string before turning into a filename.
Happily stolen from the internet, then modified.
http://stackoverflow.com/a/7406369
"""
keepcharacters = (' ', '.', '_', '-')
return "".join([c ... |
def SlaveBuildSet(master_buildbucket_id):
"""Compute the buildset id for all slaves of a master builder.
Args:
master_buildbucket_id: The buildbucket id of the master build.
Returns:
A string to use as a buildset for the slave builders, or None.
"""
if not master_buildbucket_id:
return None
r... |
def calculate_time(cents_per_kWh, wattage, dollar_amount):
""" Returns the time (in hours) that it would take to reach the monetary price (dollar_amount)
given the cost of energy usage (cents_per_kWh) and power (wattage) of a device using that energy.
"""
return 1 / (cents_per_kWh) * 1e5 * dollar_am... |
def get_max_vals(tree):
"""
Finds the max x and y values in the given tree and returns them.
"""
x_vals = [(i[0], i[2]) for i in tree]
x_vals = [item for sublist in x_vals for item in sublist]
y_vals = [(i[1], i[3]) for i in tree]
y_vals = [item for sublist in y_vals for item in sublist]
... |
def rotations(S):
"""
Returns all the rotations of a string
"""
L=list(S)
L2=list()
for i in range(0, len(L)):
L2.append(''.join(L[i:] + L[:i]))
return L2 |
def palindrome_number(x):
"""
Problem 5.9: Check if decimal integer
is palindrome
"""
if x < 0:
return False
elif x == 0:
return True
x_rep = str(x)
if len(x_rep) == 1:
return True
left = 0
right = len(x_rep) - 1
while left < right:
if x_rep... |
def combinationSum(candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
#Firstly we sort the candidates so we can keep track of our progression
candidates = sorted(candidates)
def backTrack(left, curre... |
def is_csr(r):
""" see if r is a csr """
if len(r) > 4:
return True
elif r[0] in ["m", "u", "d"]:
return True
elif r in ["frm", "fcsr", "vl", "satp"]:
return True
else:
return False |
def movable(column_name):
"""
Checks whether or not the passed column can be moved on the list.
@rtype: C{boolean}
"""
not_movable_columns = set(("Named", "Exit", "Authority", "Fast",
"Guard", "Stable", "Running", "Valid",
"V2Dir", "Plat... |
def _str_to_hex_num(in_str):
"""Turn a string into a hex number representation, little endian assumed (ie LSB is first, MSB is last)"""
return ''.join(x.encode('hex') for x in reversed(in_str)) |
def flip_rgb(rgb):
"""Reverse order of RGB hex string, prepend 'ff' for transparency.
Args:
rgb: RGB hex string (#E1C2D3)
Returns:
str: ABGR hex string (#ffd3c2e1).
"""
# because Google decided that colors in KML should be
# specified as ABGR instead of RGBA, we have to reverse ... |
def resolve_overlap(stem_start, stem_end, stemlength, loop_overlap, loop_test):
""" Function: resolve_overlap()
Purpose: Handle base pair overlap for core H-type pseudoknot.
Input: Pseudoknot stems and loop lengths.
Return: Updated pseudoknot stems ... |
def get_shadow_point(slash_k_b_list, measure_x, measure_y, target_x):
"""
get shadow point on a line from given point
"""
if slash_k_b_list:
slash_k = slash_k_b_list[0]
slash_b = slash_k_b_list[1]
x = (slash_k * (measure_y - slash_b) + measure_x) / (slash_k * slash_k + 1)
... |
def _get_runtime_from_image(image):
"""
Get corresponding runtime from the base-image parameter
"""
runtime = image[image.find("/") + 1 : image.find("-")]
return runtime |
def AddFieldToUpdateMask(field, patch_request):
"""Adds name of field to update mask."""
if patch_request is None:
return None
update_mask = patch_request.updateMask
if update_mask:
if update_mask.count(field) == 0:
patch_request.updateMask = update_mask + ',' + field
else:
patch_request.upd... |
def common_elem(start, stop, common, solution):
"""
Return the list of common elements between the sublists.
Parameters:
start -- integer
stop -- integer
common -- list of Decimal
solution -- list of Decimal
Return:
sub -- list of Decimal
"""
sub = [elem for elem in common[start:stop] if elem in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.