docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Create a DataStreamSelector from a DataStream.
Args:
stream (DataStream): The data stream that we want to convert. | def FromStream(cls, stream):
if stream.system:
specifier = DataStreamSelector.MatchSystemOnly
else:
specifier = DataStreamSelector.MatchUserOnly
return DataStreamSelector(stream.stream_type, stream.stream_id, specifier) | 522,149 |
Create a DataStreamSelector from a string.
The format of the string should either be:
all <type>
OR
<type> <id>
Where type is [system] <stream type>, with <stream type>
defined as in DataStream
Args:
rep (str): The string representation to convert ... | def FromString(cls, string_rep):
rep = str(string_rep)
rep = rep.replace(u'node', '')
rep = rep.replace(u'nodes', '')
if rep.startswith(u'all'):
parts = rep.split()
spec_string = u''
if len(parts) == 3:
spec_string = parts... | 522,151 |
Check if this selector matches the given stream
Args:
stream (DataStream): The stream to check
Returns:
bool: True if this selector matches the stream | def matches(self, stream):
if self.match_type != stream.stream_type:
return False
if self.match_id is not None:
return self.match_id == stream.stream_id
if self.match_spec == DataStreamSelector.MatchUserOnly:
return not stream.system
elif s... | 522,153 |
Run this optimization pass on the sensor graph
If necessary, information on the device model being targeted
can be found in the associated model argument.
Args:
sensor_graph (SensorGraph): The sensor graph to optimize
model (DeviceModel): The device model we're using | def run(self, sensor_graph, model):
# This check can be done if there is 1 input and it is count == 1
# and the stream type is input or unbuffered
did_downgrade = False
for node, inputs, _outputs in sensor_graph.iterate_bfs():
can_downgrade = False
if... | 522,160 |
Run command as a coroutine and return a future.
Args:
loop (BackgroundEventLoop): The loop that we should attach
the future too.
cmd (list): The command and arguments that we wish to call.
Returns:
asyncio.Future: An awaitable future with the result ... | async def future_command(self, cmd):
if self._asyncio_cmd_lock is None:
raise HardwareError("Cannot use future_command because no event loop attached")
async with self._asyncio_cmd_lock:
return await self._future_command_unlocked(cmd) | 522,164 |
Run command as a coroutine and return a future.
Args:
loop (BackgroundEventLoop): The loop that we should attach
the future too.
cmd (list): The command and arguments that we wish to call.
Returns:
asyncio.Future: An awaitable future with the result ... | def _future_command_unlocked(self, cmd):
future = self._loop.create_future()
asyncio_loop = self._loop.get_loop()
def _done_callback(result):
retval = result['return_value']
if not result['result']:
future.set_exception(HardwareError("Error exe... | 522,165 |
Return a subsystem based on the given executor. If ``executor`` is
None, use :mod:`asyncio`. If ``executor`` is a
:class:`concurrent.futures.ThreadPoolExecutor`, use :mod:`threading`.
Args:
executor: The executor in use, if any. | def for_executor(cls, executor: Optional[Executor]) -> 'Subsystem':
if isinstance(executor, ThreadPoolExecutor):
return _ThreadingSubsystem(executor)
elif executor is None:
return _AsyncioSubsystem()
else:
raise TypeError(executor) | 522,348 |
Return the message with the given UID.
Args:
uid: The message UID.
cached_msg: The last known cached message.
requirement: The data required from each message.
Raises:
IndexError: The UID is not valid in the mailbox. | async def get(self, uid: int, cached_msg: CachedMessage = None,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> Optional[MessageT]:
... | 522,370 |
Update the permanent flags of each messages.
Args:
messages: The message objects.
flag_set: The set of flags for the update operation.
flag_op: The mode to change the flags. | async def update_flags(self, messages: Sequence[MessageT],
flag_set: FrozenSet[Flag], mode: FlagOp) -> None:
... | 522,371 |
Find the active message UID and message pairs in the mailbox that
are contained in the given sequences set. Message sequence numbers
are resolved by the selected mailbox session.
Args:
seq_set: The sequence set of the desired messages.
selected: The selected mailbox sess... | async def find(self, seq_set: SequenceSet, selected: SelectedMailbox,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> AsyncIterable[Tuple[int, MessageT]]:
for seq, cached_msg in selected.messages.get_all(seq_set):
msg = await self.get(cached_ms... | 522,372 |
Return all the active message UIDs that have the ``\\Deleted`` flag.
Args:
seq_set: The sequence set of the possible messages.
selected: The selected mailbox session. | async def find_deleted(self, seq_set: SequenceSet,
selected: SelectedMailbox) -> Sequence[int]:
session_flags = selected.session_flags
return [msg.uid async for _, msg in self.find(seq_set, selected)
if Deleted in msg.get_flags(session_flags)] | 522,373 |
Parses the given buffer by attempting to parse the list of
:attr:`~Params.expected` types until one of them succeeds,
then returns the parsed object.
Args:
buf: The bytes containing the data to be parsed.
params: The parameters used by some parseable types. | def parse(cls, buf: memoryview, params: Params) \
-> Tuple[Parseable, memoryview]:
for data_type in params.expected:
try:
return data_type.parse(buf, params)
except NotParseable:
pass
raise UnexpectedType(buf) | 522,406 |
Add an untagged response. These responses are shown before the
parent response.
Args:
responses: The untagged responses to add. | def add_untagged(self, *responses: 'Response') -> None:
for resp in responses:
try:
merge_key = resp.merge_key
except TypeError:
self._untagged.append(resp)
else:
key = (type(resp), merge_key)
try:
... | 522,455 |
Add an untagged ``OK`` response.
See Also:
:meth:`.add_untagged`, :class:`ResponseOk`
Args:
text: The response text.
code: Optional response code. | def add_untagged_ok(self, text: MaybeBytes,
code: Optional[ResponseCode] = None) -> None:
response = ResponseOk(b'*', text, code)
self.add_untagged(response) | 522,456 |
Write the object to the stream, with one or more calls to
:meth:`~asyncio.WriteStream.write`.
Args:
writer: The output stream. | def write(self, writer: WriteStream) -> None:
for untagged in self._untagged:
untagged.write(writer)
writer.write(b'%b %b\r\n' % (self.tag, self.text)) | 522,458 |
Return a set of all values contained in the sequence set.
Args:
max_value: The maximum value, in place of any ``*``. | def flatten(self, max_value: int) -> FrozenSet[int]:
return frozenset(self.iter(max_value)) | 522,464 |
Iterates through the sequence numbers contained in the set, bounded
by the given maximum value (in place of any ``*``).
Args:
max_value: The maximum value of the set. | def iter(self, max_value: int) -> Iterator[int]:
return chain.from_iterable(
(self._get_range(elem, max_value) for elem in self.sequences)) | 522,465 |
Build a new sequence set that contains the given values using as
few groups as possible.
Args:
seqs: The sequence values to build.
uid: True if the sequences refer to message UIDs. | def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet':
seqs_list = sorted(set(seqs))
groups: List[Union[int, Tuple[int, int]]] = []
group: Union[int, Tuple[int, int]] = seqs_list[0]
for i in range(1, len(seqs_list)):
group_i = seqs_list[i]
... | 522,471 |
Add all the mailbox names to the tree, filling in any missing nodes.
Args:
names: The names of the mailboxes. | def update(self, *names: str) -> 'ListTree':
for name in names:
parts = name.split(self._delimiter)
self._root.add(*parts)
return self | 522,478 |
Add or remove the ``\\Marked`` and ``\\Unmarked`` mailbox
attributes.
Args:
name: The name of the mailbox.
marked: True if the ``\\Marked`` attribute should be added.
unmarked: True if the ``\\Unmarked`` attribute should be added. | def set_marked(self, name: str, marked: bool = False,
unmarked: bool = False) -> None:
if marked:
self._marked[name] = True
elif unmarked:
self._marked[name] = False
else:
self._marked.pop(name, None) | 522,479 |
Return the named entry in the list tree.
Args:
name: The entry name. | def get(self, name: str) -> Optional[ListEntry]:
parts = name.split(self._delimiter)
try:
node = self._find(self._root, *parts)
except KeyError:
return None
else:
marked = self._marked.get(name)
return ListEntry(name, node.exists, ... | 522,482 |
Return all the entries in the list tree that match the given query.
Args:
ref_name: Mailbox reference name.
filter_: Mailbox name with possible wildcards. | def list_matching(self, ref_name: str, filter_: str) \
-> Iterable[ListEntry]:
canonical, canonical_i = self._get_pattern(ref_name + filter_)
for entry in self.list():
if entry.name == 'INBOX':
if canonical_i.match('INBOX'):
yield entr... | 522,486 |
Merge the other FETCH response, adding any fetch attributes that do
not already exist in this FETCH response. For example::
* 3 FETCH (UID 119)
* 3 FETCH (FLAGS (\\Seen))
Would merge into::
* 3 FETCH (UID 119 FLAGS (\\Seen))
Args:
other: The ot... | def merge(self: 'FetchResponse', other: 'FetchResponse') \
-> 'FetchResponse':
if self.seq != other.seq:
raise ValueError(other)
new_data = OrderedDict(self.data)
new_data.update(other.data)
return FetchResponse(self.seq, list(new_data.items())) | 522,492 |
Parse the given file object containing a MIME-encoded email message
into a :class:`BaseLoadedMessage` object.
Args:
uid: The UID of the message.
data: The raw contents of the message.
permanent_flags: Permanent flags for the message.
internal_date: The in... | def parse(cls: Type[MessageT], uid: int, data: bytes,
permanent_flags: Iterable[Flag], internal_date: datetime,
expunged: bool = False, **kwargs: Any) -> MessageT:
content = MessageContent.parse(data)
return cls(uid, permanent_flags, internal_date, expunged,
... | 522,504 |
Add a new selected mailbox object to the set, which may then be
returned by :meth:`.any_selected`.
Args:
selected: The new selected mailbox object.
replace: An existing selected mailbox object that should be removed
from the weak set. | def add(self, selected: 'SelectedMailbox', *,
replace: 'SelectedMailbox' = None) -> None:
if replace is not None:
self._set.discard(replace)
self._set.add(selected) | 522,530 |
Return the given cached message.
Args:
uid: The message UID. | def get(self, uid: int) -> Optional[CachedMessage]:
return self._cache.get(uid) | 522,535 |
Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set. | def get_all(self, seq_set: SequenceSet) \
-> Sequence[Tuple[int, CachedMessage]]:
if seq_set.uid:
all_uids = seq_set.flatten(self.max_uid) & self._uids
return [(seq, self._cache[uid])
for seq, uid in enumerate(self._sorted, 1)
... | 522,536 |
This is the non-optimized alternative to :meth:`.add_updates` for
backend implementations that cannot detect their own updates and must
instead compare the entire state of the mailbox.
The ``messages`` list should contain the entire set of messages in the
mailbox, ordered by UID. Any UI... | def set_messages(self, messages: Sequence[CachedMessage]) -> None:
uids = {msg.uid for msg in messages}
expunged = self._messages._uids - uids
return self.add_updates(messages, expunged) | 522,539 |
Compares the state of the current object to that of the last fork,
returning the untagged responses that reflect any changes. A new copy
of the object is also returned, ready for the next command.
Args:
command: The command that was finished. | def fork(self, command: Command) \
-> Tuple['SelectedMailbox', Iterable[Response]]:
frozen = _Frozen(self)
cls = type(self)
copy = cls(self._guid, self._readonly, self._permanent_flags,
self._session_flags, self._selected_set, self._lookup,
... | 522,541 |
Parse the continuation line sent by the client to end the ``IDLE``
command.
Args:
buf: The continuation line to parse. | def parse_done(self, buf: memoryview) -> Tuple[bool, memoryview]:
match = self._pattern.match(buf)
if not match:
raise NotParseable(buf)
done = match.group(1).upper() == self.continuation
buf = buf[match.end(0):]
return done, buf | 522,561 |
Return the string of letter codes that are used to map to defined
IMAP flags and keywords.
Args:
flags: The flags and keywords to map. | def to_maildir(self, flags: Iterable[Union[bytes, Flag]]) -> str:
codes = []
for flag in flags:
if isinstance(flag, bytes):
flag = Flag(flag)
from_sys = self._from_sys.get(flag)
if from_sys is not None:
codes.append(from_sys)
... | 522,596 |
Return the set of IMAP flags that correspond to the letter codes.
Args:
codes: The letter codes to map. | def from_maildir(self, codes: str) -> FrozenSet[Flag]:
flags = set()
for code in codes:
if code == ',':
break
to_sys = self._to_sys.get(code)
if to_sys is not None:
flags.add(to_sys)
else:
to_kwd = s... | 522,597 |
Return a decoder from the message header object.
See Also:
:meth:`.of_cte`
Args:
msg_header: The message header object. | def of(cls, msg_header: MessageHeader) -> 'MessageDecoder':
cte_hdr = msg_header.parsed.content_transfer_encoding
return cls.of_cte(cte_hdr) | 522,607 |
Return a decoder from the CTE header value.
There is built-in support for ``7bit``, ``8bit``, ``quoted-printable``,
and ``base64`` CTE header values. Decoders can be added or overridden
with the :attr:`.registry` dictionary.
Args:
header: The CTE header value. | def of_cte(cls, header: Optional[ContentTransferEncodingHeader]) \
-> 'MessageDecoder':
if header is None:
return _NoopDecoder()
hdr_str = str(header).lower()
custom = cls.registry.get(hdr_str)
if custom is not None:
return custom
elif... | 522,608 |
Start the socket communication with the server greeting, and then
enter the command/response cycle.
Args:
login: The login/authentication function. | async def run(self, login: LoginProtocol):
self._print('%d +++| %s', bytes(socket_info.get()))
await self._do_greeting(login)
while True:
resp: Response
try:
cmd = await self._read_command()
except (ConnectionError, EOFError):
... | 522,630 |
Start the socket communication with the IMAP greeting, and then
enter the command/response cycle.
Args:
state: Defines the interaction with the backend plugin. | async def run(self, state: ConnectionState) -> None:
self._print('%d +++| %s', bytes(socket_info.get()))
bad_commands = 0
try:
greeting = await self._exec(state.do_greeting())
except ResponseError as exc:
resp = exc.get_response(b'*')
resp.con... | 522,650 |
If the given user ID exists, return its expected password and
mailbox path. Override this method to implement custom login logic.
Args:
config: The maildir config object.
user: The expected user ID.
Raises:
InvalidAuth: The user ID was not valid. | async def find_user(cls, config: Config, user: str) \
-> Tuple[str, str]:
with open(config.users_file, 'r') as users_file:
for line in users_file:
this_user, user_dir, password = line.split(':', 2)
if user == this_user:
return ... | 522,658 |
Encode the string using modified UTF-7.
Args:
data: The input string to encode. | def modutf7_encode(data: str) -> bytes:
ret = bytearray()
is_usascii = True
encode_start = None
for i, symbol in enumerate(data):
charpoint = ord(symbol)
if is_usascii:
if charpoint == 0x26:
ret.extend(b'&-')
elif 0x20 <= charpoint <= 0x7e:
... | 522,662 |
Decode the bytestring using modified UTF-7.
Args:
data: The encoded bytestring to decode. | def modutf7_decode(data: bytes) -> str:
parts = []
is_usascii = True
buf = memoryview(data)
while buf:
byte = buf[0]
if is_usascii:
if buf[0:2] == b'&-':
parts.append('&')
buf = buf[2:]
elif byte == 0x26:
is_usa... | 522,663 |
String interpolation, shortcut for :meth:`.format`.
Args:
other: The data interpolated into the format string. | def __mod__(self, other: Union[_FormatArg, Iterable[_FormatArg]]) -> bytes:
if isinstance(other, bytes):
return self.format([other])
elif hasattr(other, '__bytes__'):
supports_bytes = cast(SupportsBytes, other)
return self.format([bytes(supports_bytes)])
... | 522,666 |
String interpolation into the format string.
Args:
data: The data interpolated into the format string.
Examples:
::
BytesFormat(b'Hello, %b!') % b'World'
BytesFormat(b'%b, %b!') % (b'Hello', b'World') | def format(self, data: Iterable[_FormatArg]) -> bytes:
fix_arg = self._fix_format_arg
return self.how % tuple(fix_arg(item) for item in data) | 522,668 |
Iterable join on a delimiter.
Args:
data: Iterable of items to join.
Examples:
::
BytesFormat(b' ').join([b'one', b'two', b'three']) | def join(self, *data: Iterable[MaybeBytes]) -> bytes:
return self.how.join([bytes(item) for item in chain(*data)]) | 522,669 |
Run the filter and return the mailbox where it should be appended,
or None to discard, and the message to be appended, which is usually
the same as ``append_msg``.
Args:
sender: The envelope sender of the message.
recipient: The envelope recipient of the message.
... | async def apply(self, sender: str, recipient: str, mailbox: str,
append_msg: AppendMessage) \
-> Tuple[Optional[str], AppendMessage]:
... | 522,738 |
Retrieves a :class:`~pymap.interfaces.mailbox.MailboxInterface`
object corresponding to an existing mailbox owned by the user. Raises
an exception if the mailbox does not yet exist.
Args:
name: The name of the mailbox.
selected: If applicable, the currently selected mail... | async def get_mailbox(self, name: str, selected: SelectedMailbox = None) \
-> Tuple[MailboxInterface, Optional[SelectedMailbox]]:
... | 522,749 |
Appends a message to the end of the mailbox.
See Also:
`RFC 3502 6.3.11.
<https://tools.ietf.org/html/rfc3502#section-6.3.11>`_
Args:
name: The name of the mailbox.
messages: The messages to append.
selected: If applicable, the currently sele... | async def append_messages(self, name: str,
messages: Sequence[AppendMessage],
selected: SelectedMailbox = None) \
-> Tuple[AppendUid, Optional[SelectedMailbox]]:
... | 522,751 |
Get a list of loaded message objects corresponding to given sequence
set.
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
attributes: Fetch attributes for the messages.
Raises:
:class:`~pymap... | async def fetch_messages(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
attributes: FrozenSet[FetchAttribute]) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
... | 522,754 |
Get the messages in the current mailbox that meet all of the
given search criteria.
See Also:
`RFC 3501 7.2.5.
<https://tools.ietf.org/html/rfc3501#section-7.2.5>`_
Args:
selected: The selected mailbox session.
keys: Search keys specifying the me... | async def search_mailbox(self, selected: SelectedMailbox,
keys: FrozenSet[SearchKey]) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
... | 522,755 |
Copy a set of messages into the given mailbox.
See Also:
`RFC 3501 6.4.7.
<https://tools.ietf.org/html/rfc3501#section-6.4.7>`_
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
mailbox: Na... | async def copy_messages(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
mailbox: str) \
-> Tuple[Optional[CopyUid], SelectedMailbox]:
... | 522,756 |
Reduce a set of fetch requirements into a single requirement.
Args:
requirements: The set of fetch requirements. | def reduce(cls, requirements: Iterable['FetchRequirement']) \
-> 'FetchRequirement':
return reduce(lambda x, y: x | y, requirements, cls.NONE) | 522,758 |
Build and return a new :class:`IMAPConfig` using command-line
arguments.
Args:
args: The arguments parsed from the command-line. | def from_args(cls: Type[ConfigT], args: Namespace) -> ConfigT:
parsed_args = cls.parse_args(args)
return cls(args, host=args.host, port=args.port, debug=args.debug,
reject_insecure_auth=not args.insecure_login,
cert_file=args.cert, key_file=args.key,
... | 522,791 |
Apply the flag operation on the two sets, returning the result.
Args:
flag_set: The flag set being operated on.
operand: The flags to use as the operand. | def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) \
-> FrozenSet[Flag]:
if self == FlagOp.ADD:
return frozenset(flag_set | operand)
elif self == FlagOp.DELETE:
return frozenset(flag_set - operand)
else: # op == FlagOp.REPLACE
... | 522,909 |
Returns the subset of flags in ``other`` that are also in
:attr:`.defined`. If the wildcard flag is defined, then all flags in
``other`` are returned.
The ``&`` operator is an alias of this method, making these two
calls equivalent::
perm_flags.union(other_flags)
... | def intersect(self, other: Iterable[Flag]) -> FrozenSet[Flag]:
if Wildcard in self._defined:
return frozenset(other)
else:
return self._defined & frozenset(other) | 522,911 |
Return the session flags for the mailbox session.
Args:
uid: The message UID value. | def get(self, uid: int) -> FrozenSet[Flag]:
recent = _recent_set if uid in self._recent else frozenset()
flags = self._flags.get(uid)
return recent if flags is None else (flags | recent) | 522,914 |
Remove any session flags for the given message.
Args:
uids: The message UID values. | def remove(self, uids: Iterable[int]) -> None:
for uid in uids:
self._recent.discard(uid)
self._flags.pop(uid, None) | 522,915 |
Update the flags for the session, returning the resulting flags.
Args:
uid: The message UID value.
flag_set: The set of flags for the update operation.
op: The type of update. | def update(self, uid: int, flag_set: Iterable[Flag],
op: FlagOp = FlagOp.REPLACE) -> FrozenSet[Flag]:
orig_set = self._flags.get(uid, frozenset())
new_flags = op.apply(orig_set, self & flag_set)
if new_flags:
self._flags[uid] = new_flags
else:
... | 522,916 |
Register a new IMAP command.
Args:
cmd: The new command type. | def register(self, cmd: Type[Command]) -> None:
self.commands[cmd.command] = cmd | 522,941 |
Parse the given bytes into a command. The basic syntax is a tag
string, a command name, possibly some arguments, and then an endline.
If the command has a complete structure but cannot be parsed, an
:class:`InvalidCommand` is returned.
Args:
buf: The bytes to parse.
... | def parse(self, buf: memoryview, params: Params) \
-> Tuple[Command, memoryview]:
try:
tag, buf = Tag.parse(buf, params)
except NotParseable as exc:
return InvalidCommand(params, exc), buf[0:0]
else:
params = params.copy(tag=tag.value)
... | 522,942 |
Produce either a :class:`QuotedString` or :class:`LiteralString`
based on the contents of ``data``. This is useful to improve
readability of response data.
Args:
value: The string to serialize.
binary: True if the string should be transmitted as binary.
fallb... | def build(cls, value: object, binary: bool = False,
fallback: object = None) -> Union[Nil, 'String']:
if value is None:
if fallback is None:
return Nil()
else:
return cls.build(fallback, binary)
elif not value:
re... | 522,947 |
Return a list of tuples containing the attribute iself and the bytes
representation of that attribute from the message.
Args:
attrs: The fetch attributes. | def get_all(self, attrs: Iterable[FetchAttribute]) \
-> Sequence[Tuple[FetchAttribute, MaybeBytes]]:
ret: List[Tuple[FetchAttribute, MaybeBytes]] = []
for attr in attrs:
try:
ret.append((attr.for_response, self.get(attr)))
except NotFetchable:... | 522,967 |
Return the bytes representation of the given message attribue.
Args:
attr: The fetch attribute.
Raises:
:class:`NotFetchable` | def get(self, attr: FetchAttribute) -> MaybeBytes:
attr_name = attr.value.decode('ascii')
method = getattr(self, '_get_' + attr_name.replace('.', '_'))
return method(attr) | 522,968 |
Factory method for producing a search criteria sub-class from a
search key.
Args:
key: The search key defining the criteria.
params: The parameters that may be used by some searches. | def of(cls, key: SearchKey, params: SearchParams) -> 'SearchCriteria':
key_name = key.value
if key_name in params.disabled:
raise SearchNotAllowed(key_name)
elif key.inverse:
return InverseSearchCriteria(key.not_inverse, params)
elif key_name == b'SEQSET'... | 522,977 |
The message matches if all the defined search key criteria match.
Args:
msg_seq: The message sequence ID.
msg: The message object. | def matches(self, msg_seq: int, msg: MessageInterface) -> bool:
return all(crit.matches(msg_seq, msg) for crit in self.all_criteria) | 522,980 |
Parse the bytestring into message content.
Args:
data: The bytestring to parse. | def parse(cls, data: bytes) -> 'MessageContent':
lines = cls._find_lines(data)
view = memoryview(data)
return cls._parse(data, view, lines) | 523,003 |
Parse the header and body bytestrings into message content.
Args:
header: The header bytestring to parse.
body: The body bytestring to parse. | def parse_split(cls, header: bytes, body: bytes) -> 'MessageContent':
header_lines = cls._find_lines(header)
body_lines = cls._find_lines(body)
header_view = memoryview(header)
body_view = memoryview(body)
return cls._parse_split([header_view, body_view], header, body,
... | 523,004 |
Write the object to the stream, with one or more calls to
:meth:`~pymap.bytes.WriteStream.write`.
Args:
writer: The output stream. | def write(self, writer: WriteStream) -> None:
for part in self._raw:
writer.write(bytes(part)) | 523,009 |
Get records by a set of UIDs.
Args:
uids: The message UIDs. | def get_all(self, uids: Iterable[int]) -> Mapping[int, Record]:
return {uid: self._records[uid] for uid in uids
if uid in self._records} | 523,030 |
Must be called at some point after import and before your event loop
is run.
Populates the asynclib instance of _AsyncLib with methods relevant to the
async library you are using.
The supported libraries at the moment are:
- curio
- trio
Args:
library (str or module): Either the m... | def init(library: typing.Union[str, types.ModuleType]) -> None:
if isinstance(library, types.ModuleType):
library = library.__name__
if library not in manager._handlers:
raise ValueError("Possible values are <{}>, not <{}>".format(manager._handlers.keys(),
... | 523,079 |
Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
to op_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation... | def add_op(state, op_func, *args, **kwargs):
frameinfo = get_caller_frameinfo()
kwargs['frameinfo'] = frameinfo
for host in state.inventory:
op_func(state, host, *args, **kwargs) | 523,109 |
Prepare & add an deploy to pyinfra.state by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
deploy_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation funct... | def add_deploy(state, deploy_func, *args, **kwargs):
frameinfo = get_caller_frameinfo()
kwargs['frameinfo'] = frameinfo
for host in state.inventory:
deploy_func(state, host, *args, **kwargs) | 523,114 |
Executes a local python file within the ``pyinfra.pseudo_state.deploy_dir``
directory.
Args:
hosts (string, list): group name or list of hosts to limit this include to
when (bool): indicate whether to trigger operations in this include | def include(filename, hosts=False, when=True):
if not pyinfra.is_cli:
raise PyinfraError('local.include is only available in CLI mode.')
if not when:
return
if hosts is not False:
hosts = ensure_host_list(hosts, inventory=pseudo_state.inventory)
if pseudo_host not in ... | 523,169 |
Subprocess based implementation of pyinfra/api/ssh.py's ``run_shell_command``.
Args:
commands (string, list): command or list of commands to execute
spltlines (bool): optionally have the output split by lines
ignore_errors (bool): ignore errors when executing these commands | def shell(commands, splitlines=False, ignore_errors=False):
if isinstance(commands, six.string_types):
commands = [commands]
all_stdout = []
# Checking for pseudo_state means this function works outside a deploy
# eg the vagrant connector.
print_output = (
pseudo_state.print_... | 523,170 |
Create an authenticate object
Arguments:
func: a function to decorate
method: the method of the request to construct | def __init__(self, func, method='GET'):
self.func = func
self.owner = None
self.instance = None
self.headers = {
'Accept-Encoding': 'identity, deflate, compress, gzip',
'User-Agent': 'python-requests/1.2.0',
'Accept': 'application/... | 523,178 |
Create a GistAPI object
Arguments:
token: an authentication token
editor: path to the editor to use when editing a gist | def __init__(self, token, editor=None):
self.token = token
self.editor = editor
self.session = requests.Session() | 523,181 |
Prepare and send a request
Arguments:
request: a Request object that is not yet prepared
stem: a path to append to the root URL
Returns:
The response to the request | def send(self, request, stem=None):
if stem is not None:
request.url = request.url + "/" + stem.lstrip("/")
prepped = self.session.prepare_request(request)
settings = self.session.merge_environment_settings(url=prepped.url,
... | 523,182 |
Creates a gist
Arguments:
request: an initial request object
desc: the gist description
files: a list of files to add to the gist
public: a flag to indicate whether the gist is public or not
Returns:
The URL to the newly created gist. | def create(self, request, desc, files, public=False):
request.data = json.dumps({
"description": desc,
"public": public,
"files": files,
})
return self.send(request).json()['html_url'] | 523,184 |
Returns a list of files in the gist
Arguments:
request: an initial request object
id: the gist identifier
Returns:
A list of the files | def files(self, request, id):
gist = self.send(request, id).json()
return gist['files'] | 523,185 |
Returns the content of the gist
Arguments:
request: an initial request object
id: the gist identifier
Returns:
A dict containing the contents of each file in the gist | def content(self, request, id):
gist = self.send(request, id).json()
def convert(data):
return base64.b64decode(data).decode('utf-8')
content = {}
for name, data in gist['files'].items():
content[name] = convert(data['content'])
return content | 523,186 |
Create an archive of a gist
The files in the gist are downloaded and added to a compressed archive
(tarball). If the ID of the gist was c78d925546e964b4b1df, the
resulting archive would be,
c78d925546e964b4b1df.tar.gz
The archive is created in the directory where the comma... | def archive(self, request, id):
gist = self.send(request, id).json()
with tarfile.open('{}.tar.gz'.format(id), mode='w:gz') as archive:
for name, data in gist['files'].items():
with tempfile.NamedTemporaryFile('w+') as fp:
fp.write(data['content'... | 523,187 |
Edit a gist
The files in the gist a cloned to a temporary directory and passed to
the default editor (defined by the EDITOR environmental variable). When
the user exits the editor, they will be provided with a prompt to
commit the changes, which will then be pushed to the remote.
... | def edit(self, request, id):
with pushd(tempfile.gettempdir()):
try:
self.clone(id)
with pushd(id):
files = [f for f in os.listdir('.') if os.path.isfile(f)]
quoted = ['"{}"'.format(f) for f in files]
... | 523,188 |
Updates the description of a gist
Arguments:
request: an initial request object
id: the id of the gist we want to edit the description for
description: the new description | def description(self, request, id, description):
request.data = json.dumps({
"description": description
})
return self.send(request, id).json()['html_url'] | 523,189 |
Clone a gist
Arguments:
id: the gist identifier
name: the name to give the cloned repo | def clone(self, id, name=None):
url = 'git@gist.github.com:/{}'.format(id)
if name is None:
os.system('git clone {}'.format(url))
else:
os.system('git clone {} {}'.format(url, name)) | 523,190 |
Connect to all the configured servers in parallel. Reads/writes state.inventory.
Args:
state (``pyinfra.api.State`` obj): the state containing an inventory to connect to | def connect_all(state):
hosts = [
host for host in state.inventory
if state.is_host_in_limit(host)
]
greenlet_to_host = {
state.pool.spawn(host.connect, state): host
for host in hosts
}
with progress_spinner(greenlet_to_host.values()) as progress:
for ... | 523,310 |
Runs all operations across all servers in a configurable manner.
Args:
state (``pyinfra.api.State`` obj): the deploy state to execute
serial (boolean): whether to run operations host by host
no_wait (boolean): whether to wait for all hosts between operations | def run_ops(state, serial=False, no_wait=False):
# Flag state as deploy in process
state.deploying = True
# Run all ops, but server by server
if serial:
_run_serial_ops(state)
# Run all the ops on each server in parallel (not waiting at each operation)
elif no_wait:
_run_... | 523,356 |
Builds a loss function that masks based on targets
Args:
loss_function: The loss function to mask
mask_value: The value to mask in the targets
Returns:
function: a loss function that acts like loss_function with masked inputs | def build_masked_loss(loss_function, mask_value):
def masked_loss_function(y_true, y_pred):
mask = K.cast(K.not_equal(y_true, mask_value), K.floatx())
return loss_function(y_true * mask, y_pred * mask)
return masked_loss_function | 523,423 |
Given an executable filename, find in the PATH or find absolute path.
Args:
filename An executable filename (string)
Returns:
Absolute version of filename.
None if filename could not be found locally, absolutely, or in PATH | def GetRealPath(filename):
if os.path.isabs(filename): # already absolute
return filename
if filename.startswith('./') or filename.startswith('../'): # relative
return os.path.abspath(filename)
path = os.getenv('PATH', '')
for directory in path.split(':'):
tryname = os.path.join... | 523,444 |
Create the flag object.
Args:
flag_desc The command line forms this could take. (string)
help The help text (string) | def __init__(self, flag_desc, help):
self.desc = flag_desc # the command line forms
self.help = help # the help text
self.default = '' # default value
self.tips = '' | 523,447 |
Create object with executable.
Args:
executable Program to execute (string) | def __init__(self, executable):
self.long_name = executable
self.name = os.path.basename(executable) # name
# Get name without extension (PAR files)
(self.short_name, self.ext) = os.path.splitext(self.name)
self.executable = GetRealPath(executable) # name of the program
self.output = [] ... | 523,448 |
Create base object.
Args:
proginfo A ProgramInfo object
directory Directory to write output into | def __init__(self, proginfo, directory='.'):
self.info = proginfo
self.dirname = directory | 523,456 |
Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module. | def _RegisterFlagByModule(self, module_name, flag):
flags_by_module = self.FlagsByModuleDict()
flags_by_module.setdefault(module_name, []).append(flag) | 523,470 |
Records the module that defines a specific flag.
Args:
module_id: An int, the ID of the Python module.
flag: A Flag object, a flag that is key to the module. | def _RegisterFlagByModuleId(self, module_id, flag):
flags_by_module_id = self.FlagsByModuleIdDict()
flags_by_module_id.setdefault(module_id, []).append(flag) | 523,471 |
Specifies that a flag is a key flag for a module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module. | def _RegisterKeyFlagForModule(self, module_name, flag):
key_flags_by_module = self.KeyFlagsByModuleDict()
# The list of key flags for the module named module_name.
key_flags = key_flags_by_module.setdefault(module_name, [])
# Add flag, but avoid duplicates.
if flag not in key_flags:
key_f... | 523,472 |
Checks whether a Flag object is registered under long name or short name.
Args:
flag_obj: A Flag object.
Returns:
A boolean: True iff flag_obj is registered under long name or short name. | def _FlagIsRegistered(self, flag_obj):
flag_dict = self.FlagDict()
# Check whether flag_obj is registered under its long name.
name = flag_obj.name
if flag_dict.get(name, None) == flag_obj:
return True
# Check whether flag_obj is registered under its short name.
short_name = flag_obj.... | 523,473 |
Cleanup unregistered flags from all module -> [flags] dictionaries.
If flag_obj is registered under either its long name or short name, it
won't be removed from the dictionaries.
Args:
flag_obj: A flag object. | def _CleanupUnregisteredFlagFromModuleDicts(self, flag_obj):
if self._FlagIsRegistered(flag_obj):
return
for flags_by_module_dict in (self.FlagsByModuleDict(),
self.FlagsByModuleIdDict(),
self.KeyFlagsByModuleDict()):
for flags_i... | 523,474 |
Returns the list of flags defined by a module.
Args:
module: A module object or a module name (a string).
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object. | def _GetFlagsDefinedByModule(self, module):
if not isinstance(module, str):
module = module.__name__
return list(self.FlagsByModuleDict().get(module, [])) | 523,475 |
Returns the list of key flags for a module.
Args:
module: A module object or a module name (a string)
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object. | def _GetKeyFlagsForModule(self, module):
if not isinstance(module, str):
module = module.__name__
# Any flag is a key flag for the module that defined it. NOTE:
# key_flags is a fresh list: we can update it without affecting the
# internals of this FlagValues object.
key_flags = self._G... | 523,476 |
Return the name of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which registered the flag with this name.
If no such module exists ... | def FindModuleDefiningFlag(self, flagname, default=None):
registered_flag = self.FlagDict().get(flagname)
if registered_flag is None:
return default
for module, flags in six.iteritems(self.FlagsByModuleDict()):
for flag in flags:
# It must compare the flag with the one in FlagDict. ... | 523,477 |
Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which registered the flag with this name.
If no such module exists (i.e... | def FindModuleIdDefiningFlag(self, flagname, default=None):
registered_flag = self.FlagDict().get(flagname)
if registered_flag is None:
return default
for module_id, flags in six.iteritems(self.FlagsByModuleIdDict()):
for flag in flags:
# It must compare the flag with the one in Fla... | 523,478 |
Returns value if setting flag |name| to |value| returned True.
Args:
name: Name of the flag to set.
value: Value to set.
Returns:
Flag value on successful call.
Raises:
UnrecognizedFlagError
IllegalFlagValueError | def _SetUnknownFlag(self, name, value):
setter = self.__dict__['__set_unknown']
if setter:
try:
setter(name, value)
return value
except (TypeError, ValueError): # Flag value is not valid.
raise exceptions.IllegalFlagValueError('"{1}" is not valid for --{0}'
... | 523,479 |
Appends flags registered in another FlagValues instance.
Args:
flag_values: registry to copy from | def AppendFlagValues(self, flag_values):
for flag_name, flag in six.iteritems(flag_values.FlagDict()):
# Each flags with shortname appears here twice (once under its
# normal name, and again with its short name). To prevent
# problems (DuplicateFlagError) with double flag registration, we
... | 523,480 |
Assert if all validators in the list are satisfied.
Asserts validators in the order they were created.
Args:
validators: Iterable(validators.Validator), validators to be
verified
Raises:
AttributeError: if validators work with a non-existing flag.
IllegalFlagValueError: if validat... | def _AssertValidators(self, validators):
for validator in sorted(
validators, key=lambda validator: validator.insertion_index):
try:
validator.verify(self)
except exceptions.ValidationError as e:
message = validator.print_flags_with_values(self)
raise exceptions.Ille... | 523,487 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.