INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Create a token based on the data held in the class. | def encode(self) -> str:
"""
Create a token based on the data held in the class.
:return: A new token
:rtype: str
"""
payload = {}
payload.update(self.registered_claims)
payload.update(self.payload)
return encode(self.secret, payload, self.alg, se... |
Decodes the given token into an instance of Jwt. | def decode(secret: Union[str, bytes], token: Union[str, bytes],
alg: str = default_alg) -> 'Jwt':
"""
Decodes the given token into an instance of `Jwt`.
:param secret: The secret used to decode the token. Must match the
secret used when creating the token.
:ty... |
Compare against another Jwt. | def compare(self, jwt: 'Jwt', compare_dates: bool = False) -> bool:
"""
Compare against another `Jwt`.
:param jwt: The token to compare against.
:type jwt: Jwt
:param compare_dates: Should the comparision take dates into account?
:type compare_dates: bool
:return... |
Download a file. | def get(self, request, hash, filename):
"""Download a file."""
if _ws_download is True:
return HttpResponseForbidden()
upload = Upload.objects.uploaded().get(hash=hash, name=filename)
return FileResponse(upload.file, content_type=upload.type) |
: param data: Data the encode.: type data: bytes: return: Base 64 encoded data with padding removed.: rtype: bytes | def b64_encode(data: bytes) -> bytes:
"""
:param data: Data the encode.
:type data: bytes
:return: Base 64 encoded data with padding removed.
:rtype: bytes
"""
encoded = urlsafe_b64encode(data)
return encoded.replace(b'=', b'') |
: param data: Base 64 encoded data to decode.: type data: bytes: return: Base 64 decoded data.: rtype: bytes | def b64_decode(data: bytes) -> bytes:
"""
:param data: Base 64 encoded data to decode.
:type data: bytes
:return: Base 64 decoded data.
:rtype: bytes
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=' * (4 - missing_padding)
return urlsafe_b64decode(dat... |
: param data: Data to convert to bytes.: type data: Union [ str bytes ]: return: data encoded to UTF8.: rtype: bytes | def to_bytes(data: Union[str, bytes]) -> bytes:
"""
:param data: Data to convert to bytes.
:type data: Union[str, bytes]
:return: `data` encoded to UTF8.
:rtype: bytes
"""
if isinstance(data, bytes):
return data
return data.encode('utf-8') |
: param data: A UTF8 byte string.: type data: Union [ str bytes ]: return: data decoded from UTF8.: rtype: str | def from_bytes(data: Union[str, bytes]) -> str:
"""
:param data: A UTF8 byte string.
:type data: Union[str, bytes]
:return: `data` decoded from UTF8.
:rtype: str
"""
if isinstance(data, str):
return data
return str(data, 'utf-8') |
Produce a camelized class name e. g. | def camelize_classname(base, tablename, table):
"Produce a 'camelized' class name, e.g. "
"'words_and_underscores' -> 'WordsAndUnderscores'"
return str(tablename[0].upper() +
re.sub(r'_([a-z])', lambda m: m.group(1).upper(),
tablename[1:])) |
Produce an uncamelized pluralized class name e. g. | def pluralize_collection(base, local_cls, referred_cls, constraint):
"Produce an 'uncamelized', 'pluralized' class name, e.g. "
"'SomeTerm' -> 'some_terms'"
referred_name = referred_cls.__name__
uncamelized = re.sub(r'[A-Z]',
lambda m: "_%s" % m.group(0).lower(),
... |
Test a file is a valid json file. | def is_compressed_json_file(abspath):
"""Test a file is a valid json file.
- *.json: uncompressed, utf-8 encode json file
- *.js: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file
"""
abspath = abspath.lower()
fname, ext = os.path.splitext(abspath)
if ext i... |
set dumper. | def dump_set(self, obj, class_name=set_class_name):
"""
``set`` dumper.
"""
return {"$" + class_name: [self._json_convert(item) for item in obj]} |
collections. deque dumper. | def dump_deque(self, obj, class_name="collections.deque"):
"""
``collections.deque`` dumper.
"""
return {"$" + class_name: [self._json_convert(item) for item in obj]} |
collections. OrderedDict dumper. | def dump_OrderedDict(self, obj, class_name="collections.OrderedDict"):
"""
``collections.OrderedDict`` dumper.
"""
return {
"$" + class_name: [
(key, self._json_convert(value)) for key, value in iteritems(obj)
]
} |
numpy. ndarray dumper. | def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):
"""
``numpy.ndarray`` dumper.
"""
return {"$" + class_name: self._json_convert(obj.tolist())} |
Decorator for rruleset methods which may invalidate the cached length. | def _invalidates_cache(f):
"""
Decorator for rruleset methods which may invalidate the
cached length.
"""
def inner_func(self, *args, **kwargs):
rv = f(self, *args, **kwargs)
self._invalidate_cache()
return rv
return inner_func |
Returns the last recurrence before the given datetime instance. The inc keyword defines what happens if dt is an occurrence. With inc = True if dt itself is an occurrence it will be returned. | def before(self, dt, inc=False):
""" Returns the last recurrence before the given datetime instance. The
inc keyword defines what happens if dt is an occurrence. With
inc=True, if dt itself is an occurrence, it will be returned. """
if self._cache_complete:
gen = self... |
Returns the first recurrence after the given datetime instance. The inc keyword defines what happens if dt is an occurrence. With inc = True if dt itself is an occurrence it will be returned. | def after(self, dt, inc=False):
""" Returns the first recurrence after the given datetime instance. The
inc keyword defines what happens if dt is an occurrence. With
inc=True, if dt itself is an occurrence, it will be returned. """
if self._cache_complete:
gen = self... |
Generator which yields up to count recurrences after the given datetime instance equivalent to after. | def xafter(self, dt, count=None, inc=False):
"""
Generator which yields up to `count` recurrences after the given
datetime instance, equivalent to `after`.
:param dt:
The datetime at which to start generating recurrences.
:param count:
The maximum number... |
Return new rrule with same attributes except for those attributes given new values by whichever keyword arguments are specified. | def replace(self, **kwargs):
"""Return new rrule with same attributes except for those attributes given new
values by whichever keyword arguments are specified."""
new_kwargs = {"interval": self._interval,
"count": self._count,
"dtstart": self._dtst... |
If a BYXXX sequence is passed to the constructor at the same level as FREQ ( e. g. FREQ = HOURLY BYHOUR = { 2 4 7 } INTERVAL = 3 ) there are some specifications which cannot be reached given some starting conditions. | def __construct_byset(self, start, byxxx, base):
"""
If a `BYXXX` sequence is passed to the constructor at the same level as
`FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some
specifications which cannot be reached given some starting conditions.
This occurs w... |
Calculates the next value in a sequence where the FREQ parameter is specified along with a BYXXX parameter at the same level ( e. g. HOURLY specified with BYHOUR ). | def __mod_distance(self, value, byxxx, base):
"""
Calculates the next value in a sequence where the `FREQ` parameter is
specified along with a `BYXXX` parameter at the same "level"
(e.g. `HOURLY` specified with `BYHOUR`).
:param value:
The old value of the component.... |
Two ways to specify this: + 1MO or MO ( + 1 ) | def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs):
"""
Two ways to specify this: +1MO or MO(+1)
"""
l = []
for wday in value.split(','):
if '(' in wday:
# If it's of the form TH(+1), etc.
splt = wday.split('(')
... |
This is the only API function of the projectfile module. It parses the Projectfiles from the given path and assembles the flattened command data structure. Returned data: { min - version: ( 1 0 0 ) description: Optional main description. commands: { command_1: { description: Optional command level description for comma... | def get_data_for_root(project_root):
"""This is the only API function of the projectfile module. It parses the Projectfiles
from the given path and assembles the flattened command data structure.
Returned data: {
'min-version': (1, 0, 0),
'description': 'Optional main description.',
... |
Calculate what percentage a given number is of another e. g. 50 is 50% of 100. | def run_get_percentage():
"""
Calculate what percentage a given number is of another,
e.g. 50 is 50% of 100.
"""
description = run_get_percentage.__doc__
parser = argparse.ArgumentParser(
prog='get_percentage',
description=description,
epilog="Example use: get_percentage ... |
Run the excel_to_html function from the command - line. | def run_excel_to_html():
"""
Run the excel_to_html function from the
command-line.
Args:
-p path to file
-s name of the sheet to convert
-css classes to apply
-m attempt to combine merged cells
-c caption for accessibility
-su summary for accessibility
... |
Gets the return string for a language that s supported by python. Used in cases when python provides support for the conversion. Args: language: string the langage to return for. | def get_built_in(self, language, level, data):
"""
Gets the return string for a language that's supported by python.
Used in cases when python provides support for the conversion.
Args:
language: string the langage to return for.
level: integer, the indentat... |
Gets the requested template for the given language. | def get_inner_template(self, language, template_type, indentation, key, val):
"""
Gets the requested template for the given language.
Args:
language: string, the language of the template to look for.
template_type: string, 'iterable' or 'singular'.
An itera... |
Unserializes a serialized php array and prints it to the console as a data structure in the specified language. Used to translate or convert a php array into a data structure in another language. Currently supports PHP Python Javascript and JSON. | def translate_array(self, string, language, level=3, retdata=False):
"""Unserializes a serialized php array and prints it to
the console as a data structure in the specified language.
Used to translate or convert a php array into a data structure
in another language. Currently supports,... |
e. g. 1000 x 2 U [:: npc ] * d [: npc ] to plot etc. | def pc( self ):
""" e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc. """
n = self.npc
return self.U[:, :n] * self.d[:n] |
Only API function for the config module. | def get():
""" Only API function for the config module.
:return: {dict} loaded validated configuration.
"""
config = {}
try:
config = _load_config()
except IOError:
try:
_create_default_config()
config = _load_config()
except IOError as e:
... |
Config validation Raises: KeyError on missing mandatory key SyntaxError on invalid key ValueError on invalid value for key: param config: { dict } config to validate: return: None | def _validate(config):
""" Config validation
Raises:
KeyError on missing mandatory key
SyntaxError on invalid key
ValueError on invalid value for key
:param config: {dict} config to validate
:return: None
"""
for mandatory_key in _mandatory_keys:
i... |
Writes the full default configuration to the appropriate place. Raises: IOError - on unsuccesful file write: return: None | def _create_default_config():
""" Writes the full default configuration to the appropriate place.
Raises:
IOError - on unsuccesful file write
:return: None
"""
config_path = _get_config_path()
with open(config_path, 'w+') as f:
yaml.dump(_default_config, f, default_flow_style=Fa... |
Create a reusable class from a generator function | def reusable(func):
"""Create a reusable class from a generator function
Parameters
----------
func: GeneratorCallable[T_yield, T_send, T_return]
the function to wrap
Note
----
* the callable must have an inspectable signature
* If bound to a class, the new reusable generator i... |
Send an item into a generator expecting a final return value | def sendreturn(gen, value):
"""Send an item into a generator expecting a final return value
Parameters
----------
gen: ~typing.Generator[T_yield, T_send, T_return]
the generator to send the value to
value: T_send
the value to send
Raises
------
RuntimeError
if t... |
Apply a function to all send values of a generator | def imap_send(func, gen):
"""Apply a function to all ``send`` values of a generator
Parameters
----------
func: ~typing.Callable[[T_send], T_mapped]
the function to apply
gen: Generable[T_yield, T_mapped, T_return]
the generator iterable.
Returns
-------
~typing.Generat... |
Create a new generator by relaying yield/ send interactions through another generator | def irelay(gen, thru):
"""Create a new generator by relaying yield/send interactions
through another generator
Parameters
----------
gen: Generable[T_yield, T_send, T_return]
the original generator
thru: ~typing.Callable[[T_yield], ~typing.Generator]
the generator callable throu... |
Checks if all command dependencies refers to and existing command. If not a ProjectfileError will be raised with the problematic dependency and it s command.: param data: parsed raw data set.: return: None | def _data_integrity_check(data):
"""Checks if all command dependencies refers to and existing command. If not, a ProjectfileError
will be raised with the problematic dependency and it's command.
:param data: parsed raw data set.
:return: None
"""
deps = []
for command in data['comma... |
Populate any database related fields ( ForeignKeyField OneToOneField ) that have _get ters to populate them with | def _link_rels(obj, fields=None, save=False, overwrite=False):
"""Populate any database related fields (ForeignKeyField, OneToOneField) that have `_get`ters to populate them with"""
if not fields:
meta = obj._meta
fields = [f.name for f in meta.fields if hasattr(f, 'do_related_class') and not f.... |
Update/ populate any database fields that have _get ters to populate them with regardless of whether they are data fields or related fields | def _update(obj, fields=None, save=False, overwrite=False):
"""Update/populate any database fields that have `_get`ters to populate them with, regardless of whether they are data fields or related fields"""
if not fields:
meta = obj._meta
fields = [f.name for f in meta.fields if not f.primary_ke... |
Prints the traceback and invokes the ipython debugger on any exception | def bug_info(exc_type, exc_value, exc_trace):
"""Prints the traceback and invokes the ipython debugger on any exception
Only invokes ipydb if you are outside ipython or python interactive session.
So scripts must be called from OS shell in order for exceptions to ipy-shell-out.
Dependencies:
Nee... |
Copies a file from its location on the web to a designated place on the local machine. | def copy_web_file_to_local(file_path, target_path):
"""Copies a file from its location on the web to a designated
place on the local machine.
Args:
file_path: Complete url of the file to copy, string (e.g. http://fool.com/input.css).
target_path: Path and name of file on the local machine... |
Counts the number of lines in a file. | def get_line_count(fname):
"""Counts the number of lines in a file.
Args:
fname: string, name of the file.
Returns:
integer, the number of lines in the file.
"""
i = 0
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1 |
Indentes css that has not been indented and saves it to a new file. A new file is created if the output destination does not already exist. | def indent_css(f, output):
"""Indentes css that has not been indented and saves it to a new file.
A new file is created if the output destination does not already exist.
Args:
f: string, path to file.
output: string, path/name of the output file (e.g. /directory/output.css).
print type... |
Adds line breaks after every occurance of a given character in a file. | def add_newlines(f, output, char):
"""Adds line breaks after every occurance of a given character in a file.
Args:
f: string, path to input file.
output: string, path to output file.
Returns:
None.
"""
line_count = get_line_count(f)
f = open(f, 'r+')
output = open(... |
Adds a space before a character if there s isn t one already. Args: char: string character that needs a space before it. | def add_whitespace_before(char, input_file, output_file):
"""Adds a space before a character if there's isn't one already.
Args:
char: string, character that needs a space before it.
input_file: string, path to file to parse.
output_file: string, path to destination file.
... |
Reformats poorly written css. This function does not validate or fix errors in the code. It only gives code the proper indentation. | def reformat_css(input_file, output_file):
"""Reformats poorly written css. This function does not validate or fix errors in the code.
It only gives code the proper indentation.
Args:
input_file: string, path to the input file.
output_file: string, path to where the reformatted css should... |
Checks if a string is an integer. If the string value is an integer return True otherwise return False. Args: string: a string to test. | def is_int(string):
"""
Checks if a string is an integer. If the string value is an integer
return True, otherwise return False.
Args:
string: a string to test.
Returns:
boolean
"""
try:
a = float(string)
b = int(a)
except ValueError:
retur... |
Totals the hours for a given projct. Takes a list of input files for which to total the hours. Each input file represents a project. There are only multiple files for the same project when the duration was more than a year. A typical entry in an input file might look like this: | def total_hours(input_files):
"""
Totals the hours for a given projct. Takes a list of input files for
which to total the hours. Each input file represents a project.
There are only multiple files for the same project when the duration
was more than a year. A typical entry in an input file might l... |
Take a list of strings and clear whitespace on each one. If a value in the list is not a string pass it through untouched. | def clean_strings(iterable):
"""
Take a list of strings and clear whitespace
on each one. If a value in the list is not a
string pass it through untouched.
Args:
iterable: mixed list
Returns:
mixed list
"""
retval = []
for val in iterable:
try:
... |
Convert an excel spreadsheet to an html table. This function supports the conversion of merged cells. It can be used in code or run from the command - line. If passed the correct arguments it can generate fully accessible html. | def excel_to_html(path, sheetname='Sheet1', css_classes='', \
caption='', details=[], row_headers=False, merge=False):
"""
Convert an excel spreadsheet to an html table.
This function supports the conversion of merged
cells. It can be used in code or run from the
command-line. If passed the co... |
Calculates the future value of money invested at an anual interest rate x times per year for a given number of years. | def future_value(present_value, annual_rate, periods_per_year, years):
"""
Calculates the future value of money invested at an anual interest rate,
x times per year, for a given number of years.
Args:
present_value: int or float, the current value of the money (principal).
annual_rate:... |
Uses Heron s formula to find the area of a triangle based on the coordinates of three points. | def triangle_area(point1, point2, point3):
"""
Uses Heron's formula to find the area of a triangle
based on the coordinates of three points.
Args:
point1: list or tuple, the x y coordinate of point one.
point2: list or tuple, the x y coordinate of point two.
point3: list or tu... |
Calculates the area of a regular polygon ( with sides of equal length ). | def regular_polygon_area(number_of_sides, length_of_sides):
"""
Calculates the area of a regular polygon (with sides of equal length).
Args:
number_of_sides: Integer, the number of sides of the polygon
length_of_sides: Integer or floating point number, the length of the sides
Returns:... |
Calculates the median of a list of integers or floating point numbers. | def median(data):
"""
Calculates the median of a list of integers or floating point numbers.
Args:
data: A list of integers or floating point numbers
Returns:
Sorts the list numerically and returns the middle number if the list has an odd number
of items. If the list contains ... |
Calculates the average or mean of a list of numbers | def average(numbers, numtype='float'):
"""
Calculates the average or mean of a list of numbers
Args:
numbers: a list of integers or floating point numbers.
numtype: string, 'decimal' or 'float'; the type of number to return.
Returns:
The average (mean) of the numbers as a floa... |
Calculates the population or sample variance of a list of numbers. A large number means the results are all over the place while a small number means the results are comparatively close to the average. | def variance(numbers, type='population'):
"""
Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of integers or floa... |
Finds the percentage of one number over another. | def get_percentage(a, b, i=False, r=False):
"""
Finds the percentage of one number over another.
Args:
a: The number that is a percent, int or float.
b: The base number that a is a percent of, int or float.
i: Optional boolean integer. True if the user wants the result returned as... |
Calculate net take - home pay including employer retirement savings match using the formula laid out by Mr. Money Mustache: http:// www. mrmoneymustache. com/ 2015/ 01/ 26/ calculating - net - worth/ | def take_home_pay(gross_pay, employer_match, taxes_and_fees, numtype='float'):
"""
Calculate net take-home pay including employer retirement savings match
using the formula laid out by Mr. Money Mustache:
http://www.mrmoneymustache.com/2015/01/26/calculating-net-worth/
Args:
gross_pay: floa... |
Calculate net take - home pay including employer retirement savings match using the formula laid out by Mr. Money Mustache: http:// www. mrmoneymustache. com/ 2015/ 01/ 26/ calculating - net - worth/ | def savings_rate(take_home_pay, spending, numtype='float'):
"""
Calculate net take-home pay including employer retirement savings match
using the formula laid out by Mr. Money Mustache:
http://www.mrmoneymustache.com/2015/01/26/calculating-net-worth/
Args:
take_home_pay: float or int, month... |
Read __version__ or other properties from a python file without importing it from gist. github. com/ technonik/ 406623 but with added keyward kwarg | def get_variable(relpath, keyword='__version__'):
"""Read __version__ or other properties from a python file without importing it
from gist.github.com/technonik/406623 but with added keyward kwarg """
for line in open(os.path.join(os.path.dirname(__file__), relpath), encoding='cp437'):
if keyw... |
2018 - 01 - 01 00: 00: 00 ( str ) -- > 1514736000 | def datetime_str_to_timestamp(datetime_str):
'''
'2018-01-01 00:00:00' (str) --> 1514736000
:param str datetime_str: datetime string
:return: unix timestamp (int) or None
:rtype: int or None
'''
try:
dtf = DTFormat()
struct_time = time.st... |
Get datetime string from datetime object | def get_datetime_string(datetime_obj):
'''
Get datetime string from datetime object
:param datetime datetime_obj: datetime object
:return: datetime string
:rtype: str
'''
if isinstance(datetime_obj, datetime):
dft = DTFormat()
return date... |
1514736000 -- > datetime object | def timestamp_to_datetime(timestamp):
'''
1514736000 --> datetime object
:param int timestamp: unix timestamp (int)
:return: datetime object or None
:rtype: datetime or None
'''
if isinstance(timestamp, (int, float, str)):
try:
timest... |
attr pipe can extract attribute value of object. | def attr(prev, attr_name):
"""attr pipe can extract attribute value of object.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param attr_name: The name of attribute
:type attr_name: str
:returns: generator
"""
for obj in prev:
if hasattr(obj, attr_name):
... |
attrs pipe can extract attribute values of object. | def attrs(prev, attr_names):
"""attrs pipe can extract attribute values of object.
If attr_names is a list and its item is not a valid attribute of
prev's object. It will be excluded from yielded dict.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param attr_names: The list of ... |
attrdict pipe can extract attribute values of object into a dict. | def attrdict(prev, attr_names):
"""attrdict pipe can extract attribute values of object into a dict.
The argument attr_names can be a list or a dict.
If attr_names is a list and its item is not a valid attribute of
prev's object. It will be excluded from yielded dict.
If attr_names is dict and th... |
flatten pipe extracts nested item from previous pipe. | def flatten(prev, depth=sys.maxsize):
"""flatten pipe extracts nested item from previous pipe.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param depth: The deepest nested level to be extracted. 0 means no extraction.
:type depth: integer
:returns: generator
"""
def inn... |
values pipe extract value from previous pipe. | def values(prev, *keys, **kw):
"""values pipe extract value from previous pipe.
If previous pipe send a dictionary to values pipe, keys should contains
the key of dictionary which you want to get. If previous pipe send list or
tuple,
:param prev: The previous iterator of pipe.
:type prev: Pipe... |
pack pipe takes n elements from previous generator and yield one list to next. | def pack(prev, n, rest=False, **kw):
"""pack pipe takes n elements from previous generator and yield one
list to next.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param rest: Set True to allow to output the rest part of last elements.
:type prev: boolean
:param padding: Sp... |
The pipe greps the data passed from previous generator according to given regular expression. | def grep(prev, pattern, *args, **kw):
"""The pipe greps the data passed from previous generator according to
given regular expression.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The pattern which used to filter out data.
:type pattern: str|unicode|re pattern ob... |
The pipe greps the data passed from previous generator according to given regular expression. The data passed to next pipe is MatchObject dict or tuple which determined by to in keyword argument. | def match(prev, pattern, *args, **kw):
"""The pipe greps the data passed from previous generator according to
given regular expression. The data passed to next pipe is MatchObject
, dict or tuple which determined by 'to' in keyword argument.
By default, match pipe yields MatchObject. Use 'to' in keywor... |
The resplit pipe split previous pipe input by regular expression. | def resplit(prev, pattern, *args, **kw):
"""The resplit pipe split previous pipe input by regular expression.
Use 'maxsplit' keyword argument to limit the number of split.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The pattern which used to split string.
:type... |
sub pipe is a wrapper of re. sub method. | def sub(prev, pattern, repl, *args, **kw):
"""sub pipe is a wrapper of re.sub method.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The pattern string.
:type pattern: str|unicode
:param repl: Check repl argument in re.sub method.
:type repl: str|unicode|callab... |
wildcard pipe greps data passed from previous generator according to given regular expression. | def wildcard(prev, pattern, *args, **kw):
"""wildcard pipe greps data passed from previous generator
according to given regular expression.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The wildcard string which used to filter data.
:type pattern: str|unicode|re p... |
This pipe read data from previous iterator and write it to stdout. | def stdout(prev, endl='\n', thru=False):
"""This pipe read data from previous iterator and write it to stdout.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param endl: The end-of-line symbol for each output.
:type endl: str
:param thru: If true, data will passed to next generat... |
This pipe get filenames or file object from previous pipe and read the content of file. Then send the content of file line by line to next pipe. | def readline(prev, filename=None, mode='r', trim=str.rstrip, start=1, end=sys.maxsize):
"""This pipe get filenames or file object from previous pipe and read the
content of file. Then, send the content of file line by line to next pipe.
The start and end parameters are used to limit the range of reading fr... |
This pipe read/ write data from/ to file object which specified by file_handle. | def fileobj(prev, file_handle, endl='', thru=False):
"""This pipe read/write data from/to file object which specified by
file_handle.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param file_handle: The file object to read or write.
:type file_handle: file object
:param endl... |
sh pipe execute shell command specified by args. If previous pipe exists read data from it and write it to stdin of shell process. The stdout of shell process will be passed to next pipe object line by line. | def sh(prev, *args, **kw):
"""sh pipe execute shell command specified by args. If previous pipe exists,
read data from it and write it to stdin of shell process. The stdout of
shell process will be passed to next pipe object line by line.
A optional keyword argument 'trim' can pass a function into sh p... |
This pipe wrap os. walk and yield absolute path one by one. | def walk(prev, inital_path, *args, **kw):
"""This pipe wrap os.walk and yield absolute path one by one.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param args: The end-of-line symbol for each output.
:type args: list of string.
:param kw: The end-of-line symbol for each output... |
alias of str. join | def join(prev, sep, *args, **kw):
'''alias of str.join'''
yield sep.join(prev, *args, **kw) |
alias of string. Template. substitute | def substitute(prev, *args, **kw):
'''alias of string.Template.substitute'''
template_obj = string.Template(*args, **kw)
for data in prev:
yield template_obj.substitute(data) |
alias of string. Template. safe_substitute | def safe_substitute(prev, *args, **kw):
'''alias of string.Template.safe_substitute'''
template_obj = string.Template(*args, **kw)
for data in prev:
yield template_obj.safe_substitute(data) |
Convert data from previous pipe with specified encoding. | def to_str(prev, encoding=None):
"""Convert data from previous pipe with specified encoding."""
first = next(prev)
if isinstance(first, str):
if encoding is None:
yield first
for s in prev:
yield s
else:
yield first.encode(encoding)
... |
Regiser all default type - to - pipe convertors. | def register_default_types():
"""Regiser all default type-to-pipe convertors."""
register_type(type, pipe.map)
register_type(types.FunctionType, pipe.map)
register_type(types.MethodType, pipe.map)
register_type(tuple, seq)
register_type(list, seq)
register_type(types.GeneratorType, seq)
... |
Convert Paginator instance to dict | def get_dict(self):
'''
Convert Paginator instance to dict
:return: Paging data
:rtype: dict
'''
return dict(
current_page=self.current_page,
total_page_count=self.total_page_count,
items=self.items,
total_item_count=self.... |
This function logs a line of data to both a log file and a latest file The latest file is optional and is sent to this function as a boolean value via the variable require_latest. So the 2 log directories and filenames are: a. ( REQUIRED ): log_directory + log_filename b. ( OPTIONAL ): latest_directory + latest_filenam... | def write_log(log_directory, log_filename, header, logline, debug,
require_latest, latest_directory, latest_filename):
"""This function logs a line of data to both a 'log' file, and a 'latest'
file The 'latest' file is optional, and is sent to this function as a
boolean value via the variable ... |
Check that a process is not running more than once using PIDFILE | def check_pidfile(pidfile, debug):
"""Check that a process is not running more than once, using PIDFILE"""
# Check PID exists and see if the PID is running
if os.path.isfile(pidfile):
pidfile_handle = open(pidfile, 'r')
# try and read the PID file. If no luck, remove it
try:
... |
This function will check whether a PID is currently running | def check_pid(pid, debug):
"""This function will check whether a PID is currently running"""
try:
# A Kill of 0 is to check if the PID is active. It won't kill the process
os.kill(pid, 0)
if debug > 1:
print("Script has a PIDFILE where the process is still running")
r... |
Convert two words to a floating point | def convert_words_to_uint(high_word, low_word):
"""Convert two words to a floating point"""
try:
low_num = int(low_word)
# low_word might arrive as a signed number. Convert to unsigned
if low_num < 0:
low_num = abs(low_num) + 2**15
number = (int(high_word) << 16) | lo... |
Convert two words to a floating point | def convert_words_to_float(high_word, low_word):
"""Convert two words to a floating point"""
number, retval = convert_words_to_uint(high_word, low_word)
if not retval:
return 0.0, False
try:
packed_float = struct.pack('>l', number)
return struct.unpack('>f', packed_float)[0], Tr... |
This function will disown so the Ardexa service can be restarted | def disown(debug):
"""This function will disown, so the Ardexa service can be restarted"""
# Get the current PID
pid = os.getpid()
cgroup_file = "/proc/" + str(pid) + "/cgroup"
try:
infile = open(cgroup_file, "r")
except IOError:
print("Could not open cgroup file: ", cgroup_file)... |
Run a program and check program return code Note that some commands don t work well with Popen. So if this function is specifically called with shell = True then it will run the old os. system. In which case there is no program output | def run_program(prog_list, debug, shell):
"""Run a program and check program return code Note that some commands don't work
well with Popen. So if this function is specifically called with 'shell=True',
then it will run the old 'os.system'. In which case, there is no program output
"""
try:
... |
Yield each integer from a complex range string like 1 - 9 12 15 - 20 23 | def parse_address_list(addrs):
"""Yield each integer from a complex range string like "1-9,12,15-20,23"
>>> list(parse_address_list('1-9,12,15-20,23'))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]
>>> list(parse_address_list('1-9,12,15-20,2-3-4'))
Traceback (most recent call last):
... |
Do url - encode resource ids | def _encode_ids(*args):
"""
Do url-encode resource ids
"""
ids = []
for v in args:
if isinstance(v, basestring):
qv = v.encode('utf-8') if isinstance(v, unicode) else v
ids.append(urllib.quote(qv))
else:
qv = str(v)
ids.append(urllib.q... |
Generate random string with parameter length. Example: | def random_string(length):
'''
Generate random string with parameter length.
Example:
>>> from eggit.egg_string import random_string
>>> random_string(8)
'q4f2eaT4'
>>>
'''
str_list = [random.choice(string.digits + string.ascii_letters) for i in range(length)]
... |
Get item creator according registered item type. | def get_item_creator(item_type):
"""Get item creator according registered item type.
:param item_type: The type of item to be checed.
:type item_type: types.TypeType.
:returns: Creator function. None if type not found.
"""
if item_type not in Pipe.pipe_item_types:
for registered_type in... |
Self - cloning. All its next Pipe objects are cloned too. | def clone(self):
"""Self-cloning. All its next Pipe objects are cloned too.
:returns: cloned object
"""
new_object = copy.copy(self)
if new_object.next:
new_object.next = new_object.next.clone()
return new_object |
Append next object to pipe tail. | def append(self, next):
"""Append next object to pipe tail.
:param next: The Pipe object to be appended to tail.
:type next: Pipe object.
"""
next.chained = True
if self.next:
self.next.append(next)
else:
self.next = next |
Return an generator as iterator object. | def iter(self, prev=None):
"""Return an generator as iterator object.
:param prev: Previous Pipe object which used for data input.
:returns: A generator for iteration.
"""
if self.next:
generator = self.next.iter(self.func(prev, *self.args, **self.kw))
else:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.