INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Get the entire fact cache only if the fact_cache_type is jsonfile | def get_fact_cache(self, host):
'''
Get the entire fact cache only if the fact_cache_type is 'jsonfile'
'''
if self.config.fact_cache_type != 'jsonfile':
raise Exception('Unsupported fact cache type. Only "jsonfile" is supported for reading and writing facts from ansible-run... |
Set the entire fact cache data only if the fact_cache_type is jsonfile | def set_fact_cache(self, host, data):
'''
Set the entire fact cache data only if the fact_cache_type is 'jsonfile'
'''
if self.config.fact_cache_type != 'jsonfile':
raise Exception('Unsupported fact cache type. Only "jsonfile" is supported for reading and writing facts from ... |
Initialize the Runner () instance | def init_runner(**kwargs):
'''
Initialize the Runner() instance
This function will properly initialize both run() and run_async()
functions in the same way and return a value instance of Runner.
See parameters given to :py:func:`ansible_runner.interface.run`
'''
dump_artifacts(kwargs)
... |
Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object. | def run_async(**kwargs):
'''
Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object.
This uses the same parameters as :py:func:`ansible_runner.interface.run`
:returns: A tuple containing a :py:class:`threading.Thread` object and a :py:... |
Inspects the object and returns if it is a playbook | def isplaybook(obj):
'''
Inspects the object and returns if it is a playbook
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is a list and False if it is not
'''
return isinstance(obj, Iterable) and (not isinstance(obj, strin... |
Check that proot is installed. | def check_isolation_executable_installed(isolation_executable):
'''
Check that proot is installed.
'''
cmd = [isolation_executable, '--version']
try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
proc.communicate()
... |
Write the artifact to disk at the specified path | def dump_artifact(obj, path, filename=None):
'''
Write the artifact to disk at the specified path
Args:
obj (string): The string object to be dumped to disk in the specified
path. The artifact filename will be automatically created
path (string): The full path to the artifacts... |
Introspect the kwargs and dump objects to disk | def dump_artifacts(kwargs):
'''
Introspect the kwargs and dump objects to disk
'''
private_data_dir = kwargs.get('private_data_dir')
if not private_data_dir:
private_data_dir = tempfile.mkdtemp()
kwargs['private_data_dir'] = private_data_dir
if not os.path.exists(private_data_di... |
open_fifo_write opens the fifo named pipe in a new thread. This blocks the thread until an external process ( such as ssh - agent ) reads data from the pipe. | def open_fifo_write(path, data):
'''open_fifo_write opens the fifo named pipe in a new thread.
This blocks the thread until an external process (such as ssh-agent)
reads data from the pipe.
'''
os.mkfifo(path, stat.S_IRUSR | stat.S_IWUSR)
threading.Thread(target=lambda p, d: open(p, 'wb').write(... |
Encode Python datetime object as PDF date string | def encode_pdf_date(d: datetime) -> str:
"""Encode Python datetime object as PDF date string
From Adobe pdfmark manual:
(D:YYYYMMDDHHmmSSOHH'mm')
D: is an optional prefix. YYYY is the year. All fields after the year are
optional. MM is the month (01-12), DD is the day (01-31), HH is the
hour (0... |
Decode a pdfmark date to a Python datetime object | def decode_pdf_date(s: str) -> datetime:
"""Decode a pdfmark date to a Python datetime object
A pdfmark date is a string in a paritcular format. See the pdfmark
Reference for the specification.
"""
if isinstance(s, String):
s = str(s)
if s.startswith('D:'):
s = s[2:]
# Lite... |
Populate the XMP metadata object with DocumentInfo | def load_from_docinfo(self, docinfo, delete_missing=False, raise_failure=False):
"""Populate the XMP metadata object with DocumentInfo
Arguments:
docinfo: a DocumentInfo, e.g pdf.docinfo
delete_missing: if the entry is not DocumentInfo, delete the equivalent
from... |
Update the PDF s DocumentInfo dictionary to match XMP metadata | def _update_docinfo(self):
"""Update the PDF's DocumentInfo dictionary to match XMP metadata
The standard mapping is described here:
https://www.pdfa.org/pdfa-metadata-xmp-rdf-dublin-core/
"""
self._pdf.docinfo # Touch object to ensure it exists
for uri, element, do... |
Serialize our changes back to the PDF in memory | def _apply_changes(self):
"""Serialize our changes back to the PDF in memory
Depending how we are initialized, leave our metadata mark and producer.
"""
if self.mark:
self[QName(XMP_NS_XMP, 'MetadataDate')] = datetime.now().isoformat()
self[QName(XMP_NS_PDF, 'Pro... |
Convert name to an XML QName | def _qname(self, name):
"""Convert name to an XML QName
e.g. pdf:Producer -> {http://ns.adobe.com/pdf/1.3/}Producer
"""
if isinstance(name, QName):
return name
if not isinstance(name, str):
raise TypeError("{} must be str".format(name))
if name ==... |
Given a fully qualified XML name find a prefix | def _prefix_from_uri(self, uriname):
"""Given a fully qualified XML name, find a prefix
e.g. {http://ns.adobe.com/pdf/1.3/}Producer -> pdf:Producer
"""
uripart, tag = uriname.split('}', maxsplit=1)
uri = uripart.replace('{', '')
return self.REVERSE_NS[uri] + ':' + tag |
Gather the sub - elements attached to a node | def _get_subelements(self, node):
"""Gather the sub-elements attached to a node
Gather rdf:Bag and and rdf:Seq into set and list respectively. For
alternate languages values, take the first language only for
simplicity.
"""
items = node.find('rdf:Alt', self.NS)
i... |
Get elements from XMP | def _get_elements(self, name=''):
"""Get elements from XMP
Core routine to find elements matching name within the XMP and yield
them.
For XMP spec 7.9.2.2, rdf:Description with property attributes,
we yield the node which will have the desired as one of its attributes.
... |
Returns the PDF/ A conformance level claimed by this PDF or False | def pdfa_status(self):
"""Returns the PDF/A conformance level claimed by this PDF, or False
A PDF may claim to PDF/A compliant without this being true. Use an
independent verifier such as veraPDF to test if a PDF is truly
conformant.
Returns:
str: The conformance le... |
PDF name of the colorspace that best describes this image | def colorspace(self):
"""PDF name of the colorspace that best describes this image"""
if self.image_mask:
return None # Undefined for image masks
if self._colorspaces:
if self._colorspaces[0] in self.SIMPLE_COLORSPACES:
return self._colorspaces[0]
... |
PIL. Image. mode equivalent for this image | def mode(self):
"""``PIL.Image.mode`` equivalent for this image"""
m = ''
if self.indexed:
m = 'P'
elif self.bits_per_component == 1:
m = '1'
elif self.bits_per_component == 8:
if self.colorspace == '/DeviceRGB':
m = 'RGB'
... |
Retrieves the color palette for this image | def palette(self):
"""Retrieves the color palette for this image
:returns: (base_colorspace: str, palette: bytes)
:rtype: tuple
"""
if not self.indexed:
return None
_idx, base, hival, lookup = None, None, None, None
try:
_idx, base, hival... |
Insert a PIL image into a PDF ( rudimentary ) | def _from_pil_image(cls, *, pdf, page, name, image): # pragma: no cover
"""Insert a PIL image into a PDF (rudimentary)
:param pdf: the PDF to attach the image to
:type pdf: pikepdf.Pdf
:param page: the page to attach the image to
:param name: the name to set the image
:... |
Attempt to extract the image directly to a usable image file | def _extract_direct(self, *, stream):
"""Attempt to extract the image directly to a usable image file
If there is no way to extract the image without decompressing or
transcoding then raise an exception. The type and format of image
generated will vary.
Args:
stream... |
Attempt to extract the image directly to a usable image file | def _extract_to_stream(self, *, stream):
"""Attempt to extract the image directly to a usable image file
If possible, the compressed data is extracted and inserted into
a compressed image file format without transcoding the compressed
content. If this is not possible, the data will be d... |
Attempt to extract the image directly to a usable image file | def extract_to(self, *, stream=None, fileprefix=''):
"""Attempt to extract the image directly to a usable image file
If possible, the compressed data is extracted and inserted into
a compressed image file format without transcoding the compressed
content. If this is not possible, the da... |
Extract the image as a Pillow Image using decompression as necessary | def as_pil_image(self):
"""Extract the image as a Pillow Image, using decompression as necessary
Returns:
PIL.Image.Image
"""
from PIL import Image
try:
bio = BytesIO()
self._extract_direct(stream=bio)
bio.seek(0)
retu... |
Construct a CCITT G3 or G4 header from the PDF metadata | def _generate_ccitt_header(self, data):
"""Construct a CCITT G3 or G4 header from the PDF metadata"""
# https://stackoverflow.com/questions/2641770/
# https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
if not self.decode_parms:
raise ValueError("/CCITTFaxDecode wi... |
Display hook for IPython/ Jupyter | def _repr_png_(self):
"""Display hook for IPython/Jupyter"""
b = BytesIO()
im = self.as_pil_image()
im.save(b, 'PNG')
return b.getvalue() |
Attach methods of a Python support class to an existing class | def augments(cls_cpp):
"""Attach methods of a Python support class to an existing class
This monkeypatches all methods defined in the support class onto an
existing class. Example:
.. code-block:: python
@augments(ClassDefinedInCpp)
class SupportClass:
def foo(self):
... |
Construct a single page PDF from the provided page in memory | def _single_page_pdf(page):
"""Construct a single page PDF from the provided page in memory"""
pdf = Pdf.new()
pdf.pages.append(page)
bio = BytesIO()
pdf.save(bio)
bio.seek(0)
return bio.read() |
Use mupdf draw to rasterize the PDF in the memory buffer | def _mudraw(buffer, fmt):
"""Use mupdf draw to rasterize the PDF in the memory buffer"""
with NamedTemporaryFile(suffix='.pdf') as tmp_in:
tmp_in.write(buffer)
tmp_in.seek(0)
tmp_in.flush()
proc = run(
['mudraw', '-F', fmt, '-o', '-', tmp_in.name], stdout=PIPE, stder... |
Concatenates a rotation matrix on this matrix | def rotated(self, angle_degrees_ccw):
"""Concatenates a rotation matrix on this matrix"""
angle = angle_degrees_ccw / 180.0 * pi
c, s = cos(angle), sin(angle)
return self @ PdfMatrix((c, s, -s, c, 0, 0)) |
Return the 6 - tuple ( a b c d e f ) that describes this matrix | def shorthand(self):
"""Return the 6-tuple (a,b,c,d,e,f) that describes this matrix"""
return (self.a, self.b, self.c, self.d, self.e, self.f) |
Encode this matrix in binary suitable for including in a PDF | def encode(self):
"""Encode this matrix in binary suitable for including in a PDF"""
return '{:.6f} {:.6f} {:.6f} {:.6f} {:.6f} {:.6f}'.format(
self.a, self.b, self.c, self.d, self.e, self.f
).encode() |
Parse a PDF content stream into a sequence of instructions. | def parse_content_stream(page_or_stream, operators=''):
"""
Parse a PDF content stream into a sequence of instructions.
A PDF content stream is list of instructions that describe where to render
the text and graphics in a PDF. This is the starting point for analyzing
PDFs.
If the input is a pa... |
Check if this page print text | def has_text(self):
"""Check if this page print text
Search the content stream for any of the four text showing operators.
We ignore text positioning operators because some editors might
generate maintain these even if text is deleted etc.
This cannot detect raster text (text i... |
Groups Tokens that have beginning and end. | def _group_matching(tlist, cls):
"""Groups Tokens that have beginning and end."""
opens = []
tidx_offset = 0
for idx, token in enumerate(list(tlist)):
tidx = idx - tidx_offset
if token.is_whitespace:
# ~50% of tokens will be whitespace. Will checking early
# for ... |
Group together Identifier and Asc/ Desc token | def group_order(tlist):
"""Group together Identifier and Asc/Desc token"""
tidx, token = tlist.token_next_by(t=T.Keyword.Order)
while token:
pidx, prev_ = tlist.token_prev(tidx)
if imt(prev_, i=sql.Identifier, t=T.Number):
tlist.group_tokens(sql.Identifier, pidx, tidx)
... |
Groups together tokens that are joined by a middle token. i. e. x < y | def _group(tlist, cls, match,
valid_prev=lambda t: True,
valid_next=lambda t: True,
post=None,
extend=True,
recurse=True
):
"""Groups together tokens that are joined by a middle token. i.e. x < y"""
tidx_offset = 0
pidx, prev_ = None, None
... |
Set the filter attributes to its default values | def _reset(self):
"""Set the filter attributes to its default values"""
self._in_declare = False
self._is_create = False
self._begin_depth = 0
self.consume_ws = False
self.tokens = []
self.level = 0 |
Get the new split level ( increase decrease or remain equal ) | def _change_splitlevel(self, ttype, value):
"""Get the new split level (increase, decrease or remain equal)"""
# parenthesis increase/decrease a level
if ttype is T.Punctuation and value == '(':
return 1
elif ttype is T.Punctuation and value == ')':
return -1
... |
Process the stream | def process(self, stream):
"""Process the stream"""
EOS_TTYPE = T.Whitespace, T.Comment.Single
# Run over all stream tokens
for ttype, value in stream:
# Yield token if we finished a statement and there's no whitespaces
# It will count newline token as a non whit... |
Validates options. | def validate_options(options):
"""Validates options."""
kwcase = options.get('keyword_case')
if kwcase not in [None, 'upper', 'lower', 'capitalize']:
raise SQLParseError('Invalid value for keyword_case: '
'{0!r}'.format(kwcase))
idcase = options.get('identifier_case'... |
Setup and return a filter stack. | def build_filter_stack(stack, options):
"""Setup and return a filter stack.
Args:
stack: :class:`~sqlparse.filters.FilterStack` instance
options: Dictionary with options validated by validate_options.
"""
# Token filter
if options.get('keyword_case'):
stack.preprocess.append(
... |
Split a string on all unquoted newlines. | def split_unquoted_newlines(stmt):
"""Split a string on all unquoted newlines.
Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite
character is inside of a string."""
text = text_type(stmt)
lines = SPLIT_REGEX.split(text)
outputlines = ['']
for line in lines:
if n... |
Function decorator to help with recursion | def recurse(*cls):
"""Function decorator to help with recursion
:param cls: Classes to not recurse over
:return: function
"""
def wrap(f):
def wrapped_f(tlist):
for sgroup in tlist.get_sublists():
if not isinstance(sgroup, cls):
wrapped_f(sgro... |
Helper function to simplify comparisons Instance Match and TokenType: param token:: param i: Class or Tuple/ List of Classes: param m: Tuple of TokenType & Value. Can be list of Tuple for multiple: param t: TokenType or Tuple/ List of TokenTypes: return: bool | def imt(token, i=None, m=None, t=None):
"""Helper function to simplify comparisons Instance, Match and TokenType
:param token:
:param i: Class or Tuple/List of Classes
:param m: Tuple of TokenType & Value. Can be list of Tuple for multiple
:param t: TokenType or Tuple/List of TokenTypes
:return:... |
Parses sql statements from file - like object. | def parsestream(stream, encoding=None):
"""Parses sql statements from file-like object.
:param stream: A file-like object.
:param encoding: The encoding of the stream contents (optional).
:returns: A generator of :class:`~sqlparse.sql.Statement` instances.
"""
stack = engine.FilterStack()
s... |
Format * sql * according to * options *. | def format(sql, encoding=None, **options):
"""Format *sql* according to *options*.
Available options are documented in :ref:`formatting`.
In addition to the formatting options this function accepts the
keyword "encoding" which determines the encoding of the statement.
:returns: The formatted SQL ... |
Split * sql * into single statements. | def split(sql, encoding=None):
"""Split *sql* into single statements.
:param sql: A string containing one or more SQL statements.
:param encoding: The encoding of the statement (optional).
:returns: A list of strings.
"""
stack = engine.FilterStack()
return [text_type(stmt).strip() for stmt... |
Return an iterable of ( tokentype value ) pairs generated from text. If unfiltered is set to True the filtering mechanism is bypassed even if filters are defined. | def get_tokens(text, encoding=None):
"""
Return an iterable of (tokentype, value) pairs generated from
`text`. If `unfiltered` is set to `True`, the filtering mechanism
is bypassed even if filters are defined.
Also preprocess the text, i.e. expand tabs and strip it if
wa... |
Yields all tokens up to token but excluding current. | def _flatten_up_to_token(self, token):
"""Yields all tokens up to token but excluding current."""
if token.is_group:
token = next(token.flatten())
for t in self._curr_stmt.flatten():
if t == token:
break
yield t |
Returns the type of a statement. | def get_type(self):
"""Returns the type of a statement.
The returned value is a string holding an upper-cased reprint of
the first DML or DDL keyword. If the first token in this group
isn't a DML or DDL keyword "UNKNOWN" is returned.
Whitespaces and comments at the beginning of... |
Return True if this identifier contains a wildcard. | def is_wildcard(self):
"""Return ``True`` if this identifier contains a wildcard."""
_, token = self.token_next_by(t=T.Wildcard)
return token is not None |
Returns the typecast or None of this object as a string. | def get_typecast(self):
"""Returns the typecast or ``None`` of this object as a string."""
midx, marker = self.token_next_by(m=(T.Punctuation, '::'))
nidx, next_ = self.token_next(midx, skip_ws=False)
return next_.value if next_ else None |
Returns the ordering or None as uppercase string. | def get_ordering(self):
"""Returns the ordering or ``None`` as uppercase string."""
_, ordering = self.token_next_by(t=T.Keyword.Order)
return ordering.normalized if ordering else None |
Returns an iterator of index token lists | def get_array_indices(self):
"""Returns an iterator of index token lists"""
for token in self.tokens:
if isinstance(token, SquareBrackets):
# Use [1:-1] index to discard the square brackets
yield token.tokens[1:-1] |
Returns the identifiers. | def get_identifiers(self):
"""Returns the identifiers.
Whitespaces and punctuations are not included in this generator.
"""
for token in self.tokens:
if not (token.is_whitespace or token.match(T.Punctuation, ',')):
yield token |
Returns a list of 2 - tuples ( condition value ). | def get_cases(self, skip_ws=False):
"""Returns a list of 2-tuples (condition, value).
If an ELSE exists condition is None.
"""
CONDITION = 1
VALUE = 2
ret = []
mode = CONDITION
for token in self.tokens:
# Set mode from the current statement
... |
Return a list of parameters. | def get_parameters(self):
"""Return a list of parameters."""
parenthesis = self.tokens[-1]
for token in parenthesis.tokens:
if isinstance(token, IdentifierList):
return token.get_identifiers()
elif imt(token, i=(Function, Identifier), t=T.Literal):
... |
Turn all the output devices on. | def on(self):
"""
Turn all the output devices on.
"""
for device in self:
if isinstance(device, (OutputDevice, CompositeOutputDevice)):
device.on() |
Turn all the output devices off. | def off(self):
"""
Turn all the output devices off.
"""
for device in self:
if isinstance(device, (OutputDevice, CompositeOutputDevice)):
device.off() |
Toggle all the output devices. For each device if it s on turn it off ; if it s off turn it on. | def toggle(self):
"""
Toggle all the output devices. For each device, if it's on, turn it
off; if it's off, turn it on.
"""
for device in self:
if isinstance(device, (OutputDevice, CompositeOutputDevice)):
device.toggle() |
If no arguments are specified turn all the LEDs on. If arguments are specified they must be the indexes of the LEDs you wish to turn on. For example:: | def on(self, *args):
"""
If no arguments are specified, turn all the LEDs on. If arguments are
specified, they must be the indexes of the LEDs you wish to turn on.
For example::
from gpiozero import LEDBoard
leds = LEDBoard(2, 3, 4, 5)
leds.on(0) ... |
If no arguments are specified turn all the LEDs off. If arguments are specified they must be the indexes of the LEDs you wish to turn off. For example:: | def off(self, *args):
"""
If no arguments are specified, turn all the LEDs off. If arguments are
specified, they must be the indexes of the LEDs you wish to turn off.
For example::
from gpiozero import LEDBoard
leds = LEDBoard(2, 3, 4, 5)
leds.on() ... |
If no arguments are specified toggle the state of all LEDs. If arguments are specified they must be the indexes of the LEDs you wish to toggle. For example:: | def toggle(self, *args):
"""
If no arguments are specified, toggle the state of all LEDs. If
arguments are specified, they must be the indexes of the LEDs you wish
to toggle. For example::
from gpiozero import LEDBoard
leds = LEDBoard(2, 3, 4, 5)
led... |
Make all LEDs fade in and out repeatedly. Note that this method will only work if the * pwm * parameter was: data: True at construction time. | def pulse(self, fade_in_time=1, fade_out_time=1, n=None, background=True):
"""
Make all LEDs fade in and out repeatedly. Note that this method will
only work if the *pwm* parameter was :data:`True` at construction time.
:param float fade_in_time:
Number of seconds to spend f... |
The value of the LED bar graph. When no LEDs are lit the value is 0. When all LEDs are lit the value is 1. Values between 0 and 1 light LEDs linearly from first to last. Values between 0 and - 1 light LEDs linearly from last to first. | def value(self):
"""
The value of the LED bar graph. When no LEDs are lit, the value is 0.
When all LEDs are lit, the value is 1. Values between 0 and 1
light LEDs linearly from first to last. Values between 0 and -1
light LEDs linearly from last to first.
To light a par... |
The number of LEDs on the bar graph actually lit up. Note that just like: attr: value this can be negative if the LEDs are lit from last to first. | def lit_count(self):
"""
The number of LEDs on the bar graph actually lit up. Note that just
like :attr:`value`, this can be negative if the LEDs are lit from last
to first.
"""
lit_value = self.value * len(self)
if not isinstance(self[0], PWMLED):
lit... |
Drive the robot forward by running both motors forward. | def forward(self, speed=1, **kwargs):
"""
Drive the robot forward by running both motors forward.
:param float speed:
Speed at which to drive the motors, as a value between 0 (stopped)
and 1 (full speed). The default is 1.
:param float curve_left:
Th... |
Make the robot turn left by running the right motor forward and left motor backward. | def left(self, speed=1):
"""
Make the robot turn left by running the right motor forward and left
motor backward.
:param float speed:
Speed at which to drive the motors, as a value between 0 (stopped)
and 1 (full speed). The default is 1.
"""
self... |
Make the robot turn right by running the left motor forward and right motor backward. | def right(self, speed=1):
"""
Make the robot turn right by running the left motor forward and right
motor backward.
:param float speed:
Speed at which to drive the motors, as a value between 0 (stopped)
and 1 (full speed). The default is 1.
"""
se... |
Drive the robot forward by running both motors forward. | def forward(self, speed=1):
"""
Drive the robot forward by running both motors forward.
:param float speed:
Speed at which to drive the motors, as a value between 0 (stopped)
and 1 (full speed). The default is 1.
"""
self.left_motor.forward(speed)
... |
Drive the robot backward by running both motors backward. | def backward(self, speed=1):
"""
Drive the robot backward by running both motors backward.
:param float speed:
Speed at which to drive the motors, as a value between 0 (stopped)
and 1 (full speed). The default is 1.
"""
self.left_motor.backward(speed)
... |
Reverse the robot s current motor directions. If the robot is currently running full speed forward it will run full speed backward. If the robot is turning left at half - speed it will turn right at half - speed. If the robot is currently stopped it will remain stopped. | def reverse(self):
"""
Reverse the robot's current motor directions. If the robot is currently
running full speed forward, it will run full speed backward. If the
robot is turning left at half-speed, it will turn right at half-speed.
If the robot is currently stopped it will rema... |
Called to indicate that the device reserves the right to use the specified * pins *. This should be done during device construction. If pins are reserved you must ensure that the reservation is released by eventually called: meth: release_pins. | def reserve_pins(self, requester, *pins):
"""
Called to indicate that the device reserves the right to use the
specified *pins*. This should be done during device construction. If
pins are reserved, you must ensure that the reservation is released by
eventually called :meth:`rel... |
Releases the reservation of * reserver * against * pins *. This is typically called during: meth: ~gpiozero. Device. close to clean up reservations taken during construction. Releasing a reservation that is not currently held will be silently ignored ( to permit clean - up after failed/ partial construction ). | def release_pins(self, reserver, *pins):
"""
Releases the reservation of *reserver* against *pins*. This is
typically called during :meth:`~gpiozero.Device.close` to clean up
reservations taken during construction. Releasing a reservation that is
not currently held will be silen... |
The pin method for: class: MockFactory additionally takes a * pin_class * attribute which can be used to override the class: attr: pin_class attribute. Any additional keyword arguments will be passed along to the pin constructor ( useful with things like: class: MockConnectedPin which expect to be constructed with anot... | def pin(self, spec, pin_class=None, **kwargs):
"""
The pin method for :class:`MockFactory` additionally takes a *pin_class*
attribute which can be used to override the class' :attr:`pin_class`
attribute. Any additional keyword arguments will be passed along to the
pin constructor... |
Returns a: class: PiBoardInfo instance containing information about a * revision * of the Raspberry Pi. | def pi_info(revision=None):
"""
Returns a :class:`PiBoardInfo` instance containing information about a
*revision* of the Raspberry Pi.
:param str revision:
The revision of the Pi to return information about. If this is omitted
or :data:`None` (the default), then the library will attempt... |
Return the physical pins supporting the specified * function * as tuples of ( header pin_number ) where * header * is a string specifying the header containing the * pin_number *. Note that the return value is a: class: set which is not indexable. Use: func: physical_pin if you are expecting a single return value. | def physical_pins(self, function):
"""
Return the physical pins supporting the specified *function* as tuples
of ``(header, pin_number)`` where *header* is a string specifying the
header containing the *pin_number*. Note that the return value is a
:class:`set` which is not indexa... |
Return the physical pin supporting the specified * function *. If no pins support the desired * function * this function raises: exc: PinNoPins. If multiple pins support the desired * function *: exc: PinMultiplePins will be raised ( use: func: physical_pins if you expect multiple pins in the result such as for electri... | def physical_pin(self, function):
"""
Return the physical pin supporting the specified *function*. If no pins
support the desired *function*, this function raises :exc:`PinNoPins`.
If multiple pins support the desired *function*, :exc:`PinMultiplePins`
will be raised (use :func:`... |
Returns a bool indicating whether a physical pull - up is attached to the pin supporting the specified * function *. Either: exc: PinNoPins or: exc: PinMultiplePins may be raised if the function is not associated with a single pin. | def pulled_up(self, function):
"""
Returns a bool indicating whether a physical pull-up is attached to
the pin supporting the specified *function*. Either :exc:`PinNoPins`
or :exc:`PinMultiplePins` may be raised if the function is not
associated with a single pin.
:param... |
Parses a pin * spec * returning the equivalent Broadcom GPIO port number or raising a: exc: ValueError exception if the spec does not represent a GPIO port. | def to_gpio(self, spec):
"""
Parses a pin *spec*, returning the equivalent Broadcom GPIO port number
or raising a :exc:`ValueError` exception if the spec does not represent
a GPIO port.
The *spec* may be given in any of the following forms:
* An integer, which will be a... |
Returns an SPI interface for the specified SPI * port * and * device * or for the specified pins ( * clock_pin * * mosi_pin * * miso_pin * and * select_pin * ). Only one of the schemes can be used ; attempting to mix * port * and * device * with pin numbers will raise: exc: ~gpiozero. SPIBadArgs. | def spi(self, **spi_args):
"""
Returns an SPI interface, for the specified SPI *port* and *device*, or
for the specified pins (*clock_pin*, *mosi_pin*, *miso_pin*, and
*select_pin*). Only one of the schemes can be used; attempting to mix
*port* and *device* with pin numbers will... |
Given a set of keyword arguments splits it into those relevant to SPI implementations and all the rest. SPI arguments are augmented with defaults and converted into the pin format ( from the port/ device format ) if necessary. | def _extract_spi_args(self, **kwargs):
"""
Given a set of keyword arguments, splits it into those relevant to SPI
implementations and all the rest. SPI arguments are augmented with
defaults and converted into the pin format (from the port/device
format) if necessary.
Ret... |
Called to fire the: attr: when_changed event handler ; override this in descendents if additional ( currently redundant ) parameters need to be passed. | def _call_when_changed(self, ticks, state):
"""
Called to fire the :attr:`when_changed` event handler; override this
in descendents if additional (currently redundant) parameters need
to be passed.
"""
method = self._when_changed()
if method is None:
s... |
Given a bit - pattern expressed an integer number return a sequence of the individual words that make up the pattern. The number of bits per word will be obtained from the internal SPI interface. | def _int_to_words(self, pattern):
"""
Given a bit-pattern expressed an integer number, return a sequence of
the individual words that make up the pattern. The number of bits per
word will be obtained from the internal SPI interface.
"""
try:
bits_required = in... |
Given a sequence of words which each fit in the internal SPI interface s number of bits per word returns the value obtained by concatenating each word into a single bit - string. | def _words_to_int(self, words, expected_bits=None):
"""
Given a sequence of words which each fit in the internal SPI
interface's number of bits per word, returns the value obtained by
concatenating each word into a single bit-string.
If *expected_bits* is specified, it limits th... |
Writes data ( a list of integer words where each word is assumed to have: attr: bits_per_word bits or less ) to the SPI interface and reads an equivalent number of words returning them as a list of integers. | def transfer(self, data, clock_phase=False, lsb_first=False, bits_per_word=8):
"""
Writes data (a list of integer words where each word is assumed to have
:attr:`bits_per_word` bits or less) to the SPI interface, and reads an
equivalent number of words, returning them as a list of intege... |
Returns: data: True if the host returned a single ping and: data: False otherwise. | def value(self):
"""
Returns :data:`True` if the host returned a single ping, and
:data:`False` otherwise.
"""
# XXX This is doing a DNS lookup every time it's queried; should we
# call gethostbyname in the constructor and ping that instead (good
# for consistency... |
Returns the current CPU temperature in degrees celsius. | def temperature(self):
"""
Returns the current CPU temperature in degrees celsius.
"""
with io.open(self.sensor_file, 'r') as f:
return float(f.readline().strip()) / 1000 |
Returns the current CPU temperature as a value between 0. 0 ( representing the * min_temp * value ) and 1. 0 ( representing the * max_temp * value ). These default to 0. 0 and 100. 0 respectively hence: attr: value is: attr: temperature divided by 100 by default. | def value(self):
"""
Returns the current CPU temperature as a value between 0.0
(representing the *min_temp* value) and 1.0 (representing the
*max_temp* value). These default to 0.0 and 100.0 respectively, hence
:attr:`value` is :attr:`temperature` divided by 100 by default.
... |
Returns the current load average. | def load_average(self):
"""
Returns the current load average.
"""
with io.open(self.load_average_file, 'r') as f:
file_columns = f.readline().strip().split()
return float(file_columns[self._load_average_file_column]) |
Returns the current load average as a value between 0. 0 ( representing the * min_load_average * value ) and 1. 0 ( representing the * max_load_average * value ). These default to 0. 0 and 1. 0 respectively. | def value(self):
"""
Returns the current load average as a value between 0.0 (representing
the *min_load_average* value) and 1.0 (representing the
*max_load_average* value). These default to 0.0 and 1.0 respectively.
"""
load_average_range = self.max_load_average - self.m... |
Returns: data: True when the system clock reads between: attr: start_time and: attr: end_time and: data: False otherwise. If: attr: start_time is greater than: attr: end_time ( indicating a period that crosses midnight ) then this returns: data: True when the current time is greater than: attr: start_time or less than:... | def value(self):
"""
Returns :data:`True` when the system clock reads between
:attr:`start_time` and :attr:`end_time`, and :data:`False` otherwise.
If :attr:`start_time` is greater than :attr:`end_time` (indicating a
period that crosses midnight), then this returns :data:`True` w... |
Returns the current disk usage as a value between 0. 0 and 1. 0 by dividing: attr: usage by 100. | def value(self):
"""
Returns the current disk usage as a value between 0.0 and 1.0 by
dividing :attr:`usage` by 100.
"""
# This slightly convoluted calculation is equivalent to df's "Use%";
# it calculates the percentage of FS usage as a proportion of the
# space ... |
Returns the inversion of the supplied values ( * input_min * becomes * input_max * * input_max * becomes * input_min * input_min + 0. 1 becomes input_max - 0. 1 etc. ). All items in * values * are assumed to be between * input_min * and * input_max * ( which default to 0 and 1 respectively ) and the output will be in t... | def inverted(values, input_min=0, input_max=1):
"""
Returns the inversion of the supplied values (*input_min* becomes
*input_max*, *input_max* becomes *input_min*, `input_min + 0.1` becomes
`input_max - 0.1`, etc.). All items in *values* are assumed to be between
*input_min* and *input_max* (which d... |
Returns * values * scaled from * output_min * to * output_max * assuming that all items in * values * lie between * input_min * and * input_max * ( which default to 0 and 1 respectively ). For example to control the direction of a motor ( which is represented as a value between - 1 and 1 ) using a potentiometer ( which... | def scaled(values, output_min, output_max, input_min=0, input_max=1):
"""
Returns *values* scaled from *output_min* to *output_max*, assuming that
all items in *values* lie between *input_min* and *input_max* (which
default to 0 and 1 respectively). For example, to control the direction of
a motor (... |
Returns * values * clamped from * output_min * to * output_max * i. e. any items less than * output_min * will be returned as * output_min * and any items larger than * output_max * will be returned as * output_max * ( these default to 0 and 1 respectively ). For example:: | def clamped(values, output_min=0, output_max=1):
"""
Returns *values* clamped from *output_min* to *output_max*, i.e. any items
less than *output_min* will be returned as *output_min* and any items
larger than *output_max* will be returned as *output_max* (these default to
0 and 1 respectively). For... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.