content stringlengths 42 6.51k |
|---|
def _color(val):
"""
Parse string as hex color string. The scim CSV does some dumb things like
truncate, convert to float, and remove #, so fix all that crap.
>>> _color('#ff0000')
'#ff0000'
>>> _color('ff0000')
'#ff0000'
>>> _color('668800.00')
'#668800'
>>> _color('345')
'#000345'
"""
if va... |
def update_rooms_slider(area):
"""
Update rooms slider to sensible values.
"""
return [1, min(int(area / 30) + 1, 6)] |
def _is_chinese_char(char):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Kor... |
def PeerDownHasBgpNotification(reason):
"""Determine whether or not a BMP Peer Down message as a BGP notification.
Args:
reason: the Peer Down reason code (from the draft)
Returns:
True if there will be a BGP Notification, False if not
"""
return reason == 1 or reason == 3 |
def digits_to_number(digits, running=0):
"""Convert a list of digits to an integer"""
if len(digits) == 0:
return running
else:
r = (running * 10) + int(digits[0])
return digits_to_number(digits[1:], r) |
def add_to_dict_table(table, key, value):
"""
Converts the table from tuples (explicit or implicit) to a dict().
Where the key is the output.
:param table: dict
:param key: to be added to dict
:param value: to be added to dict
:return: modified table
"""
if key in table: # add value... |
def grep_init_lr(starting_epoch, lr_schedule):
"""
starting_epoch : starting epoch index (1 based)
lr_schedule : list of [(epoch, val), ...]. It is assumed to be sorted
by epoch
return
init_lr : learning rate at the starting epoch
"""
init_lr = lr_schedule[0][1]
for e, v in lr_... |
def det_count_elements(l):
""" Deterministically count elements in an iterable
Returns the count of each element in `l`. Costs O(n), where n is the length of `l`.
Args:
l (:obj:`iterable`): an iterable with hashable elements
Returns:
:obj:`list` of :obj:`tuple`: a list of pairs, (elem... |
def money_with_currency(money):
"""A filter function that returns a number formatted with currency info."""
return f"$ {money / 100.0:.2f} USD" |
def splitListFromSizes(lista, sizes):
"""
Agrupa elementos de una lista acorde a unos tamanhos dados
:param lista: [8, 9, 2, 7, 5]
:param sizes: [2, 3]
:return: [[8,9], [2,7,5]]
"""
sl = []
ref = 0
for i in sizes:
sl.append(lista[ref:ref + i])
ref += i
... |
def shape2d(a):
"""
a: a int or tuple/list of length 2
"""
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
raise RuntimeError("Illegal shape: {}".format(a)) |
def check_sender_agency(msg):
"""
deprecated.
originally designed to help lookup the agency by the sender.
this is problematic because occasionally a contact sends on behalf of multiple agencies.
keeping this code for reference but it's not advisable to implement,
i.e. could result in false mat... |
def filter_action_servers(topics):
""" Returns a list of action servers """
# Note(@jubeira): filtering by topic should be enough; services can be taken into account as well.
action_servers = []
possible_action_server = ''
possibility = [0, 0]
action_topics = ['feedback', 'status']
for topi... |
def num_of_1_in_b(num):
"""
due to number in Python3 has no bit limit
so flag << 1 will never equals 0
:param num:num
:return:num of 1 in bin(num)
"""
flag = 1
count = 0
for i in range(num.bit_length()):
if flag & num:
count += 1
flag <<= 1
return coun... |
def _ListToDictionary(lst, separator):
"""Splits each element of the passed-in |lst| using |separator| and creates
dictionary treating first element of the split as the key and second as the
value."""
return dict(item.split(separator, 1) for item in lst) |
def limit_on_close_order(liability: float, price: float) -> dict:
"""
Create limit order for the closing auction.
:param float liability: amount to bet.
:param float price: price at which to bet
:returns: Order information to place a limit on close order.
:rtype: dict
"""
return locals(... |
def label(dt):
""" Setting the label for the integration timestep """
return 'dt = {} s'.format(dt) |
def url(classes):
"""get URL property (u-*) names
"""
return [c.partition("-")[2] for c in classes if c.startswith("u-")] |
def KeggIdFromInt(id):
"""Makes a string KEGG id from an integral one.
Args:
id: the integer KEGG ID.
Returns:
The string format of the KEGG ID (properly 0-padded).
"""
return 'C%05d' % id |
def norm(lst: list) -> float:
"""[summary]
L^2 norm of a list
[description]
Used for internals
Arguments:
lst {list} -- vector
"""
if not isinstance(lst, list):
raise ValueError("Norm takes a list as its argument")
if lst == []:
return 0
return (sum((i**2 fo... |
def get_image_from_camera(camera):
"""Function to return an image from our camera using OpenCV"""
if camera:
# if predictor is too slow frames get buffered, this is designed to
# flush that buffer
ret, frame = camera.read()
if not ret:
raise Exception("your capture de... |
def extract_internal_id(oai_identifier):
"""
Extract the internal identifier from the full tag identifier from the OAI request
:param oai_identifier: the full OAI identifier for a record
:return: the internal identifier
"""
# most of the identifier is for show - we only care about the hex strin... |
def Lsynch_murphy(sfr, nu):
"""
Synchrotron luminosity model, taken from Eq. 9 of Bonaldi et al.
(arXiv:1805.05222).
Parameters
----------
sfr : array_like
Star-formation rate, in Msun/yr.
nu : array_like
Frequency, in GHz.
Returns
-------
L_synch ... |
def get_best_size(value):
"""
Give a size in bytes, convert it into a nice, human-readable value
with units.
"""
if value >= 1024.0**4:
value = value / 1024.0**4
unit = 'TB'
elif value >= 1024.0**3:
value = value / 1024.0**3
unit = 'GB'
elif value >= 102... |
def _compare_address_lists(list_one, list_two):
"""
Counts the number of elements in list one that are not in list two.
:param list_one: list of strings to check for existence in list_two
:param list_two: list of strings to use for existence check of
list_one parts
:return: the count of it... |
def last_index_of_(string, sub, start, length):
""":yaql:lastIndexOf
Returns an index of last occurrence sub in string beginning from start
ending with start+length.
-1 is a return value if there is no any occurrence.
:signature: string.lastIndexOf(sub, start, length)
:receiverArg string: inpu... |
def to_list(rgb, alpha=False):
"""
Break rgb channel itno a list.
Take a color of the format #RRGGBBAA (alpha optional and will be stripped)
and convert to a list with format [r, g, b].
"""
if alpha:
return [
int(rgb[1:3], 16),
int(rgb[3:5], 16),
int(... |
def bytes_to_ascii(seq):
"""Converts seq from byte array to ASCII string"""
#return ''.join(map(chr, seq))
return str(seq, 'ascii') |
def _change_type(param: dict, type_rep: dict) -> dict:
"""change type by type_rep.
change type param["type"] and param["atmicx"] according to type_rep = {"Cu_4a_0": "Cu"}.
Args:
param (dict): kkr param
type_rep (dict): replace dict
"""
newtype = []
for type_ in param["type"]:
... |
def _get_title(title, parent, default):
""" Get a sensible title for a dialog! """
if title is None:
if parent is not None:
title = parent.GetTitle()
else:
title = default
return title |
def vecDIV(first, second):
"""
Take in two arrays
multiply each element against the other at the same index
return a new array
"""
newMAT = []
for i in range(len(first)):
newMAT.append(first[i] / second[i])
return newMAT |
def optional(*elems):
"""Small helper to ignore Nones in a List"""
return [e for e in elems if e is not None] |
def _ral_contains_ ( self , i ) :
"""Check the presence of element or index in the list
"""
if isinstance ( i , int ) : return 0<= i < len(self)
return 0 <= self.index ( i ) |
def _get_color_definitions(data):
"""Returns the list of custom color definitions for the TikZ file.
"""
definitions = []
fmt = "\\definecolor{{{}}}{{rgb}}{{" + ",".join(3 * [data["float format"]]) + "}}"
for name, rgb in data["custom colors"].items():
definitions.append(fmt.format(name, rgb... |
def score1(rule, c=0):
"""
Calculate candidate score depending on the rule's confidence.
Parameters:
rule (dict): rule from rules_dict
c (int): constant for smoothing
Returns:
score (float): candidate score
"""
score = rule["rule_supp"] / (rule["body_supp"] + c)
r... |
def import_object(name):
"""
Import an object from a module, by name.
:param name: The object name, in the ``package.module:name`` format.
:return: The imported object
"""
if name.count(':') != 1:
raise ValueError("Invalid object name: {0!r}. "
"Expected format... |
def format_func(function, qualname=False):
"""Format func
Args:
function (str):
Returns:
str:
"""
if qualname:
try:
return '<' + function.__qualname__ + '>'
except AttributeError:
pass
return '<' + function.__name__ + '>' |
def get_coords_from_line(line):
""" Given a line, split it, and parse out the coordinates.
Return:
A tuple containing coords (position, color, normal)
"""
values = line.split()
pt = None
pt_n = None
pt_col = None
# The first three are always the point coords
if l... |
def abstract(record):
"""
Clean abstract string.
:param record: a record
:type record: dict
:return: dict -- the modified record
"""
try:
record['abstract'] = record['abstract'].strip(' [on SciFinder(R)]')
except KeyError:
record['abstract'] = ""
return record |
def str_to_bool(s):
"""Converts a human readable textual representation of a Boolean to a Boolean"""
if s == 'yes':
return True
elif s == 'no':
return False
else:
raise ValueError |
def map_factors(list, n):
"""Map list of factors to n scale degrees"""
mapped_factors = []
for row in range(len(list)):
new_row = []
for item in range(len(list[row])):
new_item = int(list[row][item]) % n
new_row.append(new_item)
mapped_factors.append(new_row... |
def last(word):
"""Returns the last of a string."""
return word[-1] |
def get_weight_swimmer(x):
"""Calculate the weight for a swimmer based on their place in the team.
It is a basic exponential function.
Args:
x (int): The swimmer's place on the team
1 is the best swimmer, higher numbers are worse swimmers
Returns:
float: the weight to app... |
def getdiffmeta(diff):
"""get commit metadata (date, node, user, p1) from a diff object
The metadata could be "hg:meta", sent by phabsend, like:
"properties": {
"hg:meta": {
"branch": "default",
"date": "1499571514 25200",
"node": "98c08acae292b2faf60a279b... |
def _handle_column_list(spec, property_name):
"""Convert ColumnList to a dictionary."""
return {property_name: spec} |
def score_progress(board):
"""Return # of candidates remaining in board."""
return sum(sum(len(cell) for cell in row) for row in board) |
def list_generator_op(parallelism: int) -> str:
"""Generate list for parallel"""
import json
# JSON payload is required for ParallelFor
return json.dumps([x for x in range(parallelism)]) |
def _signature_map(map_dict, parsed_sig):
"""Map values found in parsed gufunc signature.
Parameters
----------
map_dict : dict of str to int
Mapping from `str` dimension names to `int`. All strings in
`parsed_sig` must have entries in `map_dict`.
parsed_sig : list-like of tuples of... |
def is_valid_parameter(object):
"""
Checks if a parameter has the following attributes/methods:
* value
* set_value
* floating
"""
has_value = hasattr(object, "value")
has_set_value = hasattr(object, "set_value")
has_floating = hasattr(object, "floating")
return has_... |
def matrix_multiply(A, B):
""" Multiply two matrices A and B.
:param A: the right matrix
:param B: the left matrix
:return: A * B
"""
# define m and n for the matrix as well as l, the connecting dimension between A and B
m, l, n = len(A), len(A[0]), len(B[0])
# initialize an all zeros ... |
def render_instruction(name, content):
""" Render an arbitrary in-line instruction with the given name and
content """
return ':{}: {}'.format(name, content) |
def cents_to_eur(val):
"""
This function divides a float value over 1000
:param val: str
:return: Float
"""
return float(val) / 1000 |
def edges_to_lines(edges):
"""
Helper fct for plotting edges
"""
return [((e[0][0], e[1][0]), (e[0][1], e[1][1])) for e in edges] |
def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop',
'replace', 'truncate', 'load'])
return status.split(None, 1)[0].lower() in mutatin... |
def get_parameters_doc(doc):
"""
Extracts the documentation of the parameters
"""
if not doc:
return doc
found = False
parameters = []
for line in doc.split("\n"):
words = line.split()
if not found and len(words) == 1 and words[0].startswith("Parameter"):
... |
def normalize_text(text, method='str'):
"""
Parameters
----------
text : str
method : {'str', 'regex'}, default 'str'
str: cleans digits and puntuations only ('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
regex : clean digits and all special characters
Returns
-... |
def build_from_azure_calls(files, azure_location, local_location = "."):
""" Take a list of files and their location on azure and build transfer calls
to move them to a specified local location."""
outlist = []
for f in files:
outstr = f'azcopy copy "{azure_location}{f}" "{local_location}"\n'
outlist.a... |
def single_db(server, args_array, **kwargs):
"""Method: single_db
Description: Function stub holder for mongo_db_restore.single_db.
Arguments:
(input) server -> Server instance.
(input) args_array -> Dictionary of arguments.
"""
status = False
err_msg = None
if server... |
def _discretize(numeric_delta, camera_angle):
"""
This operation takes a continuous `numeric_delta` camera change value (in either pitch or yaw) and
discretizes it to be either "no change", "increase" or "decrease".
If abs(numeric_delta) > camera_angle, it gets effectively capped at `camera_angle`, sin... |
def make_safe_for_html(html):
"""Turn the text `html` into a real HTML string."""
html = html.replace("&", "&")
html = html.replace(" ", " ")
html = html.replace("<", "<")
html = html.replace("\n", "<br>")
return html |
def splitattr(url):
"""splitattr('/path;attr1=value1;attr2=value2;...') ->
'/path', ['attr1=value1', 'attr2=value2', ...]."""
words = url.split(';')
return words[0], words[1:] |
def auto_raytracing_grid_resolution(source_fwhm_parcsec, grid_resolution_scale=0.0002, ref=10., power=1.):
"""
This function returns a resolution factor in units arcsec/pixel appropriate for magnification computations with
finite-size background sources. This fit is calibrated for source sizes (interpreted... |
def permdb(ind, beta=0.5):
"""Perm function D, BETA defined as:
$$ f(x) = \sum_{i=1}^d (\sum_{j=1}^n (j^i+\beta) ((\frac{x_j}{j})^i - 1) )^2$$
with a search domain of $-n < x_i < n, 1 \leq i \leq n$.
The global minimum is at $f(x_1, ..., x_n) = f(1, 1/2, ..., 1/n) = 0.
"""
return sum(( \
... |
def phone_format(n):
"""Nicely format a number in US phone form"""
n = str(n)
return format(int(n[:-1]), ",").replace(",", "-") + n[-1] |
def parse_unity_results(output):
"""Read output from Unity and parse the results into 5-tuples:
(file, lineno, name, result, message)"""
result = []
lines = output.split('\n')
for line in lines:
if line == '':
break
parts = line.split(':', maxsplit=4)
if len(parts... |
def _get_traceback(content):
"""
Get the traceback part from the content containing the standard
error/output of a python process. It is used to get the traceback
of `ramp_test_submission` when there is an error.
Parameters
----------
content : str
Returns
-------
str with the ... |
def square_loss(labels, predictions):
""" Square loss function
Args:
labels (array[float]): 1-d array of labels
predictions (array[float]): 1-d array of predictions
Returns:
float: square loss
"""
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l -... |
def _calculate_underfulfillment_and_account(
allocable_acceptance_pos,
allocable_acceptance_neg,
upper_acceptance_limit,
lower_acceptance_limit,
setpoint_pos,
setpoint_neg,
account_pos,
account_neg,
acceptance_pool_pos,
acceptance_pool_neg,
):
"""
inner loop of calculate_... |
def datazoom(is_datazoom_show=False,
datazoom_type='slider',
datazoom_range=None,
datazoom_orient='horizontal',
**kwargs):
"""
:param is_datazoom_show:
It specifies whether to use the datazoom component.
:param datazoom_type:
datazoom type... |
def map_inputs(building_name, inputs, mapping):
"""
Maps inputs from OPC server to EnergyPlus
Inputs:
building_name- The name of the building
inputs- [(name, value, status, timestamp)] from opc
Outputs:
[value]- List of values, in the order specified by E+
"""
input_tags = mapping[building_name]["Inputs"]
re... |
def check_standard_word(tag):
"""
Checks if the values from the tag are found in the exclude array
Args:
tag (str): Tag from nltk.pos_tag(arr[str]) function
Returns:
bool: If found in the array return True, False if otherwise
"""
exclude = ["MD", "DT", "PRP", "$PRP", "IN", "CC", "CD", "EX", "NNP", "NNPS", "PO... |
def update(variable, orig_img, mode):
"""Update a variable based on mode and its difference with orig_img."""
# Apply the shrinkage-thresholding update element-wise.
z = variable - orig_img
if mode == "PP":
return (z <= 0) * variable + (z > 0) * orig_img
return (z > 0) * variable + (z <= 0) ... |
def sort_by_hierarchy(tids, taxdump):
"""Sort a sequence of taxIds by hierarchy from low to high.
Parameters
----------
tids : list of str
taxIds to sort
taxdump : dict
taxonomy database
Returns
-------
list of str
sorted taxIds
"""
# start with any taxI... |
def t_multicollinearity(rij, sr):
"""
"""
t = rij / sr
return t |
def multi_index_lookup(iterable, item, indexable_types, default=None):
"""Nested lookup of item in iterable."""
for i, inner_iterable in enumerate(iterable):
if inner_iterable == item:
return (i,)
if isinstance(inner_iterable, indexable_types):
inner_indices = multi_index... |
def check_valid(number, input_base=10):
"""
Checks if there is an invalid digit in the input number.
Args:
number: An number in the following form:
(int, int, int, ... , '.' , int, int, int)
(iterable container) containing positive integers of the input base
... |
def get_para_class(p):
""" Returns the class name of the paragraph
"""
try:
p["class"][0]
return p["class"][0]
except:
return None |
def multilabel_accuracies(gold, silver,
test_tokens, known_tokens,
print_scores=True):
"""Calculate accuracy scores, assuming a multi-label setup.
Especially useful for calculating scores on complex morpho-
logical tags. Multi-label accuracies are c... |
def calculate_stats(array):
"""Return min, max, avg in the given array.
"""
_count = 0
_max = _sum = 0.0
_min = None
for number in array:
_count += 1
if _min is None or number < _min:
_min = number
if number > _max:
_max = number
_sum += nu... |
def find_lowest_points(data) -> int:
"""Finds the lowest points in a heightmap.
A `lowest point` refers to a point that is lower (smaller) than numbers directly
above, below, left, and right of it (diagonals in this situation do not count).
Returns the `risk_level` (sum of all low points + 1 for every... |
def parse_locale(identifier, sep='_'):
"""Parse a locale identifier into a tuple of the form ``(language,
territory, script, variant)``.
>>> parse_locale('zh_CN')
('zh', 'CN', None, None)
>>> parse_locale('zh_Hans_CN')
('zh', 'CN', 'Hans', None)
The default component separator is ... |
def float_(value):
""":yaql:float
Returns a floating number built from number, string or null value.
:signature: float(value)
:arg value: input value
:argType value: number, string or null
:returnType: float
.. code::
yaql> float("2.2")
2.2
yaql> float(12)
... |
def _pos_round(position):
"""
Returns the rounded `position`.
**Don't require Pygame.**
**(Not available in SimpleGUI of CodeSkulptor.)**
:param position: (int or float, int or float)
or [int or float, int or float]
:return: (int, int)
"""
assert isinstance(posit... |
def replace_scale(string):
"""
This assumes that the string starts with "(.)", which will be replaced by
(8piG/3)
>>> print replace_scale('(.)toto')
>>> '(8\\pi G/3)toto'
"""
string_list = list(string)
string_list.pop(1)
string_list[1:1] = list('8\\pi G/3')
return ''.join(string... |
def _inferred_number_type(v):
"""Return the inferred type for the given string. The string must contain either an interger or a float.
"""
try:
return int(v)
except ValueError:
return float(v) |
def version_tuple_to_str(version_tuple):
"""
Convert the given version tuple to a string.
:param version_tuple: Version tuple to convert.
:return: String representation of version tuple.
"""
return ".".join([str(x) for x in version_tuple]) |
def _fix_absolute_import_name(name: str) -> str:
"""Replaces colons and backslashes with underscores."""
return name.replace(':', '_').replace('/', '_') |
def create(event, context):
"""Noop."""
return "PhysicalResourceId", {} |
def __filter_event_type__(trace_events, event_type):
"""
Looks for the events in the trace matching the event type
:param trace_events: Events found in the trace (filtered by family).
:param event_type: Event type to filter.
:return: Filtered trace
"""
filtered = []
for line in trace_ev... |
def spin_words(sentence):
"""
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more
letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces.
Spaces will be included only when more th... |
def xml_combine(root, elements):
"""Combine two xml elements and their subelements
This method will modify the 'root' argument and does
not return anything.
Args:
root (Element): The Element that will contain the merger
elements (Element or list): If an Element, merge all subelements o... |
def format_version_entity(major, minor, revision):
"""Return formatted UDM_VERSION entity."""
return (' <UDM_VERSION MAJOR="{}" MINOR="{}" REVISION="{}"'
' VERSIONTEXT="{}.{}.{}"/>\n').format(
major, minor, revision, major, minor, revision) |
def conta_letras(s: str):
"""
>>> conta_letras('fabiano')
{'f': 1, 'a': 2, 'b': 1, 'i': 1, 'n': 1, 'o': 1}
>>> conta_letras('Ffabiano')
{'F': 1, 'f': ', 'a': 2, 'b': 1, 'i': 1, 'n': 1, 'o': 1}
>>> conta_letras('banana')
{'b': 1, 'a': 3, 'n': 2 }
:param s:... |
def sanitize(s: str) -> str:
"""Something like b64encode; sanitize a string to a path-friendly version."""
to_del = [" ", ";", ":", "_", "-", "/", "\\", "."]
s = s.lower()
for c in to_del:
s = s.replace(c, "")
return s |
def broken_shuffle_3(values):
"""this always returns the values sorted"""
return list(sorted(values)) |
def geom2kml(geom_dict):
"""Convert a geointerface geometry to KML.
Args:
geom_dict: dict, 'geometry' as defined by the geo interface in
geojson and shapely.
"""
geom_type = geom_dict['geometry']['type']
geom_coords = geom_dict['geometry']['coordinates']
if geom_type == 'Point':
return '<Poi... |
def cross(a, b):
"""
Return the list formed by all the possible concatenations
of a letter s in string a with a letter t in string b.
Args:
a, b: strings.
Returns:
list: All the possible concatenations of letters.
"""
return [s + t for s in a for t in b] |
def is_values_of_key_matched(target_dict: dict, key_dict: dict) -> bool:
"""
:param target_dict: e.g. 1) {'winner': 'KOR', ...} 2) {'winner': 'GER', ...}
:param key_dict: e.g. {'winner': 'KOR'}
:return: e.g. 1) True 2) False
"""
for key, val in key_dict.items():
if target_dict[key] != v... |
def logon_prompt(msg="Modified with Windows Registry Fixer"):
"""Alterar a Mensagem Mostrada na Tela de Logon
DESCRIPTION
Voce pode personalizar (ou legalizar) a mensagem mostrada na caixa de
logon acima do nome de usuario e senha.
COMPATIBILITY
Windows NT/2000/XP
... |
def elina_abstract0_copy(man, a1):
"""
Return a copy of an ElinaAbstract0.
Destructive update does not affect the initial value.
Parameters
----------
man : ElinaManagerPtr
Pointer to the ElinaManager.
a1 : ElinaAbstract0Ptr
Pointer to the ElinaAbstract0.
Re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.