content stringlengths 42 6.51k |
|---|
def capabilities_to_dict(caps):
"""Convert the Node's capabilities into a dictionary."""
if not caps:
return {}
return dict(key.split(':', 1) for key in caps.split(',')) |
def _correct_p_value(tail, p_value, ref_val, current_val):
"""Determines if p-values should be tail corrected"""
return 1 if tail and ref_val > current_val else p_value |
def number_to_name(number):
"""
Helper function that converts a "number" in the range
"0" to "4" into its corresponding (string) "name"
in the way described below.
0 - rock
1 - Spock
2 - paper
3 - lizard
4 - scissors
"""
# Define a variable that will hol... |
def CountEdgesInLinkArray(linkArray):
"""
CountEdgesInLinkArray(linkArray):
Count number of edges in linkArray. This is useful for getting
the E parameter required by LDPCCode and DualLDPCCode.
"""
result = 0
for row in linkArray:
result = result + len(row)
return result |
def orient(points, i, j, k): # FIXME: add doc
"""
:param points:
:param i:
:param j:
:param k:
:return:
"""
a = points[0][j] - points[0][i]
b = points[1][j] - points[1][i]
c = points[0][k] - points[0][i]
d = points[1][k] - points[1][i]
# Determinant
r = 0.5 * (a * ... |
def RPL_WHOISSERVER(sender, receipient, message):
""" Reply Code 312 """
return "<" + sender + ">: " + message |
def _get_graph_act_qubits(graph):
"""Get all acted qubits."""
nodes = set({})
for node in graph:
nodes |= set({i for i in node})
nodes = list(nodes)
return sorted(nodes) |
def gcd_iter(a, b):
"""Find the greatest common denominator with 2 arbitrary integers.
Parameters
----------
a : int
User provided integer
b : int
User provided integer
Returns
-------
gcd : int
Greatest common denominator.
"""
orig_b = b
orig_a = a... |
def clean_elements(orig_list):
"""Strip each element in list and return a new list.
[Params]
orig_list: Elements in original list is not clean, may have blanks or
newlines.
[Return]
clean_list: Elements in clean list is striped and clean.
[Example]
>>> clean_e... |
def get_tid_timestamp_from_event(event):
"""
Return the thread ID & timestamp (in sec) from a event
"""
# line 1 of each event: the program name; thread id (tid); time (in sec); cycles took for the trace (not sure)
# Example:
# demo_sift1M_rea 3100 945.398942: 1 cycles:
fiel... |
def rename_bindnames(tqry, li_adjust):
"""use this to alter the query template to match expected attribute names in bind objects/dictionaries
For example, a predefined query may be: "select * from customers where custid = %(custid)s"
But you are repeatedly passing bind dictionaries like {"customer" ... |
def divideList(x, k):
"""
Divide list @x into roughly @k parts.
"""
if k > len(x): return [[elem] for elem in x]
part_len = int(len(x) / k)
parts = []
start = 0
while start < len(x):
parts.append(x[start: start + part_len])
start += part_len
return parts |
def sector_dict(obj):
"""Creates a dictionary for a sector."""
if obj is None:
return None
return {
'id': str(obj.id),
'name': obj.name,
'ancestors': [{
'id': str(ancestor.id),
} for ancestor in obj.get_ancestors()],
} |
def _get_roty(rot_type):
"""
Return y coordinate for this rotation
"""
return 0 if rot_type >= 4 else 1 |
def inv(R):
"""Inverts the rotation"""
Rinv = [R[0],R[3],R[6],R[1],R[4],R[7],R[2],R[5],R[8]]
return Rinv |
def triclamp(val, thresh=0.8):
"""Trinary clamps a value around 0.
The return value is::
(-inf, -thresh) -> -1.0
[-thresh, thresh] -> 0.0
(thresh, inf) -> 1.0
"""
if val < -thresh: return -1.0
elif val > thresh: return 1.0
return 0.0 |
def _get_total_for_date(basket, date_id):
""" Gets the total quantity in the basket for a given date """
total = 0
for type_id in basket[date_id]:
total += basket[date_id][type_id]
return total |
def unpack_bytes(word):
"""Unpacks a 32 bit word into 4 signed byte length values."""
def as_8bit_signed(val):
val = val & 0xff
return val if val < 128 else val - 256
return (as_8bit_signed(word),
as_8bit_signed(word >> 8),
as_8bit_signed(word >> 16),
as_8... |
def rows_with_missing_squares(squares):
"""This searches for the squares with 0 value and returns the list of corresponding rows.
"""
rows = []
for i, square in enumerate(squares):
if 0 in square:
rows.append(i)
return list(set(rows)) |
def get_best_cluster(best_results):
""" Warning: buggy code. Auxiliar function to extract the best cluster
"""
best = 0
best_cluster = []
for best_id in best_results:
b = best_results[best_id][0]
if b > best:
best = b
best_cluster = best_results[best_id][1]
... |
def is_set(obj):
"""Helper method to see if the object is a Python set.
>>> is_set(set())
True
"""
return type(obj) is set |
def _bytes_for_bits(bits):
"""
How many bytes do I need to read to get the given number of bits of
entropy?
"""
bits_per_byte = 8
return (bits + (bits_per_byte - 1)) // bits_per_byte |
def add_slash(m):
"""
Helper function that appends a / if one does not exist.
Prameters:
m: The string to append to.
"""
if m[-1] != "/":
return m + "/"
else:
return m |
def transpose(lst):
""" Swaps the first two dimensions of a two (or more) dimensional list
Args:
lst (:obj:`list` of :obj:`list`): two-dimensional list
Returns:
:obj:`list` of :obj:`list`: two-dimensional list
"""
t_lst = []
for i_row, row in enumerate(lst):
for i_col, ... |
def reverse_complement(seq: str) -> str:
"""
>>> seq_in = 'AATCGGTACAAGATGGCGGA'
>>> seq_out = 'TCCGCCATCTTGTACCGATT'
>>> reverse_complement(seq_in) == seq_out
True
>>> reverse_complement(seq_out) == seq_in
True
"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A',
... |
def GetElementValue(manifest, element_name):
"""Does some bad XML parsing."""
begin = manifest.find(element_name)
begin = manifest.find('"', begin)
begin += 1
end = manifest.find('"', begin)
return manifest[begin:end] |
def log_json(request_id, message, context={}):
"""Create JSON object for logging data."""
stmt = {"message": message, "request_id": request_id}
stmt.update(context)
return stmt |
def _get_labels(x_label, y_label, title, xlabel_str):
"""Sets the arguments *xlabel*, *ylabel*, *title* passed to the plot
functions :func:`plot_cluster_lines
<skfda.exploratory.visualization.clustering_plots.plot_cluster_lines>` and
:func:`plot_cluster_bars
<skfda.exploratory.visualization.clusteri... |
def get_ip_context(data):
"""
provide custom context information about ip address with data from Expanse API
"""
geo = {}
if len(data.get('locationInformation', [])) > 0:
if (data['locationInformation'][0].get('geolocation', {}).get('latitude') is not None
and data['locationInform... |
def about_view(request):
"""Display a page about the team."""
return {'message': 'Info about us.'} |
def default_image_name(role):
"""
Image name used by rbd and iscsi
"""
return 'testimage.{role}'.format(role=role) |
def false_negative(y_true, y_pred):
"""
Function to calculate false negative
:param y_true: list of true values
:param y_pred: list of predicted values
:return: number of false positives
"""
# intialize the counter
fn = 0
for yt, yp in zip(y_true, y_pred):
if yt == 1 and yp =... |
def pack_color(rgb_vec):
""" Returns an integer formed
by concatenating the channels of the input color vector.
Python implementation of packColor in src/neuroglancer/util/color.ts
"""
result = 0
for i in range(len(rgb_vec)):
result = ((result << 8) & 0xffffffff) + min(255,max(0,round(rg... |
def top_sentences(query, sentences, idfs, n):
"""
Given a `query` (a set of words), `sentences` (a dictionary mapping
sentences to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the `n` top sentences that match
the query, ranked according to idf... |
def logic_left_shift(a: int, b: int) -> str:
"""
Ambil 2 bilangan integer positif.
'a' adalah bilangan integer yang secara logis dibiarkan bergeser
sebanyak 'shift_amount' kali.
Yaitu (a << b) Kembalikan representasi biner yang bergeser.
>>> logic_left_shift(0, 1)
'0b00'
>>> logic_left_s... |
def make_shorthand(intrinsic_dict):
"""
Converts a given intrinsics dictionary into a short-hand notation that Fn::Sub can use. Only Ref and Fn::GetAtt
support shorthands.
Ex:
{"Ref": "foo"} => ${foo}
{"Fn::GetAtt": ["bar", "Arn"]} => ${bar.Arn}
This method assumes that the input is a val... |
def dict_match(matcher, matchee):
"""
Returns True if each key,val pair is present in the matchee
"""
for key, val in matcher.items():
if not matchee.get(key):
return False
elif not isinstance(matchee.get(key), list):
mval = [matchee.get(key)]
else:
... |
def binary_count_setbits(a: int) -> int:
"""
Take in 1 integer, return a number that is
the number of 1's in binary representation of that number.
>>> binary_count_setbits(25)
3
>>> binary_count_setbits(36)
2
>>> binary_count_setbits(16)
1
>>> binary_count_setbits(58)
4
... |
def pad_msg16(msg):
"""
Pad message with space to the nearest length of multiple of 16.
Parameters
----------
msg : bytes
The original message.
Returns
-------
bytes
Padded message to the nearest length of multiple of 16.
"""
# Calculate number of segments of 1... |
def _defaultHandler(packetNum, packet, glob):
"""default packet handler
Args:
packetNum (int): packet number
packet (obj): packet
glob (dict): global dict
Returns:
dict: glob
"""
print(packetNum, packet)
return glob |
def cast_env_to_int_error(what):
"""
Retrieves the "can not cast from environment variable to integer" error
message.
:param what: Environment variable name.
:return: String - Can not cast from environment variable to integer.
"""
return "ERROR: " + what + " value cannot be cast from ENV va... |
def text_node(tree_or_elem, xpath, onerror=None, ifnone=None):
"""
Get the text node of the referenced element.
If the node cannot be found, return `onerror`:
If the node is found, but its text content is None,
return ifnone.
"""
try:
text = tree_or_elem.find(xpath).text
except ... |
def question_node_shallow_copy(node):
"""
Create a copy of the question tree node
"""
new_node = {
'type': node['type'],
'inputs': node['inputs'],
}
if 'value_inputs' in node:
new_node['value_inputs'] = node['value_inputs']
else:
new_node['value_inputs'] = []
... |
def address_split(address, env=None):
"""The address_split() function splits an address into its four
components. Address strings are on the form
detector-detectorID|device-deviceID, where the detectors must be in
dir(xtc.DetInfo.Detector) and device must be in
(xtc.DetInfo.Device).
@param address Full dat... |
def get_manifest_indexes(manifest, channel, column):
"""Get the indices for channel and column in the manifest"""
channel_index = -1
for x in range(len(manifest["channels"])):
if manifest["channels"][x]["channel"] == channel:
channel_index = x
break
if channel_index == -1... |
def get_class_from_testname(clazz: str) -> str:
"""
get the test class from the full test method name
:param clazz: e.g. org.apache.commons.lang3.text.translate.NumericEntityUnescaperTest::testSupplementaryUnescaping
:return: e.g. org.apache.commons.lang3.text.translate.NumericEntityUnescaperTest
""... |
def utils_args_str(*args):
"""format a list of args for use with utils.py"""
return ' '.join(['--arg={}'.format(arg) for arg in args]) |
def legendre_symbol(a, p):
"""Compute the Legendre symbol."""
if a % p == 0: return 0
ls = pow(a, (p - 1)//2, p)
return -1 if ls == p - 1 else ls |
def signature(word, loc, lowercase_known):
"""
This routine returns a String that is the "signature" of the class of a
word. For, example, it might represent whether it is a number of ends in -s. The
strings returned by convention match the pattern UNK-.* , which is just assumed
to not match any rea... |
def esc_and_quotation(src):
"""Do escape and add quotations."""
return ''.join((
'"',
(src
.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\n', '\\n')
.replace('\r', '\\r')
.replace('\t', '\\t')),
'"'
)) |
def fit_to_unit(data):
"""
Shift and rescale `data` to fit unit interval.
>>> rescale_x([5, 10, 15])
[0.0, 0.5, 1.0]
"""
head = data[0]
data = [x - head for x in data]
tail = data[-1:][0]
return [x/float(tail) for x in data] |
def get_relative_project_path(project_dir, git_dir):
"""Return relative project path of absolute git repo path
/softagram/input/projects/c2d6d783-cef7-4197-b682-46ae297473d8/Project/subfolder/git-repo
-->
/Project/subfolder/git-repo
:param project_dir: Project dir, e.g. /softagram/foo/bla/parallel... |
def get_weight(item):
"""Get sort weight of a given viewlet"""
_, viewlet = item
try:
return int(viewlet.weight)
except (TypeError, AttributeError):
return 0 |
def _formparams_to_dict(s1):
""" Converts the incoming formparams from Slack into a dictionary. Ex: 'text=votebot+ping' """
retval = {}
for val in s1.split('&'):
k, v = val.split('=')
retval[k] = v
return retval |
def count_musicians_range(musicians, instrument=None):
"""Return a count of musicians by their chosen instrument.
If no instrument is provided by the caller then count all
musicians. If an instrument is provided (e.g., 'trumpet')
count only musicians whose instrument matches the passed in
instrument... |
def process_annotation(annot):
""" This function process the annotation to extract methods having given annotation
@parameters
annot: Annotation condition (Ex: @Test)
@return
This function returns starting and ending character of the annotation"""
annot_start = an... |
def replace_first_line(text: str, first_line: str) -> str:
"""Replaced the first line in 'text', setting it to 'first_line' instead.
A modified copy of the text is returned.
"""
lines = text.splitlines()
lines[0] = first_line
return '\n'.join(lines) |
def right(s, amount):
"""
Returns the right characters of amount size
"""
return s[-amount:] |
def get_list(data_dict, key, optional=False):
"""
Extract a list from a data_dict and do a bit of error checking
"""
if key not in data_dict:
if optional:
return None
else:
raise ValueError('Key "{}" not present in data'.format(key))
l = data_dict[key] # noq... |
def human_seconds_short(interval):
"""Formats a number of seconds as a short human-readable M:SS
string.
"""
interval = int(interval)
return u'%i:%02i' % (interval // 60, interval % 60) |
def get_marketing_cloud_visitor_id(visitor):
"""Get Marketing Cloud visitor ID"""
if not visitor:
return None
visitor_values = visitor.get_visitor_values()
return visitor_values.get("MCMID") |
def number_to_index(value, num_columns):
"""Given a number and a number of columns, convert the number to an absolute index.
:param value: The raw index (could be negative).
:param num_columns: The maximum number of columns available.
:returns: The adjusted positive column number.
:raises ValueErro... |
def map_diameter(c: int) -> float:
""" Compute the diameter """
return 1 / 3 * (c + 1) * (c - 1) |
def get_pipenv_dir(py_version, envs_dirs_base):
"""
Get the direcotry holding pipenv files for the specified python version
Arguments:
py_version {float} -- python version as 2.7 or 3.7
Returns:
string -- full path to the pipenv dir
"""
return "{}{}".format(envs_dirs_base, int(py... |
def foo1(value):
"""
foo1
:param value:
:return:
"""
if value:
return value
else:
return None |
def calc_diff(prev, curr):
"""Returns percentage difference between two values."""
return ((curr - prev) / prev * 100.0 if prev != 0 else float("inf") *
abs(curr) / curr if curr != 0 else 0.0) |
def sort_ipv4_addresses_without_mask(ip_address_iterable):
"""
Sort IPv4 addresses only
| :param iter ip_address_iterable: An iterable container of IPv4 addresses
| :return list : A sorted list of IPv4 addresses
"""
return sorted(
ip_address_iterable,
key=lambda ... |
def _invert_dict(dictionary):
"""
Returns:
A copy of *dictionary*, with inverted keys and values.
"""
return {v: k for k, v in dictionary.items()} |
def _get_shape_str(shape):
"""Convert image shape to string for filename description
"""
return '{}_{}'.format(*shape[:2]) |
def MEAN(src_column):
"""
Builtin average aggregator for groupby. Synonym for tc.aggregate.AVG. If
src_column is of array type, and if array's do not match in length a NoneType is
returned in the destination column.
Example: Get the average rating of each user.
>>> sf.groupby("user",
... {'r... |
def validate_int_to_str(x):
"""
Backward compatibility - field was int and now str.
Property: NetworkInterfaceProperty.DeviceIndex
Property: NetworkInterfaceAttachment.DeviceIndex
"""
if isinstance(x, int):
return str(x)
if isinstance(x, str):
return str(int(x))
raise T... |
def _reorder(string, salt):
"""Reorders `string` according to `salt`."""
len_salt = len(salt)
if len_salt != 0:
string = list(string)
index, integer_sum = 0, 0
for i in range(len(string) - 1, 0, -1):
integer = ord(salt[index])
integer_sum += integer
... |
def parse_raw(output):
"""Just return `output` as a single string assigned to dict key '_'
for reference in assertion expressions.
Returns {'_': output}
"""
return dict(_=output) |
def tempfile_content(tfile):
"""read the contents of the temp file"""
# This 'hack' is needed because some editors use an intermediate temporary
# file, and rename it to that of the correct file, overwriting it. This
# means that the tf file handle won't be updated with the new contents, and
# the t... |
def hasWildcard(name) :
"""Return true if the name has a UNIX wildcard (*,?,[,])
"""
if ( name.count('*') > 0 or name.count('?') > 0 or
name.count('[') > 0 or name.count(']') > 0 ) :
return True
else :
return False |
def calc_percent(percent, whole):
"""Utility method for getting percentage of whole
Parameters
----------
percent: int, float
whole: int, float
Returns
-------
int : the percentage of whole
"""
return int((float(percent * whole) / 100.0)) |
def filter_calls(filter_file):
"""create a filter in order to exclude traces wrapped at
calls not belonging to a specific group """
if not filter_file:
return []
temp = []
f = open(filter_file, "r")
for line in f:
temp.append(line.split('\n')[0] + ':' + 'libc.so')
return t... |
def markov_analyze(seq, order):
"""
Calculates the markov rules of the given order for the specified list of
data. The rules can be passed to `markov()` to generate a markov chain
based on the sequence analyzed.
Parameters
----------
seq : list
The list of data to analyse.
o... |
def create_interaction_id(example_id,
ith_table = None,
suffix = 0):
"""Returns an interaction_id created from example_id."""
if ith_table is None:
return f"{example_id}-{suffix}"
else:
return f"{example_id}/{ith_table}-{suffix}" |
def get_userpass_value(cli_value, config, key, prompt_strategy):
"""Gets the username / password from config.
Uses the following rules:
1. If it is specified on the cli (`cli_value`), use that.
2. If `config[key]` is specified, use that.
3. Otherwise prompt using `prompt_strategy`.
:param cli... |
def get_binary_mask_from_raw_address(raw_address: str) -> str:
"""
Return binary mask from raw address.
>>> get_binary_mask_from_raw_address("192.168.1.15/24")
'11111111.11111111.11111111.00000000'
>>> get_binary_mask_from_raw_address("91.124.230.205/30")
'11111111.11111111.11111111.11111100'
... |
def _select_algs(alg_type, algs, possible_algs, none_value=None):
"""Select a set of allowed algorithms"""
if algs == ():
return possible_algs
elif algs:
result = []
for alg_str in algs:
alg = alg_str.encode('ascii')
if alg not in possible_algs:
... |
def to_hex_colors(colors):
"""Adds # to a list of hex color codes.
Args:
colors (list): A list of hex color codes.
Returns:
list: A list of hex color codes prefixed with #.
"""
result = all([len(color.strip()) == 6 for color in colors])
if result:
return ["#" + color.st... |
def _evaluate_results(results):
""" Evaluate resulting assertions.
Evaluation is OK if all assertions are true, otherwise it is KO
Parameters
----------
results: list(bool)
List of all assertion execution results.
Returns
-------
str
'OK' if all assertions are true, 'K... |
def calc_size(shape, blocksize):
"""
Calculate the optimal size for a kernel according to the workgroup size
"""
if "__len__" in dir(blocksize):
return tuple((int(i) + int(j) - 1) & ~(int(j) - 1) for i, j in zip(shape, blocksize))
else:
return tuple((int(i) + int(blocksize) - 1) & ~(... |
def indices1d_remap_new_uv(old_indices, old_shape, new_shape, shift=(0, 0)): # Assume patch placed on left-upper
"""
:param old_indices: 1d index list for old_shape
:param old_shape: h,w of new image
:param new_shape: h,w of new image
:param shift: Horizontal and vertical shift from (left-upper) ... |
def pipe_filter(elems, pipe, fastbreak=True, w_rm=False, r_flags=False):
"""Return element given a filter pipe
Args:
elems (iterable) : list to filter from
pipe (list of callable) : a callable returns True on element to remove
fastbreak (bool) : stop pipe when a callable return T... |
def is_sorted(lst, le_cmp=None):
""" Check if a list is sorted
Args:
lst (:obj:`list`): list to check
le_cmp (:obj:`function`, optional): less than equals comparison function
Returns
:obj:`bool`: true if the list is sorted
"""
if le_cmp:
return all(le_cmp(a, b) for ... |
def get_fa_icon_class(app_config):
"""Return Font Awesome icon class to use for app."""
if hasattr(app_config, "fa_icon_class"):
return app_config.fa_icon_class
else:
return 'fa-circle' |
def bin2string(data):
"""Convert a byte-string to a unicode string."""
idx = data.find(b"\x00")
if idx != -1:
data = data[:idx]
return data.decode("utf-8") |
def isAdj(graph, i, j):
"""returns true if vertices i and j are adjacent (Undirected)"""
if (j in graph[i] or i in graph[j]):
return True
return False |
def get_credentials_from_dict(payload):
"""
Extract cloud-specific credentials from a dict with possibly other keys.
For example, given the following payload dict:
{
"os_auth_url": "https://jblb.jetstream-cloud.org:35357/v3",
"os_region_name": "RegionOne",
"id": 2,
"name... |
def find_order_price_levels(base_price, relative_levels, direction):
"""Calculates order price levels by base price and relative order levels
:param float base_price: base price for order price level calculating (f.e. current market price)
:param (list of float) relative_levels: relative order levels
:... |
def subtract(l0, l1):
"""Subtract list l1 from l0."""
return [e for e in l0 if e not in l1] |
def identify_full_ctrl_names(X_vars, orig_ctrl_names):
"""Return set of variable names actually used in regression, tolerating mangling of categoricals."""
X_vars = set(X_vars)
ctrls = []
for X_var in X_vars:
for orig_ctrl in orig_ctrl_names:
if X_var == orig_ctrl:
c... |
def gcd2(a, b):
"""
Greatest common divisor using Euclid's algorithm.
"""
while a:
a, b = b % a, a
return b |
def create_masks(degree):
"""
Create masks for taking bits from text bytes and
putting them to image bytes.
:param degree: number of bits from byte that are taken to encode text data in image
:return: a mask for a text and a mask for an image
"""
text_mask = 0b11111111
img_mask = 0b1111... |
def normalize_shape(shape):
"""
This function ensure that the given shape will be easily convertible
in a c++ callback (ie that it won't interfere badly in pybind11
overload resolution algorithm)
:example:
>>> normalize_shape([4, 5])
(4, 5)
:param shape: an iterable of integer... |
def generate_node_name(nodes):
"""
Returns a fresh node name not present in the given set. Assumes that node
names are integers.
"""
return max(nodes) + 1 |
def chunkify(input, chunk_size=20):
"""
A convenience function to chunk a list
"""
chunked = []
for i in range(0, len(input), chunk_size):
end = i + chunk_size if i + chunk_size < len(input) else len(input)
chunked.append(list(input[i:end]))
return chunked |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.