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 = file_path
created=False
if not os.path.exists(directory):
os.makedirs(directory)
created=True
return created
|
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}:{:02d}:{:07.4f}]'.format(hours, minutes, seconds)
return timeStr
|
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 specialization.
Returns
-------
result : object
The validated specialization object.
"""
if spec is None:
msg = "cannot specialize template parameter %d with None"
raise TypeError(msg % index)
try:
hash(spec)
except TypeError:
msg = "template parameter %d has unhashable type: '%s'"
raise TypeError(msg % (index, type(spec).__name__))
return spec
|
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:
A pre-existing :class:`list` to append to. An empty list is created
if one is not supplied.
Returns:
list: The flattened output.
::
>>> flatten([[1, 2], 3, [4, [5]]])
[1, 2, 3, 4, 5]
>>> flatten(1.0)
[1.0]
>>> flatten([(1, 2), 3, (4, 5)])
[1, 2, 3, 4, 5]
>>> flatten([(1, 2), 3, (4, 5)], types=list)
[(1, 2), 3, (4, 5)]
>>> flatten([(1, 2), 3, (4, 5)], initial=[6, 7])
[6, 7, 1, 2, 3, 4, 5]
"""
if initial is None:
initial = []
if isinstance(iterable, types):
for i in iterable:
flatten(i, types, initial)
else:
initial.append(iterable)
return 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 = 0
for line in lines:
if key in line:
l = k
break
k += 1
if l >= 0:
s = lines[l].split(' ')
lines[l] = s[0] + " " + str(value) + "\n"
return True
return False
|
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 = 1
for i in range(len(digits) - 1, -1, -1):
result.append((digits[i] + carry) % 10)
carry = (digits[i] + carry) // 10
if carry:
result.append(1)
return list(reversed(result))
|
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(listc1[1]-listp1[1]))
max_distance_2 = max(abs(listc2[0] - listc1[0]), abs(listc2[1]-listc1[1]))
max_distance_3 = max(abs(listp2[0] - listc2[0]), abs(listp2[1]-listc2[1]))
max_distance = max(max_distance_1, max_distance_2, max_distance_3)
t_precision = precision/max_distance
list_t = []
tvar = 0.0
while tvar < 1.0:
list_t.append(tvar)
tvar += t_precision
list_t.append(1)
return list_t
|
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_single": trigger a single waveform via dig trigger
"zsync_trigger_play_single": trigger a single waveform via zsync
"dig_trigger_play_all": trigger all waveforms via dig trigger
"zsync_trigger_play_all": trigger all waveforms via zsync
waveform_slot (optional int): waveform slot to be played
Returns:
sequencer_program (string): sequencer program to be uploaded to the SHF
"""
if task.lower() == "dig_trigger_play_single":
return f"""
repeat({num_measurements}) {{
waitDigTrigger(1);
startQA(QA_GEN_{waveform_slot}, 0x0, true, 0, 0x0);
}}
"""
if task.lower() == "zsync_trigger_play_single":
return f"""
repeat({num_measurements}) {{
waitZSyncTrigger();
startQA(QA_GEN_{waveform_slot}, 0x0, true, 0, 0x0);
}}
"""
if task.lower() == "dig_trigger_play_all":
return f"""
repeat({num_measurements}) {{
waitDigTrigger(1);
startQA(QA_GEN_ALL, QA_INT_ALL, true, 0, 0x0);
}}
"""
if task.lower() == "zsync_trigger_play_all":
return f"""
repeat({num_measurements}) {{
waitZSyncTrigger();
startQA(QA_GEN_ALL, QA_INT_ALL, true, 0, 0x0);
}}
"""
raise ValueError(
f"Unsupported task: {task.lower()}. Please refer to the docstring for "
f"more information on valid inputs."
)
|
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 > b) - (a < b)
|
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(conn):
continue
cluster = conn.split('.shard', 1)[0]
if cluster not in clusters:
clusters[cluster] = 1
else:
clusters[cluster] += 1
return clusters
|
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):
d2values = list(d2.values())
return dict((k, v) for k, v in list(d1.items()) if k in d2values)
return d1
|
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.split()
try:
column_value = line_to_list[column-1]
return column_value
except:
return False
|
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
-------
cz : :class:`numpy.cdouble`
The conjugate of z.
"""
return (z.real - 1j*z.imag)
|
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": {
"level": "INFO",
"class": "logging.StreamHandler",
"formatter": "default",
"stream": "ext://sys.stdout",
}
},
"loggers": {
name: {"level": "INFO", "handlers": ["console"]},
"usage": {"level": "INFO", "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
"""
# Check that user passes list
if not isinstance(num_list, list):
raise TypeError("Input must be type list")
# Check that the list has length
if len(num_list) == 0:
raise ZeroDivisionError("Cannot calculate mean of empty list")
try:
ret = float(sum(num_list))/len(num_list)
except TypeError:
raise TypeError("Values of list must be int or float")
return ret
|
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.
Parameters
----------
timestamps
list of timestamps we want to pull from, to get the timestamps between starttime and endtime
starttime
integer utc timestamp in seconds
endtime
integer utc timestamp in seconds
Returns
-------
list
list of timestamps that are within the starttime/endtime range
"""
final_timestamps = []
# we require a starting time stamp that is either less than the given starttime or no greater than
# the given starttime by 60 seconds
buffer = 60
starting_timestamp = None
for tstmp in timestamps: # first pass, find the nearest timestamp (to starttime) without going over the starttime
if tstmp < starttime + buffer:
if not starting_timestamp:
starting_timestamp = tstmp
elif (tstmp > starting_timestamp) and (tstmp <= starttime):
starting_timestamp = tstmp
if starting_timestamp is None:
# raise ValueError('VesselFile: Found no overlapping timestamps for range {} -> {}, within the available timestamps: {}'.format(starttime, endtime, timestamps))
return final_timestamps
starttime = starting_timestamp
final_timestamps.append(str(starttime))
for tstmp in timestamps: # second pass, append all timestamps that are between the starting timestamp and endtime
if (tstmp > starttime) and (tstmp <= endtime):
final_timestamps.append(str(tstmp))
return final_timestamps
|
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] = max(the_list[i], the_list[i] + memory[i-1])
print(memory)
return max(memory)
|
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 / 10 ** x) % r + 9].append(y)
else:
# otherwise
bins[int(y / 10 ** x) % r].append(y)
lst = []
# apply bins to list
for section in bins:
lst.extend(section)
return lst
|
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 ':
return 'Brooklyn'
else:
return row
|
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[channel_key]:
if json_data[channel_key][question_key] is None:
return False
if json_data[channel_key][question_key]['question'] is None:
return False
if json_data[channel_key][question_key]['answers'] is None:
return False
for answer in json_data[channel_key][question_key]['answers']:
if answer['answer'] is None:
return False
if answer['votes'] is None:
return False
return True
except (TypeError, KeyError):
return False
|
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:]:
if changep['label'] != previous['label']:
previous['to'] = changep['from']
grouped.append(previous)
previous = changep
previous['to'] = modes[-1]['to']
grouped.append(previous)
return grouped
else:
return modes
|
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:
raise ValueError("List contains less than 2 values to compare")
count_of_increased_sequent = 0
for i in range(len(measurements)-1):
if int(measurements[i+1]) > int(measurements[i]):
count_of_increased_sequent += 1
return count_of_increased_sequent
|
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_name)
|
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 RETURNING in statement
:return: String of an insert statement
"""
columns = []
for key, value in row_json.items():
if key in columns:
continue
else:
columns.append(key)
values = [':' + item for item in columns]
values = ', '.join(map(str, values))
list_columns = ', '.join(map(str, columns))
if return_field is not None:
statement = 'INSERT INTO ' + str(table_name) + '(' + list_columns + ')' \
+ ' VALUES (' + values + ') RETURNING ' + str(return_field)
else:
statement = 'INSERT INTO ' + str(table_name) + '(' + list_columns + ')' \
+ ' VALUES (' + values + ')'
return statement
|
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
-------
ibit : int
The bit-slice of the original integer
Examples
--------
>>> get_ibit(0, 0) # binary: 0000
0
>>> get_ibit(7, 0) # binary: 0111
1
>>> get_ibit(7, 1) # binary: 0111
1
>>> get_ibit(7, 3) # binary: 0111
0
>>> get_ibit(7, 0, length=2) # binary: 0111
3
"""
mask = 2**length - 1
return (num >> index) & mask
|
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 = filter(lambda c: c[0].isdigit() and '.' in c, vers)
vers = map(lambda c: tuple(c.split('.')), vers)
vers = sorted(vers)
del vers[1:-1]
return 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_transport_address', \
'native_transport_broadcast_address', \
'system_info_encryption', 'data_file_directories', \
'audit_logging_options', 'transparent_data_encryption_options', \
'initial_token', \
]
return {x: y for (x, y) in node_config_params.items() if x not in always_unique_conf}
|
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:
return l
|
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 pengecekan)
filename_upper = filename.upper()
# Validasi: cek ekstensi (harus .eps atau .ps)
if not (filename_upper.endswith(".EPS") or filename_upper.endswith(".PS")):
return False
# Validasi: check illegal characters dalam filename
filename_filter = [character for character in filename_upper if character in ILLEGAL_CHARACTERS]
if filename_filter != []:
return False
# Ketika filename sudah benar return True
return True
|
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}
>>> from gender_analysis import document
>>> from pathlib import Path
>>> from gender_analysis import common
>>> document_metadata = {'filename': 'hawthorne_scarlet.txt',
... 'filepath': Path(common.TEST_DATA_PATH, 'sample_novels', 'texts', 'hawthorne_scarlet.txt')}
>>> scarlet = document.Document(document_metadata)
>>> d = {'he':scarlet.get_word_freq('he'), 'she':scarlet.get_word_freq('she')}
>>> d
{'he': 0.007099649057997783, 'she': 0.005702807536017732}
>>> x = get_comparative_word_freq(d)
>>> x
{'he': 0.5545536519386836, 'she': 0.44544634806131655}
>>> d2 = {'he': 0, 'she': 0}
>>> d2
{'he': 0, 'she': 0}
"""
total_freq = sum(freqs.values())
comp_freqs = {}
for k, v in freqs.items():
try:
freq = v / total_freq
except ZeroDivisionError:
freq = 0
comp_freqs[k] = freq
return comp_freqs
|
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
for o in observed:
chi_squared += (o - expected) ** 2 / expected
return chi_squared
|
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_config
|
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)
else:
return (1 < len(mmm) < 12 and n != -1) or mmm.lower() in s4
|
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))]
for i in range(len(values))]
return oneHotArr
|
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 False
"""
return class_name.capitalize()[0] == class_name[0]
|
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()
return data
|
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 element of
`questions`.
"""
text = []
for question in questions:
text.append("Customer: " + question)
text.append("Owner: " + answerfunc(question))
text.append("Customer: <Kill the owner.>")
return '\n'.join(text)
|
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:
ending = 'th'
return ending
|
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 multiple
dictionaries, so that it follows arithmetic identities and callers can avoid
special cases for their inputs: the sum of zero dictionaries is the empty
dictionary, and the sum of a single dictionary is a copy of itself.
Args:
*dictionaries: Zero or more dictionaries to be added.
Returns:
A new `dict` that has all the entries of the given dictionaries.
"""
result = {}
for d in dictionaries:
result.update(d)
return result
|
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 prefix + path.replace('/', u'/\u200b').replace('\\', u'\\\u200b') \
.replace(' ', u'\u00a0')
|
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.stat(filename)[0]
except OSError:
return 0
|
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():
inconsistent_stations.append(station.name)
return inconsistent_stations
|
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 : str
full path of the directory
name_list : list
list of folder names obtained from model_input_func to compare that the obtained directory name is correct
Returns
-------
name : str
name of the isolated folder (used as a model name in this case)
"""
#Isolates the folder name from one end of the path.
half_name = dirpath[dirpath.index(r"\\")+2:]
#Removes the slashes to isolate only the folder name.
full_name = half_name.split("\\")[0]
#Check if the name matches the names in the name list.
for name in name_list:
if name == full_name:
return name
|
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 the match results,
the less likely it will be that the Team will need to be modified if
we modify how we represent match results.
:param result: Game Outcome
:param index: Team Index
:return:
"""
# remove spaces and convert chars to lower case
result = result.strip().lower()
possible_results = ('win', 'loss', 'draw')
if result not in possible_results:
raise ValueError("ERROR: this is invalid game outcome: {}".format(result))
if result == 'win' and index == 0:
return possible_results[0]
elif result == 'win' and index == 1:
return possible_results[1]
elif result == 'loss' and index == 0:
return possible_results[1]
elif result == 'loss' and index == 1:
return possible_results[0]
else:
return possible_results[2]
|
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.
key is now 'number.funcname.argument'
"""
newdict = {}
for i, ai in enumerate(a):
funcname = ai[0]
adict = ai[1]
# Record data even if method has no arguments.
if len(adict) == 0:
newkey = '%s.%s.' % (i, funcname)
newdict[newkey] = None
# Record all arguments of method
for k, v in adict.items():
newkey = '%s.%s.%s' % (i, funcname, k)
newdict[newkey] = v
return newdict
|
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 the from_protocols of the
two edges are not subclasses of one another, they are considered "equal".
"""
# edge_1 and edge_2 are edges, of the form (mro_distance, offer)
mro_distance_1, offer_1 = edge_1
mro_distance_2, offer_2 = edge_2
# First, compare the MRO distance.
if mro_distance_1 < mro_distance_2:
return -1
elif mro_distance_1 > mro_distance_2:
return 1
# The distance is equal, prefer more specific 'from_protocol's
if offer_1.from_protocol is offer_2.from_protocol:
return 0
if issubclass(offer_1.from_protocol, offer_2.from_protocol):
return -1
elif issubclass(offer_2.from_protocol, offer_1.from_protocol):
return 1
return 0
|
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[month-1]
|
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/196345/241720
"""
try:
string.encode('ascii')
except UnicodeEncodeError:
return False
else:
return True
|
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 strategy (e.g., 0) this returns just its label (e.g., "R").
Args:
num_populations: Number of populations.
strat_profile: Strategy profile of interest.
strat_labels: Strategy labels.
Returns:
Human-readable label string.
"""
if num_populations == 1:
return strat_labels[strat_profile]
else:
label = "("
for i_population, i_strat in enumerate(strat_profile):
label += strat_labels[i_population][i_strat]
if i_population < len(strat_profile) - 1:
label += ","
label += ")"
return label
|
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 index of the box, in which the field (row, col) lies.
"""
return col // width + row - (row % height)
|
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[item] += 1
return dico
|
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 tag.split('-')[0] == 'B':
begin = i
type = tag.split('-')[1]
check_if_closing_range()
elif tag.split('-')[0] == 'I':
check_if_closing_range()
return ranges
|
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 for c in value if c.isalnum() or c in keepcharacters]).rstrip()
|
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
return 'cros/master_buildbucket_id/%s' % master_buildbucket_id
|
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_amount / wattage
|
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]
return max(x_vals), max(y_vals)
|
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[left] != x_rep[right]:
return False
left += 1
right -= 1
return True
|
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, current, results):
#Our base case is when nothing is left, in which case we add the current solution to the results
if not left:
results += [current]
return
#Now we address all candidates
for number in candidates:
#If the number is greater than whats left over, we can break this loop, and in turn the recursio
if number > left: break
#This (along with the sorted candidates) ensures uniqueness because if the number we're at is less than the last number in the curent solution, we can skip it over
if current and number < current[-1]: continue
#In the case that this number is smaller than whats left over, we continue backtracking
backTrack(left - number, current + [number], results)
#We can return results in the higest function call
return results
return backTrack(target, [], [])
|
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", "Platform", "Hibernating"))
if column_name in not_movable_columns:
return False;
else:
return True;
|
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 the
# sense of our color.
# so given #E1C2D3, (red E1, green C2, blue D3) convert to #ffd3c2e1
# where the first hex pair is transparency and the others are in
# reverse order.
abgr = rgb.replace("#", "")
abgr = "#FF" + abgr[4:6] + abgr[2:4] + abgr[0:2]
abgr = abgr.lower()
return abgr
|
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 and loop lengths.
"""
# Case that base pair overlap of 1 bp occurs at loop
if loop_overlap == -1 and stemlength >= 4 and loop_test >= 0:
stemlength = stemlength - 1 # Cut stem if possible
loop_overlap = loop_overlap + 1
loop_test = loop_test + 1
stem_shortended = stem_start, stem_end, stemlength
# Case that base pair overlap of 2 bp occurs at loop
elif loop_overlap == -2 and stemlength >= 5 and loop_test >= -1:
stemlength = stemlength - 2 # Cut stem if possible
loop_overlap = loop_overlap + 2
loop_test = loop_test + 2
stem_shortended = stem_start, stem_end, stemlength
else:
stem_shortended = None
return stem_shortended, loop_overlap, loop_test
|
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)
y = slash_k * x + slash_b
else:
x = target_x
y = measure_y
return x, y
|
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.updateMask = field
return patch_request
|
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 solution[start:stop]]
return sub
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.