content stringlengths 42 6.51k |
|---|
def _format_defs(defs):
"""Write a dictionary with all the definitions used in the
module. """
ans = 'DEFS = {\n'
for key in defs:
ans += "'%s': [\n" % key
for item in defs[key]:
ans += ' %s,\n' % repr(item)
ans += '],\n'
ans += '}'
return ans |
def flat(lst):
""" [(1,2), (3,4)] -> [1, 2, 3, 4]"""
return sum([list(item) for item in lst], []) |
def _stream_cmd(job_id: str) -> str:
"""Returns a CLI command that, if executed, will stream the logs for the job
with the supplied ID to the terminal.
"""
items = ["gcloud", "ai-platform", "jobs", "stream-logs", job_id]
return " ".join(items) |
def retrieve_keys(management, storageacct_name):
"""retrieve primary and secondary keys."""
try:
storage_keys = management.get_storage_account_keys(storageacct_name)
primary_key = storage_keys.storage_service_keys.primary
secondary_key = storage_keys.storage_service_keys.secondary
... |
def get_string_for_language(language_name):
"""
Maps language names to the corresponding string for qgrep.
"""
language_name = language_name.lower().lstrip()
if language_name == "c":
return "tc-getCC"
if language_name in ('c++', 'cxx'):
return "tc-getCXX"
return language_name |
def _extend_docstring_3d(docstring):
"""Change docstring to include 3D numpy support."""
# the indentation must be this way, since tabs are included in the string
# if one more tab is added, the replacement is not correctly done
to_replace = """x: np.ndarray (1d or 2d array)
First time series.... |
def parse_float(m, default = 0.0):
"""parse_float
:param m:
:param default:
"""
if type(m) == int:
return m
elif type(m) == str:
try:
return float(m)
except:
return default
else:
raise Exception('error input %s, cannot parse' % m) |
def filter_not_empty_values(value):
"""Returns a list of non empty values or None"""
if not value:
return None
data = [x for x in value if x]
if not data:
return None
return data |
def format_placeholders_args(args, filename=None, handle=None):
"""Formats `args` with Infinitepush replacements.
Hack to get `str.format()`-ed strings working in a BC way with
bytes.
"""
formatted_args = []
for arg in args:
if filename and arg == b'{filename}':
formatted_ar... |
def find_with(f, iter, default=None):
"""Find the value in an iterator satisfying f(x)"""
return next((x for x in iter if f(x)), default) |
def extract_port(url):
"""Returns the port number out of a url"""
for prefix in ['http://', 'https://']:
if prefix in url:
url = url.replace(prefix, '')
break
else:
prefix = ''
url = url.split('/')[0]
url = url.split(':')
if len(url) > 1:
return in... |
def TryConvert(fn, val):
"""Try to convert a value ignoring errors.
This function tries to apply function I{fn} to I{val}. If no
C{ValueError} or C{TypeError} exceptions are raised, it will return
the result, else it will return the original value. Any other
exceptions are propagated to the caller.
@type ... |
def Str2FloatList(str_values, expected_nvalues=3):
"""Convert a string into a list of values. It returns None if the array is smaller than the expected size."""
import re
if str_values is None:
return None
values = re.findall("[-+]?\d+[\.]?\d*", str_values)
valuesok = []
for i in range(... |
def choose(color):
"""
Used to convert the png into 4 color.
"""
r, g, b, a = color
if r < 90:
return (0, 0, 0, 255)
if r >= 77 and r < 160:
return (134, 30, 214, 255)
if r >= 160 and r < 208:
return (172, 143, 239, 255)
else:
return (255, 255, 255, 255) |
def tuple_key(tup):
"""Return a sort key for mixed int/string tuples.
Strings sort first.
"""
def generator():
for item in tup:
try:
yield (1, int(item))
except ValueError:
yield (0, item)
return tuple(generator()) |
def UC_C(C_kgmm, A_catch):
""" Convert concentration from units of kg/mm to mg/l.
Divide answer by 10**6 to convert from mg/mm to mg/l
Args:
C_kgmm: Float. Concentration in kg/mm
A_catch: Float. Catchment area in km2
Returns:
Float. Concentration in mg/l
"""
C_... |
def overlap(box1, box2):
"""
Check the overlap of two boxes
"""
endx = max(box1[0] + box1[2], box2[0] + box2[2])
startx = min(box1[0], box2[0])
width = box1[2] + box2[2] - (endx - startx)
endy = max(box1[1] + box1[3], box2[1] + box2[3])
starty = min(box1[1], box2[1])
height = box1[3... |
def find(r):
"""around 0.3ms"""
if r.find(b"response") != -1:
return True
return False |
def reverse_insort_pos(a, x):
""" find position to insert item x in list a, keep it reverse sorted
"""
lo = 0
hi = len(a)
while lo < hi:
mid = (lo + hi) // 2
if x > a[mid]:
hi = mid
else:
lo = mid + 1
# makes sure to insert to the left
if (lo ... |
def es_subcadena(adn1, adn2):
"""
(str, str) -> boolean
funcion que nos permite definir la subcadena de una secuencia dada
>>> es_subcadena('atcgta', 'gta')
True
>>> es_subcadena('atcg', 'tta')
False
:param adn1: str con la cadena 1
:param adn2: str con la cadena 2
:return: s... |
def get_masked_password(password: str, secret: str, given_secret: str) -> str:
"""
Use secret correctness as a password mask.
For each correct secret character, password character in the same position will be
exposed.
"""
if len(password) != len(secret):
raise ValueError("Password and s... |
def ip_to_int(ip):
"""
convert ip(ipv4) address to a int num
:param ip:
:return: int num
"""
lp = [int(x) for x in ip.split('.')]
return lp[0] << 24 | lp[1] << 16 | lp[2] << 8 | lp[3] |
def parse_metadata(metadata_list):
"""Parse the metadata from a set of strings to a dictionary"""
if not metadata_list:
return {}
metadata = {}
# Loop through the list of metadata values
for pair in metadata_list:
# Split the key part from the value
key_path, value = pair.spl... |
def apnumber(value):
"""
Borrowed with love and adapted from django.contrib.humanize: https://github.com/django/django/blob/master/django/contrib/humanize/templatetags/humanize.py
For numbers 1-9, returns the number spelled out. Otherwise, returns the
number. This follows Associated Press style.
""... |
def to_3_list(item):
"""
Converts item into a 3 item list
:param item: var
:return: list<var, var, var>
"""
if not isinstance(item, list):
item = [item] * 3
return item |
def cubic_objective(x, a, b, c, d):
"""Cubic objective function."""
return a*x**3 + b*x**2 + c*x + d |
def get_model_name(name, batch_size, learning_rate, epoch):
""" Generate a name for the model consisting of all the hyperparameter values
Args:
config: Configuration object containing the hyperparameters
Returns:
path: A string with the hyperparameter name and value concatenated
"""
... |
def funcion_factorial(n: int ):
"""El factorial de un numero.
Parameters
----------
n : int
Numero entero `n`.
Returns
-------
int
Retorna el factorial del numero `n`
"""
facto= 1
for i in range(1,n+1):
facto = facto * i
return facto |
def defvalkeys(js, key, default=None):
"""
Returns js[key] if set, otherwise default. Note js[key] can be None.
Key is array of keys. js[k1][k2][k3]...
:param js:
:param key:
:param default:
:param take_none:
:return:
"""
if js is None:
return default
if not isinstan... |
def join_str(str_ls, sep=None):
""" join a list of strings"""
if sep is None:
sep = ''
return sep.join([w for w in str_ls if w is not None]) |
def coerce_date_dict(date_dict):
"""
given a dictionary (presumed to be from request.GET) it returns a tuple
that represents a date. It will return from year down to seconds until one
is not found. ie if year, month, and seconds are in the dictionary, only
year and month will be returned, the rest ... |
def _depgrep_rel_disjunction_action(_s, _l, tokens):
"""
Builds a lambda function representing a predicate on a tree node
from the disjunction of several other such lambda functions.
"""
# filter out the pipe
tokens = [x for x in tokens if x != "|"]
# print 'relation disjunction tokens: ', t... |
def porridge_for_the_bears(were_you_robbed):
"""
Did Goldie Locks break in and rob you?
Parameters
----------
were_you_robbed : bool
The question is in the title
Returns
-------
p_bear_emo, m_bear_emo, b_bear_emo : string
The emotional status of the three bears
"""
... |
def valid_account_id(account_id):
"""Returns True if account_id is valid
Returns False if account_id is not valid
"""
valid = True
# Valid length
valid = valid and len(account_id) == 64
# Valid characters
valid_chars = '_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
tmp_account_id = str(ac... |
def value_to_print(value, optype):
"""String of code that represents a value according to its type
"""
if (value is None):
return "NULL"
if (optype == 'numeric'):
return value
return u"'%s'" % value.replace("'", '\\\'') |
def fixstyle(obj):
"""Try to convert styles into a dictionary"""
if obj:
if isinstance(obj, list):
lengths = [len(x) for x in obj]
if min(lengths) == max(lengths) == 2:
obj = dict(obj)
elif isinstance(obj, dict) and 'styles' in obj:
obj['styles... |
def extract_filename(string, remove_trailing_ftype=True, trailing_type_max_len=7):
""" removes path (in front of the file name) and removes the file-type after the '.' (optional).
returns: path & file_name"""
A = string.replace("\\","/").split("/")
path = ("/".join(A[:-1]))+"/"
if len(path)==1:
... |
def class_of(obj):
"""Return the class or type of the input object as a string."""
if obj is None:
return 'None'
if hasattr(obj,'__class__'):
return obj.__class__.__name__
return str(type(obj)) |
def extract_parameter_value_from_url(param_dic, key, default):
"""
"""
if key in param_dic:
val = param_dic[key]
else:
val = default
return val |
def repunit(number):
""" Returns True if number is repunit """
while number > 9:
if number % 10 != 1:
return False
else:
number = number // 10
return number == 1 |
def hex_to_rgb(rgb_string):
"""
Takes #112233 and returns the RGB values in decimal
"""
if rgb_string.startswith('#'):
rgb_string = rgb_string[1:]
red = int(rgb_string[0:2], 16)
green = int(rgb_string[2:4], 16)
blue = int(rgb_string[4:6], 16)
return (red, green, blue) |
def ERR_TOOMANYTARGETS(sender, receipient, message):
""" Error Code 407 """
return "ERROR from <" + sender + ">: " + message |
def shared_lib_name(group_name: str) -> str:
"""Given a group name, return the actual name of its extension module.
(This just adds a suffix to the final component.)
"""
return '{}__mypyc'.format(group_name) |
def pad_sents(sents, pad_idx):
"""
@param sents (list[list[int]]):
@param pad_idx (int): Pad ID
@return sents_padded (list[list[int]]): sents with padding according to max_sent_len
"""
max_len = 0
sents_padded = []
for sent in sents: max_len = max(max_len, len(sent))
for sent in sent... |
def parse_user(line):
"""
Parses a user in MovieLens format userID::gender::age::occupation::zip
Parameters
----------
line : str
The line that contains user information
Returns
-------
list : list
A list containing userID, gender, age, occupation, zip
"""
field... |
def plausible_file_extension(s):
"""given some string, likely a mime-type,
return either a .SOMETHING extension, or an
empty string"""
ext = ""
l = len(s)
for i in range(l-1, -1, -1):
if s[i].isalpha():
ext = s[i] + ext
else:
break
return ext |
def _interpolate(a,b,v):
"""interpolate values by factor v"""
return a + (b-a) * v |
def readall(fd):
"""My own read loop, bc the one in python3.4 is derpy atm:
http://bugs.python.org/issue21090#msg231093
"""
from os import read
result = []
lastread = None
while lastread != b'':
try:
lastread = read(fd, 4 * 1024)
except OSError as error:
... |
def first_of(value, arg=10):
"""
Only returns first X of list
"""
if not value:
return value
count = int(arg)
if len(value) > arg:
return value[:arg]
else:
return value |
def test_ppm(h, f):
"""PPM (portable pixmap)"""
if len(h) >= 3 and \
h[0] == 'P' and h[1] in '36' and h[2] in ' \t\n\r':
return 'ppm' |
def rensure(items, count):
"""Make sure there are `count` number of items in the list otherwise
just fill in `None` from the beginning until it reaches `count` items."""
fills = count - len(items)
if fills >= 1:
return [None] * fills + items
return items |
def get_fixture_name(fixture_fun):
"""
Internal utility to retrieve the fixture name corresponding to the given fixture function .
Indeed there is currently no pytest API to do this.
:param fixture_fun:
:return:
"""
try: # pytest 3
custom_fixture_name = fixture_fun._pytestfixturefu... |
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
O(1) if item is the first that is checked
O(n*m) where n is the length of the pattern and m is the length of the text"""
assert isinstance(text, str), 'text... |
def get_pos_association_dict(volumestokeep, outfiles_partititon):
""" Converts 3d index to numeric index
"""
index = 0
_3d_to_numeric_pos_dict = dict()
for i in range(outfiles_partititon[0]):
for j in range(outfiles_partititon[1]):
for k in range(outfiles_partititon[2]):
... |
def limit(value, min_val, max_val):
"""Returns value clipped to the range [min_val, max_val]"""
return max(min_val, min(value, max_val)) |
def _nested_delete(document, key):
"""
Method to delete a key->value pair from a nested document
Args:
document: Might be List of Dicts (or) Dict of Lists (or)
Dict of List of Dicts etc...
key: Key to delete
Return:
Returns a document that includes everything but the giv... |
def S_downsample_data(_data_list, _factor=1):
"""
Returns a two dimensional data set with a reduced number of samples.
Use the sample skipping factor to get required result, the factor tells how many samples to skip for one data sample.
"""
ds_data = []
ds = len(_data_list)
skip_count = _fa... |
def char_size(c):
"""Get `UTF8` char size."""
value = ord(c)
if value <= 0xffff:
return 1
elif value <= 0x10ffff:
return 2
raise ValueError('Invalid code point') |
def update(old, new, priority='new'):
""" Update a nested dictionary with values from another
This is like dict.update except that it smoothly merges nested values
This operates in-place and modifies old
Parameters
----------
priority: string {'old', 'new'}
If new (default) then the n... |
def collect_uppercase_words(tokens):
"""Given list of tokens, collect only uppercase words"""
return [1 for token in tokens if token.isupper()] |
def all_true(iterable):
""" Helper that returns true if the iterable is not empty and all its elements evaluate to true. """
items = list(iterable)
return all(items) if items else False |
def from_size(n):
"""
Constructs a zeroed, *n* sized vector clock.
"""
return (0,) * n |
def keypath_drop_last(keypath: str) -> str:
"""Drop the last part of a keypath. If it only has one part, empty string
is returned. If it's empty string, empty string is returned.
Args:
keypath (str): The keypath to drop last from.
Returns:
str: A new keypath with last component dropped... |
def add_to_table(name, table):
"""Add a string to the table
Args:
name (str): the same to add to the table
table (bytearray): the table to add to
Returns:
int: the start index of the name in the table
"""
start_point = len(table)
for character in name:
table.app... |
def common_get(obj, key, default):
"""Can be used to access an element via the index or key.
Works with numpy arrays, lists, and dicts.
Args:
``obj`` (list,array,dict): Mapping
``key`` (int): Index or key of the element to retrieve
``default`` (object): Default return value if ... |
def zeropad(anint):
"""Convert an integer to a two character string."""
intstr = str(anint)
if len(intstr) == 1:
intstr = '0' + intstr
return intstr |
def _hex_to_rgb(value):
"""Convert a hex-formatted color to rgb, ignoring alpha values."""
value = value.lstrip("#")
return [int(value[i:i + 2], 16) for i in range(0, 6, 2)] |
def svpwat(t):
"""e = svpwat(t)
Calculates the water vapor mixing ratio
Inputs: (all vectors of same length)
t = dry bulb temperature(s) (K)
Outputs:
e = saturation vapor pressure with respect to a plane surface of ice (mb)
RLT, 010710
"""
A0 = 0.999996876e0
A1 = -0.9082695004e-2
A2 = 0.7873616869e... |
def extract_extension(filename, extension):
""" filters out files with specific extensions like .py or .txt or even entire filenames """
if not extension:
return filename
# reverse filename
filename = filename[::-1]
extracted = ""
for char in filename:
extracted = extracted + ... |
def _days_in_month(year, month):
"""Return the number of days in the given (year, month).
"""
DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
is_leap = (year % 4 == 0) and ((year % 100 != 0) or (year % 400) == 0)
days = DAYS_IN_MONTH[month - 1]
if month == 2:
days += is_... |
def insertion_sort(items):
"""Sorts a list of items.
Uses inserstion sort to sort the list items.
Args:
items: A list of items.
Returns:
The sorted list of items.
"""
for j in range(1, len(items)):
key = items[j]
# Insert items[j] into the sorted sequenc... |
def with_progress(iterable, desc=None, total=None, leave=True):
"""
Return an iterator which prints the iteration progress using tqdm package.
Return iterable intact if tqdm is not available.
"""
try:
from tqdm import tqdm
# workarounds for tqdm bugs
def _it(iterable, desc, ... |
def insertion_sort_loops_combined(items: list) -> list:
"""
Args:
items:
Returns:
Examples:
>>> items = [random.randrange(0, 100) for _ in range(100)]
>>> assert(insertion_sort_loops_combined(items.copy()) == sorted(items))
"""
for unsorted_start_idx in range(1, len(... |
def generate_parameters_string(parameters):
"""Generates the parameters string from the parameters dictionary
Parameters
----------
parameters : dict
The parameter values, keyed by parameter name
Returns
-------
str
A string with the parameters to the CLI call
"""
f... |
def v(n):
"""compute u value of the lhs matrix"""
return ((n ** 2) * (n + 1)) / 2 |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(n)
"""
if not nums or len(nums) == 0:
return 0
sum_so_far = 0 # from wherever we starting to where ... |
def format_xi_stats(users_as_nodes, exp, xi_mean, xi_std, tot):
"""Formats the curvature estimates for logging.
Args:
users_as_nodes: Bool indicating which interaction graph was generated. If
True (False), a user-user (item-item) interaction graph was generated.
exp: Boolean indicating if the interac... |
def lambda_lr_schedule(epoch):
"""Multiplicative Factor for Learning Rate Schedule.
Computes a multiplicative factor for the initial learning rate based
on the current epoch. This method can be used as argument
``lr_lambda`` of class :class:`torch.optim.lr_scheduler.LambdaLR`.
The schedule is insp... |
def canvas(with_attribution=True):
"""
Placeholder function to show example of docstring (NumPy format)
Replace this function and doc string for your own project
Parameters
----------
with_attribution : bool, Optional, default: True
Set whether or not to display who quote is fr... |
def convert_to_demisto_severity(ib_severity="medium", tp_score_based=False, score=0):
"""
Converts the IllusionBLACK Threat Parse score for an attacker to demisto incident severity
Args:
ib_severity: IllusionBLACK severity. Some events do not have threat parse score.
tp_score_based: If score... |
def min_value(a, b):
""" Compute min of a pair of two ints. """
return b ^ ((a ^ b) & -(a < b)) |
def _or(newscore: float, oldscore: float, howold: int) -> float:
"""Logical 'or', but with float scores
An internal utility function to weight old scores
and 'or' them, i.e., add them to new scores
to calculate the matches if there are misses
Adds the two scores, but limits the return value
to... |
def extract(dic, lis):
"""
Devuelve una lista con el valor que se encuentra en dic
para cada elemento de lis
"""
r = []
for l in lis:
r.append(dic[l])
return r |
def connect_bases(char1, char2):
"""
For two aligned bases, get connecting symbol.
Bases on whether bases match, mismatch or are part of a gap.
Args:
char1, char2 (str): Two aligned bases.
"""
if char1 == '-' or char2 == '-':
return ' '
if char1 == char2:
return '|'
... |
def get_alt_support_by_color(is_in_support):
"""
***NOT USED YET***
:param is_in_support:
:return:
"""
if 248 <= is_in_support <= 256:
return 1
elif 48 <= is_in_support <= 55:
return 0 |
def transfer_weights(model, weights=None):
"""
Always trains from scratch; never transfers weights
:param model:
:param weights:
:return:
"""
print('ENet has found no compatible pretrained weights! Skipping weight transfer...')
return model |
def consistentCase(description):
"""Converts snake_case strings to CameCase"""
splitted = description.split('_')
out = ''.join([word[0].upper() + word[1:] for word in splitted])
return out |
def non_null_size(filename):
"""
Control if the file has nonzero size and exists
"""
from os.path import getsize, isfile
return isfile(filename) and (getsize(filename) > 0) |
def remove_trailing_prefs(proposal_record, preferences):
""" Function trims each preference list by eliminating possibilities indexed
after accepted proposal
Takes in two dictionaries: proposal_record and preference_lists
Returns updated preference_lists
For example:
Inputs ... |
def signum(x):
"""Sign of `x`: ``-1 if x<0, 0 if x=0, +1 if x>0``."""
if x < 0:
return -1
elif 0 < x:
return +1
else:
return 0 |
def is_dark(hsv, threshold=0.15):
"""Check if a color is close to black"""
return hsv[2] <= threshold |
def _getFilterID(tuples, value):
"""
Given a the tuples generated by getTuples and a value, will return a list of gmlIDs
associated with the value specified.
"""
value = str(value)
filter_id = []
for item in tuples:
if item[0] == value:
filter_id.append(item[1])
if no... |
def _filter_empty_field(data_d):
"""
Remove empty lists from dictionary values
Before: {'target': {'CHECKSUM': {'checksum-fill': []}}}
After: {'target': {'CHECKSUM': {'checksum-fill': ''}}}
Before: {'tcp': {'dport': ['22']}}}
After: {'tcp': {'dport': '22'}}}
"""
for k, v in data_d.item... |
def val_test_func(item):
"""Test func for check_valid."""
return item != 'BAD' |
def getattr_silent(obj, attr):
""" This turns of verbose logging of missing attributes for huggingface transformers.
This is motivated by huggingface transformers objects that print error warnings
when we access unset properties.
"""
reset_verbose = False
if getattr(obj, 'verbose', False):
... |
def is_composite_sampler(sampler_type):
"""Composite samplers return a [key, val, ...] list as opposed to just a val."""
composite_samplers = ["regnet_sampler"]
return sampler_type in composite_samplers |
def flattenDict(flattenable, flattenKey):
""" turns a list into a flatstring on the first value"""
flatstring = ""
if type(flattenable) == list:
for tag in flattenable:
if flattenKey in tag:
flatstring = tag[flattenKey]
elif type(flattenable) == dict:
if flat... |
def restrict_to_range(x: int, lower_bound: int, upper_bound: int):
"""
Takes an integer x and restricts its range by the following:
- If x is above the upper_bound, make x the upper_bound.
- If x is below the lower_bound, make x the lower_bound.
- Otherwise leave x the same.
"""
return min(m... |
def chomp_empty(seq):
"""Return slice of sequence seq without trailing empty tuples."""
n = len(seq)
while (n > 0) and seq[n - 1] == ():
n -= 1
return seq[:n] |
def enum(word_sentences, tag_sentences):
"""
enumerate words, chars and tags for
constructing vocabularies.
"""
words = sorted(list(set(sum(word_sentences, []))))
chars = sorted(list(set(sum([list(word) for word in words], []))))
tags = sorted(list(set(sum(tag_sentences, []))))
return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.