content stringlengths 42 6.51k |
|---|
def vis10(n): # DONE
"""
O OO OOO
O OO
Number of Os:
1 3 5"""
result = 'O' * n + '\n'
result += 'O' * (n - 1) + '\n'
return result |
def str2val(val, na="na", list_detection=False):
"""guess type (int, float) of value.
If `val` is neither int nor float, the value
itself is returned.
"""
if val is None:
return val
def _convert(v):
try:
x = int(v)
except ValueError:
try:
... |
def get_types(type2freq_1, type2score_1, type2freq_2, type2score_2):
"""
Returns the common "vocabulary" between the types of both systems and
the types in the dictionaries
Parameters
----------
type2freq: dict
Keys are types and values are frequencies
type2score: dict
Keys ... |
def _add_row_index(columns, rows, indices):
"""
Add row indices as the first column to the columns and rows data.
:param columns: List of the column names, maintains the display order.
:type columns: ``list`` of ``str``
:param rows: List of lists containing row data.
:type rows: ``list`` of ``l... |
def cmp(a, b):
"""
Python 3 does not have a cmp function, this will do the cmp.
:param a: first object to check
:param b: second object to check
:return:
"""
return (a > b) - (a < b) |
def all(iterable):
"""The built-in was unavailable no Python 2.4."""
for element in iterable:
if not element:
return False
return True |
def add(x: int, y: int = 5) -> str:
"""Add two numbers."""
return str(x + y) |
def merge(user_profile, full_user_data):
""" Merges the user_profile and the full user data, such that existing attributes in user_profile will remain as
they are, but attributes not provided will be added to it.
Args:
user_profile (dict): The user profile data, in Okta format.
full_user_da... |
def plugin_init(config):
"""Registers HTTP Listener handler to accept sensor readings
Args:
config: JSON configuration document for the South device configuration category
Returns:
handle: JSON object to be used in future calls to the plugin
Raises:
"""
handle = config
retur... |
def discount_factor(base_price):
"""Returns the dicount percentage based on price"""
if base_price > 1000:
return 0.95
else:
return 0.98 |
def dict_add(d1, d2):
"""Add two dicts together without overwriting any values in the first dict. Returns a new dict without modifying
the input dicts.
Parameters
----------
d1 : dict
Main dictionary
d2 : dict
Dictionary of values to try to add
Returns
-------
dict
... |
def _check_extension_file(filename, extension):
"""Check the extension file correspond to the extension asked
:param filename: file to chek
:type filename: str
:param extension: extensions to find
:type extension: [type]
:return:
:rtype: [type]
"""
finalname = ""
if str(filenam... |
def get_format(suffix):
"""Get the archive format.
Get the archive format of the archive file with its suffix.
Args:
suffix: suffix of the archive file.
Return:
the archive format of the suffix.
"""
format_map = {
"bz2": "bztar",
"gz": "gztar",
}
if suff... |
def get_ns_name(uri):
"""
Get the namespace (the namespace is placed before the first '#' character or the last '/' character)
"""
hash_index = uri.find('#')
index = hash_index if hash_index != -1 else uri.rfind('/')
namespace = uri[0: index + 1]
return namespace |
def parse_sim(target):
""" Based on Makefile target name, parse which read simulator is involved """
sim = 'mason'
toks = target.split('_')
# Parsing simulator info:
if toks[2] == 'wgsim':
sim = 'wgsim'
if toks[2] == 'art':
sim = 'art'
return sim |
def spectrallib_path(lib="Kurucz"):
"""
Path of the synthetic spectra.
Optional arg:
lib: Spectral model name. Default: "Kurucz"
Output:
Path name
History:
2018-07-30 - Written - F. Anders (AIP)
2019-06-10 - Ported to pysvo.path - F. An... |
def mapdict(itemfunc, dictionary):
"""
Much like the builtin function 'map', but works on dictionaries.
*itemfunc* should be a function which takes one parameter, a (key,
value) pair, and returns a new (or same) (key, value) pair to go in
the dictionary.
"""
return dict(map(itemfunc, ... |
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8
It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
... |
def char_encoding(value):
""" Encode unicode into 'UTF-8' string.
:param value:
:return:
"""
if not isinstance(value, bytes):
return value.encode('utf-8')
# consider it to be 'utf-8' character
return value |
def pair(t):
"""
Parameters
----------
t: tuple[int] or int
"""
return t if isinstance(t, tuple) else (t, t) |
def dict_hangman(num_of_tries):
"""
The function return the "photo" of the hangman.
:param num_of_tries: the user's number of guessing
:type num_of_tries: int
:return: the photo of the hangman
:rtype: string
"""
HANGMAN_PHOTHOS = {
'1': """ x-------x""",
'2':
"""
x-------x
|
|
|
|
... |
def non_modal_frac_melt(Co, Do, F, P):
"""
non_modal_frac_melt calculates the composition of a trace element in a melt produced from non modal
fractional melting of a source rock as described by Rollinson 1993 Eq. 4.13 and 4.14.
Inputs:
Co = Concentration of trace element in the original sol... |
def calc_check_digit(number):
"""Calculate the check digit. The number passed should not have the
check digit included."""
c = -sum(i * int(n) for i, n in enumerate(reversed(number), 2)) % 11
return 'K' if c == 10 else str(c) |
def as_linker_lib_path(p):
"""Return as an ld library path argument"""
if p:
return '-L' + p
return '' |
def slash_join(base, extension):
"""Join two strings with a '/', avoiding duplicate slashes
If any of the strings is None the other is returned as is.
"""
if extension is None:
return base
if base is None:
return extension
return '/'.join(
(base.rstrip('/'),
ext... |
def update_label_lst(label_lst):
"""
Desc:
label_lst is a list of entity category such as: ["NS", "NT", "NM"]
after update, ["B-NS", "E-NS", "S-NS"]
"""
update_label_lst = []
for label_item in label_lst:
if label_item != "O":
update_label_lst.append("B-{}".format(... |
def sub_scr_num(inputText):
""" Converts any digits in the input text into their Unicode subscript equivalent.
Expects a single string argument, returns a string"""
subScr = (u'\u2080',u'\u2081',u'\u2082',u'\u2083',u'\u2084',u'\u2085',u'\u2086',u'\u2087',u'\u2088',u'\u2089')
outputText = ''
for char in inputText:
... |
def split_params(s):
"""Turn foo,bar=baz into {'foo': None, 'bar': 'baz'}
"""
xsl_params = {}
for param in s.split(','):
tokens = [t.strip() for t in param.split('=')]
xsl_params[tokens[0]] = len(tokens) > 1 and tokens[1] or None
return xsl_params |
def _create_http_error_dict(status_code, reason, message):
"""Creates a basic error dict similar to most Google API Errors.
Args:
status_code: Int, the error's HTTP response status code.
reason: String, a camelCase reason for the HttpError being given.
message: String, a general error message describ... |
def get_name(spec):
"""Retrieves the name from the provided Kubernetes object
Args:
spec - Spec for a properly constructed kubernetes object
Returns:
The name of the Kubernetes object as a string
"""
return spec["metadata"]["name"] |
def find_missing_number(numbers: list) -> int:
"""
A function that takes a shuffled list of unique numbers
from 1 to n with one element missing (which can be any
number including n). Return this missing number.
:param numbers: a shuffled list of unique numbers
from 1 to n with o... |
def clean_country(cnt):
"""
Special country names:
- Others
- Cruise Ship
"""
# if type(cnt)==float:
# return "Others"
if cnt=="Viet Nam":
return "Vietnam"
if cnt=="United Kingdom":
return "UK"
if cnt=="Taipei and environs" or cnt=="Taiwan*":
return "Taiwan"
if cnt=="Republic of... |
def get_fish_xn_yn(source_x, source_y, radius, distortion, increment):
"""
Get normalized x, y pixel coordinates from the original image and return normalized
x, y pixel coordinates in the destination fished image.
:param distortion: Amount in which to move pixels from/to center.
As distortion grow... |
def check_win(player, board):
"""Checks if the given player has won"""
# Check all horizontal lines
for i in range(len(board)):
for j in range(len(board[0]) - 4 + 1):
if (
board[i][j]
== board[i][j + 1]
== board[i][j + 2]
=... |
def findAll(haystack, needle) :
"""returns a list of all occurances of needle in haystack"""
h = haystack
res = []
f = haystack.find(needle)
offset = 0
while (f >= 0) :
#print h, needle, f, offset
res.append(f+offset)
offset += f+len(needle)
h = h[f+len(needle):]
f = h.find(needle)
return res |
def pg_varchar(size=0):
""" Returns the VARCHAR declaration for the provided size:
* If no size (or an empty or negative size is provided) return an
'infinite' VARCHAR
* Otherwise return a VARCHAR(n)
:type int size: varchar size, optional
:rtype: str
"""
if size:
if not isins... |
def rect_y(value, arg):
"""Computes rect offset for invoice print"""
return int(value) - ((int(arg) - 1) * 35) |
def normalize_boxes(all_boxes, image_width, image_height):
"""
We normalize the box parameters -- we also have to convert to center coordinate format, but this the network will do for us
:param all_boxes:
:param image_width:
:param image_height:
:return:
"""
new_boxes = []
for boxes_... |
def getPruning(table, index):
"""Extract pruning value"""
if ((index & 1) == 0):
res = table[index // 2] & 0x0f
else:
res = (table[index // 2] & 0xf0) >> 4
return res
# return table[index] & 0xf |
def get_mms_run_command(model_names, processor="cpu"):
"""
Helper function to format run command for MMS
:param model_names:
:param processor:
:return: <str> Command to start MMS server with given model
"""
if processor != "eia":
mxnet_model_location = {
"squeezenet": "ht... |
def bytelist_to_hex_string(bytelist):
"""
:param bytelist: list of byte values
:return: String representation of the bytelist with each item as a byte value on the format 0xXX
"""
return '[' + ', '.join("0x%02X" % x for x in bytelist) + ']' |
def gas_filter(label, which_gas):
"""
Utility: processes the mask / which_gas selector for gas_injection_overlay
:param label: string
Label for a gas pipe / inlet to be tested
:param which_gas: string or list
See gas_injection_overlay docstring
:return: bool
Flag indicatin... |
def format_actions(action_list):
""" Returns the action list, initially a list with elements "[op][val]"
like /2.0, -3.0, +1.0, formatted as a dictionary.
The dictionary keys are the unique indices (to retrieve the action) and
the values are lists ['op', val], such as ['+', '2.0'].
"""
return {... |
def ema(decay, prev_val, new_val):
"""Compute exponential moving average.
Args:
decay: 'sum' to sum up values, otherwise decay in [0, 1]
prev_val: previous value of accumulator
new_val: new value
Returns:
updated accumulator
"""
if decay == 'sum':
return prev... |
def toposort(graph, nodes):
"""Topological sort-styled traversal of graph with counting of steps"""
memo = set()
indegree = [0 for _ in range(nodes + 1)]
for adj in graph:
for dest in adj:
indegree[dest] += 1
memo.add((1, 0))
zero_degree = [1]
while zero_degree:
... |
def NormalCamel(name):
"""Convert C++ ASTClassName into normalized AstClassName.
A few legacy classes have irregular names requiring special-casing in order to
be remapped to an ASTNodeKind.
Args:
name: name of the C++ class.
Returns:
Normalized camel-case equivalent of the class name.
"""
if na... |
def getLevelNames(names):
"""Retrieve the list of names in a given level.
This method assumes that names description structure is good (i.e.
that nestedrecords.checkNames method raised no errors.).
"""
topNames = []
deeperNames = []
for item in names:
if isinstance(item, str):
... |
def add_inplace(X,varX, Y,varY):
"""In-place addition with error propagation"""
# Z = X + Y
# varZ = varX + varY
X += Y
varX += varY
return X,varX |
def fiscal_to_calendar(fiscal_year, fiscal_mo):
"""Converts a fiscal year and month into a calendar year and month for graphing purposes.
Returns (calendar_year, calendar_month) tuple."""
if fiscal_mo > 6:
calendar_month = fiscal_mo - 6
calendar_year = fiscal_year
else:
cale... |
def split_list(lst):
"""Split a list in half"""
half = int(len(lst) / 2)
return lst[:half], lst[half:] |
def buildBoard(x, y): # function that creates a board with 1 values and returns it
"""
:param x - horizontal length
:param y - vertical length
:return: created board
"""
board = []
for i in range(x):
board_row = []
for j in range(y):
board_row.append(1)... |
def max_sum_distance(arr):
"""
Computes M = max{arr[i] + arr[j] + (j - i) | 0 <= i < j <= n}.
Intuition:
Maximizing the separable bivariate objective function is equivalent to
maximizing two univariate objective functions: just rewrite!
M = max{arr[i] - i} + max{arr[j] + j}
... |
def discord_user_from_id(channel, user_id):
"""Returns the discord user from the given channel and user id."""
if user_id is None:
return None
iid = int(user_id)
members = channel.members
return next(filter(lambda member: iid == member.id, members), None) |
def turn(p1, p2, p3):
"""
0 if points are colinear
1 if points define a left turn
-1 if points define a right turn
"""
# Compute the z-coordinate of the vectorial product p1p2 x p2p3
z = (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0]- p1[0])
return 0 if z == 0 else int(z / ... |
def url(tile, imagery):
"""Return a tile url provided an imagery template and a tile"""
return imagery.replace('{x}', tile[0]).replace('{y}', tile[1]).replace('{z}', tile[2]) |
def get_labels_from_macrostate(macrostate):
"""Get labels from macrostate."""
labels = set()
for states in macrostate:
for state in states:
labels = labels.union(state.s.find_labels())
return labels |
def dobro(preco, moeda=''):
"""
--> Multiplica o valor inserido por 2.
:param preco: valor a ser multiplicado
:param moeda: qual a moeda a ser exibida
:return: valor dobrado
"""
final = preco * 2
if moeda == '':
return f'{final}'.replace('.', ',')
else:
return f'{moed... |
def _translate_message(message):
"""Translate the Message model to a dict."""
return {
'id': message['id'],
'project_id': message['project_id'],
'request_id': message['request_id'],
'resource_type': message['resource_type'],
'resource_uuid': message.get('resource_uuid'),
... |
def get_public_instance_attributes(instance):
"""
Get list of all instance public atrributes.
Parameters
----------
instance : optional
Returns
-------
list of str
"""
public_attributes = [
attribute
for attribute in instance.__dir__() if attribute[0] != '_'
... |
def break_before_after(computer, name, value):
"""Compute the ``break-before`` and ``break-after`` properties."""
# 'always' is defined as an alias to 'page' in multi-column
# https://www.w3.org/TR/css3-multicol/#column-breaks
if value == 'always':
return 'page'
else:
return value |
def get_confidence_score(scores):
"""
:param scores: list of scores for [abstract, title, author, year]
:return:
"""
confidence = sum([1 for score in scores if score >= 0.8]) >= len(scores) - 1 or \
sum(scores[0:2]) >= 1.8
if confidence:
return 1
confidence = sum(s... |
def skip_empty_strings(string_list):
"""
Given a list of strings, remove the strings that are empty (zero length):
"""
return list(filter(lambda s: len(s)>0, string_list)) |
def merge_dict_of_dicts(*dicts):
"""
Return a dict of dicts with values updated in left-to-right
order.
"""
if len(dicts) < 2:
raise TypeError('merge_dict_of_dicts requires at least two arguments')
out = {}
for d in dicts:
for key, inner in d.items():
out_inner =... |
def invert_colors_manual(input_img):
"""Function that invert color of an image
Args:
input_img: an ndarray
return an ndarray of inverted color
"""
rows=len(input_img)
cols=len(input_img[0])
channels=len(input_img[0][0])
for r in range(rows):
for c in range(cols):
... |
def tuplify_port_dicts(dicts):
"""
Input:
dicts (dict): embedded state dictionaries with the {'port_id': {'state_id': state_value}}
Return:
dict: tuplified dictionary with {(port_id','state_id'): value}
"""
merge = {}
for port, states_dict in dicts.items():
if states_dic... |
def count_circles_of_dictionary_with_arrays(dictionary):
"""
Returns: Total number of circles in dictionary
"""
total_circles = 0
for key, array in dictionary.items():
total_circles += len(array)
return total_circles |
def list_get_index(list_var, index, default=None):
"""Provide equivalent of dict().get()."""
if index < len(list_var):
return list_var[index]
else:
return default |
def regular_polygon_area(perimeter, apothem):
"""Returns the area of a regular polygon"""
return float((perimeter * apothem) / 2) |
def full_width(txt):
"""translate to unicode letters"""
WIDE_MAP = dict((i, i + 0xFEE0) for i in range(0x21, 0x7F))
WIDE_MAP[0x20] = 0x3000
return str(txt).translate(WIDE_MAP) |
def get_delim(fn):
"""
Get the expected delimiter for a data file based on the extension of the filename:
',' .csv
'\t' .tsv .tab
' ' otherwise
The filename may also have a .gz or .bz2 extension which will be ignored.
"""
fn = fn.lower()
if fn.endswith('.gz'): fn =... |
def onehot(i, width, values=[0,1]):
"""
>>> onehot(0, 5)
[1, 0, 0, 0, 0]
>>> onehot(3, 5)
[0, 0, 0, 1, 0]
>>> onehot(3, 5, values=[False, True])
[False, False, False, True, False]
"""
v = [values[0]] * width
v[i] = values[1]
return v |
def performance_info(standard, nss, width):
"""Return a readable string from output of performance_characteristics.
Arguments:
standard: 802.11 standard like 'a/b/g', 'n', 'ac', etc.
nss: number of spatial streams as an int, 0 for unknown.
width: channel width as a string: '20', '40', '80', '160', '80+... |
def hex_to_rgba(hex_color, opacity):
"""Embed opacity in a colour by converting calliope HEX colours to an RGBA"""
_NUMERALS = "0123456789abcdefABCDEF"
_HEXDEC = {v: int(v, 16) for v in (x + y for x in _NUMERALS for y in _NUMERALS)}
hex_color = hex_color.lstrip("#")
rgb = [_HEXDEC[hex_color[0:2]], _... |
def norm(value, low, high):
"""Normalizes a number from another range into a value between 0 and 1.
Identical to map(value, low, high, 0, 1)."""
return float(value - low) / (high - low) |
def parse_value(data, byte_order, start_byte, num_bytes, scale=None):
"""Returns an int from a sequence of bytes.
Scale is an optional argument that handles decimals encoded as int.
Parameters
----------
data : bytes
A sequence of bytes for one full sensor message
byte_order : str,... |
def maxArea(height):
"""
:type height: List[int]
:rtype: int
"""
left = 0
right = len(height) - 1
area = 0
while left < right:
area = max(area, (right - left) * min(height[left], height[right]))
if height[left] > height[right]:
right -= 1
else:
... |
def is_valid_xvg_param(ext):
""" Checks xvg parameter """
formats = ['xmgrace', 'xmgr', 'none']
return ext in formats |
def create_array(n) -> list:
"""This function create an array, populated with integers from 1 to n."""
res=[]
for i in range(1, n + 1):
res.append(i)
return res |
def decode_data(data, table):
""" Decode data with precalculated table """
dec = []
for i in range(0, len(data), 16):
dec.append(table[data[i:i+16]])
return bytes(dec) |
def is_prime(number):
"""Check if a number is prime."""
if number < 2:
return False
if number == 2:
return True
if number % 2 == 0:
return False
for _ in range(3, int(number ** 0.5) + 1, 2):
if number % _ == 0:
return False
return True |
def _merge_dicts(*dicts):
"""Merge any number of dictionaries, some of which may be None."""
final = {}
for dict in dicts:
if dict is not None:
final.update(dict)
return final |
def UniqueLabelIndices(flabels: list) -> list:
"""Indices of unique fingerprint labels."""
sort_ = [sorted(x) for x in flabels]
tuple_ = [tuple(x) for x in sort_]
unique_labels = [list(x) for x in sorted(set(tuple_), key=tuple_.index)]
return [[i for (i, x) in enumerate(sort_) if x == y] for y in ... |
def ms_to_s(time):
"""Convert time in ms to seconds."""
if time is None:
return 0
# Happens in some special cases, just return 0
if time >= (2**32 - 1):
return 0
return round(time / 1000.0) |
def _rgb_to_hex(rgb):
"""
>>> _rgb_to_hex((222, 173, 19))
'#dead13'
"""
return '#%02x%02x%02x' % tuple(rgb) |
def cz_gate_counts_nondeterministic(shots, hex_counts=True):
"""CZ-gate circuits reference counts."""
targets = []
if hex_counts:
# (I^H).CZ.(H^H) = CX10.(H^I), Bell state
targets.append({'0x0': shots / 2, '0x3': shots / 2})
# (H^I).CZ.(H^H) = CX01.(I^H), Bell state
targets.a... |
def _path_to_target(package, path):
""" Converts a path to a Bazel target. """
return "@{package}//:{path}".format(package = package, path = path) |
def format_time(t):
"""
Format time with two decimals.
"""
return round(t,2) |
def validate_queue_state(queue_state):
"""Validate response type
:param queue_state: State of the queue
:return: The provided value if valid
Property: JobQueue.State
"""
valid_states = ["ENABLED", "DISABLED"]
if queue_state not in valid_states:
raise ValueError("{} is not a valid q... |
def rdp_parse(s):
"""Parse RDP taxonomy string with 7 level format (SILVA uses it.)
D_0__Bacteria;D_1__Epsilonbacteraeota;D_2__Campylobacteria;D_3__Campylobacterales;D_4__Thiovulaceae;D_5__Sulfuricurvum;D_6__Sulfuricurvum sp. EW1
The ambiguous_taxa will be convert to empty string.
"""
abbr_dct = {
... |
def logical_left_shift(number: int, shift_amount: int) -> str:
"""
Take in 2 positive integers.
'number' is the integer to be logically left shifted 'shift_amount' times.
i.e. (number << shift_amount)
Return the shifted binary representation.
>>> logical_left_shift(0, 1)
'0b00'
>>> logi... |
def _is_closing_message(commit_message: str) -> bool:
"""
Determines for a given commit message whether it indicates that a bug has
been closed by the corresponding commit.
Args:
commit_message: the commit message to be checked
Returns:
true if the commit message contains key words... |
def filter_string(s):
"""
Make (unicode) string fit for passing it to lxml, which means (at least)
removing null characters.
"""
return s.replace("\x00", "") |
def remove_space_in_between_words(seq):
"""
Remove space between words
args:
seq: String
output:
seq: String
"""
return seq.replace(" ", " ").replace(" ", " ").replace(" ", " ").replace(" ", " ").strip().lstrip() |
def shift_and_pad(array, dist, pad="__null__"):
"""Shift and pad with item.
:params array: list like iterable object
:params dist: int
:params pad: any value
Example::
>>> array = [0, 1, 2]
>>> shift_and_pad(array, 0)
[0, 1, 2]
>>> shift_and_pad(array, 1)
... |
def trim_docstring(docstring):
"""Removes indentation from triple-quoted strings.
This is the function specified in PEP 257 to handle docstrings:
https://www.python.org/dev/peps/pep-0257/.
Args:
docstring: str, a python docstring.
Returns:
str, docstring with indentation removed.
"""
if not doc... |
def split_route(route):
""" Checks to see if a route contains an out and back.
If so, split it into 2 separate routes
"""
split_index = None
# Loop over each step
for index, hop in enumerate(route):
if index == 0:
continue
curr_stop = hop[0]
prev_stop = ro... |
def _func_or_float(f,x):
"""
Evaluates `f` at x. If `f` is float, value is returned
"""
if isinstance(f, float):
return f
else:
return f(x) |
def LCM(a, b):
""" Implementation of of LCM algorithm. """
temporary = a
while (temporary % b) != 0:
temporary += a
return temporary |
def read_blacklisted_ranges(fn, num_alignments):
"""Read list of blacklisted ranges.
There must be 3 columns in the file:
1 - an identifier for an alignment that the guide should be
covering (0-based, with maxmimum value < num_alignments)
2 - the start position (inclusive) of a rang... |
def needs_copy_instead_of_move(type_name):
"""
Those are types which need initialised data or we'll get warning spam so need a copy instead of move.
"""
return type_name in [
"Dictionary",
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.