content stringlengths 42 6.51k |
|---|
def get_activities_from_log(trace_log, attribute_key="concept:name"):
"""
Get the attributes of the log along with their count
Parameters
----------
trace_log
Trace log
attribute_key
Attribute key (must be specified if different from concept:name)
Returns
----------
... |
def unique(seq):
"""Keep unique while preserving order."""
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))] |
def bytes_to_hex(bstr):
"""Convert a bytestring to a text string of hexadecimal digits.
This exists solely to support Python 3.4 for Cygwin users.
bytes(...).hex() was added in Python 3.5.
Note that most callers of this function need to encode the text string
back into a bytestring of ASCII charac... |
def T(a, p):
"""
the number of dots in tri-angle down
"""
ret = 0
ed = (p + 1) >> 1
for i in range(ed):
ret += a * i // p
return ret |
def create_message(payload, event_status, environment):
"""
Parameters
----------
payload: dict
Status -- str in {New Data Loaded, Daily Data Updated}
New Records -- int, number of new records added since previous run
Updated Records -- int, number of updated records from this ne... |
def gemi(red, nir):
"""Global Environment Monitoring Index boosted with Numba
See:
https://www.indexdatabase.de/db/i-single.php?id=25
"""
red2 = red ** 2
nir2 = nir ** 2
eta = (2 * (nir2 - red2) + (1.5 * nir) + (0.5 * red)) / (nir + red + 0.5)
return eta * (1 - 0.25*eta) - ((... |
def standardise_efficiency(efficiency):
"""Standardise efficiency types; one of the five categories:
poor, very poor, average, good, very good
Parameters
----------
efficiency : str
Raw efficiency type.
Return
----------
standardised efficiency : str
Standardised effici... |
def convert_public_keys_to_names(nodes_by_public_key, public_keys):
"""Convert a set/list of node public keys to a set of names"""
return {
nodes_by_public_key[public_key]['name'] if 'name' in nodes_by_public_key[public_key] \
else public_key \
for public_key in public_keys
} |
def get_datasets_and_restrictions(train_datasets='',
eval_datasets='',
use_dumped_episodes=False,
restrict_classes=None,
restrict_num_per_class=None):
"""Gets the list of dataset nam... |
def pwlcm(x, p):
"""
"""
if 0 < x <= p:
return x/p
elif p < x < 1:
return (1-x)/(1-p)
else:
print(x)
raise ValueError |
def startswith(string, prefixes):
"""Checks if str starts with any of the strings in the prefixes tuple.
Returns the first string in prefixes that matches. If there is no match,
the function returns None.
"""
if isinstance(prefixes, tuple):
for prefix in prefixes:
if string.start... |
def has_valid_parens(text):
"""
Checks if an input string contains valid parenthesis patterns.
:param text: input string
:return: boolean (True if the parentheses are valid, False otherwise)
"""
for i in range(len(text)):
text = text.replace('()', '').replace('{}', '').repla... |
def reverse_value_map(key_map, value_map):
"""Utility function for creating a
"reverse" value map from a given key map and value map.
"""
r_value_map = {}
for k, v in value_map.items():
sub_values = r_value_map[key_map[k]] = {}
for k2, v2 in v.items():
sub_values[v2] = k2... |
def _get_default_value_name(name):
"""Returns the class default value of an attribute.
For each specified attribute, we create a default value that is class-specific
and not thread-specific. This class-wide default value is stored in an
internal attribute that is named `_attr_default` where `attr` is the name ... |
def filterOnRange(intime,tstart,tstop):
"""filter on data within time ranges"""
outlist = []
for i in range(len(intime)):
for j in range(len(tstart)):
if intime[i] > tstart[j] and intime[i] < tstop[j]:
if len(outlist) == 0:
outlist.append(i)
... |
def check_ssid(ssid: str) -> str:
""" Check if SSID is valid """
if len(ssid) > 32:
raise ValueError("%s length is greater than 32" % ssid)
return ssid |
def is_pair(arg):
"""Return True if ARG is a non-empty list or vector."""
if isinstance(arg, list) and len(arg) > 0:
return True
else:
return False |
def pythagore_triangle(c, b):
"""
This function calculate the side of a right triangle using the Pythagore Theorem
:param c:
:param b:
:return:
"""
return ((c ** 2 - b ** 2) ** (0.5)) |
def newB(m, point):
"""find the y-intersection that the function/point pair passes through"""
b = (point[1] - (m * point[0]))
return b |
def walk(G, s, S=set()):
"""
Returns a traversal path from s on G
source: Python Algorithms Mastering Basic Algorithms in the Python Language, 2010, p.104
"""
P, Q, SG = dict(), set(), dict()
P[s] = None
SG[s] = G[s]
Q.add(s)
while Q:
u = Q.pop()
for v in set(G[u].ke... |
def get_latex_image_string(filename):
""" This function removes the final dot (".") and extension from the
filename, surrounds the remaining bits with braces ("{"), and sticks
the dot and extension back on.
"""
last_dot_index = filename.rfind(".")
f = filename[:last_dot_index]
exten... |
def dictation(m) -> str:
"""Arbitrary dictation."""
# Custom words are strings, phrases are lists
return " ".join([str(part).strip() for part in m]) |
def unquote(str):
"""Remove quotes from a string."""
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
return str[1:-1]
return str |
def _is_const(expr, value):
"""
Helper Method, given an expression, returns True
if the expression is a constant and is equal to
the value passed in with VALUE
"""
if expr["type"] == "const":
return value == expr["value"]
return False |
def create_composite_func(func0, func1):
"""Return a composite of two functions."""
if func0 is None:
return func1
if func1 is None:
return func0
return lambda x: func0(func1(x)) |
def validate_string(data: str) -> bool:
"""
Validate input for a field that must have a ``str`` value.
Args:
data (str): The data to be validated.
Returns:
bool: Validation passed.
Raises:
ValueError: Validation failed.
"""
if not isinstance(data, str):
rai... |
def short_to_decimal(code):
"""
Convert an ICD9 code from short format to decimal format.
"""
if len(code) <= 3:
return code.lstrip("0")
else:
return code[:3].lstrip("0") + "." + code[3:] |
def percent_clear_days(clear_days, total_days):
"""Returns the percentage of clear days, given
the number total days and clear days.
Parameters
----------
clear_days : int
Number of clear days.
total_days : int
Number of total days
Returns
-------
percent_clear : f... |
def eye(n, K):
"""
Returns an identity matrix of size n.
Examples
========
>>> from sympy.matrices.densetools import eye
>>> from sympy import ZZ
>>> eye(3, ZZ)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
result = []
for i in range(n):
result.append([])
for j in r... |
def format_underscore_template(name, content):
"""
Format the template as an Underscore.js template.
:param name: name of the template
:param content: content of the template
:return: string containing formatted template
"""
return '\n<script type="text/template" id="{0}">\n{1}\n</script>\n... |
def dict_merge(dct, merge_dct, add_keys=True):
"""
https://gist.github.com/angstwad/bf22d1822c38a92ec0a9?permalink_comment_id=2622319#gistcomment-2622319
Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
updating only top-level keys, dict_merge recurses down into dicts nested
... |
def safe_eval(source):
"""
Protected string evaluation.
Evaluate a string containing a Python literal expression without
allowing the execution of arbitrary non-literal code.
Parameters
----------
source : str
The string to evaluate.
Returns
-------
obj : object
... |
def is_number(obj):
"""
Checks if the given object is a number.
Parameters
----------
obj : Any
The input argument.
Returns
-------
test result : bool
The test result of whether obj can be converted to a number or not.
>>> is_number(3)
True
>>> is_number(1... |
def legacy_position_transform(positions):
"""
Transforms positions in the tree sequence into VCF coordinates under
the pre 0.2.0 legacy rule.
"""
last_pos = 0
transformed = []
for pos in positions:
pos = int(round(pos))
if pos <= last_pos:
pos = last_pos + 1
... |
def map_reads(snps, reads):
"""
Find READS mapped to each SNP position.
:return list of snps have read mapped to
"""
return [snp.detect_mapped_reads(reads) for snp in snps] |
def parse_response(response):
"""
Utility function to parse a response into a list.
"""
elements = []
for element in response['responses'][0]['labelAnnotations']:
elements.append(element['description'].capitalize())
return elements |
def sim_percentage_change(obj_1, obj_2):
"""Calculate the percentage change of two objects
Args:
obj_1 ([type]): object 1
obj_2 ([type]): object 2
Returns:
float: numerical similarity
"""
try:
a = float(obj_1)
b = float(obj_2)
max_ab = max(abs(a), ab... |
def find_missing_number_using_sum(arr, arr2):
"""
This approach may be problematic in case if arrays are two long
or elements are very small
"""
complete_sum = 0
for val in arr:
complete_sum += val
missing_sum = 0
for val in arr2:
missing_sum += val
return complet... |
def _verbosity_from_log_level(level):
"""Get log level from verbosity."""
if level == 40:
return 0
elif level == 20:
return 1
elif level == 10:
return 2 |
def _make_radial_gradient(X, Y):
"""Generates index map for radial gradients."""
import numpy as np
Z = np.sqrt(np.power(X, 2) + np.power(Y, 2))
return Z |
def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges |
def testMacFormat(macF):
"""Savoir si le format est dans la liste."""
if macF and macF.upper() in ('CISCO', 'UNIXE', 'BARE', 'NORMAL', 'UNIX', 'PGSQL'):
return macF
else:
return 'unixe' |
def w_binary_to_hex(word):
"""Converts binary word to hex (word is a list)
>>> w_binary_to_hex("111")
'0x7'
>>> w_binary_to_hex([1,1,1,1])
'0xf'
>>> w_binary_to_hex([0,0,0,0,1,1,1,1])
'0xf'
>>> w_binary_to_hex([0,1,1,1,1,1,0,0])
'0x7c'
"""
if isinstance(word, str):
... |
def sql(request_type, *args):
"""
Composes queries based on type of request.
"""
query = ''
if request_type == 'GET_ALL_USERS':
query = """ SELECT name FROM users"""
elif request_type == 'GET_USER_BY_ID':
query = """SELECT * FROM users where id = %s"""
elif request_type =... |
def keywords_parser(keywords):
"""
EM : Converts the string input from the GUI to a list object of strings.
"""
# Remove spaces
kwrds = keywords.replace(' ','')
# Split at ',' to separate time windows, then keep non-empty words
kwrds = [x for x in kwrds.split(',') if x]
if kwrds:
... |
def check_diagonals(board, player):
""" 2 diagonals check """
diagonal_1 = [board[0],board[4],board[8]] # 0 | 4 | 8
diagonal_2 = [board[2],board[4],board[6]] # 2 | 4 | 6
d_1_win = (diagonal_1.count(player) == 3)
d_2_win = (diagonal_2.count(player) == 3)
win = (d_1_win or d_2_win)
return w... |
def camelize(string, uppercase_first_letter=True):
"""
Convert a string with underscores to a camelCase string.
Inspired by :func:`inflection.camelize` but even seems to run a little faster.
Args:
string (str): The string to be converted.
uppercase_first_letter (bool): Determin... |
def try_id(item):
"""
Try and get the ID from an item, otherwise returning None.
"""
try:
return item.id
except AttributeError:
return None |
def generate_color_series(color, variation, diff=10, reverse=False):
"""Generate light and dark color series.
Args:
color (tuple) : Color [0,255]
variation (int) : How many colors to create.
diff (int) : How much to change
reverse (bool) : If ``True``, sort in descending... |
def sum_valid_rooms(valid_rooms):
"""
Get the sum of all the sector IDs in valid rooms.
Args:
valid_rooms (list): List containting tuples of valid rooms.
Returns:
int
"""
# Valid Room:
# (room_name, sector_id, checksum)
return sum([i[1] for i in valid_rooms]) |
def min_ge(seq, val):
"""
Same as min_gt() except items equal to val are accepted as well.
:param seq:
:param val:
:return:
Examples:
min_ge([1, 3, 6, 7], 6)
>>>6
min_ge([2, 3, 4, 8], 8)
>>>8
"""
for v in seq:
if v >= val:
return v
... |
def get_alpha(score, weighted_ave, C=8):
"""
Get the main interest score of the lean
return: score is from 0 to 1
"""
alpha = 1 + C * abs(score - weighted_ave) / weighted_ave
return alpha |
def _verify_src_version(version):
"""Checks to make sure an arbitrary character string is a valid version id
Version numbers are expected to be of the form X.Y.Z
Args:
version (str): string to validate
Returns:
bool: True if the string is a version number, else false
"""
if no... |
def execute(st, **kwargs):
"""
Work around for Python3 exec function which doesn't allow changes to the local namespace because of scope.
This breaks a lot of the old functionality in the code which was originally in Python2. So this function
runs just like exec except that it returns the output of the ... |
def hex2dec(s):
""" Convert hex string to decimal number. Answer None if conversion raises
an error.
>>> hex2dec('0064')
100
>>> hex2dec('FFFF')
65535
>>> hex2dec(dec2hex(32))
32
>>> hex2dec('FFZ') is None
True
"""
try:
return int(s, 16)
except ValueError:
... |
def get_param_map(iline, word, required_keys=None):
"""
get the optional arguments on a line
Examples
--------
>>> iline = 0
>>> word = 'elset,instance=dummy2,generate'
>>> params = get_param_map(iline, word, required_keys=['instance'])
params = {
'elset' : None,
'instan... |
def qsort_partition(arr: list, low: int, high: int):
"""
Quicksort partition logic.
The first element is chosen as the pivot
"""
i = low
j = high
pivot = arr[low]
while i < j:
i += 1
while i < high and pivot > arr[i]:
i += 1
j -= 1
... |
def list2dict(values_list):
"""A super simple function that takes a list of two element iterables
and returns a dictionary of lists keyed by the first element.
This: [("A","1"), ("A","2"), ("B","1"), ("C","1")]
Becomes: {"A": ["1", "2"], "B": ["1"], "C": ["1"] }
Arguments:
- `... |
def isInt(string):
"""
Determine whether a string is an int
@param string: the string to check
@return True if the string is an int, False otherwise
"""
try: int(string)
except: return False
return True |
def sequential_search_ordered(a_list, item):
"""Sequential search by ordering first."""
a_list = sorted(a_list)
pos = 0
is_found = False
is_stop = False
while pos < len(a_list) and not is_found and not is_stop:
if a_list[pos] == item:
is_found = True
else:
... |
def generate_search_space(max_x, max_y):
"""
@params: max_x : x axis consists of integer multiples of 8. (each value in the range(8, max_x+1. 8) represents one ihls)
@params: max_y : y axis just consists of powers of 2. (each value in the range 1,2,4,8,16,32 ... max_y (exclusive) represents one df)
Each... |
def cmds_to_bash(cmds):
"""Turn a list of cmds into a bash script.
"""
return """\
#!/bin/bash
set -vexubE -o pipefail
%s
""" % '\n'.join(cmds) |
def create_8021Q_vea_cmd(lpar_id, slotnum, port_vlan_id, addl_vlan_ids):
"""
Generate IVM command to create 8021Q virtual ethernet adapter.
:param lpar_id: LPAR id
:param slotnum: virtual adapter slot number
:param port_vlan_id: untagged port vlan id
:param addl_vlan_ids: tagged VLAN id list
... |
def pluralized(word):
"""
Get the plural of the given word. Contains a dictionary for non-standard
plural forms. If the word ends in one of 5 known endings, appends an 'es'
to the end. By default, just appends an 's' to the given word.
@param word: the word to pluralize
@return: the plural form... |
def is_class_or_instance(obj, cls):
"""returns True is obj is an instance of cls or is cls itself"""
return isinstance(obj, cls) or obj is cls |
def camel_to_snake(name: str) -> str:
"""Convert CamelCase to snake_case, handling acronyms properly."""
out = name[0].lower()
for c0, c1, c2 in zip(name[:-2], name[1:-1], name[2:]):
# Catch lower->upper transitions.
if not c0.isupper() and c1.isupper():
out += "_"
# Catc... |
def needs_update(version, upstream):
"""
Do a dumb comparison to determine if the version needs to be updated.
"""
if "+git" in version:
# strip +git and see if this is a post-release snapshot
version = version.replace("+git", "")
return version != upstream |
def unpack_numpy(var, count, dtype, buff):
"""
create numpy deserialization code
"""
return var + " = numpy.frombuffer(%s, dtype=%s, count=%s)"%(buff, dtype, count) |
def print_formatted_2(output):
"""
textual output of mecules in 3 |-separated field per line (and per molecule).
molecule id | list of atom indexes | list of chemical shifts in the same order as in the list of atom indexes
"""
output_formatted = ""
for (molid, curmol) in output:
atomids = ' '.join([str(curatom[... |
def remove_blank_chars(text):
"""
(str) -> str
Removes superfluous blank characters from text, leaving at most
a single space behind where there was more than one (space or newline)
>>> remove_blank_chars('Happy \n \n Birthday')
"Happy Birthday"
:param text: text from which to rem... |
def format_line(line):
"""format list into a csv line"""
return ",".join(line) |
def _test(language, test_language=None):
"""Test language."""
return test_language is None or test_language == '*' or language == test_language |
def select(subject, result_if_one, result_if_zero):
# type: (int, int, int) -> int
"""Perform a constant time(-ish) branch operation"""
return (~(subject - 1) & result_if_one) | ((subject - 1) & result_if_zero) |
def truncate(n: float, decimals: int = 0) -> float:
"""
Support function to truncate any float value to a specified decimal points
"""
multiplier = 10 ** decimals
return int(n * multiplier) / multiplier |
def preprocess_for_cse(expr, optimizations):
""" Preprocess an expression to optimize for common subexpression
elimination.
Parameters
==========
expr : sympy expression
The target expression to optimize.
optimizations : list of (callable, callable) pairs
The (preprocessor, pos... |
def unquote_to_bytes(string):
"""unquote_to_bytes('abc%20def') -> b'abc def'."""
# Note: strings are encoded as UTF-8. This is only an issue if it contains
# unescaped non-ASCII characters, which URIs should not.
if isinstance(string, str):
string = string.encode('utf-8')
res = string.split(... |
def check_x_path(current, end, state):
"""Tells the robot to change spaces on the x axis."""
change = False
if current[1] > end[1] and state[current[0]][current[1] - 1].get() == 0:
current[1] -= 1
change = True
elif current[1] < end[1] and state[current[0]][current[1] + 1].get() == 0:
... |
def format_price(price):
"""Format price with two decimal places."""
return f"${price:.2f}" |
def strtobool(val: str) -> bool:
"""Convert a string representation of truth to True or False.
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
if not isinstance(val, str):
... |
def ternary_search(func, lo, hi, abs_prec=1e-7):
""" Find maximum of unimodal function func() within [lo, hi] """
while abs(hi - lo) > abs_prec:
lo_third = lo + (hi - lo) / 3
hi_third = hi - (hi - lo) / 3
if func(lo_third) < func(hi_third):
lo = lo_third
else:
... |
def escape_underscores(s):
"""
escape underscores with back slashes
separate function to keep f strings
from getting too long
:param s: a string
:return: s with underscores prefixed with back slashes
"""
return s.replace("_", "\_") |
def select_pred_files(model_fn,curr_ana_l):
"""
Get all files related to a particular analysis
Parameters
----------
model_fn : list
all files in a particular analysis folder
curr_ana_l : list
name of model we are going to analyze
Returns
-------
list
files t... |
def get_techniques_of_tactic(tactic, techniques):
"""Given a tactic and a full list of techniques, return techniques that
appear inside of tactic
"""
techniques_list = []
for technique in techniques:
for phase in technique['kill_chain_phases']:
if phase['phase_name'] == tact... |
def copy_peps_tensors(peps):
"""
Create a copy of the PEPS tensors
"""
cp = []
for x in range(len(peps)):
tmp = []
for y in range(len(peps[0])):
tmp += [peps[x][y].copy()]
cp += [tmp]
return cp |
def is_list(obj: object):
"""Returns true if object is a list. Principle use is to determine if a
field has undergone validation: unvalidated field.errors is a tuple,
validated field.errors is a list."""
return isinstance(obj, list) |
def _to_value_seq(values):
"""
:param values: Either a single numeric value or a sequence of numeric values
:return: A sequence, possibly of length one, of all the values in ``values``
"""
try:
val = float(values)
return [val,]
except (ValueError, TypeError):
return valu... |
def SplitLines( contents ):
"""Return a list of each of the lines in the unicode string |contents|."""
# We often want to get a list representation of a buffer such that we can
# index all of the 'lines' within it. Python provides str.splitlines for this
# purpose. However, this method not only splits on newli... |
def compute_Cp(T,Cv,V,B0,beta):
"""
This function computes the isobaric heat capacity from the equation:
:math:`Cp - Cv = T V beta^2 B0`
where *Cp,Cv* are the isobaric and isocoric heat capacities respectively,
*T* is the temperature, *V* the unit cell volume, *beta* the volumetric
thermal... |
def convert_to_pronoun(day):
"""Take input "day" as a datatype integer, and convert to datatype string"""
if day == 0:
return "Monday"
if day == 1:
return "Tuesday"
if day == 2:
return "Wednesday"
if day == 3:
return "Thursday"
if day == 4:
return "Friday"
if day == 5:
return "Saturday"
if day == 6:... |
def isint(a):
"""
Test for integer.
"""
return(type(a) == int) |
def parser_preferred_name_list_Descriptor(data,i,length,end):
"""\
parser_preferred_name_list_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "preferred_name_list", "contents" : unparsed_descriptor_co... |
def divisors(n, with_1_and_n=False):
"""
https://stackoverflow.com/questions/171765/what-is-the-best-way-to-get-all-the-divisors-of-a-number#171784
"""
# Get factors and their counts
factors = {}
nn = n
i = 2
while i*i <= nn:
while nn % i == 0:
if i not in factors:
... |
def build_type_define(build_type=None):
"""
returns definitions specific to the build type (Debug, Release, etc.)
like DEBUG, _DEBUG, NDEBUG
"""
return 'NDEBUG' if build_type in ['Release', 'RelWithDebInfo', 'MinSizeRel'] else "" |
def parse_file_path(file_path):
"""Extract file metadata from its path."""
file_name = file_path.split('/')[-1]
name_components = file_name.split('.')
sample_name = name_components[0]
result_type = name_components[1]
file_type = name_components[2]
return sample_name, result_type, file_type |
def get_joints_time(controller_joints, time):
""" Converte a single time to an array of time """
if isinstance(time, (int, float)):
times = {}
for key in controller_joints:
times[key] = time
else:
times = time
return times |
def order_validation(order):
"""
Validate the order. If it's under 2 then raise a ValueError
"""
if order < 2:
raise ValueError("An order lower than two is not allowed.")
else:
return order |
def get_sid_set(sources):
"""
Compile all the SID's which appear inside the Chemical Vendors or Legacy
Depositors entries in a pubchem JSON file. From my current understanding
SID is a unique entry that identifies a product+manufacturer. There should
be no duplicates. Therefore we assert that this i... |
def get_num_den_accs(acc_time_str):
"""
Get num and den for accumulation period.
Parameters
----------
acc_time_str : str
accumulation time (e.g. "1/3").
Returns
-------
num : int
numerator of the fraction.
den : int
denominator of the fractio... |
def build_evaluation_from_config_item(configuration_item, compliance_type, annotation=None):
"""Form an evaluation as a dictionary. Usually suited to report on configuration change rules.
Keyword arguments:
configuration_item -- the configurationItem dictionary in the invokingEvent
compliance_type -- ei... |
def listdir_matches(match):
"""Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash.
"""
import os
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.