content stringlengths 42 6.51k |
|---|
def _parse_tags(note):
""" convert a note into tags """
return [tag.strip() for tag in note.split(';') if len(tag) > 0] |
def format_proxies(proxy_options):
"""
Format the data from the proxy_options object into a format for use with the requests library
"""
proxies = {}
if proxy_options:
# Basic address/port formatting
proxy = "{address}:{port}".format(
address=proxy_options.proxy_address, ... |
def get_params_from_prefix_dict(param_prefix, lda_pipeline_params):
"""
Strip away the param_prefix from the lda_pipeline_params' keys.
:param param_prefix: string such as 'lda__' or 'stemmer__'.
:param lda_pipeline_params: dict such as {'lda__learning_decay': 0.5, 'stemmer__language': 'french',}
:... |
def BuildTreeForCombine(parsed_expression, operator, parsed_body, full_text):
"""Construct a tree for a combine expression from the parsed components."""
aggregated_field_value = {
'field': 'logica_value',
'value': {
'aggregation': {
'operator': operator,
'argument'... |
def average_above_zero(tab):
"""
Brief: computes the average with positiv value
Args:
tab: a liste of numeric value exepcts at least one positive valus, raise expection
Return: the computedd average
Raises :
ValueError if no positive value is found
ValueError if input is no... |
def appendformat(filepath, form):
"""
Append a format string to the end of a file path.
**Parameters**\n
filepath: str
File path of interest.
form: str
File format of interest.
"""
format_string = '.'+form
if filepath:
if not filepath.endswith(format_string):
... |
def chunkInto64CharsPerLine(data, separator=b'\n'):
"""Chunk **data** into lines with 64 characters each.
:param basestring data: The data to be chunked up.
:keyword basestring separator: The character to use to join the chunked
lines. (default: ``b'\n'``)
:rtype: basestring
:returns: The *... |
def _get_default_route(version, subnet):
"""Get a default route for a network
:param version: IP version as an int, either '4' or '6'
:param subnet: Neutron subnet
"""
if subnet.get('gateway') and subnet['gateway'].get('address'):
gateway = subnet['gateway']['address']
else:
ret... |
def g(R):
""" range -> int"""
# s : int
s = 0
# i : int
for i in R:
s = s + i
return s |
def digits_ratio_extractor(raws):
"""digits_ratio
Percentage of digits over all characters in a given text.
Known differences with Writeprints Static feature "percentage of digits": None.
Args:
raws: List of documents.
Returns:
Percentage of digits over all characters in the docu... |
def divmult(n: int, m: int = 2) -> int:
"""
Checks how many times n is divisible by m. Returns -1 if n=0
@author = Joel
:param n: Numerator
:param m: Denominator
:return: Multiplicity
"""
if n < 0:
raise ValueError('Only non-negative integers are supported for n.')
elif n =... |
def CountScores(outfile, t1, t2,
graph, separator="|",
cds1={}, cds2={},
options={}):
"""count scores between t1 and t2 in graph.
return lists of scores between t1 and within clusters and
the number of not found vertices and links
"""
between_scores ... |
def get_real(real_or_complex_number):
"""Gets the real part of a complex number as a double.
If the argument is already a real number does nothing. It works only with
numbers, not with other user defined types, such as numpy arrays.
Parameters
----------
real_or_complex_number : a real or... |
def get_version_name(lang: str, major: int, minor: int, patch: int):
"""Return the package name associated with the lang ``name`` and version (``major``, ``minor``, ``patch``)"""
return f"{lang}_{major}_{minor}_{patch}" |
def set_recursive(d, names, v):
""" Recursively set dictionary keys so that final leaf is ``v``
The ``names`` argument should be a list of keys from top level to bottom.
Example::
>>> d = {}
>>> set_recursive(d, ['foo', 'bar', 'baz'], 12)
>>> d
{u'foo': {u'bar': {u'baz': 1... |
def is_real(qid, claims, fiction_filter):
"""check for claims that an item is fictional"""
if 'P31' in claims:
for spec in claims['P31']:
if 'id' in spec['mainsnak'].get('datavalue', {}).get('value', {}):
thing = spec['mainsnak']['datavalue']['value']['id']
if... |
def info_from_jwt(token):
"""
Check and retrieve authentication information from custom bearer token.
Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one.
:pa... |
def _get_session_key_payload(_username, _password=None, _return_json=True):
"""This function constructs the payload used to request a session key.
.. versionadded:: 3.5.0
:param _username: The username (i.e. login) for the user being authenticated
:type _username: str
:param _password: The passwor... |
def any_in_text(items, text):
"""Utility function.
Returns True if any of the item in items is in text, False otherwise.
"""
for item in items:
if item in text:
return True
return False |
def base_n(
num: int, b: int, numerals: str = "0123456789abcdefghijklmnopqrstuvwxyz"
) -> str:
"""
Convert any integer to a Base-N string representation.
Shamelessly stolen from http://stackoverflow.com/a/2267428/1399279
"""
neg = num < 0
num = abs(num)
val = ((num == 0) and numerals[0])... |
def save_file(filename, contents):
"""Save a file from the editor"""
if not filename:
return 0, 0
with open(filename, 'w') as f:
f.write(contents)
return len(contents), hash(contents) |
def _merge_cipher(clist):
"""Flatten 'clist' [List<List<int>>] and return the corresponding string [bytes]."""
cipher = [e for sublist in clist for e in sublist]
return bytes(cipher) |
def subtract(curvelist):
"""
Take difference of curves.
>>> curves = pydvif.read('testData.txt')
>>> c = pydvif.subtract(curves)
:param curvelist: The list of curves
:type curvelist: list
:returns: curve -- the curve containing the difference of the curves
"""
numcurves = len(cur... |
def add_flag(var, flag):
"""
for use when calling command-line scripts from within a program.
if a variable is present, add its proper command_line flag.
return a string.
"""
if var:
var = flag + " " + str(var)
else:
var = ""
return var |
def expectedWork(etotal, estart, efinish, t):
"""Get expected work progress given total work, start, finish, and point t in time (in seconds since the Epoch)."""
if t<=estart:
return 0.0
elif t>efinish:
return float(etotal)
else:
p = float(etotal)*(t-estart)/(efinish-estart) # li... |
def turn_from_binary_to_decimal(bin_adress: str) -> str:
"""
Return decimal address from binary address.
>>> turn_from_binary_to_decimal('11111111.11111111.11111111.00000000')
'255.255.255.0'
"""
bin_numbers = bin_adress.split('.')
decimal_adress = ''
for number in bin_numbers:
... |
def get_asterisks_for_pvalues(p_value: float) -> str:
"""Receives the p-value and returns asterisks string.
Args:
p_value: A float that represents a p-value.
Returns:
p_text: A string containing an asterisk representation of the p-value significance.
"""
if p_value > 0.05:
... |
def _is_galactic(source_class):
"""Re-group sources into rough categories.
Categories:
- 'galactic'
- 'extra-galactic'
- 'unknown'
- 'other'
Source identifications and associations are treated identically,
i.e. lower-case and upper-case source classes are not distinguished.
Refere... |
def rollingchecksum(removed, new, a, b, blocksize=4096):
"""
Generates a new weak checksum when supplied with the internal state
of the checksum calculation for the previous window, the removed
byte, and the added byte.
"""
a -= removed - new
b -= removed * blocksize - a
return (b << 16)... |
def get_concordance(text,
keyword,
idx,
window):
"""
For a given keyword (and its position in an article), return
the concordance of words (before and after) using a window.
:param text: text
:type text: string
:param keyword: keyword... |
def _float(text):
"""Fonction to convert the 'decimal point assumed' format of TLE to actual
float
>>> _float('0000+0')
0.0
>>> _float('+0000+0')
0.0
>>> _float('34473-3')
0.00034473
>>> _float('-60129-4')
-6.0129e-05
>>> _float('+45871-4')
4.5871e-05
"""
text ... |
def _letter_to_number(letter):
"""converts letters to numbers between 1 and 27"""
# ord of lower case 'a' is 97
return ord(letter) - 96 |
def ec_key(path, *merge_by):
"""Returns the context key and merge logic for the given context path and ID field name(s)."""
if len(merge_by) == 0:
return path
js_condition = ''
for key in merge_by:
if js_condition:
js_condition += ' && '
js_condition += 'val.{0} && ... |
def first_element(input):
"""Improve compatibility of single and multiple output components.
"""
if type(input) == tuple or type(input) == list:
return input[0]
else:
return input |
def get_page(query_dict, n_total):
"""Return: start, count."""
n_start = int(query_dict["start"][0]) if "start" in query_dict else 0
n_count = int(query_dict["count"][0]) if "count" in query_dict else n_total
if n_start + n_count > n_total:
n_count = n_total - n_start
return n_start, n_count |
def convertValueOrNone(value, convert=int):
"""Convert a value to a type unless NoneType.
Parameters
----------
value : anything
The value to possibly convert.
convert : TYPE, optional
The type for conversion.
Returns
-------
convert type
The converted value.
... |
def to_list_name(name):
"""Return a splited name by `_`.
:param name: name of the product.
:type name: str.
"""
return name.split('_') |
def quote(s: str) -> str:
"""
Quotes the identifier.
This ensures that the identifier is valid to use in SQL statements even if it
contains special characters or is a SQL keyword.
It DOES NOT protect against malicious input. DO NOT use this function with untrusted
input.
"""
if not (s.... |
def event_count(events):
"""Returns the total number of events in multiple events lists."""
return sum([len(e) for e in events]) |
def get_options(options, names):
"""options is a dictionary; names is a list of keys.
return a new dictionary that contains the key-value
pairs for each key that appears in options.
"""
new = {}
for name in names:
if name in options:
new[name] = options[name]
return new |
def is_instance(instance):
"""
Detects whether some object is a real number.
:param instance: The instance of which to check whether it is a real number.
:return: ``True`` if the object is a real number, or ``False`` if it isn't.
"""
return type(instance) == float |
def _GetWireVersion(urn):
"""Get version from URN string"""
# Strip whitespaces
urn = urn.strip()
if urn.startswith('"'):
urn = urn.strip('"')
elif urn.startswith("'"):
urn = urn.strip("'")
return urn[4:].strip() if urn.startswith("urn:") else None |
def binarize_syllable(syllable):
"""Return 1 or 0 depending on Guru or Laghu syllable.
Input
syllable : string of characters denoting a syllable
Ouptut
0 for Laghu, 1 for Guru
"""
guruMarkers = [u'\N{DEVANAGARI LETTER AA}', u'\N{DEVANAGARI LETTER II}',
u'\N{DEVANAGARI LETTER UU}', u'... |
def group_anagram(strs):
"""
Given an array of strings, group anagrams together.
:param strs: list[strs]
:return: list[list[strs]
"""
ana = {}
for string in strs:
s = ''.join(sorted(string))
if s in ana:
ana[s].append(string)
else:
ana[s] = [st... |
def dup_index(s: list) -> dict:
"""Gets a list that might have duplicates and creates a dict with the list
items as keys and their index as values. Only return items that have duplicates.
"""
d = {}
for element in s:
# This could be easily done with a Numpy array
indices = [ind... |
def NameValueListToDict(name_value_list):
"""
Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary
of the pairs. If a string is simply NAME, then the value in the dictionary
is set to True. If VALUE can be converted to an integer, it is.
"""
result = { }
for item in name_value_lis... |
def get_train_val_split_from_idx(src, val_list):
"""
Get indices split for train and validation subsets
src -- dataset size (int) or full range of indices (list)
val_list -- indices that belong to the validation subset
"""
train_idx = []
val_idx = val_list
if not hasattr(src, '__i... |
def option_list(opts):
"""Convert key, value pairs into a list.
This converts a dictionary into an options list that can be passed to
ArgumentParser.parse_args(). The value for each dictionary key will be
converted to a string. Values that are True will be assumed to not have
a string argument ad... |
def prod(l):
"""Returns the product of the elements of an iterable."""
if len(l) == 0:
return 1
else:
return l[0] * prod(l[1:]) |
def _vec_vec_elem_div_fp(x, y):
"""Divide two vectors element wise."""
return [a / b for a, b in zip(x, y)] |
def get_filtered_key(input_key, indices):
"""Filter input keys to indices.
Args:
input_key (tuple): Contains input key information.
indices: Which indices to select from the input key.
Returns:
filtered_key (tuple): The components of the input key designated by indices.
"""
return tuple([input_k... |
def ensureInt(value):
"""
Convert C{value} from a L{float} to an equivalent L{int}/L{long} if
possible, else raise L{ValueError}. C{int}s and C{long}s pass through.
@rtype: L{int} or L{long}
@return: non-float equivalent of C{value}
"""
if value is True or value is False:
raise TypeError("Even though int(Fal... |
def _GetMuteConfigIdFromFullResourceName(mute_config):
"""Gets muteConfig id from the full resource name."""
mute_config_components = mute_config.split("/")
return mute_config_components[len(mute_config_components) - 1] |
def build_diff_filename(name, ver_old, ver_new):
""" Returns filename for an abidiff content
Parameters:
name(str): package spec name
old(str): old version
new(str): new version
"""
bad_ch = ["/"]
for c in bad_ch:
ver_old = ver_old.replace(c, "")
ver_new = ver... |
def monthly_N_fixation_point(
precip, annual_precip, baseNdep, epnfs_2, prev_minerl_1_1):
"""Add monthly N fixation to surface mineral N pool.
Monthly N fixation is calculated from annual N deposition according to
the ratio of monthly precipitation to annual precipitation.
Parameters:
... |
def bin(s, m=1):
"""Converts the number s into its binary representation (as a string)"""
return str(m*s) if s<=1 else bin(s>>1, m) + str(m*(s&1)) |
def isValid(s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 1:
return False
stack = []
for x in s:
if x in ['(', '[', '{']:
stack.append(x)
else:
if len(stack) == 0:
return False
if x == ')' and stack[-1] != '(... |
def array_reverse_order_transform_next_index_to_current_index(frm, to, move):
"""Transforms frm and to depending on a move
Works with the array_reverse_order move type.
This function transforms the indices frm and to so that they can
be used as indices in the unaltered array, yet return the value
t... |
def int_(s):
"""
Converts strings to int, raises exception
for non-int literals
"""
reslt = 0
for i in s:
if ord(i) in range(48,58): # checks that string character is something in [0-9]
reslt = reslt*10 + (ord(i) - ord('0'))
else:
raise ValueError
ret... |
def get_character_bullet(index: int) -> str:
"""Takes an index and converts it to a string containing a-z, ie.
0 -> 'a'
1 -> 'b'
.
.
.
27 -> 'aa'
28 -> 'ab'
"""
result = chr(ord('a') + index % 26) # Should be 0-25
if index > 25:
current = index // 26
whi... |
def titleize(phrase):
"""Return phrase in title case (each word capitalized).
>>> titleize('this is awesome')
'This Is Awesome'
>>> titleize('oNLy cAPITALIZe fIRSt')
'Only Capitalize First'
"""
return phrase.title() |
def extract_options(args):
"""
Extracts the optional arguments from the command line arguments.
An optional argument is any that starts with '--' and has the form 'name=value'.
This function returns this arguments as a dictionary name:value pairs. In
addition, values are converted to Python t... |
def longest_common_substring(s1, s2):
"""
From https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python
:param s1: string 1
:param s2: string 2
:return: string: the longest common string!
"""
# noinspection PyUnusedLocal
m = [[0] * (1 + len(s2)) for ... |
def msg_disconnect(timestamp_str: str, ip_address: str, node_id: str) -> str:
"""Get a fake log msg for a disconnecting harvester to a farmer"""
line = (
f"{timestamp_str} farmer farmer_server : INFO"
+ f" Connection closed: {ip_address},"
+ f" node id: {node_id}"
)
... |
def ldapmask2filemask(ldm):
"""Takes the access mask of a DS ACE and transform them in a File ACE mask.
"""
RIGHT_DS_CREATE_CHILD = 0x00000001
RIGHT_DS_DELETE_CHILD = 0x00000002
RIGHT_DS_LIST_CONTENTS = 0x00000004
ACTRL_DS_SELF = 0x00000008
RIGHT_DS_READ_PROPERTY = ... |
def extract_retry(request):
"""extracts the value of the key retry from the dict or returns 0 if Not found
Args:
request(dict): required to have
- method(string): http method to use
- url(string): url of the requested resource
- kwargs(dict): defines more specs for th... |
def calculate_snr(rx_power, noise_power):
""" Function that calculates SNR in dB!
Args:
rx_power: (numpy array) received power in dB!
noise_power: noise power in dB!
Returns:
snr: (numpy array) Signal-to-Noise ratio in dB!
"""
snr = rx_power - noise_power # rx_po... |
def first_not_none(*args):
"""Return first item from given arguments that is not None."""
for item in args:
if item is not None:
return item
raise ValueError("No not-None values given.") |
def regenerate_chunks(shape, chunks):
"""
Regenerate new chunks based on given zarr chunks
Parameters
----------
shape : list/tuple
the zarr shape
chunks : list/tuple
the original zarr chunks
Returns
-------
list
the regenerated new zarr chunks
"""
#... |
def variant_str(variant):
"""Return a string representation of variant."""
if variant is None:
return ''
return variant |
def gen_timeout(total, step):
"""Break the total timeout value into steps
that are a specific size.
Args:
total (int) : total number seconds
step (int) : length of step
Returns:
(list) : list containing a repeated number of step
plus the remainder if step doesn... |
def prefix_attrs(source, keys, prefix):
"""Rename some of the keys of a dictionary by adding a prefix.
Parameters
----------
source : dict
Source dictionary, for example data attributes.
keys : sequence
Names of keys to prefix.
prefix : str
Prefix to prepend to keys.
Retu... |
def exclude(counter, signal):
""" decide which counters/signals to include in our end2end coverage metric """
return signal['port'] not in ['auto_cover_out'] |
def ndwi2(green, nir):
"""Normalized Difference 857/1241 Normalized Difference Water Index boosted with Numba
See:
https://www.indexdatabase.de/db/i-single.php?id=546
"""
return (green - nir) / (green + nir) |
def _transpose(mat):
""" Transpose matrice made of lists
INPUTS
------
mat: iterable 2d list like
OUTPUTS
-------
r: list of list, 2d list like
transposed matrice
"""
r = [ [x[i] for x in mat] for i in range(len(mat[0])) ]
return r |
def s_gate_counts_deterministic(shots, hex_counts=True):
"""S-gate circuits reference counts."""
targets = []
if hex_counts:
# S
targets.append({'0x0': shots})
# S.X
targets.append({'0x1': shots})
# HSSH = HZH = X
targets.append({'0x1': shots})
else:
... |
def create_url(user_id):
"""
Returns endpoint to get historical tweets of a handle
Args:
user_id: User Id of Twitter handle
Returns:
Endpoint where to make request
"""
return f"https://api.twitter.com/2/users/{user_id}/tweets" |
def assign_tenure_bucket(tenure):
"""Bucket tenure into one of three groups"""
if tenure < 2:
return "less than two"
elif tenure < 5:
return "between two and five"
else:
return "more than five" |
def get_index(value, bitindex):
"""
Returns the bit at position `bitindex` of the integer `value`
Parameters
----------
value : Integer
Input value
bitindex : Integer
Bitindex selector of `value`
"""
# bitstring = '{0:32b}'.format(value)
r... |
def get_stack_name(seedkit_name: str) -> str:
"""Helper function to calculate the name of a CloudFormation Stack for a given Seedkit
Parameters
----------
seedkit_name : str
Name of the Seedkit
Returns
-------
str
Name of the Stack Name associated with the Seedkit
"""
... |
def find_indexes(string):
""" Find indexes of all N's in string """
return [i for i, s in enumerate(string) if s == 'N'] |
def _get_studygenes(study_orig, num_stu_in_pop):
"""Get a study set having genes not found in the population."""
study = set()
for idx, gene in enumerate(study_orig):
if idx > num_stu_in_pop:
gene += 'A'
study.add(gene)
return study |
def is_fasta_label(x):
"""Checks if x looks like a FASTA label line."""
return x.startswith('>') |
def exp_lr_scheduler(optimizer, epoch, init_lr=5e-3, lr_decay_epoch=40):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
lr = init_lr * (0.1**(epoch // lr_decay_epoch))
if epoch % lr_decay_epoch == 0:
print('LR is set to {}'.format(lr))
for param_group in optimizer.... |
def str_list_to_int_list(array_like):
"""
Function to map list of strings to list of integers
Parameters:
df_trips: DataFrame containing the column 'locations' and 'times'
"""
return list(map(int,array_like)) |
def is_private(event):
"""Chechenada al canto para saber si es privado."""
return event.get('channel').startswith('D') |
def range_string_to_list(range_string):
"""returns a list of the values represented by a range string"""
if range_string == "":
return []
output = list()
for x in range_string.split(","):
y = x.split("-")
if len(y) > 1:
output.extend(range(int(y[0]), int(y[1]) + 1))
... |
def calculate_interval(timeout_int):
"""Calculates interval based on timeout.
Some customers require long timeouts and polling every 0.1s results
very longs logs. Poll less often if timeout is large.
"""
if timeout_int > 60:
interval = 3
elif timeout_int > 10:
interval = 1
e... |
def _array_blocks(arr, step=1000):
"""
Break up large arrays so we have predictable updates or queries.
:param arr:
:param step:
:return:
"""
end = len(arr)
blocks = [0]
if end > step:
for start in range(step, end, step):
blocks.append(start)
return blocks |
def multi_f(f_args):
"""Takes a tuple (f, loni, lati, lon, lat), evaluates and returns f(lon, lat)"""
return f_args[0](*f_args[3:5]) |
def is_str_float(i):
"""Check if a string can be converted into a float"""
try: float(i); return True
except ValueError: return False
except TypeError: return False |
def merge_two_dicts(x, y):
"""
Given two dicts, merge them into a new dict as a shallow copy.
"""
z = x.copy()
z.update(y)
return z |
def str_to_list(s):
"""
Function to turn a string separated by space into list of words
:param s: input string
:return: a list of words
"""
result = s.split()
# check if the last word is ';' and remove it
#if len(result) >= 1:
# if result[len(result) - 1] == ";":
# resu... |
def simplify_record(record_comps):
"""
Replace the names of some standard record by shorter names
Parameter
---------
record_comps: a list of strings
A list of available particle record components
Returns
-------
A list with shorter names, where applicable
"""
# Replace... |
def anagram_solution1(s1, s2):
"""
@rtype : bool
@param s1: str1
@param s2: str2
@return: True or False
"""
anagram_list = list(s2)
pos1 = 0
still_ok = True
while pos1 < len(s1) and still_ok:
pos2 = 0
found = False
while pos2 < len(anagram_list) and no... |
def get_normal_form(obj_name, title=True):
"""Replaces underscores with spaces.
Transforms to title form if title is True.
(product_groups -> Product Groups).
"""
obj_name_wo_spaces = obj_name.replace("_", " ")
return obj_name_wo_spaces.title() if title else obj_name_wo_spaces |
def _eq(prop_value, cmp_value, ignore_case=False):
"""
Helper function that take two arguments and checks if :param prop_value:
equals :param cmp_value:
:param prop_value: Property value that you are checking.
:type prop_value: :class:`str`
:param cmp_value: Value that you are checking if they ... |
def remove_single_lines(string: str) -> str:
"""
Attempts to remove single line breaks. This should take into account
lists correctly this time! This will treat line breaks proceeded by
anything that is not an alpha as a normal line break to keep. Thus, you
must ensure each line of a continuing para... |
def ConvertStringToListFloat(line, space = " ", endline = ""):
"""This function converts a string into a list of floats
"""
list_values = []
string_values = (line.replace(endline,"")).split(space)
for string in string_values:
if (string != ""):
list_values.append(float(string))
... |
def remove_junk_from_filestream(
lines, banner="-----oOo-----", comment_chars=["#", "!", "*"]
):
"""
Removes comments, headers, and whitespace from a list of strings,
parsed from a lagrit.out file.
"""
newlines = []
in_banner = False
for line in lines:
stripped = line.strip()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.