content stringlengths 42 6.51k |
|---|
def _row_key(row):
"""
:param row: a normalized row from STATEMENT_METRICS_QUERY
:return: a tuple uniquely identifying this row
"""
return row['database_name'], row['user_name'], row['query_signature'], row['query_hash'], row['query_plan_hash'] |
def print_variables(dictionary:dict):
"""Print the top level elements in a dictionary"""
keys = dictionary.keys()
for k in keys:
print(k,':', dictionary[k])
return None |
def _GetValueOrBlank(element, user_input=None):
"""
If an element is missing from the XML file reading the .text value will return an error.
If the element does not exist return ""
"""
if user_input == None:
return element.text
else:
return user_input |
def flatten_list_of_lists(list_of_lists):
"""
Flattens a list of lists
:param list_of_lists: List of lists
:return: Flatten list of lists
"""
return [item for sublist in list_of_lists for item in sublist] |
def parse_int (string: str) -> int:
""" Transform a string into a digit """
return int(''.join((filter(lambda x: x.isdigit(), string)))) |
def format_table(table, extra_space=1):
"""
Note: src.utils.prettytable is more powerful than this, but this
function can be useful when the number of columns and rows are
unknown and must be calculated on the fly.
Takes a table of collumns: [[val,val,val,...], [val,val,val,...], ...]
where eac... |
def get_file_line_count(filename):
""" Get the line count for the specified file """
with open(filename) as f:
return sum(1 for _ in f) |
def parse_kernel_arguments(block):
"""
Parse the kernel arguments of a code block,
returning a tuple of (args, kwargs)
Parameters
----------
block
Returns
-------
tuple
Notes
-----
The allowed positional arguments are
- kernel_name
- chunk_name
Other posi... |
def _standardize_args(
inputs, initial_state, constants, num_constants, num_inputs=1):
"""Standardizes `__call__` to a single list of tensor inputs.
When running a model loaded from a file, the input tensors
`initial_state` and `constants` can be passed to `RNN.__call__()` as part
of `inputs` instead of by... |
def check_show_plat_vm(output, supported_nodes):
"""Check if all supported nodes reached FINAL Band status"""
entries_in_show_plat_vm = []
lines = output.splitlines()
for line in lines:
line = line.strip()
if len(line) > 0 and line[0].isdigit():
entries_in_show_plat_vm.appen... |
def adjust_to_360(val, key):
"""
Take in a value and a key. If the key is of the type:
declination/longitude/azimuth/direction, adjust it to be within
the range 0-360 as required by the MagIC data model
"""
CheckDec = ['_dec', '_lon', '_azimuth', 'dip_direction']
adjust = False
for dec_... |
def match_context_key(key):
"""Set the case of a context key appropriately for this project, Roman
always uses upper case.
"""
return key.upper() |
def encode2(Gender):
"""
This function encodes a loan status to either 1 or 0.
"""
if Gender == 'Male':
return 1
else:
return 0 |
def get_list_of_new_entries(device_entries: list, file_entries: list) -> list:
"""
Compares log entries from the local logfile with the log entries from the device
Args:
device_entries (list): List of LogEntry Objects, fetched from the device
file_entries (list): List of LogEntry Objects, f... |
def no_control_panel(on=0):
"""Desabilitar o Painel de Controle
DESCRIPTION
Esta configuracao lhe permite restringir o acesso dos usuarios as
opcoes do Painel de Controle.
COMPATIBILITY
Windows 2000/Me/XP
MODIFIED VALUES
NoControlPanel : dword : 00000000... |
def _buf_split(b):
""" take an integer or iterable and break it into a -x, +x, -y, +y
value representing a ghost cell buffer
"""
try:
bxlo, bxhi, bylo, byhi = b
except (ValueError, TypeError):
try:
blo, bhi = b
except (ValueError, TypeError):
blo = b
... |
def command_requires_log_name(command):
"""Check if the specified command requires the --audit-log-name option.
command[in] command to be checked
"""
return command == "COPY" |
def recvall(sock, n):
"""
returns the data from a recieved bytestream, helper function to receive n bytes or return None if EOF is hit
:param sock: socket
:param n: length in bytes (number of bytes)
:return: message
"""
data = b''
while len(data) < n:
packet = sock.recv(n - len(d... |
def newtons_method_1d(f, df_dx, x0, tol):
"""Return the root of `f` within `tol` by using Newton's method.
Parameters
----------
f : callable[[float], float]
The function of which the root should be found.
df_dx : callable[[float], float]
The derivative of `f`.
x_0 : float
... |
def is_empty_questiongroup(qg_dict):
"""
Check if a questiongroup dictionary contains only empty values. Also checks
for empty translation strings.
Args:
qg_dict: dict.
Returns:
bool.
"""
for question, question_data in qg_dict.items():
if isinstance(question_data, d... |
def reformat_matrix(index, weigths):
"""Reformating of the embedded matrix for exporting.
Args:
index: index of activities or roles.
weigths: matrix of calculated coordinates.
Returns:
matrix with indexes.
"""
matrix = list()
for i, _ in enumerate(index):
data = [... |
def mean(data):
"""Calculate the mean of a list."""
return sum(data) / float(len(data)) |
def array_get(array, idx, fallback):
"""
Retrieves the item at position idx in array, or fallback if out of bounds
"""
try:
return array[idx]
except IndexError:
return fallback |
def avg_precision(labeled_results, k=10):
"""
Returns The average precision at k.
"""
labeled_results = labeled_results[:k]
result_count = 0
_sum = 0
for idx, val in enumerate(labeled_results):
if val == 1:
result_count += 1
_sum += result_count / (idx + 1)
... |
def fnsMakeReadable(sCmd, lOut):
""" Put HTML line breaks into command and its output lines. """
sOut = "<br/>".join(lOut)
return sCmd + "<br/>" + sOut |
def convert_sv_types(field_dict):
"""
SignalVine has it's own types that we'll map over to Python primatives.
"""
new_dict = {}
for k, v in field_dict.items():
print(k, v)
if "Maybe" in v:
required = False
else:
required = True
if "Boolean" ... |
def payoff_call(underlying, strike, gearing=1.0):
"""payoff_call
Payoff of call option.
:param float underlying:
:param float strike:
:param float gearing: Coefficient of this option. Default value is 1.
:return: payoff call option.
:rtype: float
"""
return gearing * max(underlying ... |
def green(string):
"""
Convert a string to green text
:string: the string to convert to green text
"""
return f'\033[92m{string}\033[0m' |
def aliasDictionary(sequence, aliases):
"""
Given a dictionary of
aliases of the form {standard_string_names: list of possible aliases}
this finds occurances of aliases (ignoring capitalization) in the sequence
of strings called sequence and returns a dictionary
Dict(alias: standard_string_name)... |
def extract_ip_from_oid(oid):
"""Given a dotted OID string, this extracts an IPv4 address from the end of it (i.e. the last four decimals)"""
return ".".join(oid.split(".")[-4:]) |
def remove_empty_parameters(data):
"""Accepts a dictionary and returns a dict with only the key, values where the values are not None."""
return {key: value for key, value in data.items() if value is not None} |
def validate_input(input_list):
"""
>>> validate_input([1,2,3])
False
>>> validate_input([[1,2,3]])
False
>>> validate_input([])
False
>>> validate_input([[1,3], [12, 9]])
False
>>> validate_input([[1,3], [12, "33"]])
False
>>> validate_input([[1,3]])
True
... |
def get_entity_name(entity):
"""
Returns the entity name after stripping off namespace and/or version information
Args:
entity: The full entity name
"""
components = entity.split('.')
return components[len(components)-1] |
def hex8_ctr(elem_coords):
"""Compute the coordinates of the center of a hex8 element.
Simple average in physical space.
The result is the same as for hex8_subdiv with intervals=1.
Input:
elem_coords: coordinates of element's nodes, assuming exodus
node order convention - (co... |
def encode_special_characters(string: str) -> str:
"""Make string safe for urls as required by REST APIs"""
char_mapping = {"#": ";23", "&": ";26", "/": "|", "*": ";2A"}
for char, encoded_char in char_mapping.items():
string = string.replace(char, encoded_char)
return string |
def insensitive(string):
"""Given a string, returns its lower/upper case insensitive string"""
if getattr(str,'casefold',None) is not None:
insen = lambda str_name: str_name.casefold()
else:
insen = lambda str_name: str_name.upper().lower()
return insen(string) |
def add_months(year, months, offset):
"""
Add a number of months to the passed in year and month, returning
a tuple of (year, month)
"""
months = months - 1 # 0 index months coming in
nextmonths = months + offset
months_offset = nextmonths % 12 + 1 # 1 index it going out
years_offset =... |
def str_time(t):
""" Return the time such as %H:%M:%S.
Parameters
----------
t : int
Time in seconds.
Returns
-------
str
Time in hours, minutes and seconds.
"""
txt = ''
s, t = t % 60, t // 60
if s < 10:
s = '0' + str(s)
m, h = t % 60, t // 60... |
def monobook_hack_skin_html(doc):
"""
Hacks Monobook HTML output: use CSS ids for hacked skin.
See monobook_hack_skin_css.
"""
doc = doc.replace('<div id="globalWrapper">', '<div id="globalWrapperHacked">')
doc = doc.replace('<div id="footer">', '<div id="footerHacked">')
doc = doc.replace(... |
def upperfy(key):
"""Receive a string key and returns its upper version.
Example:
input: foo
output: FOO
input: foo_bar
output: FOO_BAR
input: foo__bar__ZAZ
output: FOO__bar__ZAZ
Arguments:
key {str} -- A string key that may contain dunders `__`
Returns:... |
def caesar(shift, data, shift_ranges=('az', 'AZ')):
"""
Apply a caesar cipher to a string.
The caesar cipher is a substition cipher where each letter in the given
alphabet is replaced by a letter some fixed number down the alphabet.
If ``shift`` is ``1``, *A* will become *B*, *B* will become *C*, ... |
def kwsparams2list(params):
"""Convert parameters dict to a list of string of a format 'key=value'"""
return ['{}={}'.format(k, v) for k, v in params.items()] |
def fibonacci(number:int) -> int:
"""
Returns the n'th fibonacci sequence number
>>> fibonacci(number=10)
55
"""
PHI = (1 + 5 ** 0.5) / 2
return int((PHI**number - (-PHI)**(-number))/(5**0.5)) |
def _compute_fans(shape):
"""Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of integer scalars (fan_in, fan_out).
"""
if len(shape) < 1: # Just to avoid errors for constants.
fan_in = 1
fan_out = 1
el... |
def get_conns_regex(with_groups=False):
"""
Notes:
Function was created to have groups and no-groups regex near, to
remember to change both simultaneously.
Need to groups and no-groups are mixed meshes.
When returning groups, the following groups are returned:
* ele... |
def update(_dict, obj, keys):
"""
Update *_dict* with *obj*'s values from keys.
"""
for field_name in keys:
_dict[field_name] = getattr(obj, field_name)
return _dict |
def generate_submission_compiled_patch_notes_template_line(line_number: int):
"""
For a given line number, construct the template line for the community-compiled patch notes.
"""
return f">{str(line_number)} |\n\n" |
def factorial_iterative(n):
"""factorial_iterative(n) returns product of the integers 1 thru n """
factorial = 1
for i in range(n):
factorial = factorial * (i + 1)
return factorial |
def balanced_parenthesis(string2check: str) -> bool:
"""Check for balanced parenthesis. Used for syntax check."""
pairs = {"(": ")"}
match_chk = []
for char in string2check:
if char == "(":
match_chk.append(char)
elif match_chk and char == pairs[match_chk[-1]]:
ma... |
def valid_tour(tour, cities) -> bool:
"""
Is tour a valid tour for these cities?
"""
return set(tour) == set(cities) and len(tour) == len(cities) |
def dec_to_bin(x):
"""Convert from decimal number to a binary string representation."""
return bin(x)[2:].zfill(4) |
def dategetter(date_property, collection):
"""
Attempts to obtain a date value from a collection.
:param date_property: property representing the date
:param collection: dictionary to check within
:returns: `str` (ISO8601) representing the date (allowing
for an open interval using n... |
def hours_to_minutes(hours:str)->int:
""" Converts hours to minutes """
return int(hours)*60 |
def mark_train_test(filename_parts):
"""Mark video with train/test
This script contains the rules with which we create train and test set.
The rules are based on the filename_parts string list
"""
assert len(filename_parts)>=4
classname, location, date, time_interval = filename_parts[:4]
... |
def is_boolean(val):
"""
Return True iff this is a boolean
"""
return isinstance(val, bool) |
def _no_constraint(info_list):
"""
If there is no constraint set, then anything passes.
"""
try:
if len(info_list) == 0:
return True
except TypeError:
# constraint not set (weirdness in DB)
return True
return False |
def _chain_dicts(dict0, *dicts):
"""
Combine / concatenate multiple dicts
"""
r = dict(dict0.items())
for dict_i in dicts:
r.update(dict_i)
return r |
def invert(array):
"""return a dictionary mapping array values to arrays of indices
containing those values
"""
inverted_array = {}
for i, val in enumerate(array):
inverted_array.setdefault(val, []).append(i)
return inverted_array |
def dual_norm(lp):
""" Returns the dual norm value (as a numeric!) from a (possibly numeric)
input
"""
return {'l_2': 2,
'l2': 2,
'l_inf': 1,
'linf': 1,
'l_1': float('inf'),
'l1': float('inf'),
2: 2,
float('inf'): 1,... |
def create_board(size):
""" Returns an board of size n^2
Arguments:
size {[int]} -- [size of the board]
Returns:
board{array[int]} -- [ matrix of size nxn]
"""
board = [0]*size
for ix in range(size):
board[ix] = [0]*size
return board |
def object_origin(width, height, depth):
"""
This function takes inputs and returns vertex and face arrays.
no actual mesh data creation is done here.
"""
verts = [(+0.0, +0.0, +0.0)]
faces = []
# apply size
for i, v in enumerate(verts):
verts[i] = v[0] * width, v[1] * depth, v[... |
def ajuda(msn):
"""Funcao de apresentar o help em Python
Args:
msn (str): Faz chamada para a variavel fun do programa principal
Returns:
str: Retorno da funcao help do Python
"""
print('\033[0;34;47m')
return help(msn) |
def scale(v,sc):
"""Create Scaled Vector function.
Parameters
----------
v : list
A 3-element list.
sc : int or float
The scaling factor.
Returns
-------
tuple
Returns the given vector scaled by scaling factor.
Examples
--------
>>> import numpy... |
def fromTrajectory1d( traj ):
"""Converts Core.Trajectory1d to a list of 2-tuple"""
if traj is None: return None
return [ (traj.getKnotPosition(i), traj.getKnotValue(i)) for i in range(traj.getKnotCount()) ] |
def _get_last_td(el):
"""
Return last <td> found in `el` DOM.
Args:
el (obj): :class:`dhtmlparser.HTMLElement` instance.
Returns:
obj: HTMLElement instance if found, or None if there are no <td> tags.
"""
if not el:
return None
if type(el) in [list, tuple, set]:
... |
def ends_with(needle, haystack):
"""Checks if a list ends with the provided values"""
return haystack[-len(needle) :] == needle |
def str2bool(v):
"""
Converts string to bool. True for any term from "yes", "true", "t", "1"
:param str v: Term
:return bool:
"""
try:
return v.lower() in ("yes", "true", "t", "1")
except:
return False |
def auto_int(hex_or_dec):
"""Supports parsing 0xNNNN arguments, in addition to decimal"""
return int(hex_or_dec, 0) |
def _create_cql_update_query(key_space: str, table_name: str,
set_columns_value_dict: dict,
primary_key_values: dict) -> str:
""" This function will create an update CQL query"""
cql_update = "UPDATE " + key_space + "." + table_name + " SET "
fo... |
def blue_bold(msg: str) -> str:
"""
Given an 'str' object, wraps it between ANSI blue & bold escape characters.
:param msg: Message to be wrapped.
:return: The same message, which will be displayed as blue & bold by the terminal.
"""
return '\u001b[1;34m%s\u001b[0m' % msg |
def always_verify_user(user, token):
"""Always verifys the user/token pair"""
return True, 'User verified', True |
def custom_cycle_time_columns(minimal_fields):
"""A columns list for the results of CycleTimeCalculator with the three
custom fields from `custom_settings`.
"""
return [
'key', 'url', 'issue_type', 'summary', 'status', 'resolution',
'Estimate', 'Release', 'Team',
'cycle_time', 'c... |
def reindent(s, numSpaces=4, lstrip=True):
"""add indentation to a multiline string.
Parameters
----------
s : str
string to reformat
numSpaces : str, optional
number of spaces to indent each line by
lstrip : bool, optional
if True, lstrip() prior to adding numSpaces
... |
def replace_consts_with_values(s, c):
"""
Replace the constants in a given string s with the values in a list c.
:param s: A given phenotype string.
:param c: A list of values which will replace the constants in the
phenotype string.
:return: The phenotype string with the constants replaced... |
def add_dependencies(dep : dict,l):
"""Adds supplementary dependencies from l to dep.
Returns the total number of dependencies"""
i_0 = len(dep.values())
for i,dep_to_add in enumerate(l):
dep[dep_to_add] = i+i_0
return len(dep.values()) |
def merge_countsplit(b,c):
"""
Given two sorted arrays b and c, output a merged sorted array and the number of inversions.
Output:
d, num_split: Merged array d and number of inversions.
"""
i=0
j=0
k=0
n1 = len(b)
n2 = len(c)
d = [None]*(n1+n2)
num_split = 0
... |
def bib_escape(text):
"""Replace special characters to render bibentries in HTML."""
escape_entities = [
('"', '"'),
('\\', '\'),
('{', '{'),
('}', '}'),
('~', '~')
]
for search, repl in escape_entities:
text = text.replace(search, ... |
def _tokenize_line(line, quote_strings=False, infer_name=True):
"""
Tokenize a line:
* split tokens on whitespace
* treat quoted strings as a single token
"""
ret = []
escape = False
quote = False
tokbuf = ""
firstchar = True
ll = list(line)
while len(ll) > 0:
c =... |
def sort_fields(fields):
"""Helper to ensure named fields are sorted for the test."""
return ', '.join(sorted(field.lstrip() for field in fields.split(','))) |
def is_protein_db(blast_cfg):
"""
>>> is_protein_db({'p': 'blastx'})
True
"""
return blast_cfg["p"] in ("blastx", "blastp") |
def maxsubarray(list):
"""
Find a maximum subarray following this idea:
Knowing a maximum subarray of list[0..j]
find a maximum subarray of list[0..j+1] which is either
(I) the maximum subarray of list[0..j]
(II) or is a maximum subarray list[i..j+1] for some 0 <= i <= j
... |
def str_or_empty(value):
"""Stringify an object, but if none return empty string"""
if value is None:
return ''
else:
return str(value) |
def unit_to_agg(row):
"""
args:
row - should look like (maf, (ten, hhgq, geo))
returns tuple with cnt appended
"""
assert len(row) == 2, f"Unit row tuple {row} is not of length 2"
_, (ten, hhgq, geo) = row
return ((geo, 8), 1) if hhgq == 0 and ten == 0 else ((geo, hhgq), ... |
def bacon_strategy(score, opponent_score, margin=8, num_rolls=5):
"""This strategy rolls 0 dice if that gives at least MARGIN points,
and rolls NUM_ROLLS otherwise.
"""
def beacon(x):
return 1+abs(x//10 - x%10)
bacon_opponent = beacon(opponent_score)
if bacon_opponent >= margin:
... |
def get_length(x):
"""Return int or len(x)"""
try:
return int(x)
except Exception:
return len(x) |
def has_palindrome(i, start, len):
"""return True if the integer i, when written as a string,
contains a palindrome with length (len), starting at index (start).
"""
s = str(i)[start:start+len]
return s[::-1] == s |
def max_STR_repeats(sequence: str, STR: str) -> int:
"""Given both a DNA sequence and an STR as inputs,
returns the maximum number of times that the STR repeats"""
# Initialize list of number of repeats by position
repeats = [0] * len(sequence)
# For each position of the sequence, compute the repe... |
def if_else(predicate, on_true_func, on_false_func, value):
"""Creates a function that will process either the onTrue or the onFalse
function depending upon the result of the condition predicate"""
return on_true_func(value) if predicate(value) else on_false_func(value) |
def dictMerge(main, default):
"""
Pure dict deep-merge function. First dict has precedence.
"""
if isinstance(main, dict):
return {
k: dictMerge(
main[k],
default=({} if default is None else default).get(k),
) if k in main else default[k]
... |
def recipe_template(environ):
"""
Provide a means to specify custom {{ key }} values in recipes which
are then replaced with the value specified in
environ['tiddlyweb.recipe_template']
"""
template = {}
if environ:
template = environ.get('tiddlyweb.recipe_template', {})
try:
... |
def delta_EF_lin(ave,t_e,t_mu,comp,t_f,n=None,alpha = None):
"""computes \DeltaEF/EF in the case of invariant composition
For computational background see Eq. 4
per capita contribution is assumed constant
Input
ave, t_e, t_mu, t_f, comp:
As in output of rand_par
alp... |
def parse_entry(entry):
""" Separates an entry into a numeric value and a tied/fixed
parameter, if present.
"""
if entry.startswith('nan'):
val = float(entry[:3])
par = entry[3:]
else:
i = -1
while not entry[i].isdigit(): i -= 1
if i != -1:
val = ... |
def update_item_metadata(data, form):
"""Update the metadata / IRT for an edX item
:param request:
:param data:
:param form:
:return:
"""
if ('genusTypeId' in data and
'edx' in data['genusTypeId']):
valid_fields = ['attempts', 'markdown', 'rerandomize', 'showanswer', 'we... |
def bboxCenter(bbox):
"""
Returns (x_c,y_c) of center of bounding box list (x_0,y_0,x_1,y_1)
"""
return [(bbox[0] + bbox[2])/2,(bbox[1] + bbox[3])/2] |
def find_low_index1(arr, key):
"""Find the low index of the key in the array arr.
Time: O(log n)
Space: O(1)
"""
lo, hi = 0, len(arr)
while lo < hi:
mi = (lo + hi) // 2
if arr[mi] < key:
lo = mi + 1
elif arr[mi] >= key:
hi = mi
if hi < len(ar... |
def list_to_string(base_list, ignore_string = False):
"""
Convert a list to its string reprensatation
"""
try:
_ = float(base_list[0])
isNumber = True
except:
isNumber = False
result = '['
for element in base_list:
if isNumber or ignore_string:
r... |
def is_tls_handshake_record(d: bytes) -> bool:
"""
Returns:
True, if the passed bytes start with the TLS record magic bytes
False, otherwise.
"""
# TLS ClientHello magic, works for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2.
# TLS 1.3 mandates legacy_record_version to be 0x0301.
# http://w... |
def numberOfUniqueTranscripts(transcripts):
""" Given a list of transcripts, return the number of unique names.
"""
names = set()
for t in transcripts:
if t not in names:
names.add(t)
return len(names) |
def listDimensionRemover(processList, numberOfDimensions):
"""
:param processList: list array
:param numberOfDimensions: number of dimensions to flatten
:return: flattened list by n dimensions
"""
flat_list = [item for sublist in processList for item in sublist]
if numberOfDimensions == 1:
... |
def emotion_pet_function(e_hungry, e_dirt, e_mood):
"""Deze functie controleert de totale emotie voor de afbeelding
van de tamagotchi en stuurt deze terug."""
total = sum([e_hungry, e_dirt, e_mood])
if e_hungry > 12:
return 6
elif total < 6:
return 1
elif total < 10:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.