content stringlengths 42 6.51k |
|---|
def compare_not_none(this, other):
"""Oldschool (python 2.x) cmp.
if this < other return -1
if this = other return 0
if this > other return 1
"""
if len(this) != len(other):
return -1 if len(this) < len(other) else 1
for i in range(len(this)):
this_item, other_item ... |
def sec2frames(time_in_seconds, winlength, winstep):
""" turn time in seconds into time in frames"""
time_in_frames = (time_in_seconds - winlength/2)/winstep
time_in_frames = int(round(time_in_frames))
if time_in_frames < 0:
time_in_frames = 0
return time_in_frames |
def _grid_to_commands(grid_dict):
"""Translate a dictionary of parameter values into a list of commands.
The entire set of possible combinations is generated.
Args:
grid_dict: A dictionary of argument names to lists, where each list
contains possible values for this argument.
Retu... |
def selectionSort(array: list):
"""
Best : O(n^2) Time | O(1) Space
Average : O(n^2) Time | O(1) Space
Worst : O(n^2) Time | O(1) Space
"""
n: int = len(array)
for currentIdx in range(n - 1):
smallestIdx = currentIdx
for i in range(currentIdx + 1, n):
if array[sma... |
def split_category(category: str):
"""
Split category string into category and sub-category. The category and sub-category
are separated by a colon (":"). However, not all categories have sub-categories. This
method handles both cases.
Args:
category (str): Category[:sub-category] String, e... |
def _tuple_from_ver(version_string):
"""
:param version_string:
A unicode dotted version string
:return:
A tuple of integers
"""
return tuple(map(int, version_string.split('.'))) |
def split(x, divider):
"""Split a string.
Parameters
----------
x : any
A str object to be split. Anything else is returned as is.
divider : str
Divider string.
"""
if isinstance(x, str):
return x.split(divider)
return x |
def _histc(x, edges):
"""
Histogram without plot
>>> x = xrange(0, 100)
>>> edges = range(0, 110, 10)
>>> _histc(x, edges)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
:param x: set of seq
:param edges: histogram edges
:return: histogram count
"""
i = 0
ks = []
while i ... |
def create_codes_and_names_of_A_matrix(db):
"""
Create a dictionary a tuple (activity name, reference product,
unit, location) as key, and its code as value.
:return: a dictionary to map indices to activities
:rtype: dict
"""
return {
(i["name"], i["reference product"], i["unit"], i[... |
def parrot(voltage, state='a stiff', action='voom', parrot_type='Norwegian Blue'):
"""Example of multi-argument function
This function accepts one required argument (voltage) and three optional arguments
(state, action, and type).
"""
message = 'This parrot wouldn\'t ' + action + ' '
message +... |
def replay(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return':1, 'error':'TBD'}
# TBD - take pa... |
def round_key(matrix, key_block):
"""
This function is used for both AES encryption and AES decryption.
The function will divide the matrix into four 4 bytes blocks (each column as a block), and perform XOR operation
between block and key which contained in the key_block. At last, create and return the... |
def _merge_dicts(*args):
"""
Shallow copy and merge dicts together, giving precedence to last in.
"""
ret = dict()
for arg in args:
ret.update(arg)
return ret |
def summary_to_entries(summary):
"""
"Height": 140,
"Width": 59.3,
"marked_graph": [1],
"marked_text": [1],
"n_chars": 2936,
"n_pages": 1,
"name": "-patente-de-invencion-1445369-1.pdf",
"page_texts"
"""
name = summary['path']
page_texts = s... |
def filter_dictionary(function, dictionary, by="keys"):
"""Filter a dictionary by conditions on keys or values.
Args:
function (callable): Function that takes one argument and returns True or False.
dictionary (dict): Dictionary to be filtered.
Returns:
dict: Filtered dictionary
... |
def sort(xs):
"""Returns a list containing the same elements as xs, but in sorted order."""
xs.sort()
return xs |
def J_p(Ep, norm=1.0, alpha=2.0):
"""
Defines the particle distribution of the protons as a power law.
Parameters
----------
- Ep = E_proton (GeV)
- alpha = slope
- norm = the normalization (at 1 GeV) in units of cm^-3 GeV-1
Outputs
--------
- The particle distribution in units... |
def kareler_toplami(sayi):
""" Bir sayinin kareler toplami zincirinin hangi sayida
sonlandigini ozyinelemeli bulur.
"""
if sayi in [0, 1, 89]:
return sayi
else:
yeni_toplam = sum([int(i)**2 for i in str(sayi)])
return kareler_toplami(yeni_toplam) |
def halton_seq(prime, index=1):
""" Low discrepancy halton sequence with a given prime """
r, f, i = 0.0, 1.0, index
while i > 0:
f /= prime
r += f * (i % prime)
i = int(i / float(prime))
return r |
def is_main_process(local_rank):
"""
Whether or not the current process is the local process, based on `xm.get_ordinal()` (for TPUs) first, then on
`local_rank`.
"""
return local_rank in [-1, 0] |
def trunc_bytes_at(
msg: bytes, delim: bytes = b"{", start: int = 1, occurrence: int = 1
):
"""Truncates bytes starting from a given point at nth occurrence of a
delimiter."""
return delim.join(msg[start:].split(delim, occurrence)[:occurrence]) |
def correct_flask_vol(flask_vol, t=20.0, glass="borosilicate"):
"""
Correct flask volume for changes from thermal expansion of glass.
Parameters
----------
flask_vol : array-like
Flask volumes at standard temperature (20C)
t : float, optional
New temperature to calculate volume
... |
def command_add(date, start_time, end_time, title, calendar):
"""
(str, int, int, str, dict) -> boolean
Add title to the list at calendar[date]
Create date if it was not there
Adds the date if start_time is less or equal to the end_time
date: A string date formatted as "YYYY-MM-DD"
start_ti... |
def stringify_list(ls):
""" string conversion of all elements in a list,
e.g. stringify_list([1,'2',u'3']) -> ['1', '2', u'3']
Mostly a support function for some other things here.
"""
if type(ls) is list:
return list('%s'%s for s in ls)
else: # tuple. Or something you sho... |
def charScore(c):
"""return character score for a character. 'A'=1,'B'=2, etc"""
return ord(c) - ord('A') + 1 |
def as_int(n):
"""
Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is
raised if the input has a non-integral value.
Examples
========
>>> from sympy.core.compatibility import as_int
>>> from sympy import sqrt
>>> 3.0
... |
def decode_binary_rle(data):
"""
decodes binary rle to integer list rle
"""
m = len(data)
cnts = [0] * m
h = 0
p = 0
while p < m:
x = 0
k = 0
more = 1
while more > 0:
c = ord(data[p]) - 48
x |= (c & 0x1F) << 5 * k
more =... |
def postfixe(arbre):
"""Fonction qui retourne le parcours prefixe de l'arbre
sous la forme d'une liste
"""
liste = []
if arbre != None:
liste += postfixe(arbre.get_ag())
liste += postfixe(arbre.get_ad())
liste.append(arbre.get_val())
return liste |
def sanatize(input):
"""
Convert input command line arguments into format contained by documents.
"""
return input.upper() |
def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float:
"""
Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
>>> fahrenhe... |
def is_in(el, list):
"""Decides whether an element is
in a list of elements.
Arguments:
- `el`: an expression
- `a list of expressions`:
"""
for e in list:
if el.equals(e):
return True
return False |
def parse_exif_val(val):
"""
Sometimes EXIF values are stored in a fraction as a string.
This will return the value as a decimal.
"""
nums = val.split('/')
if len(nums) == 1:
return float(nums[0])
return float(nums[0]) / float(nums[1]) |
def is_suspension(melody, position, cantus_firmus):
"""
Returns true if the note in the melody at the specified position is part of
a correctly formed suspension (dissonance resolving by step onto a
consonance)
"""
current_note = melody[position]
resolution_note = melody[position + 1]
ca... |
def valid_generalisation(new_norm, input_norm, ruleset_norm):
""" Check if it is useful to generalise the match on this rule
If we do not include all matches of the original rule in the new
rule, then the new rule will match more packets than the old. If
that extra packet-space matched has ... |
def get_list_of_active_skills(utterances):
"""
Extract list of active skills names
Args:
utterances: utterances, the first one is user's reply
Returns:
list of string skill names
"""
result = []
for uttr in utterances:
if "active_skill" in uttr:
result.... |
def matrixReshape(nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
A = [x for row in nums for x in row]
return [A[i*c:(i+1)*c] for i in range(r)] if c * r == len(A) else nums |
def compose(d1, d2):
"""Compose two homomorphisms given by dicts."""
res = dict()
for key, value in d1.items():
if value in d2.keys():
res[key] = d2[value]
return res |
def set_import_style(style, origin="unknown", version="unknown"):
""" Let EDIF determine an nuances for more accurate conversion """
if origin == "unknown":
style['views_as_components'] = False
elif origin == "OrCAD Capture":
style['views_as_components'] = True
return style |
def meets_criteria(value):
"""Determine if a number meets the criteria
>>> meets_criteria(111111)
True
>>> meets_criteria(223450)
False
>>> meets_criteria(123789)
False
"""
digits = [int(d) for d in str(value)]
if len(digits) != 6:
return False
# No repeats.
if ... |
def add_uic_ref(shape, properties, fid, zoom):
"""
If the feature has a valid uic_ref tag (7 integers), then move it
to its properties.
"""
tags = properties.get('tags')
if not tags:
return shape, properties, fid
uic_ref = tags.get('uic_ref')
if not uic_ref:
return shap... |
def convert_strips_to_bytes_list(playcloud_strips):
"""Extract the data bytes from alist of playcloud strips"""
return [strip.data for strip in playcloud_strips] |
def parse_data(data):
"""Takes a dictionary of keys and produces a single byte array,
ready to be encrypted.
:param data: Dictionary of (blockchain) private keys
:type data: ``dict``
:returns: Binary blob of encoded keys
:rtype: ``bytes``
"""
text = ""
tickers = ["BCH", "tBCH", "ETH... |
def _isfloat(x):
"""
returns True if x is a float,
returns False otherwise
"""
try:
float(x)
except:
return False
return True |
def count_unique_word(x, sep=None):
""" Extract number of unique words in a string """
try:
return len(set(str(x).split(sep)))
except Exception as e:
print(f"Exception raised:\n{e}")
return 0 |
def b128_varint_decode(value: bytes, pos = 0):
"""
Reads the weird format of VarInt present in src/serialize.h of bitcoin core
and being used for storing data in the leveldb.
This is not the VARINT format described for general bitcoin serialization
use.
"""
n = 0
while True:
data... |
def sentencify(sentence):
"""Ensures a capital letter at the beginning and a full stop at the end of a given sentence."""
sentence = list(sentence)
sentence[0] = sentence[0].upper()
if sentence[-1] != ".":
sentence.append(".")
sentence = "".join(sentence)
return sentence |
def parsePreprocessorLine( line ):
""" Experimental """
parts = line.split( '"' )
fileName = parts[1]
noFileLine = line.replace( '"' + fileName + '"', '' )
parts = noFileLine.split()
lineNum = int( parts[1] )
flags = []
index = 2
while index < len( parts ):
flags.append( i... |
def changeTubleToListOfDects(data, columns):
""" this function take the tuble returned by database and tranform it to list of dicts.
the keys of the dects is the table columns."""
result = []
columns = str(columns).split()
loop = len(columns)
for row in data:
d = {}
for i in range(loop):
d[str(columns[i])... |
def mock_any(cls):
"""Returns Any class to use in mock."""
class Any(cls):
"""Any class used for mocks."""
def __eq__(self, other):
return True
return Any() |
def truncate(s, l):
"""
Truncates the string `s` to length `l`
"""
if l is None or len(s) <= l:
return s
return (s[:l-3] + '...') if l >= 3 else '' |
def intersperse(lis, value):
"""Put value between each existing item in list.
Parameters
----------
lis : list
List to intersperse.
value : object
Value to insert.
Returns
-------
list
interspersed list
"""
out = [value] * (len(lis) * 2 - 1)
out[0::2... |
def mult(k, v):
"""
Returns the vector result of multipling scalar k with vector v
"""
return tuple(k*e for e in v) |
def IsStringInt(string_to_check):
"""Checks whether or not the given string can be converted to a integer.
Args:
string_to_check: Input string to check if it can be converted to an int.
Returns:
True if the string can be converted to an int.
"""
try:
int(string_to_check)
return True
except... |
def copy_location(new_node, old_node):
"""Copy the source location hint (`lineno` and `col_offset`) from the
old to the new node if possible and return the new one.
"""
new_attributes = getattr(new_node, '_attributes', ()) or ()
old_attributes = getattr(old_node, '_attributes', ()) or ()
for att... |
def get_note(dist=0):
""" Compute the note based on the distance measurements, get percentages of each scale and compare """
# Config
# you can play with these settings
#scale = [-1, -5, 60, 60, -5 ,62, 62, -5, 64, 64, -5, 67, 67, -5, 69, 69, -5, 72, -5, -1]
#distances = [38, 29, 28, ... |
def maybe_tuple(value):
"""Return `value` as a tuple. If it is already a tuple, return it
unchanged. Otherwise return a 1-element tuple containing `value`."""
if isinstance(value, tuple):
return value
return (value,) |
def TCn(x, ystress=1.0, eta_bg=0.1, gammadot_crit=0.1,n=0.5):
"""Three component model
Note:
.. math::
\sigma=\sigma_y+\sigma_y\cdot(\dot\gamma/\dot\gamma_c)^n+\eta_{bg}\cdot\dot\gamma
Args:
ystress: yield stress [Pa]
eta_bg : Background viscosity [Pa s]
gammadot_crit... |
def filterObjInfo(objInfo):
"""
filter out noisy object info
Args:
objInfo (struct): object information
"""
# filter params
keep_id = [2, 5] # kept id
keep_class = [1, 2, 3, 4, 5, 6, 7, 8] # kept class
min_obj_area = 400 # minimal kept object (pixel^2) #zzh
# consecutive... |
def kwargs_to_flags(valid_flags, arguments):
""" Takes an iterable containing a list of valid flags and a flattened
kwargs dict containing the flag values received by the function.
The key for each dict entry should be the name of a valid flag for the
command being run, with any hypn... |
def get_mod_mappings(mappings):
"""
Returns a dict of all known modification mappings.
Parameters
----------
mappings: collections.abc.Iterable[vermouth.map_parser.Mapping]
All known mappings.
Returns
-------
dict[tuple[str], vermouth.map_parser.Mapping]
All mappings th... |
def rotate(string, n):
"""Rotate characters in a string. Expects string and n (int) for
number of characters to move.
"""
return string[n:] + string[:n] |
def is_external_plugin(appname):
"""
Returns true when the given app is an external plugin.
Implementation note: does a simple check on the name to see if it's
prefixed with "kolibri_". If so, we think it's a plugin.
"""
return not appname.startswith("kolibri.") |
def status_to_dict(status_str):
"""
Helper that converts the semicolon delimited status values to
a dict
"""
status = {}
params = [param.strip() for param in status_str.split(";") if param.strip()]
for param in params:
(key, val) = param.split(":")
status[key] = val
retur... |
def bounds_to_offset(bounds):
"""Defines a transfer function offset given a transfer function.
"""
mi, ma = bounds
return mi |
def insert_before(src: str, sub: str, data) -> str:
"""
>>> insert_before("long_filename.mha", ".mha", "_newfile")
long_filename_newfile.mha
"""
i = src.find(sub)
return f"{src[:i]}{data}{src[i:]}" |
def eh_posicao_unidade (m, p):
"""Esta funcao indica se a posicao p do mapa p se encontra ocupada por uma unidade"""
return p in (m["ex1"], m["ex2"]) |
def flip_dict(dict, unique_items=False, force_list_values=False):
"""Swap keys and values in a dictionary
Parameters
----------
dict: dictionary
dictionary object to flip
unique_items: bool
whether to assume that all items in dict are unique, potential speedup but repeated items wil... |
def is_reset(command: str) -> bool:
"""Test whether a command is a reset command
Parameters
----------
command : str
The command to test
Returns
----------
answer : bool
Whether the command is a reset command
"""
if "reset" in command:
return True
if com... |
def createFolderUrl(foldersIn):
"""
Takes a list of folders separated by '|' and returns the proper url
"""
folderUrl = ""
d = foldersIn.split("|")
for folder in d:
folderUrl += "job/" + folder + "/"
return folderUrl |
def to_selector(labels):
"""
Transfer Labels to selector.
"""
parts = []
for key in labels.keys():
parts.append("{0}={1}".format(key, labels[key]))
return ",".join(parts) |
def stream_output(output: dict):
"""
Transform a stream output into a human readable str
:param output:
:return:
"""
return "".join(output["text"]) |
def precision(x, p):
"""
Returns a string representation of `x` formatted with precision `p`.
Based on the webkit javascript implementation taken
`from here <https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp>`_,
and implemented by `randlet <https://github.co... |
def remove_first_line(string):
"""
Returns the copy of string without first line (needed for descriptions which differ in one line)
:param string:
:return: copy of string.
"""
return '\n'.join(string.split('\n')[1:]) |
def col(loc, string):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See
`ParserElement.parse_string` for more
informati... |
def second_step_season(cal, teams):
"""
second_step_season(cal, teams) -> list
Create the second round for season
"""
scond_round_cal = []
for match in cal:
n, team1, team2 = match
scond_round_cal.append((int(n) + len(teams) - 1, team2, team1))
return scond_round_cal |
def entity(ent):
"""
Returns the value of an entity separated from its datatype ('represented by a string')
:param ent:
:return:
"""
if ent.startswith('_'):
return ent, 'blank_node'
if ent.startswith('"'):
if '^^' in ent:
datatype, ent = ent[::-1].split('^^', ma... |
def override_if_any(_ref, _path, _translated_ref, _translated_path, **kwargs):
"""override if any kwargs is True"""
return any(kwargs.values()) |
def from_uint8_bytes(uint8: bytes) -> int:
"""Convert from uint8 to python int."""
return int.from_bytes(uint8, byteorder="little") |
def clean_number(text):
"""
>>> clean_number("3.14159")
3.14159
>>> clean_number("two")
>>> clean_number("1,956")
>>> row = ['heading', '23', '2.718']
>>> list(map(clean_number, row))
[None, 23.0, 2.718]
"""
try:
value= float(text)
except ValueError:
value= No... |
def to_currency(n: int, currency: str = "USD") -> str:
"""
Returns numbers formatted as currency, in case of PYG
currency replaces default thousand separator ',' with '.'
"""
if currency == "PYG":
return str(n).translate(str.maketrans(",.", ".,"))
return f"{n:,}" |
def deep_equals(value, other):
"""Compare elements and deeply compare lists,, tuples and dict values."""
value_type = type(value)
assert value_type is type(other), (value_type, type(other))
if value_type in (list, tuple):
return len(value) == len(other) and all(
deep_equals(value[i],... |
def bb_intersect(a,b):
"""Returns true if the bounding boxes (a[0]->a[1]) and (b[0]->b[1]) intersect"""
amin,amax=a
bmin,bmax=b
return not any(q < u or v < p for (p,q,u,v) in zip(amin,amax,bmin,bmax)) |
def cof2amp(z):
""" Calculate a signal amplitude from a model coefficient """
# z = amp*exp(phase*i) so amp is abs(z)
return abs(z) |
def manhattan_dist(a, b):
"""
Returns the Manhattan distance between two points.
>>> manhattan_dist((0, 0), (5, 5))
10
>>> manhattan_dist((0, 5), (10, 7))
12
>>> manhattan_dist((12, 9), (2, 3))
16
>>> manhattan_dist((0, 5), (5, 0))
10
"""
return abs(a[0] - b[0]) + abs(a[... |
def get_url(userid, access_token):
"""
Generates a useable facebook graph API url
"""
root = 'https://graph.facebook.com/'
endpoint = '%s/photos?type=uploaded&fields=source,updated_time&access_token=%s' % \
(userid, access_token)
return '%s%s' % (root, endpoint) |
def _escape_regexp(s):
"""escape characters with specific regexp use"""
return (
str(s)
.replace('|', '\\|')
.replace('.', '\.') # `.` has to be replaced before `*`
.replace('*', '.*')
.replace('+', '\+')
.replace('(', '\(')
.replace(')', '\)')
.r... |
def format_date(start_date, format, offset=None):
"""Format a date given an optional offset.
:param start_date: an Arrow object representing the start date
:param format: the format string
:param offset: an offset measured in days
:return: a formatted datestring
"""
i... |
def get_viscosity_from_temperature(temperature):
"""
Finds the dynamics viscosity of air from a specified temperature. Uses Sutherland's Law
:param temperature: Temperature, in Kelvin
:return: Dynamic viscosity, in kg/(m*s)
"""
# Uses Sutherland's law from the temperature
# From CFDWiki
... |
def fillout(template, adict):
"""returns copy of template filled out per adict
applies str.replace for every entry in adict
"""
rval = template[:]
for key in adict:
rval = rval.replace(key, adict[key])
return rval |
def sphinx_type_in_doc(weight):
"""
:type weight: int
:param weight: weight of mail package, that we need to validate, type int
:return: if package weight > 200 - return False (we cannot deliver this package)
"""
if weight <= 0:
raise Exception("Weight of package cannot be 0 or below")
... |
def _page_obj(json_object):
"""takes json input and returns a page object
Args:
json_object (dict): json data from api
Returns:
dict: json object for the 'pages' of an article
"""
query_object = json_object['query']
return(query_object['pages']) |
def convert_mpas_fgco2(mpas_fgco2):
"""Convert native MPAS CO2 flux (mmol m-3 m s-1) to (molC m-2 yr-1)
Args:
mpas_fgco2 (xarray object): Dataset or DataArray containing native MPAS-O
CO2 flux output.
Returns:
conv_fgco2 (xarray object): MPAS-O CO2 flux ... |
def recipients_args(keys):
"""Returns the list representation of a set of GPG
keys to be used as recipients when encrypting."""
return [["--recipient", key.encode('ASCII')] for key in keys] |
def enum_os_name(
os_int # type: int
):
"""Parse InMon-defined Operating System names"""
if os_int == 0:
os_name = "Unknown"
elif os_int == 1:
os_name = "Other"
elif os_int == 2:
os_name = "Linux"
elif os_int == 3:
os_name = "Windows"
elif os_int == 4:
os_name = "Darwin"
elif os_int == 5:
os_name =... |
def index_where(collection, predicate):
""":yaql:indexWhere
Returns the index in the collection of the first item which value
satisfies the predicate. -1 is a return value if there is no such item
:signature: collection.indexWhere(predicate)
:receiverArg collection: input collection
:argType c... |
def get_update_author_name(d_included):
"""Parse a dict and returns, if present, the post author name
:param d_included: a dict, as returned by res.json().get("included", {})
:type d_raw: dict
:return: Author name
:rtype: str
"""
try:
return d_included["actor"]["name"]["text"]
... |
def _select_cols(a_dict, keys):
"""Filteres out entries in a dictionary that have a key which is not part of 'keys' argument. `a_dict` is not
modified and a new dictionary is returned."""
if keys == list(a_dict.keys()):
return a_dict
else:
return {field_name: a_dict[field_name] for field... |
def _HighByte(x):
"""This reflects what can be expressed as immediates by add_imm and sub_imm"""
shift = 0
while x > 255:
x >>= 2
shift += 2
return x << shift |
def cx_u(cD):
""" This calculates the coefficient of force in the x direction
with respect to the change in forward velocity of the aircraft
Assumptions:
None
Source:
J.H. Blakelock, "Automatic Control of Aircraft and Missiles"
Wiley & Sons, Inc. New York, 1991, (pg 23)
Input... |
def staticTunnelTemplate(user, device, ip, aaa_server, group_policy):
"""
Template for static IP tunnel configuration for a user.
This creates a unique address pool and tunnel group for a user.
:param user: username id associated with static IP
:type user: str
:param device:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.