content stringlengths 42 6.51k |
|---|
def measurement_from_sds011(timestamp, measurement, pm25, pm100, geohash, location):
"""Turn the SDS011 object into a set of influx-db compatible measurement object"""
return {
"measurement": str(measurement),
"tags": {
"sensor": "sds011",
"location": str(location),
... |
def upper(string):
"""
Return string converted to upper case.
"""
return str(string).upper() |
def e_noroeste(arg):
"""
e_noroeste: direcao --> logico
e_noroeste(arg) tem o valor verdadeiro se arg for o elemento 'NW' e falso
caso contrario.
"""
return arg == 'NW' |
def seq2seq_rev_indexer(output_idxr):
""" b2s model inverse output vocabulary """
rev_map = {}
for key, value in output_idxr.items():
rev_map[value] = key
return rev_map |
def as_ascii(input_string):
"""Helper function to parse a byte string to an ascii string if necessary"""
try:
return input_string.decode('ascii')
except AttributeError:
return input_string |
def hmsdms_to_deg(hmsdms):
"""
Convert HMS (hours, minutes, seconds) and DMS (degrees, minutes, seconds) to
RA, DEC in decimal degrees.
Example:
hmsdms_to_deg('06 45 08.91728 -16 42 58.0171')
Return:
(101.28715533333333, -15.28388413888889)
"""
ls = hmsdms.split(' ')
ra_h... |
def _makeBool(value, default=True):
""" Helper to make boolean out of a .ini value """
if default is True:
if (value or '').lower() in ('off', 'false', '0'):
return False
else:
if (value or '').lower() in ('on', 'true', '1'):
return True
return default |
def frames_ascii(minFrameNum, maxFrameNum, frames):
"""Create a string represention.
Args:
minFrameNum ([type]): [description]
maxFrameNum ([type]): [description]
frames ([type]): [description]
Returns:
[type]: [description]
"""
framesRepresentation = []
for... |
def get_id_from_url(url: str) -> str:
"""Get the id of the image from the url.
The url is of the format https://sxcu.net/{image_id},
so we simply split the url by `/` and return the last part.
Parameters
----------
url : str
The original url.
Returns
-------
str
The... |
def noam_decay(step, warmup_steps, model_size):
"""Learning rate schedule described in
https://arxiv.org/pdf/1706.03762.pdf.
"""
return (
model_size ** (-0.5) *
min(step ** (-0.5), step * warmup_steps ** (-1.5))) |
def bounding_box(X):
"""
Calculates the boundaries of a given dataset on all sides
Parameters:
X - a data matrix where each row is a dimensional array of an item to be clustered
Returns:
Two tuples, where the first contains the minimum and maximum x values, and the
second con... |
def gl_get_projects(gl, config):
"""Return a list of all the projects.
This function looks at the config and returns all the projects of a user if
`user` is specified and all the projects of a group if `group` is specified
in the config.
:param gl: An instance of Gitlab's API.
:type gl: :class... |
def p_ext_virus(B, t, delta, N0):
"""
An approximate solution for the probability of extinction for phage clones, valid at large t
t is time in minutes
This is the NEUTRAL APPROXIMATION (p = 1/B)
"""
return ((B*delta*t)/(B*delta*t + 2))**N0 |
def sizeof_fmt(num, suffix='B'):
"""
Copied from https://web.archive.org/web/20111010015624/http://blogmag.net/
blog/read/38/Print_human_readable_file_size .
Author:
Fred Cirera
"""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suf... |
def make_shell_job_url(host, shell_port, _):
"""
Make the job url from the info
stored in stmgr. This points to dir from where
all the processes are started.
If shell port is not present, it returns None.
"""
if not shell_port:
return None
return "http://%s:%d/browse/" % (host, shell_port) |
def base36_encode(integer, width=None):
"""
Encodes integer as a string in base 36, prepending 0's until string is of
length equal to width.
Parameters
----------
integer : int
width : int, optional
Returns
-------
str
"""
digit_set = "0123456789abcdefghijklmnopqrstuvwxyz"
digits = []
whil... |
def zig_zag(items: list) ->list:
"""Rearrange the elements of a list in zig-zag fashion.
Changes to the list are made in place.
"""
less_than = True
for i in range(len(items)-1):
if (less_than) and items[i] > items[i+1]:
items[i], items[i+1] = items[i+1], items[i]
else:
... |
def read_sentences_from_file(filename):
"""
This function accepts a path to a file and returns a list of all the sentences found in the file, each
paired with the number of the first character in the sentence in the file
"""
sentence_start = 0
char_count = -1
sentences = []
old_sentence ... |
def clean_token(token):
"""
Cleans a token such as a Twitter screen name.
"""
if token is None:
return None
stripped_token = token.strip()
return stripped_token[1:] if stripped_token.startswith('@') else stripped_token |
def expand_time(t, start, step):
"""Takes a time (usually year) and returns the number of days since @param:start"""
return (t - start) * step |
def is_there_any_common_element(first: set, second: set) -> int:
"""
The function checks if there are common elements in two sets and if there are any then it returns 1, else 0.
Parameters
----------
first : set
unique items from the set A
second : set
unique items fro... |
def phantom_ammo_dict(logger):
"""Phantom ammo parameters without body."""
ammo_dict = {
'host': '127.0.0.1',
'port': 8888,
'url': '/auth',
'method': 'GET',
'log': logger,
'case': 'tests',
'extra_headers': {'Authorization': 'token'},
'body': {}
... |
def get_sentences_list_matches_2(text, keysentence):
"""
Check which key-sentences from occurs within a string
and return the list of matches.
:param text: text
:type text: str or unicode
:param keysentence: sentences
:type: list(str or uniocde)
:return: Set of sentences
:rtype: set... |
def get_object_id(object_url):
""" 'http://.../api/run/123/' => 123"""
url = object_url[:-1]
return int(url[url.rindex('/') + 1:]) |
def getType(v):
"""
Returns a tuple with type information.
Most of the time getType(v)[2] will be the information needed.
getType(v)[0] is the module (python, vsip, or pyJvsip).
getType(v)[1] is the class (scalar, View, Block, etc).
getType(v)[2] is the type which is dependen... |
def extract_molecule(string):
"""
Extract the molecule(s) from an input string in the format moleculeID,startres,endres;moleculeID,startres,endres
"""
unique_molecule_id = []
for molecule_info in string.split(';'):
molecule_id = molecule_info.split(',')[0]
if molecule_id not... |
def minindex(A):
"""Return the index of the minimum entry in a list. If there are
multiple minima return one."""
return min((a, i) for i, a in enumerate(A))[1] |
def create_pad(size, pad_id):
"""
Create a padding list of a given size
Args:
size: nd list shape
pad_id: padding index
Returns:
- padding list of the given size
"""
if len(size) == 1:
return [pad_id for _ in range(size[0])]
else:
return [create_pad(... |
def _get_class_href(c_name: str) -> str:
"""Return a href for linking to the specified class."""
return 'class_' + c_name.replace('.', '_') |
def ERR_UNKNOWNMODE(sender, receipient, message):
""" Error Code 472 """
return "ERROR from <" + sender + ">: " + message |
def is_valid_email(email):
"""
RFC822 Email Address Regex
--------------------------
Originally written by Cal Henderson
c.f. http://iamcal.com/publish/articles/php/parsing_email/
Translated to Python by Tim Fletcher, with changes suggested by Dan Kubb.
Licensed under a Creative Commons A... |
def _PERM_OP(a,b,n,m):
"""Cleverer bit manipulation."""
t = ((a >> n) ^ b) & m
b = b ^ t
a = a ^ (t << n)
return a,b |
def calculate_mant_exp(value, precision=8):
"""
This function calculates the exponent and mantissa from a desired value. Can e.g. be used for weights.
:param value: the value for which you want to calculate mantissa and exponent
:param precision: the allowed precision in bits for the mantissa
:retur... |
def DeleteKeys(d, keys):
"""Delete the keys from the given dictionary, if present.
Args:
d: The dictionary to remove the keys from.
keys: The list of keys to remove.
Returns:
The dictionary.
"""
for key in keys:
if key in d:
del d[key]
return d |
def do_strip(s):
"""
Removes all whitespace (tabs, spaces, and newlines) from both the left and
right side of a string. It does not affect spaces between words.
https://github.com/Shopify/liquid/blob/b2feeacbce8e4a718bde9bc9fa9d00e44ab32351/lib/liquid/standardfilters.rb#L92
"""
return str(s).str... |
def _lenlastline(s):
"""Get the length of the last line. More intelligent than
len(s.splitlines()[-1]).
"""
if not s or s.endswith(('\n', '\r')):
return 0
return len(s.splitlines()[-1]) |
def unpack_pdb_id(pdb_id_str):
"""Unpack a coded PDB string from the dm file format"""
spl = pdb_id_str.split(':')
pdb_id, chain = spl[0:2]
offset = int(spl[2]) if len(spl) > 2 else 0
return pdb_id, chain, offset |
def kwargs2urlparams(kwargs):
"""Converts a key-value dict into a string of URL parameters.
Dict entries with empty values will be ignored. This is used when
redirecting API requests to existing methods of the rstWeb app.
Example:
>>> kwargs2urlparams({'foo': 'bar', 'ham': 'egg', 'a': ''})
... |
def and_operator(x: bool, y: bool) -> float:
"""
Poses the AND operator as an optimization problem.
Useful only for testing that the genetic algorithm
doesn't choke on a discrete function.
"""
return 1.0 if x and y else 0.0 |
def find_extended_row_candidates(frnum, row_candidates, traces):
"""
Attempt to add further traces to each of the row candidates.
row_candidates = find_extended_row_candidates(frnum, row_candidates, traces)
At this stage, a single trace may appear in multiple row candidates.
Only one of the re... |
def invert_dict(d):
"""
Returns dictionaries with swapped key-values.
"""
return dict((v, k) for k,v in d.items()) |
def get_pred_dict(pred_name):
"""
Create a dict mapping predicate names to indices
:param pred_name: list of pred names, in order
:return: dict
"""
return {p:i for i,p in enumerate(pred_name)} |
def filter_lines(lines, comment='#'):
""" Filter lines by removing comments and empty lines
"""
filtered_list = []
for line in lines:
line = line.strip()
if not line.startswith(comment) and line != '':
filtered_list.append(line)
return filtered_list |
def key_to_option(key):
"""Convert a dictionary key to a valid command line option. This simply
replaces underscores with dashes.
"""
return key.replace('_', '-') |
def collimate(a_string, column_widths):
"""
Split a list-type thing, like a string, into slices that are column_widths
length.
>>> collimate("a b1 c2345",[2,3,3,2])
['a ','b1 ','c23','45']
Args:
a_string: The string to split. This parameter can actually be anything
sl... |
def sub2ind(shape, row_sub, col_sub):
"""
Return the linear index equivalents to the row and column subscripts for
given matrix shape.
:param shape: Preferred matrix shape for subscripts conversion.
:type shape: `tuple`
:param row_sub: Row subscripts.
:type row_sub: `list`
:param col_su... |
def _encode_answer(sentence, dictionary):
"""
:param sentence: answer sentence
:param: answer - index dictionary
:return: indices
"""
# encode = torch.zeros((len(dictionary) + 1)).type(torch.LongTensor)
idx = len(dictionary)
if sentence in dictionary.keys():
idx = dictionary[sen... |
def sum_nums(d) -> int:
"""Return the sum of all integers in the parm dictionary."""
if type(d) == int:
return d
elif type(d) == list:
total = 0
for i in d:
total += sum_nums(i)
return total
elif type(d) == dict:
total = 0
for k in d:
... |
def student_ranking(student_scores, student_names):
"""
:param student_scores: list of scores in descending order.
:param student_names: list of names in descending order by exam score.
:return: list of strings in format ["<rank>. <student name>: <score>"].
"""
ranking = [str(index+1) + '. '... |
def _calc_detlam(xx, yy, zz, yx, zx, zy):
"""
Calculate determinant of symmetric 3x3 matrix
[[xx,yx,xz],
[yx,yy,zy],
[zx,zy,zz]]
"""
return zz * (yy*xx - yx**2) - \
zy * (zy*xx - zx*yx) + \
zx * (zy*yx - zx*yy) |
def lower_bound(l, k):
"""
>>> lower_bound([1, 2, 2, 3, 4], 2)
1
>>> lower_bound([1, 2, 2, 3, 4], 5)
-1
:param l:
:param k:
:return:
"""
if l[-1] < k:
return -1
i = len(l) // 2
start, end = 0, len(l) - 1
while start < end:
if l... |
def dtypes2pg(dtype):
"""Returns equivalent PostgreSQL type for input `dtype`"""
mapping = {
'int16': 'smallint',
'int32': 'integer',
'int64': 'bigint',
'float32': 'real',
'float64': 'double precision',
'object': 'text',
'bool': 'boolean',
'datetim... |
def join_res(d, keys, sep=' '):
"""template like join dict values in signle string, safe for nonexists keys"""
return sep.join([str(d[k]) for k in keys if k in d and d[k]]) |
def normalize_timestamp(timestamp):
"""
Format a timestamp (string or numeric) into a standardized
xxxxxxxxxx.xxxxx (10.5) format.
Note that timestamps using values greater than or equal to November 20th,
2286 at 17:46 UTC will use 11 digits to represent the number of
seconds.
:param times... |
def bisect_left(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x. So if x already appears in the list, a.insert(x) will
insert just before the leftmost x already th... |
def non_repeat(line):
"""
the longest substring without repeating chars
"""
if not line:
return ""
if (max(line) == min(line)):
return line[0]
max_repeat = ""
for i in range(len(line)):
current = ""
for x in range(i, len(line)):
... |
def printTable(data: list) -> None:
"""Prints data (list of lists)
in a nicely formatted table"""
colWidths = [0] * len(data)
for idx, row in enumerate(data):
colWidths[idx] = max([len(word) for word in row])
newTable = {}
for i in range(len(data)):
for j in range(len(data[0]))... |
def find_subclasses(klass, include_self=False):
"""find all subclasses
"""
subclasses = []
for subclass in klass.__subclasses__():
subclasses.extend(find_subclasses(subclass, True))
if include_self:
subclasses.append(klass)
return subclasses |
def regional_sheet_name(df_column_name):
"""Takes a column name (string) found in the regional dataframe returned from
seaicetimeseries, and returns a name that can be used for a sheet in a
regional xlsx file. Example: "bering_area_km2" => "Bering-Area-km^2"
"""
sheet_name = df_column_name.title()... |
def is_emoji(content: str) -> bool:
""" judge str is emoji
Args: str type
Return : Bool type , return True if is Emoji , else False
"""
if not content:
return False
if u"\U0001F600" <= content and content <= u"\U0001F64F":
return True
elif u"\U0001F300" <= content and cont... |
def GetSumByIteration(array , target):
"""
THis function uses iterations
"""
NumSums =[]
for i in range(len(array)-2):
for j in range(i+1 , len(array)-1):
for k in range(j+1 , len(array)):
currSum = array[i]+array[j]+array[k]
if currSum == target:
... |
def brier_score_calc(
classes,
prob_vector,
actual_vector,
sample_weight=None,
pos_class=None):
"""
Calculate Brier score.
:param classes: confusion matrix classes
:type classes: list
:param prob_vector: probability vector
:type prob_vector: python list o... |
def ver_to_int(*va):
"""Split the version number into parts."""
return int('%x%02x%02x%02x%x' % va, 16) |
def format_row(row: list) -> list:
"""Format a row of scraped data into correct type
All elements are scraped as strings and should be converted to the proper format to be used. This converts the
following types:
- Percentages become floats (Ex: '21.5%' --> 0.215)
- Numbers become ints (Ex: '2020'... |
def Powerlaw(x, n=0.5, K=0.1):
"""Powerlaw model for the stress data
Note:
.. math::
\sigma=K \cdot \dot\gamma^n
Args:
K : consistency index [Pa s]
n : shear thinning index (1 for Newtonian) []
Returns:
stress : Shear Stress, [Pa]
"""
return K * x ** n |
def create_url(event_id: int) -> str:
"""
Return the correct link to the event by its id
:param event_id: id of the event
:return: link to the event
"""
return f'https://olimpiada.ru/activity/{event_id}' |
def get_common_shape(x, y):
""" Get common shape z from two shapes, x and y.
If x and y are of different ranks, error out.
If x and y have the same rank, but x[i] != y[i] for some i, then z[i] = -1, indicating UNKNOWN.
If x and y are equal, z = x
"""
z = None
if len(x) == len(y):
z =... |
def getlambda(pixel, lo, hi):
#-----------------------------------------------------------------------------
"""
Small utility to calculate lambda on a line for given position
in pixels
"""
#-----------------------------------------------------------------------------
if pixel is None:
return 0.5
... |
def homogenize_unit_array(arr, unit=None):
""" takes an list with quantities and turns it into a numpy array with a
single associated unit
`arr` is the (not nested) list of values
`unit` defines the unit to which all items are converted. If it is omitted,
the unit is determined automaticall... |
def calculatePostIapAggregateInterference(q_p, num_sas, iap_interfs):
"""Computes post IAP allowed aggregate interference.
Routine to calculate aggregate interference from all the CBSDs managed by the
SAS at protected entity.
Args:
q_p: Pre IAP threshold value for protection type (mW)
num_sas: Number ... |
def parse_ignore_classifiers(value):
"""Extract flag ignore classifiers value from the param for validation.
:param value: Input ignore_classifiers value.
:return: A Boolean value [True, False], otherwise ``None``.
"""
if value == 'true':
return True
elif value == 'false':
return... |
def distance(left, right):
"""
Return the Hamming distance between to strings.
Note: Strings are shortened to the shortest length.
"""
distance = 0
for left_token, right_token in zip(left, right):
if left_token != right_token:
distance += 1
return distance |
def starts_with(values, list):
"""Checks if a list starts with the provided values"""
return list[: len(values)] == values |
def raw(text):
"""Convert to HTML unescaped element (use with caution).
Example:
>>> raw("<p></p>")
b'<p></p>'
"""
return text.encode() |
def fib(n):
"""generic fibonacci"""
if n < 2:
return n
return fib(n-1) + fib(n-2) |
def _comp_suffix(s):
"""
Returns the comparison operator suffix given a search field.
This does not include the `__` (double underscore).
If no suffix is present, then `eq` is returned.
"""
suffixes = ['eq', 'ne', 'lt', 'le', 'gt', 'ge']
for suffix in suffixes:
if s.endswith(suffix)... |
def solver_problem1(inputs):
""" Count the number of increasement from given list """
num_increased = 0
for i in range(1, len(inputs)):
if inputs[i] > inputs[i - 1]:
num_increased += 1
return num_increased |
def _sort_dictionary(input: dict, reverse: bool = False) -> dict:
"""Rebuild a dictionary with the same keys and values but where the keys are inserted in sorted order. This can be useful for display purposes."""
sorted_keys = sorted(input, reverse=reverse)
return {k: input[k] for k in sorted_keys} |
def dms(degrees):
"""
Calculate degrees, minutes, seconds representation from decimal degrees.
Parameters
----------
degrees : float
Returns
-------
(int, int, float)
"""
degrees_int = int(abs(degrees)) # integer degrees
degrees_frac = abs(degrees) - degrees_int # fracti... |
def join(front, back, joiner='AND'):
"""Join strings together with a specified joiner.
Parameters
----------
front, back : str
Strings to join together.
joiner : {'AND', 'OR', 'NOT'}
The string to join together the inputs with.
Returns
-------
str
Concatenated s... |
def guess(key, values):
"""
Returns guess values for the parameters of this function class based on the input. Used for fitting using this
class.
:param key:
:param values:
:return:
"""
return [min(values)-max(values), (max(key)-min(key))/3, min(values)] |
def MakePrototypeString(params):
"""Given a list of (name, type, vectorSize) parameters, make a C-style
parameter prototype string (types only).
Ex return: 'GLuint, GLfloat, GLfloat, GLfloat'.
"""
n = len(params)
if n == 0:
return 'void'
else:
result = ''
i = 1
for (name, type, vecSize) in params:
res... |
def get_number(line, position):
"""Searches for the end of a number.
Args:
line (str): The line in which the number was found.
position (int): The starting position of the number.
Returns:
str: The number found.
int: The position after the number found.
"""
word = ... |
def ceaser_ciper_encryption(input_to_encode, key_length):
"""Ceaser Encryption method"""
enc_output = chech_char = ""
for letter in input_to_encode:
if letter.isalpha():
n_uni_char = ord(letter) + key_length
chech_char = 'Z'
if letter.islower():
ch... |
def approach(B, dx, dy):
""" add dx and dy to point B's coordinates """
return B[0] + dx, B[1] + dy; |
def getattr_str(obj, attr, fmt=None, fallback='?'):
"""Returns a string of the given object's attribute, defaulting to the
fallback value if attribute is not present."""
if hasattr(obj, attr):
if fmt is not None:
return fmt % getattr(obj, attr)
return str(getattr(obj, attr))
... |
def better_join( char, strlis ):
"""Uses the supplied character to join a list of strings into a long string."""
return char.join( [s for s in strlis if s is not None and len(s)>0] ) |
def getHoliday(holidayName):
"""Returns a specific holiday.
Args:
holidayName (str): The name of the holiday to return.
Case-sensitive.
Returns:
HolidayModel: The holiday, as a HolidayModel object, or None if
not found.
"""
print(holidayName)
return None |
def get_producer_map(ssa):
"""
Return dict from versioned blob to (i, j),
where i is index of producer op, j is the index of output of that op.
"""
producer_map = {}
for i in range(len(ssa)):
outputs = ssa[i][1]
for j, outp in enumerate(outputs):
producer_map[outp... |
def get_ext_temperature_level(avg_temp, ext_max_temp, ext_min_temp, ext_start_threshold):
"""
Calculates the level of the external temperature for controlling the heating period
:param avg_temp: The average temperature
:param ext_max_temp: The maximum external temperature to start heating
:param ext... |
def array_pair_sum(k, array):
"""
Iterative method
Loops through the array, checking if a pair sums up to the value k
Returns all pairs that sum up to k
complexity: O(n^2)
:param k: The value to check sum of pairs against
:param array: The array of integers to loop through
:return: The s... |
def fib_recursion(n):
"""
Assum n is an integer n > 0
"""
if n == 1:
return 0
if n == 2:
return 1
return fib_recursion(n-1) + fib_recursion(n-2) |
def map_save_result(process, in_place=False, format_type = None, band_label=None):
"""
"""
bands = []
if 'options' in process['arguments']:
for item in process['arguments']['options']:
bands.append(process['arguments']['options'][item])
if bands:
dict_item = {
... |
def str_to_bool(s):
"""
Basic converter for Python boolean values written as a str.
:param s: The value to convert.
:return: The boolean value of the given string.
@raises: ValueError if the string value cannot be converted.
"""
if s == 'True':
return True
elif s == 'False':
... |
def colormap_select(base_colormap, start=0, end=1.0, reverse=False):
"""
Given a colormap in the form of a list, such as a Bokeh palette,
return a version of the colormap reversed if requested, and selecting
a subset (on a scale 0,1.0) of the elements in the colormap list.
For instance:
... |
def get_sizes_purities(clusters):
"""Return two lists containing the sizes and purities of `clusters`."""
sizes = []
purities = []
for cluster in clusters:
sizes.append(cluster["size"])
purities.append(cluster["purity"])
return sizes, purities |
def dropFeatures(features, remove_list):
"""
Parameters:
features = Python list of unique features in the data_dict.
remove_list = Python list of features to be removed.(drop
non-numeric features such as the email address)
Output:
Python list... |
def get_label_addr(_lbls: list, label: str) -> int:
"""
Given a label, get the address for that label.
Parameters
----------
_lbls : list, mandatory
A list of the known labels and their addresses
label: str, mandatory
The label whose address is required
Returns
-------... |
def signature_check(dummy, *args, **kwargs):
"""Checks whether the arguments match the signature of a dummy function by catching a TypeError"""
try:
dummy(*args, **kwargs)
return True
except TypeError:
return False |
def swap(x, i, j):
"""
swap bits i and j of x.
"""
mask = (1<<i) | (1<<j)
m = x&mask
if m == 0 or m == mask:
return x
return x^mask |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.