repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
benedictpaten/sonLib
bioio.py
TempFileTree.destroyTempFile
def destroyTempFile(self, tempFile): """Removes the temporary file in the temp file dir, checking its in the temp file tree. """ #Do basic assertions for goodness of the function assert os.path.isfile(tempFile) assert os.path.commonprefix((self.rootDir, tempFile)) == self.rootDir #Checks file is part of tree #Update stats. self.tempFilesDestroyed += 1 #Do the actual removal os.remove(tempFile) self.__destroyFile(tempFile)
python
def destroyTempFile(self, tempFile): """Removes the temporary file in the temp file dir, checking its in the temp file tree. """ #Do basic assertions for goodness of the function assert os.path.isfile(tempFile) assert os.path.commonprefix((self.rootDir, tempFile)) == self.rootDir #Checks file is part of tree #Update stats. self.tempFilesDestroyed += 1 #Do the actual removal os.remove(tempFile) self.__destroyFile(tempFile)
[ "def", "destroyTempFile", "(", "self", ",", "tempFile", ")", ":", "#Do basic assertions for goodness of the function", "assert", "os", ".", "path", ".", "isfile", "(", "tempFile", ")", "assert", "os", ".", "path", ".", "commonprefix", "(", "(", "self", ".", "r...
Removes the temporary file in the temp file dir, checking its in the temp file tree.
[ "Removes", "the", "temporary", "file", "in", "the", "temp", "file", "dir", "checking", "its", "in", "the", "temp", "file", "tree", "." ]
1decb75bb439b70721ec776f685ce98e25217d26
https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L557-L567
train
22,700
benedictpaten/sonLib
bioio.py
TempFileTree.destroyTempDir
def destroyTempDir(self, tempDir): """Removes a temporary directory in the temp file dir, checking its in the temp file tree. The dir will be removed regardless of if it is empty. """ #Do basic assertions for goodness of the function assert os.path.isdir(tempDir) assert os.path.commonprefix((self.rootDir, tempDir)) == self.rootDir #Checks file is part of tree #Update stats. self.tempFilesDestroyed += 1 #Do the actual removal try: os.rmdir(tempDir) except OSError: shutil.rmtree(tempDir) #system("rm -rf %s" % tempDir) self.__destroyFile(tempDir)
python
def destroyTempDir(self, tempDir): """Removes a temporary directory in the temp file dir, checking its in the temp file tree. The dir will be removed regardless of if it is empty. """ #Do basic assertions for goodness of the function assert os.path.isdir(tempDir) assert os.path.commonprefix((self.rootDir, tempDir)) == self.rootDir #Checks file is part of tree #Update stats. self.tempFilesDestroyed += 1 #Do the actual removal try: os.rmdir(tempDir) except OSError: shutil.rmtree(tempDir) #system("rm -rf %s" % tempDir) self.__destroyFile(tempDir)
[ "def", "destroyTempDir", "(", "self", ",", "tempDir", ")", ":", "#Do basic assertions for goodness of the function", "assert", "os", ".", "path", ".", "isdir", "(", "tempDir", ")", "assert", "os", ".", "path", ".", "commonprefix", "(", "(", "self", ".", "rootD...
Removes a temporary directory in the temp file dir, checking its in the temp file tree. The dir will be removed regardless of if it is empty.
[ "Removes", "a", "temporary", "directory", "in", "the", "temp", "file", "dir", "checking", "its", "in", "the", "temp", "file", "tree", ".", "The", "dir", "will", "be", "removed", "regardless", "of", "if", "it", "is", "empty", "." ]
1decb75bb439b70721ec776f685ce98e25217d26
https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L569-L584
train
22,701
benedictpaten/sonLib
bioio.py
TempFileTree.destroyTempFiles
def destroyTempFiles(self): """Destroys all temp temp file hierarchy, getting rid of all files. """ os.system("rm -rf %s" % self.rootDir) logger.debug("Temp files created: %s, temp files actively destroyed: %s" % (self.tempFilesCreated, self.tempFilesDestroyed))
python
def destroyTempFiles(self): """Destroys all temp temp file hierarchy, getting rid of all files. """ os.system("rm -rf %s" % self.rootDir) logger.debug("Temp files created: %s, temp files actively destroyed: %s" % (self.tempFilesCreated, self.tempFilesDestroyed))
[ "def", "destroyTempFiles", "(", "self", ")", ":", "os", ".", "system", "(", "\"rm -rf %s\"", "%", "self", ".", "rootDir", ")", "logger", ".", "debug", "(", "\"Temp files created: %s, temp files actively destroyed: %s\"", "%", "(", "self", ".", "tempFilesCreated", ...
Destroys all temp temp file hierarchy, getting rid of all files.
[ "Destroys", "all", "temp", "temp", "file", "hierarchy", "getting", "rid", "of", "all", "files", "." ]
1decb75bb439b70721ec776f685ce98e25217d26
https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L605-L609
train
22,702
penguinolog/sqlalchemy_jsonfield
sqlalchemy_jsonfield/jsonfield.py
mutable_json_field
def mutable_json_field( # pylint: disable=keyword-arg-before-vararg enforce_string=False, # type: bool enforce_unicode=False, # type: bool json=json, # type: typing.Union[types.ModuleType, typing.Any] *args, # type: typing.Any **kwargs # type: typing.Any ): # type: (...) -> JSONField """Mutable JSONField creator. :param enforce_string: enforce String(UnicodeText) type usage :type enforce_string: bool :param enforce_unicode: do not encode non-ascii data :type enforce_unicode: bool :param json: JSON encoding/decoding library. By default: standard json package. :return: Mutable JSONField via MutableDict.as_mutable :rtype: JSONField """ return sqlalchemy.ext.mutable.MutableDict.as_mutable( JSONField(enforce_string=enforce_string, enforce_unicode=enforce_unicode, json=json, *args, **kwargs) )
python
def mutable_json_field( # pylint: disable=keyword-arg-before-vararg enforce_string=False, # type: bool enforce_unicode=False, # type: bool json=json, # type: typing.Union[types.ModuleType, typing.Any] *args, # type: typing.Any **kwargs # type: typing.Any ): # type: (...) -> JSONField """Mutable JSONField creator. :param enforce_string: enforce String(UnicodeText) type usage :type enforce_string: bool :param enforce_unicode: do not encode non-ascii data :type enforce_unicode: bool :param json: JSON encoding/decoding library. By default: standard json package. :return: Mutable JSONField via MutableDict.as_mutable :rtype: JSONField """ return sqlalchemy.ext.mutable.MutableDict.as_mutable( JSONField(enforce_string=enforce_string, enforce_unicode=enforce_unicode, json=json, *args, **kwargs) )
[ "def", "mutable_json_field", "(", "# pylint: disable=keyword-arg-before-vararg", "enforce_string", "=", "False", ",", "# type: bool", "enforce_unicode", "=", "False", ",", "# type: bool", "json", "=", "json", ",", "# type: typing.Union[types.ModuleType, typing.Any]", "*", "ar...
Mutable JSONField creator. :param enforce_string: enforce String(UnicodeText) type usage :type enforce_string: bool :param enforce_unicode: do not encode non-ascii data :type enforce_unicode: bool :param json: JSON encoding/decoding library. By default: standard json package. :return: Mutable JSONField via MutableDict.as_mutable :rtype: JSONField
[ "Mutable", "JSONField", "creator", "." ]
a2af90e64d82a3a28185e1e0828757bf2829be06
https://github.com/penguinolog/sqlalchemy_jsonfield/blob/a2af90e64d82a3a28185e1e0828757bf2829be06/sqlalchemy_jsonfield/jsonfield.py#L103-L123
train
22,703
penguinolog/sqlalchemy_jsonfield
sqlalchemy_jsonfield/jsonfield.py
JSONField.load_dialect_impl
def load_dialect_impl(self, dialect): # type: (DefaultDialect) -> TypeEngine """Select impl by dialect.""" if self.__use_json(dialect): return dialect.type_descriptor(self.__json_type) return dialect.type_descriptor(sqlalchemy.UnicodeText)
python
def load_dialect_impl(self, dialect): # type: (DefaultDialect) -> TypeEngine """Select impl by dialect.""" if self.__use_json(dialect): return dialect.type_descriptor(self.__json_type) return dialect.type_descriptor(sqlalchemy.UnicodeText)
[ "def", "load_dialect_impl", "(", "self", ",", "dialect", ")", ":", "# type: (DefaultDialect) -> TypeEngine", "if", "self", ".", "__use_json", "(", "dialect", ")", ":", "return", "dialect", ".", "type_descriptor", "(", "self", ".", "__json_type", ")", "return", "...
Select impl by dialect.
[ "Select", "impl", "by", "dialect", "." ]
a2af90e64d82a3a28185e1e0828757bf2829be06
https://github.com/penguinolog/sqlalchemy_jsonfield/blob/a2af90e64d82a3a28185e1e0828757bf2829be06/sqlalchemy_jsonfield/jsonfield.py#L78-L82
train
22,704
penguinolog/sqlalchemy_jsonfield
sqlalchemy_jsonfield/jsonfield.py
JSONField.process_bind_param
def process_bind_param(self, value, dialect): # type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any] """Encode data, if required.""" if self.__use_json(dialect) or value is None: return value return self.__json_codec.dumps(value, ensure_ascii=not self.__enforce_unicode)
python
def process_bind_param(self, value, dialect): # type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any] """Encode data, if required.""" if self.__use_json(dialect) or value is None: return value return self.__json_codec.dumps(value, ensure_ascii=not self.__enforce_unicode)
[ "def", "process_bind_param", "(", "self", ",", "value", ",", "dialect", ")", ":", "# type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any]", "if", "self", ".", "__use_json", "(", "dialect", ")", "or", "value", "is", "None", ":", "return", "value", "ret...
Encode data, if required.
[ "Encode", "data", "if", "required", "." ]
a2af90e64d82a3a28185e1e0828757bf2829be06
https://github.com/penguinolog/sqlalchemy_jsonfield/blob/a2af90e64d82a3a28185e1e0828757bf2829be06/sqlalchemy_jsonfield/jsonfield.py#L84-L89
train
22,705
penguinolog/sqlalchemy_jsonfield
sqlalchemy_jsonfield/jsonfield.py
JSONField.process_result_value
def process_result_value( self, value, # type: typing.Union[str, typing.Any] dialect # type: DefaultDialect ): # type: (...) -> typing.Any """Decode data, if required.""" if self.__use_json(dialect) or value is None: return value return self.__json_codec.loads(value)
python
def process_result_value( self, value, # type: typing.Union[str, typing.Any] dialect # type: DefaultDialect ): # type: (...) -> typing.Any """Decode data, if required.""" if self.__use_json(dialect) or value is None: return value return self.__json_codec.loads(value)
[ "def", "process_result_value", "(", "self", ",", "value", ",", "# type: typing.Union[str, typing.Any]", "dialect", "# type: DefaultDialect", ")", ":", "# type: (...) -> typing.Any", "if", "self", ".", "__use_json", "(", "dialect", ")", "or", "value", "is", "None", ":"...
Decode data, if required.
[ "Decode", "data", "if", "required", "." ]
a2af90e64d82a3a28185e1e0828757bf2829be06
https://github.com/penguinolog/sqlalchemy_jsonfield/blob/a2af90e64d82a3a28185e1e0828757bf2829be06/sqlalchemy_jsonfield/jsonfield.py#L91-L100
train
22,706
icgood/pymap
pymap/backend/mailbox.py
MailboxDataInterface.get
async def get(self, uid: int, cached_msg: CachedMessage = None, requirement: FetchRequirement = FetchRequirement.METADATA) \ -> Optional[MessageT]: """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. """ ...
python
async def get(self, uid: int, cached_msg: CachedMessage = None, requirement: FetchRequirement = FetchRequirement.METADATA) \ -> Optional[MessageT]: """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", "]", ":", "..."...
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.
[ "Return", "the", "message", "with", "the", "given", "UID", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L120-L134
train
22,707
icgood/pymap
pymap/backend/mailbox.py
MailboxDataInterface.update_flags
async def update_flags(self, messages: Sequence[MessageT], flag_set: FrozenSet[Flag], mode: FlagOp) -> None: """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. """ ...
python
async def update_flags(self, messages: Sequence[MessageT], flag_set: FrozenSet[Flag], mode: FlagOp) -> None: """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", ":", "..." ]
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.
[ "Update", "the", "permanent", "flags", "of", "each", "messages", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L158-L168
train
22,708
icgood/pymap
pymap/backend/mailbox.py
MailboxDataInterface.find
async def find(self, seq_set: SequenceSet, selected: SelectedMailbox, requirement: FetchRequirement = FetchRequirement.METADATA) \ -> AsyncIterable[Tuple[int, MessageT]]: """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 session. requirement: The data required from each message. """ for seq, cached_msg in selected.messages.get_all(seq_set): msg = await self.get(cached_msg.uid, cached_msg, requirement) if msg is not None: yield (seq, msg)
python
async def find(self, seq_set: SequenceSet, selected: SelectedMailbox, requirement: FetchRequirement = FetchRequirement.METADATA) \ -> AsyncIterable[Tuple[int, MessageT]]: """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 session. requirement: The data required from each message. """ for seq, cached_msg in selected.messages.get_all(seq_set): msg = await self.get(cached_msg.uid, cached_msg, requirement) if msg is not None: yield (seq, msg)
[ "async", "def", "find", "(", "self", ",", "seq_set", ":", "SequenceSet", ",", "selected", ":", "SelectedMailbox", ",", "requirement", ":", "FetchRequirement", "=", "FetchRequirement", ".", "METADATA", ")", "->", "AsyncIterable", "[", "Tuple", "[", "int", ",", ...
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 session. requirement: The data required from each message.
[ "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", ...
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L186-L202
train
22,709
icgood/pymap
pymap/backend/mailbox.py
MailboxDataInterface.find_deleted
async def find_deleted(self, seq_set: SequenceSet, selected: SelectedMailbox) -> Sequence[int]: """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. """ 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)]
python
async def find_deleted(self, seq_set: SequenceSet, selected: SelectedMailbox) -> Sequence[int]: """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. """ 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)]
[ "async", "def", "find_deleted", "(", "self", ",", "seq_set", ":", "SequenceSet", ",", "selected", ":", "SelectedMailbox", ")", "->", "Sequence", "[", "int", "]", ":", "session_flags", "=", "selected", ".", "session_flags", "return", "[", "msg", ".", "uid", ...
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.
[ "Return", "all", "the", "active", "message", "UIDs", "that", "have", "the", "\\\\", "Deleted", "flag", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L204-L215
train
22,710
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.content_type
def content_type(self) -> Optional[ContentTypeHeader]: """The ``Content-Type`` header.""" try: return cast(ContentTypeHeader, self[b'content-type'][0]) except (KeyError, IndexError): return None
python
def content_type(self) -> Optional[ContentTypeHeader]: """The ``Content-Type`` header.""" try: return cast(ContentTypeHeader, self[b'content-type'][0]) except (KeyError, IndexError): return None
[ "def", "content_type", "(", "self", ")", "->", "Optional", "[", "ContentTypeHeader", "]", ":", "try", ":", "return", "cast", "(", "ContentTypeHeader", ",", "self", "[", "b'content-type'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "IndexError...
The ``Content-Type`` header.
[ "The", "Content", "-", "Type", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L63-L68
train
22,711
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.date
def date(self) -> Optional[DateHeader]: """The ``Date`` header.""" try: return cast(DateHeader, self[b'date'][0]) except (KeyError, IndexError): return None
python
def date(self) -> Optional[DateHeader]: """The ``Date`` header.""" try: return cast(DateHeader, self[b'date'][0]) except (KeyError, IndexError): return None
[ "def", "date", "(", "self", ")", "->", "Optional", "[", "DateHeader", "]", ":", "try", ":", "return", "cast", "(", "DateHeader", ",", "self", "[", "b'date'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "IndexError", ")", ":", "return", ...
The ``Date`` header.
[ "The", "Date", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L71-L76
train
22,712
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.subject
def subject(self) -> Optional[UnstructuredHeader]: """The ``Subject`` header.""" try: return cast(UnstructuredHeader, self[b'subject'][0]) except (KeyError, IndexError): return None
python
def subject(self) -> Optional[UnstructuredHeader]: """The ``Subject`` header.""" try: return cast(UnstructuredHeader, self[b'subject'][0]) except (KeyError, IndexError): return None
[ "def", "subject", "(", "self", ")", "->", "Optional", "[", "UnstructuredHeader", "]", ":", "try", ":", "return", "cast", "(", "UnstructuredHeader", ",", "self", "[", "b'subject'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "IndexError", ")"...
The ``Subject`` header.
[ "The", "Subject", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L79-L84
train
22,713
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.from_
def from_(self) -> Optional[Sequence[AddressHeader]]: """The ``From`` header.""" try: return cast(Sequence[AddressHeader], self[b'from']) except KeyError: return None
python
def from_(self) -> Optional[Sequence[AddressHeader]]: """The ``From`` header.""" try: return cast(Sequence[AddressHeader], self[b'from']) except KeyError: return None
[ "def", "from_", "(", "self", ")", "->", "Optional", "[", "Sequence", "[", "AddressHeader", "]", "]", ":", "try", ":", "return", "cast", "(", "Sequence", "[", "AddressHeader", "]", ",", "self", "[", "b'from'", "]", ")", "except", "KeyError", ":", "retur...
The ``From`` header.
[ "The", "From", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L87-L92
train
22,714
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.sender
def sender(self) -> Optional[Sequence[SingleAddressHeader]]: """The ``Sender`` header.""" try: return cast(Sequence[SingleAddressHeader], self[b'sender']) except KeyError: return None
python
def sender(self) -> Optional[Sequence[SingleAddressHeader]]: """The ``Sender`` header.""" try: return cast(Sequence[SingleAddressHeader], self[b'sender']) except KeyError: return None
[ "def", "sender", "(", "self", ")", "->", "Optional", "[", "Sequence", "[", "SingleAddressHeader", "]", "]", ":", "try", ":", "return", "cast", "(", "Sequence", "[", "SingleAddressHeader", "]", ",", "self", "[", "b'sender'", "]", ")", "except", "KeyError", ...
The ``Sender`` header.
[ "The", "Sender", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L95-L100
train
22,715
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.reply_to
def reply_to(self) -> Optional[Sequence[AddressHeader]]: """The ``Reply-To`` header.""" try: return cast(Sequence[AddressHeader], self[b'reply-to']) except KeyError: return None
python
def reply_to(self) -> Optional[Sequence[AddressHeader]]: """The ``Reply-To`` header.""" try: return cast(Sequence[AddressHeader], self[b'reply-to']) except KeyError: return None
[ "def", "reply_to", "(", "self", ")", "->", "Optional", "[", "Sequence", "[", "AddressHeader", "]", "]", ":", "try", ":", "return", "cast", "(", "Sequence", "[", "AddressHeader", "]", ",", "self", "[", "b'reply-to'", "]", ")", "except", "KeyError", ":", ...
The ``Reply-To`` header.
[ "The", "Reply", "-", "To", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L103-L108
train
22,716
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.to
def to(self) -> Optional[Sequence[AddressHeader]]: """The ``To`` header.""" try: return cast(Sequence[AddressHeader], self[b'to']) except KeyError: return None
python
def to(self) -> Optional[Sequence[AddressHeader]]: """The ``To`` header.""" try: return cast(Sequence[AddressHeader], self[b'to']) except KeyError: return None
[ "def", "to", "(", "self", ")", "->", "Optional", "[", "Sequence", "[", "AddressHeader", "]", "]", ":", "try", ":", "return", "cast", "(", "Sequence", "[", "AddressHeader", "]", ",", "self", "[", "b'to'", "]", ")", "except", "KeyError", ":", "return", ...
The ``To`` header.
[ "The", "To", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L111-L116
train
22,717
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.cc
def cc(self) -> Optional[Sequence[AddressHeader]]: """The ``Cc`` header.""" try: return cast(Sequence[AddressHeader], self[b'cc']) except KeyError: return None
python
def cc(self) -> Optional[Sequence[AddressHeader]]: """The ``Cc`` header.""" try: return cast(Sequence[AddressHeader], self[b'cc']) except KeyError: return None
[ "def", "cc", "(", "self", ")", "->", "Optional", "[", "Sequence", "[", "AddressHeader", "]", "]", ":", "try", ":", "return", "cast", "(", "Sequence", "[", "AddressHeader", "]", ",", "self", "[", "b'cc'", "]", ")", "except", "KeyError", ":", "return", ...
The ``Cc`` header.
[ "The", "Cc", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L119-L124
train
22,718
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.bcc
def bcc(self) -> Optional[Sequence[AddressHeader]]: """The ``Bcc`` header.""" try: return cast(Sequence[AddressHeader], self[b'bcc']) except KeyError: return None
python
def bcc(self) -> Optional[Sequence[AddressHeader]]: """The ``Bcc`` header.""" try: return cast(Sequence[AddressHeader], self[b'bcc']) except KeyError: return None
[ "def", "bcc", "(", "self", ")", "->", "Optional", "[", "Sequence", "[", "AddressHeader", "]", "]", ":", "try", ":", "return", "cast", "(", "Sequence", "[", "AddressHeader", "]", ",", "self", "[", "b'bcc'", "]", ")", "except", "KeyError", ":", "return",...
The ``Bcc`` header.
[ "The", "Bcc", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L127-L132
train
22,719
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.in_reply_to
def in_reply_to(self) -> Optional[UnstructuredHeader]: """The ``In-Reply-To`` header.""" try: return cast(UnstructuredHeader, self[b'in-reply-to'][0]) except (KeyError, IndexError): return None
python
def in_reply_to(self) -> Optional[UnstructuredHeader]: """The ``In-Reply-To`` header.""" try: return cast(UnstructuredHeader, self[b'in-reply-to'][0]) except (KeyError, IndexError): return None
[ "def", "in_reply_to", "(", "self", ")", "->", "Optional", "[", "UnstructuredHeader", "]", ":", "try", ":", "return", "cast", "(", "UnstructuredHeader", ",", "self", "[", "b'in-reply-to'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "IndexError...
The ``In-Reply-To`` header.
[ "The", "In", "-", "Reply", "-", "To", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L135-L140
train
22,720
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.message_id
def message_id(self) -> Optional[UnstructuredHeader]: """The ``Message-Id`` header.""" try: return cast(UnstructuredHeader, self[b'message-id'][0]) except (KeyError, IndexError): return None
python
def message_id(self) -> Optional[UnstructuredHeader]: """The ``Message-Id`` header.""" try: return cast(UnstructuredHeader, self[b'message-id'][0]) except (KeyError, IndexError): return None
[ "def", "message_id", "(", "self", ")", "->", "Optional", "[", "UnstructuredHeader", "]", ":", "try", ":", "return", "cast", "(", "UnstructuredHeader", ",", "self", "[", "b'message-id'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "IndexError",...
The ``Message-Id`` header.
[ "The", "Message", "-", "Id", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L143-L148
train
22,721
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.content_disposition
def content_disposition(self) -> Optional[ContentDispositionHeader]: """The ``Content-Disposition`` header.""" try: return cast(ContentDispositionHeader, self[b'content-disposition'][0]) except (KeyError, IndexError): return None
python
def content_disposition(self) -> Optional[ContentDispositionHeader]: """The ``Content-Disposition`` header.""" try: return cast(ContentDispositionHeader, self[b'content-disposition'][0]) except (KeyError, IndexError): return None
[ "def", "content_disposition", "(", "self", ")", "->", "Optional", "[", "ContentDispositionHeader", "]", ":", "try", ":", "return", "cast", "(", "ContentDispositionHeader", ",", "self", "[", "b'content-disposition'", "]", "[", "0", "]", ")", "except", "(", "Key...
The ``Content-Disposition`` header.
[ "The", "Content", "-", "Disposition", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L151-L157
train
22,722
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.content_language
def content_language(self) -> Optional[UnstructuredHeader]: """The ``Content-Language`` header.""" try: return cast(UnstructuredHeader, self[b'content-language'][0]) except (KeyError, IndexError): return None
python
def content_language(self) -> Optional[UnstructuredHeader]: """The ``Content-Language`` header.""" try: return cast(UnstructuredHeader, self[b'content-language'][0]) except (KeyError, IndexError): return None
[ "def", "content_language", "(", "self", ")", "->", "Optional", "[", "UnstructuredHeader", "]", ":", "try", ":", "return", "cast", "(", "UnstructuredHeader", ",", "self", "[", "b'content-language'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "...
The ``Content-Language`` header.
[ "The", "Content", "-", "Language", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L160-L165
train
22,723
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.content_location
def content_location(self) -> Optional[UnstructuredHeader]: """The ``Content-Location`` header.""" try: return cast(UnstructuredHeader, self[b'content-location'][0]) except (KeyError, IndexError): return None
python
def content_location(self) -> Optional[UnstructuredHeader]: """The ``Content-Location`` header.""" try: return cast(UnstructuredHeader, self[b'content-location'][0]) except (KeyError, IndexError): return None
[ "def", "content_location", "(", "self", ")", "->", "Optional", "[", "UnstructuredHeader", "]", ":", "try", ":", "return", "cast", "(", "UnstructuredHeader", ",", "self", "[", "b'content-location'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "...
The ``Content-Location`` header.
[ "The", "Content", "-", "Location", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L168-L173
train
22,724
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.content_id
def content_id(self) -> Optional[UnstructuredHeader]: """The ``Content-Id`` header.""" try: return cast(UnstructuredHeader, self[b'content-id'][0]) except (KeyError, IndexError): return None
python
def content_id(self) -> Optional[UnstructuredHeader]: """The ``Content-Id`` header.""" try: return cast(UnstructuredHeader, self[b'content-id'][0]) except (KeyError, IndexError): return None
[ "def", "content_id", "(", "self", ")", "->", "Optional", "[", "UnstructuredHeader", "]", ":", "try", ":", "return", "cast", "(", "UnstructuredHeader", ",", "self", "[", "b'content-id'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "IndexError",...
The ``Content-Id`` header.
[ "The", "Content", "-", "Id", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L176-L181
train
22,725
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.content_description
def content_description(self) -> Optional[UnstructuredHeader]: """The ``Content-Description`` header.""" try: return cast(UnstructuredHeader, self[b'content-description'][0]) except (KeyError, IndexError): return None
python
def content_description(self) -> Optional[UnstructuredHeader]: """The ``Content-Description`` header.""" try: return cast(UnstructuredHeader, self[b'content-description'][0]) except (KeyError, IndexError): return None
[ "def", "content_description", "(", "self", ")", "->", "Optional", "[", "UnstructuredHeader", "]", ":", "try", ":", "return", "cast", "(", "UnstructuredHeader", ",", "self", "[", "b'content-description'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",...
The ``Content-Description`` header.
[ "The", "Content", "-", "Description", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L184-L189
train
22,726
icgood/pymap
pymap/mime/parsed.py
ParsedHeaders.content_transfer_encoding
def content_transfer_encoding(self) \ -> Optional[ContentTransferEncodingHeader]: """The ``Content-Transfer-Encoding`` header.""" try: return cast(ContentTransferEncodingHeader, self[b'content-transfer-encoding'][0]) except (KeyError, IndexError): return None
python
def content_transfer_encoding(self) \ -> Optional[ContentTransferEncodingHeader]: """The ``Content-Transfer-Encoding`` header.""" try: return cast(ContentTransferEncodingHeader, self[b'content-transfer-encoding'][0]) except (KeyError, IndexError): return None
[ "def", "content_transfer_encoding", "(", "self", ")", "->", "Optional", "[", "ContentTransferEncodingHeader", "]", ":", "try", ":", "return", "cast", "(", "ContentTransferEncodingHeader", ",", "self", "[", "b'content-transfer-encoding'", "]", "[", "0", "]", ")", "...
The ``Content-Transfer-Encoding`` header.
[ "The", "Content", "-", "Transfer", "-", "Encoding", "header", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L192-L199
train
22,727
icgood/pymap
pymap/parsing/__init__.py
Params.copy
def copy(self, *, continuations: List[memoryview] = None, expected: Sequence[Type['Parseable']] = None, list_expected: Sequence[Type['Parseable']] = None, command_name: bytes = None, uid: bool = None, charset: str = None, tag: bytes = None, max_append_len: int = None, allow_continuations: bool = None) -> 'Params': """Copy the parameters, possibly replacing a subset.""" kwargs: Dict[str, Any] = {} self._set_if_none(kwargs, 'continuations', continuations) self._set_if_none(kwargs, 'expected', expected) self._set_if_none(kwargs, 'list_expected', list_expected) self._set_if_none(kwargs, 'command_name', command_name) self._set_if_none(kwargs, 'uid', uid) self._set_if_none(kwargs, 'charset', charset) self._set_if_none(kwargs, 'tag', tag) self._set_if_none(kwargs, 'max_append_len', max_append_len) self._set_if_none(kwargs, 'allow_continuations', allow_continuations) return Params(**kwargs)
python
def copy(self, *, continuations: List[memoryview] = None, expected: Sequence[Type['Parseable']] = None, list_expected: Sequence[Type['Parseable']] = None, command_name: bytes = None, uid: bool = None, charset: str = None, tag: bytes = None, max_append_len: int = None, allow_continuations: bool = None) -> 'Params': """Copy the parameters, possibly replacing a subset.""" kwargs: Dict[str, Any] = {} self._set_if_none(kwargs, 'continuations', continuations) self._set_if_none(kwargs, 'expected', expected) self._set_if_none(kwargs, 'list_expected', list_expected) self._set_if_none(kwargs, 'command_name', command_name) self._set_if_none(kwargs, 'uid', uid) self._set_if_none(kwargs, 'charset', charset) self._set_if_none(kwargs, 'tag', tag) self._set_if_none(kwargs, 'max_append_len', max_append_len) self._set_if_none(kwargs, 'allow_continuations', allow_continuations) return Params(**kwargs)
[ "def", "copy", "(", "self", ",", "*", ",", "continuations", ":", "List", "[", "memoryview", "]", "=", "None", ",", "expected", ":", "Sequence", "[", "Type", "[", "'Parseable'", "]", "]", "=", "None", ",", "list_expected", ":", "Sequence", "[", "Type", ...
Copy the parameters, possibly replacing a subset.
[ "Copy", "the", "parameters", "possibly", "replacing", "a", "subset", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/__init__.py#L66-L86
train
22,728
icgood/pymap
pymap/parsing/response/code.py
Capability.string
def string(self) -> bytes: """The capabilities string without the enclosing square brackets.""" if self._raw is not None: return self._raw self._raw = raw = BytesFormat(b' ').join( [b'CAPABILITY', b'IMAP4rev1'] + self.capabilities) return raw
python
def string(self) -> bytes: """The capabilities string without the enclosing square brackets.""" if self._raw is not None: return self._raw self._raw = raw = BytesFormat(b' ').join( [b'CAPABILITY', b'IMAP4rev1'] + self.capabilities) return raw
[ "def", "string", "(", "self", ")", "->", "bytes", ":", "if", "self", ".", "_raw", "is", "not", "None", ":", "return", "self", ".", "_raw", "self", ".", "_raw", "=", "raw", "=", "BytesFormat", "(", "b' '", ")", ".", "join", "(", "[", "b'CAPABILITY'"...
The capabilities string without the enclosing square brackets.
[ "The", "capabilities", "string", "without", "the", "enclosing", "square", "brackets", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/code.py#L29-L35
train
22,729
icgood/pymap
pymap/parsing/response/__init__.py
Response.text
def text(self) -> bytes: """The response text.""" if self.condition: if self.code: return BytesFormat(b'%b %b %b') \ % (self.condition, self.code, self._text) else: return BytesFormat(b'%b %b') % (self.condition, self._text) else: return bytes(self._text)
python
def text(self) -> bytes: """The response text.""" if self.condition: if self.code: return BytesFormat(b'%b %b %b') \ % (self.condition, self.code, self._text) else: return BytesFormat(b'%b %b') % (self.condition, self._text) else: return bytes(self._text)
[ "def", "text", "(", "self", ")", "->", "bytes", ":", "if", "self", ".", "condition", ":", "if", "self", ".", "code", ":", "return", "BytesFormat", "(", "b'%b %b %b'", ")", "%", "(", "self", ".", "condition", ",", "self", ".", "code", ",", "self", "...
The response text.
[ "The", "response", "text", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L81-L90
train
22,730
icgood/pymap
pymap/parsing/response/__init__.py
Response.add_untagged
def add_untagged(self, *responses: 'Response') -> None: """Add an untagged response. These responses are shown before the parent response. Args: responses: The untagged responses to add. """ for resp in responses: try: merge_key = resp.merge_key except TypeError: self._untagged.append(resp) else: key = (type(resp), merge_key) try: untagged_idx = self._mergeable[key] except KeyError: untagged_idx = len(self._untagged) self._mergeable[key] = untagged_idx self._untagged.append(resp) else: merged = self._untagged[untagged_idx].merge(resp) self._untagged[untagged_idx] = merged self._raw = None
python
def add_untagged(self, *responses: 'Response') -> None: """Add an untagged response. These responses are shown before the parent response. Args: responses: The untagged responses to add. """ for resp in responses: try: merge_key = resp.merge_key except TypeError: self._untagged.append(resp) else: key = (type(resp), merge_key) try: untagged_idx = self._mergeable[key] except KeyError: untagged_idx = len(self._untagged) self._mergeable[key] = untagged_idx self._untagged.append(resp) else: merged = self._untagged[untagged_idx].merge(resp) self._untagged[untagged_idx] = merged self._raw = None
[ "def", "add_untagged", "(", "self", ",", "*", "responses", ":", "'Response'", ")", "->", "None", ":", "for", "resp", "in", "responses", ":", "try", ":", "merge_key", "=", "resp", ".", "merge_key", "except", "TypeError", ":", "self", ".", "_untagged", "."...
Add an untagged response. These responses are shown before the parent response. Args: responses: The untagged responses to add.
[ "Add", "an", "untagged", "response", ".", "These", "responses", "are", "shown", "before", "the", "parent", "response", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L102-L126
train
22,731
icgood/pymap
pymap/parsing/response/__init__.py
Response.add_untagged_ok
def add_untagged_ok(self, text: MaybeBytes, code: Optional[ResponseCode] = None) -> None: """Add an untagged ``OK`` response. See Also: :meth:`.add_untagged`, :class:`ResponseOk` Args: text: The response text. code: Optional response code. """ response = ResponseOk(b'*', text, code) self.add_untagged(response)
python
def add_untagged_ok(self, text: MaybeBytes, code: Optional[ResponseCode] = None) -> None: """Add an untagged ``OK`` response. See Also: :meth:`.add_untagged`, :class:`ResponseOk` Args: text: The response text. code: Optional response code. """ response = ResponseOk(b'*', text, code) self.add_untagged(response)
[ "def", "add_untagged_ok", "(", "self", ",", "text", ":", "MaybeBytes", ",", "code", ":", "Optional", "[", "ResponseCode", "]", "=", "None", ")", "->", "None", ":", "response", "=", "ResponseOk", "(", "b'*'", ",", "text", ",", "code", ")", "self", ".", ...
Add an untagged ``OK`` response. See Also: :meth:`.add_untagged`, :class:`ResponseOk` Args: text: The response text. code: Optional response code.
[ "Add", "an", "untagged", "OK", "response", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L128-L141
train
22,732
icgood/pymap
pymap/parsing/response/__init__.py
Response.is_terminal
def is_terminal(self) -> bool: """True if the response contained an untagged ``BYE`` response indicating that the session should be terminated. """ for resp in self._untagged: if resp.is_terminal: return True return False
python
def is_terminal(self) -> bool: """True if the response contained an untagged ``BYE`` response indicating that the session should be terminated. """ for resp in self._untagged: if resp.is_terminal: return True return False
[ "def", "is_terminal", "(", "self", ")", "->", "bool", ":", "for", "resp", "in", "self", ".", "_untagged", ":", "if", "resp", ".", "is_terminal", ":", "return", "True", "return", "False" ]
True if the response contained an untagged ``BYE`` response indicating that the session should be terminated.
[ "True", "if", "the", "response", "contained", "an", "untagged", "BYE", "response", "indicating", "that", "the", "session", "should", "be", "terminated", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L144-L152
train
22,733
icgood/pymap
pymap/parsing/specials/sequenceset.py
SequenceSet.is_all
def is_all(self) -> bool: """True if the sequence set starts at ``1`` and ends at the maximum value. This may be used to optimize cases of checking for a value in the set, avoiding the need to provide ``max_value`` in :meth:`.flatten` or :meth:`.iter`. """ first = self.sequences[0] return isinstance(first, tuple) \ and first[0] == 1 and isinstance(first[1], MaxValue)
python
def is_all(self) -> bool: """True if the sequence set starts at ``1`` and ends at the maximum value. This may be used to optimize cases of checking for a value in the set, avoiding the need to provide ``max_value`` in :meth:`.flatten` or :meth:`.iter`. """ first = self.sequences[0] return isinstance(first, tuple) \ and first[0] == 1 and isinstance(first[1], MaxValue)
[ "def", "is_all", "(", "self", ")", "->", "bool", ":", "first", "=", "self", ".", "sequences", "[", "0", "]", "return", "isinstance", "(", "first", ",", "tuple", ")", "and", "first", "[", "0", "]", "==", "1", "and", "isinstance", "(", "first", "[", ...
True if the sequence set starts at ``1`` and ends at the maximum value. This may be used to optimize cases of checking for a value in the set, avoiding the need to provide ``max_value`` in :meth:`.flatten` or :meth:`.iter`.
[ "True", "if", "the", "sequence", "set", "starts", "at", "1", "and", "ends", "at", "the", "maximum", "value", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/sequenceset.py#L61-L72
train
22,734
icgood/pymap
pymap/parsing/specials/sequenceset.py
SequenceSet.flatten
def flatten(self, max_value: int) -> FrozenSet[int]: """Return a set of all values contained in the sequence set. Args: max_value: The maximum value, in place of any ``*``. """ return frozenset(self.iter(max_value))
python
def flatten(self, max_value: int) -> FrozenSet[int]: """Return a set of all values contained in the sequence set. Args: max_value: The maximum value, in place of any ``*``. """ return frozenset(self.iter(max_value))
[ "def", "flatten", "(", "self", ",", "max_value", ":", "int", ")", "->", "FrozenSet", "[", "int", "]", ":", "return", "frozenset", "(", "self", ".", "iter", "(", "max_value", ")", ")" ]
Return a set of all values contained in the sequence set. Args: max_value: The maximum value, in place of any ``*``.
[ "Return", "a", "set", "of", "all", "values", "contained", "in", "the", "sequence", "set", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/sequenceset.py#L96-L103
train
22,735
icgood/pymap
pymap/parsing/specials/sequenceset.py
SequenceSet.build
def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet': """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. """ 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] if isinstance(group, int): if group_i == group + 1: group = (group, group_i) else: groups.append(group) group = group_i elif isinstance(group, tuple): if group_i == group[1] + 1: group = (group[0], group_i) else: groups.append(group) group = group_i groups.append(group) return SequenceSet(groups, uid)
python
def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet': """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. """ 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] if isinstance(group, int): if group_i == group + 1: group = (group, group_i) else: groups.append(group) group = group_i elif isinstance(group, tuple): if group_i == group[1] + 1: group = (group[0], group_i) else: groups.append(group) group = group_i groups.append(group) return SequenceSet(groups, uid)
[ "def", "build", "(", "cls", ",", "seqs", ":", "Iterable", "[", "int", "]", ",", "uid", ":", "bool", "=", "False", ")", "->", "'SequenceSet'", ":", "seqs_list", "=", "sorted", "(", "set", "(", "seqs", ")", ")", "groups", ":", "List", "[", "Union", ...
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.
[ "Build", "a", "new", "sequence", "set", "that", "contains", "the", "given", "values", "using", "as", "few", "groups", "as", "possible", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/sequenceset.py#L173-L200
train
22,736
icgood/pymap
pymap/listtree.py
ListTree.update
def update(self, *names: str) -> 'ListTree': """Add all the mailbox names to the tree, filling in any missing nodes. Args: names: The names of the mailboxes. """ for name in names: parts = name.split(self._delimiter) self._root.add(*parts) return self
python
def update(self, *names: str) -> 'ListTree': """Add all the mailbox names to the tree, filling in any missing nodes. Args: names: The names of the mailboxes. """ for name in names: parts = name.split(self._delimiter) self._root.add(*parts) return self
[ "def", "update", "(", "self", ",", "*", "names", ":", "str", ")", "->", "'ListTree'", ":", "for", "name", "in", "names", ":", "parts", "=", "name", ".", "split", "(", "self", ".", "_delimiter", ")", "self", ".", "_root", ".", "add", "(", "*", "pa...
Add all the mailbox names to the tree, filling in any missing nodes. Args: names: The names of the mailboxes.
[ "Add", "all", "the", "mailbox", "names", "to", "the", "tree", "filling", "in", "any", "missing", "nodes", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L93-L103
train
22,737
icgood/pymap
pymap/listtree.py
ListTree.set_marked
def set_marked(self, name: str, marked: bool = False, unmarked: bool = False) -> None: """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. """ if marked: self._marked[name] = True elif unmarked: self._marked[name] = False else: self._marked.pop(name, None)
python
def set_marked(self, name: str, marked: bool = False, unmarked: bool = False) -> None: """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. """ if marked: self._marked[name] = True elif unmarked: self._marked[name] = False else: self._marked.pop(name, None)
[ "def", "set_marked", "(", "self", ",", "name", ":", "str", ",", "marked", ":", "bool", "=", "False", ",", "unmarked", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "marked", ":", "self", ".", "_marked", "[", "name", "]", "=", "True", "...
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.
[ "Add", "or", "remove", "the", "\\\\", "Marked", "and", "\\\\", "Unmarked", "mailbox", "attributes", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L105-L121
train
22,738
icgood/pymap
pymap/listtree.py
ListTree.get
def get(self, name: str) -> Optional[ListEntry]: """Return the named entry in the list tree. Args: name: The entry name. """ 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, marked, bool(node.children))
python
def get(self, name: str) -> Optional[ListEntry]: """Return the named entry in the list tree. Args: name: The entry name. """ 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, marked, bool(node.children))
[ "def", "get", "(", "self", ",", "name", ":", "str", ")", "->", "Optional", "[", "ListEntry", "]", ":", "parts", "=", "name", ".", "split", "(", "self", ".", "_delimiter", ")", "try", ":", "node", "=", "self", ".", "_find", "(", "self", ".", "_roo...
Return the named entry in the list tree. Args: name: The entry name.
[ "Return", "the", "named", "entry", "in", "the", "list", "tree", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L142-L156
train
22,739
icgood/pymap
pymap/listtree.py
ListTree.list
def list(self) -> Iterable[ListEntry]: """Return all the entries in the list tree.""" for entry in self._iter(self._root, ''): yield entry
python
def list(self) -> Iterable[ListEntry]: """Return all the entries in the list tree.""" for entry in self._iter(self._root, ''): yield entry
[ "def", "list", "(", "self", ")", "->", "Iterable", "[", "ListEntry", "]", ":", "for", "entry", "in", "self", ".", "_iter", "(", "self", ".", "_root", ",", "''", ")", ":", "yield", "entry" ]
Return all the entries in the list tree.
[ "Return", "all", "the", "entries", "in", "the", "list", "tree", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L186-L189
train
22,740
icgood/pymap
pymap/listtree.py
ListTree.list_matching
def list_matching(self, ref_name: str, filter_: str) \ -> Iterable[ListEntry]: """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. """ canonical, canonical_i = self._get_pattern(ref_name + filter_) for entry in self.list(): if entry.name == 'INBOX': if canonical_i.match('INBOX'): yield entry elif canonical.match(entry.name): yield entry
python
def list_matching(self, ref_name: str, filter_: str) \ -> Iterable[ListEntry]: """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. """ canonical, canonical_i = self._get_pattern(ref_name + filter_) for entry in self.list(): if entry.name == 'INBOX': if canonical_i.match('INBOX'): yield entry elif canonical.match(entry.name): yield entry
[ "def", "list_matching", "(", "self", ",", "ref_name", ":", "str", ",", "filter_", ":", "str", ")", "->", "Iterable", "[", "ListEntry", "]", ":", "canonical", ",", "canonical_i", "=", "self", ".", "_get_pattern", "(", "ref_name", "+", "filter_", ")", "for...
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.
[ "Return", "all", "the", "entries", "in", "the", "list", "tree", "that", "match", "the", "given", "query", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L203-L218
train
22,741
icgood/pymap
pymap/selected.py
SynchronizedMessages.get
def get(self, uid: int) -> Optional[CachedMessage]: """Return the given cached message. Args: uid: The message UID. """ return self._cache.get(uid)
python
def get(self, uid: int) -> Optional[CachedMessage]: """Return the given cached message. Args: uid: The message UID. """ return self._cache.get(uid)
[ "def", "get", "(", "self", ",", "uid", ":", "int", ")", "->", "Optional", "[", "CachedMessage", "]", ":", "return", "self", ".", "_cache", ".", "get", "(", "uid", ")" ]
Return the given cached message. Args: uid: The message UID.
[ "Return", "the", "given", "cached", "message", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L161-L168
train
22,742
icgood/pymap
pymap/selected.py
SynchronizedMessages.get_all
def get_all(self, seq_set: SequenceSet) \ -> Sequence[Tuple[int, CachedMessage]]: """Return the cached messages, and their sequence numbers, for the given sequence set. Args: seq_set: The message sequence set. """ 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) if uid in all_uids] else: all_seqs = seq_set.flatten(self.exists) return [(seq, self._cache[uid]) for seq, uid in enumerate(self._sorted, 1) if seq in all_seqs]
python
def get_all(self, seq_set: SequenceSet) \ -> Sequence[Tuple[int, CachedMessage]]: """Return the cached messages, and their sequence numbers, for the given sequence set. Args: seq_set: The message sequence set. """ 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) if uid in all_uids] else: all_seqs = seq_set.flatten(self.exists) return [(seq, self._cache[uid]) for seq, uid in enumerate(self._sorted, 1) if seq in all_seqs]
[ "def", "get_all", "(", "self", ",", "seq_set", ":", "SequenceSet", ")", "->", "Sequence", "[", "Tuple", "[", "int", ",", "CachedMessage", "]", "]", ":", "if", "seq_set", ".", "uid", ":", "all_uids", "=", "seq_set", ".", "flatten", "(", "self", ".", "...
Return the cached messages, and their sequence numbers, for the given sequence set. Args: seq_set: The message sequence set.
[ "Return", "the", "cached", "messages", "and", "their", "sequence", "numbers", "for", "the", "given", "sequence", "set", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L170-L188
train
22,743
icgood/pymap
pymap/selected.py
SelectedMailbox.add_updates
def add_updates(self, messages: Iterable[CachedMessage], expunged: Iterable[int]) -> None: """Update the messages in the selected mailboxes. The ``messages`` should include non-expunged messages in the mailbox that should be checked for updates. The ``expunged`` argument is the set of UIDs that have been expunged from the mailbox. In an optimized implementation, ``messages`` only includes new messages or messages with metadata updates. This minimizes the comparison needed to determine what untagged responses are necessary. The :attr:`.mod_sequence` attribute may be used to support this optimization. If a backend implementation lacks the ability to determine the subset of messages that have been updated, it should instead use :meth:`.set_messages`. Args: messages: The cached message objects to add. expunged: The set of message UIDs that have been expunged. """ self._messages._update(messages) self._messages._remove(expunged, self._hide_expunged) if not self._hide_expunged: self._session_flags.remove(expunged)
python
def add_updates(self, messages: Iterable[CachedMessage], expunged: Iterable[int]) -> None: """Update the messages in the selected mailboxes. The ``messages`` should include non-expunged messages in the mailbox that should be checked for updates. The ``expunged`` argument is the set of UIDs that have been expunged from the mailbox. In an optimized implementation, ``messages`` only includes new messages or messages with metadata updates. This minimizes the comparison needed to determine what untagged responses are necessary. The :attr:`.mod_sequence` attribute may be used to support this optimization. If a backend implementation lacks the ability to determine the subset of messages that have been updated, it should instead use :meth:`.set_messages`. Args: messages: The cached message objects to add. expunged: The set of message UIDs that have been expunged. """ self._messages._update(messages) self._messages._remove(expunged, self._hide_expunged) if not self._hide_expunged: self._session_flags.remove(expunged)
[ "def", "add_updates", "(", "self", ",", "messages", ":", "Iterable", "[", "CachedMessage", "]", ",", "expunged", ":", "Iterable", "[", "int", "]", ")", "->", "None", ":", "self", ".", "_messages", ".", "_update", "(", "messages", ")", "self", ".", "_me...
Update the messages in the selected mailboxes. The ``messages`` should include non-expunged messages in the mailbox that should be checked for updates. The ``expunged`` argument is the set of UIDs that have been expunged from the mailbox. In an optimized implementation, ``messages`` only includes new messages or messages with metadata updates. This minimizes the comparison needed to determine what untagged responses are necessary. The :attr:`.mod_sequence` attribute may be used to support this optimization. If a backend implementation lacks the ability to determine the subset of messages that have been updated, it should instead use :meth:`.set_messages`. Args: messages: The cached message objects to add. expunged: The set of message UIDs that have been expunged.
[ "Update", "the", "messages", "in", "the", "selected", "mailboxes", ".", "The", "messages", "should", "include", "non", "-", "expunged", "messages", "in", "the", "mailbox", "that", "should", "be", "checked", "for", "updates", ".", "The", "expunged", "argument",...
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L281-L306
train
22,744
icgood/pymap
pymap/selected.py
SelectedMailbox.silence
def silence(self, seq_set: SequenceSet, flag_set: AbstractSet[Flag], flag_op: FlagOp) -> None: """Runs the flags update against the cached flags, to prevent untagged FETCH responses unless other updates have occurred. For example, if a session adds ``\\Deleted`` and calls this method, the FETCH response will be silenced. But if another added ``\\Seen`` at the same time, the FETCH response will be sent. Args: seq_set: The sequence set of messages. flag_set: The set of flags for the update operation. flag_op: The mode to change the flags. """ session_flags = self.session_flags permanent_flag_set = self.permanent_flags & flag_set session_flag_set = session_flags & flag_set for seq, msg in self._messages.get_all(seq_set): msg_flags = msg.permanent_flags msg_sflags = session_flags.get(msg.uid) updated_flags = flag_op.apply(msg_flags, permanent_flag_set) updated_sflags = flag_op.apply(msg_sflags, session_flag_set) if msg_flags != updated_flags: self._silenced_flags.add((msg.uid, updated_flags)) if msg_sflags != updated_sflags: self._silenced_sflags.add((msg.uid, updated_sflags))
python
def silence(self, seq_set: SequenceSet, flag_set: AbstractSet[Flag], flag_op: FlagOp) -> None: """Runs the flags update against the cached flags, to prevent untagged FETCH responses unless other updates have occurred. For example, if a session adds ``\\Deleted`` and calls this method, the FETCH response will be silenced. But if another added ``\\Seen`` at the same time, the FETCH response will be sent. Args: seq_set: The sequence set of messages. flag_set: The set of flags for the update operation. flag_op: The mode to change the flags. """ session_flags = self.session_flags permanent_flag_set = self.permanent_flags & flag_set session_flag_set = session_flags & flag_set for seq, msg in self._messages.get_all(seq_set): msg_flags = msg.permanent_flags msg_sflags = session_flags.get(msg.uid) updated_flags = flag_op.apply(msg_flags, permanent_flag_set) updated_sflags = flag_op.apply(msg_sflags, session_flag_set) if msg_flags != updated_flags: self._silenced_flags.add((msg.uid, updated_flags)) if msg_sflags != updated_sflags: self._silenced_sflags.add((msg.uid, updated_sflags))
[ "def", "silence", "(", "self", ",", "seq_set", ":", "SequenceSet", ",", "flag_set", ":", "AbstractSet", "[", "Flag", "]", ",", "flag_op", ":", "FlagOp", ")", "->", "None", ":", "session_flags", "=", "self", ".", "session_flags", "permanent_flag_set", "=", ...
Runs the flags update against the cached flags, to prevent untagged FETCH responses unless other updates have occurred. For example, if a session adds ``\\Deleted`` and calls this method, the FETCH response will be silenced. But if another added ``\\Seen`` at the same time, the FETCH response will be sent. Args: seq_set: The sequence set of messages. flag_set: The set of flags for the update operation. flag_op: The mode to change the flags.
[ "Runs", "the", "flags", "update", "against", "the", "cached", "flags", "to", "prevent", "untagged", "FETCH", "responses", "unless", "other", "updates", "have", "occurred", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L349-L375
train
22,745
icgood/pymap
pymap/selected.py
SelectedMailbox.fork
def fork(self, command: Command) \ -> Tuple['SelectedMailbox', Iterable[Response]]: """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. """ frozen = _Frozen(self) cls = type(self) copy = cls(self._guid, self._readonly, self._permanent_flags, self._session_flags, self._selected_set, self._lookup, _mod_sequence=self._mod_sequence, _prev=frozen, _messages=self._messages) if self._prev is not None: with_uid: bool = getattr(command, 'uid', False) untagged = self._compare(self._prev, frozen, with_uid) else: untagged = [] return copy, untagged
python
def fork(self, command: Command) \ -> Tuple['SelectedMailbox', Iterable[Response]]: """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. """ frozen = _Frozen(self) cls = type(self) copy = cls(self._guid, self._readonly, self._permanent_flags, self._session_flags, self._selected_set, self._lookup, _mod_sequence=self._mod_sequence, _prev=frozen, _messages=self._messages) if self._prev is not None: with_uid: bool = getattr(command, 'uid', False) untagged = self._compare(self._prev, frozen, with_uid) else: untagged = [] return copy, untagged
[ "def", "fork", "(", "self", ",", "command", ":", "Command", ")", "->", "Tuple", "[", "'SelectedMailbox'", ",", "Iterable", "[", "Response", "]", "]", ":", "frozen", "=", "_Frozen", "(", "self", ")", "cls", "=", "type", "(", "self", ")", "copy", "=", ...
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.
[ "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", "return...
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L377-L398
train
22,746
icgood/pymap
pymap/parsing/command/select.py
IdleCommand.parse_done
def parse_done(self, buf: memoryview) -> Tuple[bool, memoryview]: """Parse the continuation line sent by the client to end the ``IDLE`` command. Args: buf: The continuation line to parse. """ 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
python
def parse_done(self, buf: memoryview) -> Tuple[bool, memoryview]: """Parse the continuation line sent by the client to end the ``IDLE`` command. Args: buf: The continuation line to parse. """ 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
[ "def", "parse_done", "(", "self", ",", "buf", ":", "memoryview", ")", "->", "Tuple", "[", "bool", ",", "memoryview", "]", ":", "match", "=", "self", ".", "_pattern", ".", "match", "(", "buf", ")", "if", "not", "match", ":", "raise", "NotParseable", "...
Parse the continuation line sent by the client to end the ``IDLE`` command. Args: buf: The continuation line to parse.
[ "Parse", "the", "continuation", "line", "sent", "by", "the", "client", "to", "end", "the", "IDLE", "command", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/command/select.py#L485-L498
train
22,747
icgood/pymap
pymap/backend/maildir/subscriptions.py
Subscriptions.set
def set(self, folder: str, subscribed: bool) -> None: """Set the subscribed status of a folder.""" if subscribed: self.add(folder) else: self.remove(folder)
python
def set(self, folder: str, subscribed: bool) -> None: """Set the subscribed status of a folder.""" if subscribed: self.add(folder) else: self.remove(folder)
[ "def", "set", "(", "self", ",", "folder", ":", "str", ",", "subscribed", ":", "bool", ")", "->", "None", ":", "if", "subscribed", ":", "self", ".", "add", "(", "folder", ")", "else", ":", "self", ".", "remove", "(", "folder", ")" ]
Set the subscribed status of a folder.
[ "Set", "the", "subscribed", "status", "of", "a", "folder", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/subscriptions.py#L41-L46
train
22,748
icgood/pymap
pymap/mailbox.py
MailboxSnapshot.new_uid_validity
def new_uid_validity(cls) -> int: """Generate a new UID validity value for a mailbox, where the first two bytes are time-based and the second two bytes are random. """ time_part = int(time.time()) % 4096 rand_part = random.randint(0, 1048576) return (time_part << 20) + rand_part
python
def new_uid_validity(cls) -> int: """Generate a new UID validity value for a mailbox, where the first two bytes are time-based and the second two bytes are random. """ time_part = int(time.time()) % 4096 rand_part = random.randint(0, 1048576) return (time_part << 20) + rand_part
[ "def", "new_uid_validity", "(", "cls", ")", "->", "int", ":", "time_part", "=", "int", "(", "time", ".", "time", "(", ")", ")", "%", "4096", "rand_part", "=", "random", ".", "randint", "(", "0", ",", "1048576", ")", "return", "(", "time_part", "<<", ...
Generate a new UID validity value for a mailbox, where the first two bytes are time-based and the second two bytes are random.
[ "Generate", "a", "new", "UID", "validity", "value", "for", "a", "mailbox", "where", "the", "first", "two", "bytes", "are", "time", "-", "based", "and", "the", "second", "two", "bytes", "are", "random", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mailbox.py#L56-L63
train
22,749
icgood/pymap
pymap/backend/maildir/flags.py
MaildirFlags.to_maildir
def to_maildir(self, flags: Iterable[Union[bytes, Flag]]) -> str: """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. """ 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) else: from_kwd = self._from_kwd.get(flag) if from_kwd is not None: codes.append(from_kwd) return ''.join(codes)
python
def to_maildir(self, flags: Iterable[Union[bytes, Flag]]) -> str: """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. """ 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) else: from_kwd = self._from_kwd.get(flag) if from_kwd is not None: codes.append(from_kwd) return ''.join(codes)
[ "def", "to_maildir", "(", "self", ",", "flags", ":", "Iterable", "[", "Union", "[", "bytes", ",", "Flag", "]", "]", ")", "->", "str", ":", "codes", "=", "[", "]", "for", "flag", "in", "flags", ":", "if", "isinstance", "(", "flag", ",", "bytes", "...
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.
[ "Return", "the", "string", "of", "letter", "codes", "that", "are", "used", "to", "map", "to", "defined", "IMAP", "flags", "and", "keywords", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/flags.py#L71-L90
train
22,750
icgood/pymap
pymap/backend/maildir/flags.py
MaildirFlags.from_maildir
def from_maildir(self, codes: str) -> FrozenSet[Flag]: """Return the set of IMAP flags that correspond to the letter codes. Args: codes: The letter codes to map. """ 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 = self._to_kwd.get(code) if to_kwd is not None: flags.add(to_kwd) return frozenset(flags)
python
def from_maildir(self, codes: str) -> FrozenSet[Flag]: """Return the set of IMAP flags that correspond to the letter codes. Args: codes: The letter codes to map. """ 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 = self._to_kwd.get(code) if to_kwd is not None: flags.add(to_kwd) return frozenset(flags)
[ "def", "from_maildir", "(", "self", ",", "codes", ":", "str", ")", "->", "FrozenSet", "[", "Flag", "]", ":", "flags", "=", "set", "(", ")", "for", "code", "in", "codes", ":", "if", "code", "==", "','", ":", "break", "to_sys", "=", "self", ".", "_...
Return the set of IMAP flags that correspond to the letter codes. Args: codes: The letter codes to map.
[ "Return", "the", "set", "of", "IMAP", "flags", "that", "correspond", "to", "the", "letter", "codes", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/flags.py#L92-L110
train
22,751
icgood/pymap
pymap/backend/dict/__init__.py
Session.login
async def login(cls, credentials: AuthenticationCredentials, config: Config) -> 'Session': """Checks the given credentials for a valid login and returns a new session. The mailbox data is shared between concurrent and future sessions, but only for the lifetime of the process. """ user = credentials.authcid password = cls._get_password(config, user) if user != credentials.identity: raise InvalidAuth() elif not credentials.check_secret(password): raise InvalidAuth() mailbox_set, filter_set = config.set_cache.get(user, (None, None)) if not mailbox_set or not filter_set: mailbox_set = MailboxSet() filter_set = FilterSet() if config.demo_data: await cls._load_demo(mailbox_set, filter_set) config.set_cache[user] = (mailbox_set, filter_set) return cls(credentials.identity, config, mailbox_set, filter_set)
python
async def login(cls, credentials: AuthenticationCredentials, config: Config) -> 'Session': """Checks the given credentials for a valid login and returns a new session. The mailbox data is shared between concurrent and future sessions, but only for the lifetime of the process. """ user = credentials.authcid password = cls._get_password(config, user) if user != credentials.identity: raise InvalidAuth() elif not credentials.check_secret(password): raise InvalidAuth() mailbox_set, filter_set = config.set_cache.get(user, (None, None)) if not mailbox_set or not filter_set: mailbox_set = MailboxSet() filter_set = FilterSet() if config.demo_data: await cls._load_demo(mailbox_set, filter_set) config.set_cache[user] = (mailbox_set, filter_set) return cls(credentials.identity, config, mailbox_set, filter_set)
[ "async", "def", "login", "(", "cls", ",", "credentials", ":", "AuthenticationCredentials", ",", "config", ":", "Config", ")", "->", "'Session'", ":", "user", "=", "credentials", ".", "authcid", "password", "=", "cls", ".", "_get_password", "(", "config", ","...
Checks the given credentials for a valid login and returns a new session. The mailbox data is shared between concurrent and future sessions, but only for the lifetime of the process.
[ "Checks", "the", "given", "credentials", "for", "a", "valid", "login", "and", "returns", "a", "new", "session", ".", "The", "mailbox", "data", "is", "shared", "between", "concurrent", "and", "future", "sessions", "but", "only", "for", "the", "lifetime", "of"...
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/dict/__init__.py#L125-L145
train
22,752
icgood/pymap
pymap/mime/cte.py
MessageDecoder.of
def of(cls, msg_header: MessageHeader) -> 'MessageDecoder': """Return a decoder from the message header object. See Also: :meth:`.of_cte` Args: msg_header: The message header object. """ cte_hdr = msg_header.parsed.content_transfer_encoding return cls.of_cte(cte_hdr)
python
def of(cls, msg_header: MessageHeader) -> 'MessageDecoder': """Return a decoder from the message header object. See Also: :meth:`.of_cte` Args: msg_header: The message header object. """ cte_hdr = msg_header.parsed.content_transfer_encoding return cls.of_cte(cte_hdr)
[ "def", "of", "(", "cls", ",", "msg_header", ":", "MessageHeader", ")", "->", "'MessageDecoder'", ":", "cte_hdr", "=", "msg_header", ".", "parsed", ".", "content_transfer_encoding", "return", "cls", ".", "of_cte", "(", "cte_hdr", ")" ]
Return a decoder from the message header object. See Also: :meth:`.of_cte` Args: msg_header: The message header object.
[ "Return", "a", "decoder", "from", "the", "message", "header", "object", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/cte.py#L27-L38
train
22,753
icgood/pymap
pymap/mime/cte.py
MessageDecoder.of_cte
def of_cte(cls, header: Optional[ContentTransferEncodingHeader]) \ -> 'MessageDecoder': """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. """ 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 hdr_str in ('7bit', '8bit'): return _NoopDecoder() elif hdr_str == 'quoted-printable': return _QuotedPrintableDecoder() elif hdr_str == 'base64': return _Base64Decoder() else: raise NotImplementedError(hdr_str)
python
def of_cte(cls, header: Optional[ContentTransferEncodingHeader]) \ -> 'MessageDecoder': """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. """ 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 hdr_str in ('7bit', '8bit'): return _NoopDecoder() elif hdr_str == 'quoted-printable': return _QuotedPrintableDecoder() elif hdr_str == 'base64': return _Base64Decoder() else: raise NotImplementedError(hdr_str)
[ "def", "of_cte", "(", "cls", ",", "header", ":", "Optional", "[", "ContentTransferEncodingHeader", "]", ")", "->", "'MessageDecoder'", ":", "if", "header", "is", "None", ":", "return", "_NoopDecoder", "(", ")", "hdr_str", "=", "str", "(", "header", ")", "....
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.
[ "Return", "a", "decoder", "from", "the", "CTE", "header", "value", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/cte.py#L41-L66
train
22,754
icgood/pymap
pymap/backend/maildir/__init__.py
Session.find_user
async def find_user(cls, config: Config, user: str) \ -> Tuple[str, str]: """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. """ 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 password.rstrip('\r\n'), user_dir or user raise InvalidAuth()
python
async def find_user(cls, config: Config, user: str) \ -> Tuple[str, str]: """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. """ 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 password.rstrip('\r\n'), user_dir or user raise InvalidAuth()
[ "async", "def", "find_user", "(", "cls", ",", "config", ":", "Config", ",", "user", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "with", "open", "(", "config", ".", "users_file", ",", "'r'", ")", "as", "users_file", ":", "for",...
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.
[ "If", "the", "given", "user", "ID", "exists", "return", "its", "expected", "password", "and", "mailbox", "path", ".", "Override", "this", "method", "to", "implement", "custom", "login", "logic", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/__init__.py#L208-L226
train
22,755
icgood/pymap
pymap/parsing/modutf7.py
modutf7_encode
def modutf7_encode(data: str) -> bytes: """Encode the string using modified UTF-7. Args: data: The input string to encode. """ 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: ret.append(charpoint) else: encode_start = i is_usascii = False else: if 0x20 <= charpoint <= 0x7e: to_encode = data[encode_start:i] encoded = _modified_b64encode(to_encode) ret.append(0x26) ret.extend(encoded) ret.extend((0x2d, charpoint)) is_usascii = True if not is_usascii: to_encode = data[encode_start:] encoded = _modified_b64encode(to_encode) ret.append(0x26) ret.extend(encoded) ret.append(0x2d) return bytes(ret)
python
def modutf7_encode(data: str) -> bytes: """Encode the string using modified UTF-7. Args: data: The input string to encode. """ 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: ret.append(charpoint) else: encode_start = i is_usascii = False else: if 0x20 <= charpoint <= 0x7e: to_encode = data[encode_start:i] encoded = _modified_b64encode(to_encode) ret.append(0x26) ret.extend(encoded) ret.extend((0x2d, charpoint)) is_usascii = True if not is_usascii: to_encode = data[encode_start:] encoded = _modified_b64encode(to_encode) ret.append(0x26) ret.extend(encoded) ret.append(0x2d) return bytes(ret)
[ "def", "modutf7_encode", "(", "data", ":", "str", ")", "->", "bytes", ":", "ret", "=", "bytearray", "(", ")", "is_usascii", "=", "True", "encode_start", "=", "None", "for", "i", ",", "symbol", "in", "enumerate", "(", "data", ")", ":", "charpoint", "=",...
Encode the string using modified UTF-7. Args: data: The input string to encode.
[ "Encode", "the", "string", "using", "modified", "UTF", "-", "7", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/modutf7.py#L26-L60
train
22,756
icgood/pymap
pymap/parsing/modutf7.py
modutf7_decode
def modutf7_decode(data: bytes) -> str: """Decode the bytestring using modified UTF-7. Args: data: The encoded bytestring to decode. """ 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_usascii = False buf = buf[1:] else: parts.append(chr(byte)) buf = buf[1:] else: for i, byte in enumerate(buf): if byte == 0x2d: to_decode = buf[:i].tobytes() decoded = _modified_b64decode(to_decode) parts.append(decoded) buf = buf[i + 1:] is_usascii = True break if not is_usascii: to_decode = buf.tobytes() decoded = _modified_b64decode(to_decode) parts.append(decoded) return ''.join(parts)
python
def modutf7_decode(data: bytes) -> str: """Decode the bytestring using modified UTF-7. Args: data: The encoded bytestring to decode. """ 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_usascii = False buf = buf[1:] else: parts.append(chr(byte)) buf = buf[1:] else: for i, byte in enumerate(buf): if byte == 0x2d: to_decode = buf[:i].tobytes() decoded = _modified_b64decode(to_decode) parts.append(decoded) buf = buf[i + 1:] is_usascii = True break if not is_usascii: to_decode = buf.tobytes() decoded = _modified_b64decode(to_decode) parts.append(decoded) return ''.join(parts)
[ "def", "modutf7_decode", "(", "data", ":", "bytes", ")", "->", "str", ":", "parts", "=", "[", "]", "is_usascii", "=", "True", "buf", "=", "memoryview", "(", "data", ")", "while", "buf", ":", "byte", "=", "buf", "[", "0", "]", "if", "is_usascii", ":...
Decode the bytestring using modified UTF-7. Args: data: The encoded bytestring to decode.
[ "Decode", "the", "bytestring", "using", "modified", "UTF", "-", "7", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/modutf7.py#L63-L98
train
22,757
icgood/pymap
pymap/bytes.py
BytesFormat.format
def format(self, data: Iterable[_FormatArg]) -> bytes: """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') """ fix_arg = self._fix_format_arg return self.how % tuple(fix_arg(item) for item in data)
python
def format(self, data: Iterable[_FormatArg]) -> bytes: """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') """ fix_arg = self._fix_format_arg return self.how % tuple(fix_arg(item) for item in data)
[ "def", "format", "(", "self", ",", "data", ":", "Iterable", "[", "_FormatArg", "]", ")", "->", "bytes", ":", "fix_arg", "=", "self", ".", "_fix_format_arg", "return", "self", ".", "how", "%", "tuple", "(", "fix_arg", "(", "item", ")", "for", "item", ...
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')
[ "String", "interpolation", "into", "the", "format", "string", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/bytes.py#L179-L193
train
22,758
icgood/pymap
pymap/bytes.py
BytesFormat.join
def join(self, *data: Iterable[MaybeBytes]) -> bytes: """Iterable join on a delimiter. Args: data: Iterable of items to join. Examples: :: BytesFormat(b' ').join([b'one', b'two', b'three']) """ return self.how.join([bytes(item) for item in chain(*data)])
python
def join(self, *data: Iterable[MaybeBytes]) -> bytes: """Iterable join on a delimiter. Args: data: Iterable of items to join. Examples: :: BytesFormat(b' ').join([b'one', b'two', b'three']) """ return self.how.join([bytes(item) for item in chain(*data)])
[ "def", "join", "(", "self", ",", "*", "data", ":", "Iterable", "[", "MaybeBytes", "]", ")", "->", "bytes", ":", "return", "self", ".", "how", ".", "join", "(", "[", "bytes", "(", "item", ")", "for", "item", "in", "chain", "(", "*", "data", ")", ...
Iterable join on a delimiter. Args: data: Iterable of items to join. Examples: :: BytesFormat(b' ').join([b'one', b'two', b'three'])
[ "Iterable", "join", "on", "a", "delimiter", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/bytes.py#L195-L207
train
22,759
icgood/pymap
pymap/interfaces/filter.py
FilterInterface.apply
async def apply(self, sender: str, recipient: str, mailbox: str, append_msg: AppendMessage) \ -> Tuple[Optional[str], AppendMessage]: """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. mailbox: The intended mailbox to append the message. append_msg: The message to be appended. raises: :exc:`~pymap.exceptions.AppendFailure` """ ...
python
async def apply(self, sender: str, recipient: str, mailbox: str, append_msg: AppendMessage) \ -> Tuple[Optional[str], AppendMessage]: """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. mailbox: The intended mailbox to append the message. append_msg: The message to be appended. raises: :exc:`~pymap.exceptions.AppendFailure` """ ...
[ "async", "def", "apply", "(", "self", ",", "sender", ":", "str", ",", "recipient", ":", "str", ",", "mailbox", ":", "str", ",", "append_msg", ":", "AppendMessage", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "AppendMessage", "]", ":", ...
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. mailbox: The intended mailbox to append the message. append_msg: The message to be appended. raises: :exc:`~pymap.exceptions.AppendFailure`
[ "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", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/filter.py#L23-L40
train
22,760
icgood/pymap
pymap/interfaces/session.py
SessionInterface.list_mailboxes
async def list_mailboxes(self, ref_name: str, filter_: str, subscribed: bool = False, selected: SelectedMailbox = None) \ -> Tuple[Iterable[Tuple[str, Optional[str], Sequence[bytes]]], Optional[SelectedMailbox]]: """List the mailboxes owned by the user. See Also: `RFC 3501 6.3.8. <https://tools.ietf.org/html/rfc3501#section-6.3.8>`_, `RFC 3501 6.3.9. <https://tools.ietf.org/html/rfc3501#section-6.3.9>`_ Args: ref_name: Mailbox reference name. filter_: Mailbox name with possible wildcards. subscribed: If True, only list the subscribed mailboxes. selected: If applicable, the currently selected mailbox name. """ ...
python
async def list_mailboxes(self, ref_name: str, filter_: str, subscribed: bool = False, selected: SelectedMailbox = None) \ -> Tuple[Iterable[Tuple[str, Optional[str], Sequence[bytes]]], Optional[SelectedMailbox]]: """List the mailboxes owned by the user. See Also: `RFC 3501 6.3.8. <https://tools.ietf.org/html/rfc3501#section-6.3.8>`_, `RFC 3501 6.3.9. <https://tools.ietf.org/html/rfc3501#section-6.3.9>`_ Args: ref_name: Mailbox reference name. filter_: Mailbox name with possible wildcards. subscribed: If True, only list the subscribed mailboxes. selected: If applicable, the currently selected mailbox name. """ ...
[ "async", "def", "list_mailboxes", "(", "self", ",", "ref_name", ":", "str", ",", "filter_", ":", "str", ",", "subscribed", ":", "bool", "=", "False", ",", "selected", ":", "SelectedMailbox", "=", "None", ")", "->", "Tuple", "[", "Iterable", "[", "Tuple",...
List the mailboxes owned by the user. See Also: `RFC 3501 6.3.8. <https://tools.ietf.org/html/rfc3501#section-6.3.8>`_, `RFC 3501 6.3.9. <https://tools.ietf.org/html/rfc3501#section-6.3.9>`_ Args: ref_name: Mailbox reference name. filter_: Mailbox name with possible wildcards. subscribed: If True, only list the subscribed mailboxes. selected: If applicable, the currently selected mailbox name.
[ "List", "the", "mailboxes", "owned", "by", "the", "user", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L70-L90
train
22,761
icgood/pymap
pymap/interfaces/session.py
SessionInterface.rename_mailbox
async def rename_mailbox(self, before_name: str, after_name: str, selected: SelectedMailbox = None) \ -> Optional[SelectedMailbox]: """Renames the mailbox owned by the user. See Also: `RFC 3501 6.3.5. <https://tools.ietf.org/html/rfc3501#section-6.3.5>`_ Args: before_name: The name of the mailbox before the rename. after_name: The name of the mailbox after the rename. selected: If applicable, the currently selected mailbox name. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxConflict` """ ...
python
async def rename_mailbox(self, before_name: str, after_name: str, selected: SelectedMailbox = None) \ -> Optional[SelectedMailbox]: """Renames the mailbox owned by the user. See Also: `RFC 3501 6.3.5. <https://tools.ietf.org/html/rfc3501#section-6.3.5>`_ Args: before_name: The name of the mailbox before the rename. after_name: The name of the mailbox after the rename. selected: If applicable, the currently selected mailbox name. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxConflict` """ ...
[ "async", "def", "rename_mailbox", "(", "self", ",", "before_name", ":", "str", ",", "after_name", ":", "str", ",", "selected", ":", "SelectedMailbox", "=", "None", ")", "->", "Optional", "[", "SelectedMailbox", "]", ":", "..." ]
Renames the mailbox owned by the user. See Also: `RFC 3501 6.3.5. <https://tools.ietf.org/html/rfc3501#section-6.3.5>`_ Args: before_name: The name of the mailbox before the rename. after_name: The name of the mailbox after the rename. selected: If applicable, the currently selected mailbox name. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxConflict`
[ "Renames", "the", "mailbox", "owned", "by", "the", "user", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L151-L170
train
22,762
icgood/pymap
pymap/interfaces/session.py
SessionInterface.append_messages
async def append_messages(self, name: str, messages: Sequence[AppendMessage], selected: SelectedMailbox = None) \ -> Tuple[AppendUid, Optional[SelectedMailbox]]: """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 selected mailbox name. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.AppendFailure` """ ...
python
async def append_messages(self, name: str, messages: Sequence[AppendMessage], selected: SelectedMailbox = None) \ -> Tuple[AppendUid, Optional[SelectedMailbox]]: """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 selected mailbox name. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.AppendFailure` """ ...
[ "async", "def", "append_messages", "(", "self", ",", "name", ":", "str", ",", "messages", ":", "Sequence", "[", "AppendMessage", "]", ",", "selected", ":", "SelectedMailbox", "=", "None", ")", "->", "Tuple", "[", "AppendUid", ",", "Optional", "[", "Selecte...
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 selected mailbox name. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.AppendFailure`
[ "Appends", "a", "message", "to", "the", "end", "of", "the", "mailbox", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L213-L233
train
22,763
icgood/pymap
pymap/interfaces/session.py
SessionInterface.select_mailbox
async def select_mailbox(self, name: str, readonly: bool = False) \ -> Tuple[MailboxInterface, SelectedMailbox]: """Selects an existing mailbox owned by the user. The returned session is then used as the ``selected`` argument to other methods to fetch mailbox updates. See Also: `RFC 3501 6.3.1. <https://tools.ietf.org/html/rfc3501#section-6.3.1>`_, `RFC 3501 6.3.2. <https://tools.ietf.org/html/rfc3501#section-6.3.2>`_ Args: name: The name of the mailbox. readonly: True if the mailbox is read-only. Raises: :class:`~pymap.exceptions.MailboxNotFound` """ ...
python
async def select_mailbox(self, name: str, readonly: bool = False) \ -> Tuple[MailboxInterface, SelectedMailbox]: """Selects an existing mailbox owned by the user. The returned session is then used as the ``selected`` argument to other methods to fetch mailbox updates. See Also: `RFC 3501 6.3.1. <https://tools.ietf.org/html/rfc3501#section-6.3.1>`_, `RFC 3501 6.3.2. <https://tools.ietf.org/html/rfc3501#section-6.3.2>`_ Args: name: The name of the mailbox. readonly: True if the mailbox is read-only. Raises: :class:`~pymap.exceptions.MailboxNotFound` """ ...
[ "async", "def", "select_mailbox", "(", "self", ",", "name", ":", "str", ",", "readonly", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "MailboxInterface", ",", "SelectedMailbox", "]", ":", "..." ]
Selects an existing mailbox owned by the user. The returned session is then used as the ``selected`` argument to other methods to fetch mailbox updates. See Also: `RFC 3501 6.3.1. <https://tools.ietf.org/html/rfc3501#section-6.3.1>`_, `RFC 3501 6.3.2. <https://tools.ietf.org/html/rfc3501#section-6.3.2>`_ Args: name: The name of the mailbox. readonly: True if the mailbox is read-only. Raises: :class:`~pymap.exceptions.MailboxNotFound`
[ "Selects", "an", "existing", "mailbox", "owned", "by", "the", "user", ".", "The", "returned", "session", "is", "then", "used", "as", "the", "selected", "argument", "to", "other", "methods", "to", "fetch", "mailbox", "updates", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L236-L256
train
22,764
icgood/pymap
pymap/interfaces/session.py
SessionInterface.check_mailbox
async def check_mailbox(self, selected: SelectedMailbox, *, wait_on: Event = None, housekeeping: bool = False) -> SelectedMailbox: """Checks for any updates in the mailbox. If ``wait_on`` is given, this method should block until either this event is signalled or the mailbox has detected updates. This method may be called continuously as long as ``wait_on`` is not signalled. If ``housekeeping`` is True, perform any house-keeping necessary by the mailbox backend, which may be a slower operation. See Also: `RFC 3501 6.1.2. <https://tools.ietf.org/html/rfc3501#section-6.1.2>`_, `RFC 3501 6.4.1. <https://tools.ietf.org/html/rfc3501#section-6.4.1>`_ `RFC 2177 <https://tools.ietf.org/html/rfc2177>`_ Args: selected: The selected mailbox session. wait_on: If given, block until this event signals. housekeeping: If True, the backend may perform additional housekeeping operations if necessary. Raises: :class:`~pymap.exceptions.MailboxNotFound` """ ...
python
async def check_mailbox(self, selected: SelectedMailbox, *, wait_on: Event = None, housekeeping: bool = False) -> SelectedMailbox: """Checks for any updates in the mailbox. If ``wait_on`` is given, this method should block until either this event is signalled or the mailbox has detected updates. This method may be called continuously as long as ``wait_on`` is not signalled. If ``housekeeping`` is True, perform any house-keeping necessary by the mailbox backend, which may be a slower operation. See Also: `RFC 3501 6.1.2. <https://tools.ietf.org/html/rfc3501#section-6.1.2>`_, `RFC 3501 6.4.1. <https://tools.ietf.org/html/rfc3501#section-6.4.1>`_ `RFC 2177 <https://tools.ietf.org/html/rfc2177>`_ Args: selected: The selected mailbox session. wait_on: If given, block until this event signals. housekeeping: If True, the backend may perform additional housekeeping operations if necessary. Raises: :class:`~pymap.exceptions.MailboxNotFound` """ ...
[ "async", "def", "check_mailbox", "(", "self", ",", "selected", ":", "SelectedMailbox", ",", "*", ",", "wait_on", ":", "Event", "=", "None", ",", "housekeeping", ":", "bool", "=", "False", ")", "->", "SelectedMailbox", ":", "..." ]
Checks for any updates in the mailbox. If ``wait_on`` is given, this method should block until either this event is signalled or the mailbox has detected updates. This method may be called continuously as long as ``wait_on`` is not signalled. If ``housekeeping`` is True, perform any house-keeping necessary by the mailbox backend, which may be a slower operation. See Also: `RFC 3501 6.1.2. <https://tools.ietf.org/html/rfc3501#section-6.1.2>`_, `RFC 3501 6.4.1. <https://tools.ietf.org/html/rfc3501#section-6.4.1>`_ `RFC 2177 <https://tools.ietf.org/html/rfc2177>`_ Args: selected: The selected mailbox session. wait_on: If given, block until this event signals. housekeeping: If True, the backend may perform additional housekeeping operations if necessary. Raises: :class:`~pymap.exceptions.MailboxNotFound`
[ "Checks", "for", "any", "updates", "in", "the", "mailbox", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L259-L288
train
22,765
icgood/pymap
pymap/interfaces/session.py
SessionInterface.fetch_messages
async def fetch_messages(self, selected: SelectedMailbox, sequence_set: SequenceSet, attributes: FrozenSet[FetchAttribute]) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """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.exceptions.MailboxNotFound` """ ...
python
async def fetch_messages(self, selected: SelectedMailbox, sequence_set: SequenceSet, attributes: FrozenSet[FetchAttribute]) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """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.exceptions.MailboxNotFound` """ ...
[ "async", "def", "fetch_messages", "(", "self", ",", "selected", ":", "SelectedMailbox", ",", "sequence_set", ":", "SequenceSet", ",", "attributes", ":", "FrozenSet", "[", "FetchAttribute", "]", ")", "->", "Tuple", "[", "Iterable", "[", "Tuple", "[", "int", "...
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.exceptions.MailboxNotFound`
[ "Get", "a", "list", "of", "loaded", "message", "objects", "corresponding", "to", "given", "sequence", "set", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L291-L307
train
22,766
icgood/pymap
pymap/interfaces/session.py
SessionInterface.search_mailbox
async def search_mailbox(self, selected: SelectedMailbox, keys: FrozenSet[SearchKey]) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """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 message criteria. Raises: :class:`~pymap.exceptions.MailboxNotFound` """ ...
python
async def search_mailbox(self, selected: SelectedMailbox, keys: FrozenSet[SearchKey]) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """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 message criteria. Raises: :class:`~pymap.exceptions.MailboxNotFound` """ ...
[ "async", "def", "search_mailbox", "(", "self", ",", "selected", ":", "SelectedMailbox", ",", "keys", ":", "FrozenSet", "[", "SearchKey", "]", ")", "->", "Tuple", "[", "Iterable", "[", "Tuple", "[", "int", ",", "MessageInterface", "]", "]", ",", "SelectedMa...
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 message criteria. Raises: :class:`~pymap.exceptions.MailboxNotFound`
[ "Get", "the", "messages", "in", "the", "current", "mailbox", "that", "meet", "all", "of", "the", "given", "search", "criteria", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L310-L328
train
22,767
icgood/pymap
pymap/interfaces/session.py
SessionInterface.copy_messages
async def copy_messages(self, selected: SelectedMailbox, sequence_set: SequenceSet, mailbox: str) \ -> Tuple[Optional[CopyUid], SelectedMailbox]: """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: Name of the mailbox to copy messages into. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxReadOnly` """ ...
python
async def copy_messages(self, selected: SelectedMailbox, sequence_set: SequenceSet, mailbox: str) \ -> Tuple[Optional[CopyUid], SelectedMailbox]: """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: Name of the mailbox to copy messages into. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxReadOnly` """ ...
[ "async", "def", "copy_messages", "(", "self", ",", "selected", ":", "SelectedMailbox", ",", "sequence_set", ":", "SequenceSet", ",", "mailbox", ":", "str", ")", "->", "Tuple", "[", "Optional", "[", "CopyUid", "]", ",", "SelectedMailbox", "]", ":", "..." ]
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: Name of the mailbox to copy messages into. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxReadOnly`
[ "Copy", "a", "set", "of", "messages", "into", "the", "given", "mailbox", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L353-L373
train
22,768
icgood/pymap
pymap/interfaces/session.py
SessionInterface.update_flags
async def update_flags(self, selected: SelectedMailbox, sequence_set: SequenceSet, flag_set: FrozenSet[Flag], mode: FlagOp = FlagOp.REPLACE) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """Update the flags for the given set of messages. See Also: `RFC 3501 6.4.6. <https://tools.ietf.org/html/rfc3501#section-6.4.6>`_ Args: selected: The selected mailbox session. sequence_set: Sequence set of message sequences or UIDs. flag_set: Set of flags to update. mode: Update mode for the flag set. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxReadOnly` """ ...
python
async def update_flags(self, selected: SelectedMailbox, sequence_set: SequenceSet, flag_set: FrozenSet[Flag], mode: FlagOp = FlagOp.REPLACE) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """Update the flags for the given set of messages. See Also: `RFC 3501 6.4.6. <https://tools.ietf.org/html/rfc3501#section-6.4.6>`_ Args: selected: The selected mailbox session. sequence_set: Sequence set of message sequences or UIDs. flag_set: Set of flags to update. mode: Update mode for the flag set. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxReadOnly` """ ...
[ "async", "def", "update_flags", "(", "self", ",", "selected", ":", "SelectedMailbox", ",", "sequence_set", ":", "SequenceSet", ",", "flag_set", ":", "FrozenSet", "[", "Flag", "]", ",", "mode", ":", "FlagOp", "=", "FlagOp", ".", "REPLACE", ")", "->", "Tuple...
Update the flags for the given set of messages. See Also: `RFC 3501 6.4.6. <https://tools.ietf.org/html/rfc3501#section-6.4.6>`_ Args: selected: The selected mailbox session. sequence_set: Sequence set of message sequences or UIDs. flag_set: Set of flags to update. mode: Update mode for the flag set. Raises: :class:`~pymap.exceptions.MailboxNotFound` :class:`~pymap.exceptions.MailboxReadOnly`
[ "Update", "the", "flags", "for", "the", "given", "set", "of", "messages", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L376-L398
train
22,769
icgood/pymap
pymap/parsing/specials/fetchattr.py
FetchRequirement.reduce
def reduce(cls, requirements: Iterable['FetchRequirement']) \ -> 'FetchRequirement': """Reduce a set of fetch requirements into a single requirement. Args: requirements: The set of fetch requirements. """ return reduce(lambda x, y: x | y, requirements, cls.NONE)
python
def reduce(cls, requirements: Iterable['FetchRequirement']) \ -> 'FetchRequirement': """Reduce a set of fetch requirements into a single requirement. Args: requirements: The set of fetch requirements. """ return reduce(lambda x, y: x | y, requirements, cls.NONE)
[ "def", "reduce", "(", "cls", ",", "requirements", ":", "Iterable", "[", "'FetchRequirement'", "]", ")", "->", "'FetchRequirement'", ":", "return", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "|", "y", ",", "requirements", ",", "cls", ".", "NONE", ...
Reduce a set of fetch requirements into a single requirement. Args: requirements: The set of fetch requirements.
[ "Reduce", "a", "set", "of", "fetch", "requirements", "into", "a", "single", "requirement", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/fetchattr.py#L31-L39
train
22,770
icgood/pymap
pymap/parsing/specials/searchkey.py
SearchKey.requirement
def requirement(self) -> FetchRequirement: """Indicates the data required to fulfill this search key.""" key_name = self.key if key_name == b'ALL': return FetchRequirement.NONE elif key_name == b'KEYSET': keyset_reqs = {key.requirement for key in self.filter_key_set} return FetchRequirement.reduce(keyset_reqs) elif key_name == b'OR': left, right = self.filter_key_or key_or_reqs = {left.requirement, right.requirement} return FetchRequirement.reduce(key_or_reqs) elif key_name in (b'SENTBEFORE', b'SENTON', b'SENTSINCE', b'BCC', b'CC', b'FROM', b'SUBJECT', b'TO', b'HEADER'): return FetchRequirement.HEADERS elif key_name in (b'BODY', b'TEXT', b'LARGER', b'SMALLER'): return FetchRequirement.BODY else: return FetchRequirement.METADATA
python
def requirement(self) -> FetchRequirement: """Indicates the data required to fulfill this search key.""" key_name = self.key if key_name == b'ALL': return FetchRequirement.NONE elif key_name == b'KEYSET': keyset_reqs = {key.requirement for key in self.filter_key_set} return FetchRequirement.reduce(keyset_reqs) elif key_name == b'OR': left, right = self.filter_key_or key_or_reqs = {left.requirement, right.requirement} return FetchRequirement.reduce(key_or_reqs) elif key_name in (b'SENTBEFORE', b'SENTON', b'SENTSINCE', b'BCC', b'CC', b'FROM', b'SUBJECT', b'TO', b'HEADER'): return FetchRequirement.HEADERS elif key_name in (b'BODY', b'TEXT', b'LARGER', b'SMALLER'): return FetchRequirement.BODY else: return FetchRequirement.METADATA
[ "def", "requirement", "(", "self", ")", "->", "FetchRequirement", ":", "key_name", "=", "self", ".", "key", "if", "key_name", "==", "b'ALL'", ":", "return", "FetchRequirement", ".", "NONE", "elif", "key_name", "==", "b'KEYSET'", ":", "keyset_reqs", "=", "{",...
Indicates the data required to fulfill this search key.
[ "Indicates", "the", "data", "required", "to", "fulfill", "this", "search", "key", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/searchkey.py#L53-L71
train
22,771
icgood/pymap
pymap/backend/maildir/mailbox.py
Maildir.claim_new
def claim_new(self) -> Iterable[str]: """Checks for messages in the ``new`` subdirectory, moving them to ``cur`` and returning their keys. """ new_subdir = self._paths['new'] cur_subdir = self._paths['cur'] for name in os.listdir(new_subdir): new_path = os.path.join(new_subdir, name) cur_path = os.path.join(cur_subdir, name) try: os.rename(new_path, cur_path) except FileNotFoundError: pass else: yield name.rsplit(self.colon, 1)[0]
python
def claim_new(self) -> Iterable[str]: """Checks for messages in the ``new`` subdirectory, moving them to ``cur`` and returning their keys. """ new_subdir = self._paths['new'] cur_subdir = self._paths['cur'] for name in os.listdir(new_subdir): new_path = os.path.join(new_subdir, name) cur_path = os.path.join(cur_subdir, name) try: os.rename(new_path, cur_path) except FileNotFoundError: pass else: yield name.rsplit(self.colon, 1)[0]
[ "def", "claim_new", "(", "self", ")", "->", "Iterable", "[", "str", "]", ":", "new_subdir", "=", "self", ".", "_paths", "[", "'new'", "]", "cur_subdir", "=", "self", ".", "_paths", "[", "'cur'", "]", "for", "name", "in", "os", ".", "listdir", "(", ...
Checks for messages in the ``new`` subdirectory, moving them to ``cur`` and returning their keys.
[ "Checks", "for", "messages", "in", "the", "new", "subdirectory", "moving", "them", "to", "cur", "and", "returning", "their", "keys", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/mailbox.py#L34-L49
train
22,772
icgood/pymap
pymap/admin/handlers.py
AdminHandlers.Append
async def Append(self, stream) -> None: """Append a message directly to a user's mailbox. If the backend session defines a :attr:`~pymap.interfaces.session.SessionInterface.filter_set`, the active filter implementation will be applied to the appended message, such that the message may be discarded, modified, or placed into a specific mailbox. For example, using the CLI client:: $ cat message.txt | pymap-admin append user@example.com See ``pymap-admin append --help`` for more options. Args: stream (:class:`~grpclib.server.Stream`): The stream for the request and response. """ from .grpc.admin_pb2 import AppendRequest, AppendResponse, \ ERROR_RESPONSE request: AppendRequest = await stream.recv_message() mailbox = request.mailbox or 'INBOX' flag_set = frozenset(Flag(flag) for flag in request.flags) when = datetime.fromtimestamp(request.when, timezone.utc) append_msg = AppendMessage(request.data, flag_set, when, ExtensionOptions.empty()) try: session = await self._login_as(request.user) if self._with_filter and session.filter_set is not None: filter_value = await session.filter_set.get_active() if filter_value is not None: filter_ = await session.filter_set.compile(filter_value) new_mailbox, append_msg = await filter_.apply( request.sender, request.recipient, mailbox, append_msg) if new_mailbox is None: await stream.send_message(AppendResponse()) return else: mailbox = new_mailbox append_uid, _ = await session.append_messages( mailbox, [append_msg]) except ResponseError as exc: resp = AppendResponse(result=ERROR_RESPONSE, error_type=type(exc).__name__, error_response=bytes(exc.get_response(b'.')), mailbox=mailbox) await stream.send_message(resp) else: validity = append_uid.validity uid = next(iter(append_uid.uids)) resp = AppendResponse(mailbox=mailbox, validity=validity, uid=uid) await stream.send_message(resp)
python
async def Append(self, stream) -> None: """Append a message directly to a user's mailbox. If the backend session defines a :attr:`~pymap.interfaces.session.SessionInterface.filter_set`, the active filter implementation will be applied to the appended message, such that the message may be discarded, modified, or placed into a specific mailbox. For example, using the CLI client:: $ cat message.txt | pymap-admin append user@example.com See ``pymap-admin append --help`` for more options. Args: stream (:class:`~grpclib.server.Stream`): The stream for the request and response. """ from .grpc.admin_pb2 import AppendRequest, AppendResponse, \ ERROR_RESPONSE request: AppendRequest = await stream.recv_message() mailbox = request.mailbox or 'INBOX' flag_set = frozenset(Flag(flag) for flag in request.flags) when = datetime.fromtimestamp(request.when, timezone.utc) append_msg = AppendMessage(request.data, flag_set, when, ExtensionOptions.empty()) try: session = await self._login_as(request.user) if self._with_filter and session.filter_set is not None: filter_value = await session.filter_set.get_active() if filter_value is not None: filter_ = await session.filter_set.compile(filter_value) new_mailbox, append_msg = await filter_.apply( request.sender, request.recipient, mailbox, append_msg) if new_mailbox is None: await stream.send_message(AppendResponse()) return else: mailbox = new_mailbox append_uid, _ = await session.append_messages( mailbox, [append_msg]) except ResponseError as exc: resp = AppendResponse(result=ERROR_RESPONSE, error_type=type(exc).__name__, error_response=bytes(exc.get_response(b'.')), mailbox=mailbox) await stream.send_message(resp) else: validity = append_uid.validity uid = next(iter(append_uid.uids)) resp = AppendResponse(mailbox=mailbox, validity=validity, uid=uid) await stream.send_message(resp)
[ "async", "def", "Append", "(", "self", ",", "stream", ")", "->", "None", ":", "from", ".", "grpc", ".", "admin_pb2", "import", "AppendRequest", ",", "AppendResponse", ",", "ERROR_RESPONSE", "request", ":", "AppendRequest", "=", "await", "stream", ".", "recv_...
Append a message directly to a user's mailbox. If the backend session defines a :attr:`~pymap.interfaces.session.SessionInterface.filter_set`, the active filter implementation will be applied to the appended message, such that the message may be discarded, modified, or placed into a specific mailbox. For example, using the CLI client:: $ cat message.txt | pymap-admin append user@example.com See ``pymap-admin append --help`` for more options. Args: stream (:class:`~grpclib.server.Stream`): The stream for the request and response.
[ "Append", "a", "message", "directly", "to", "a", "user", "s", "mailbox", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/admin/handlers.py#L39-L92
train
22,773
icgood/pymap
pymap/flags.py
FlagOp.apply
def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) \ -> FrozenSet[Flag]: """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. """ if self == FlagOp.ADD: return frozenset(flag_set | operand) elif self == FlagOp.DELETE: return frozenset(flag_set - operand) else: # op == FlagOp.REPLACE return frozenset(operand)
python
def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) \ -> FrozenSet[Flag]: """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. """ if self == FlagOp.ADD: return frozenset(flag_set | operand) elif self == FlagOp.DELETE: return frozenset(flag_set - operand) else: # op == FlagOp.REPLACE return frozenset(operand)
[ "def", "apply", "(", "self", ",", "flag_set", ":", "AbstractSet", "[", "Flag", "]", ",", "operand", ":", "AbstractSet", "[", "Flag", "]", ")", "->", "FrozenSet", "[", "Flag", "]", ":", "if", "self", "==", "FlagOp", ".", "ADD", ":", "return", "frozens...
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.
[ "Apply", "the", "flag", "operation", "on", "the", "two", "sets", "returning", "the", "result", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L30-L44
train
22,774
icgood/pymap
pymap/flags.py
SessionFlags.get
def get(self, uid: int) -> FrozenSet[Flag]: """Return the session flags for the mailbox session. Args: uid: The message UID value. """ recent = _recent_set if uid in self._recent else frozenset() flags = self._flags.get(uid) return recent if flags is None else (flags | recent)
python
def get(self, uid: int) -> FrozenSet[Flag]: """Return the session flags for the mailbox session. Args: uid: The message UID value. """ recent = _recent_set if uid in self._recent else frozenset() flags = self._flags.get(uid) return recent if flags is None else (flags | recent)
[ "def", "get", "(", "self", ",", "uid", ":", "int", ")", "->", "FrozenSet", "[", "Flag", "]", ":", "recent", "=", "_recent_set", "if", "uid", "in", "self", ".", "_recent", "else", "frozenset", "(", ")", "flags", "=", "self", ".", "_flags", ".", "get...
Return the session flags for the mailbox session. Args: uid: The message UID value.
[ "Return", "the", "session", "flags", "for", "the", "mailbox", "session", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L138-L147
train
22,775
icgood/pymap
pymap/flags.py
SessionFlags.remove
def remove(self, uids: Iterable[int]) -> None: """Remove any session flags for the given message. Args: uids: The message UID values. """ for uid in uids: self._recent.discard(uid) self._flags.pop(uid, None)
python
def remove(self, uids: Iterable[int]) -> None: """Remove any session flags for the given message. Args: uids: The message UID values. """ for uid in uids: self._recent.discard(uid) self._flags.pop(uid, None)
[ "def", "remove", "(", "self", ",", "uids", ":", "Iterable", "[", "int", "]", ")", "->", "None", ":", "for", "uid", "in", "uids", ":", "self", ".", "_recent", ".", "discard", "(", "uid", ")", "self", ".", "_flags", ".", "pop", "(", "uid", ",", "...
Remove any session flags for the given message. Args: uids: The message UID values.
[ "Remove", "any", "session", "flags", "for", "the", "given", "message", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L149-L158
train
22,776
icgood/pymap
pymap/flags.py
SessionFlags.update
def update(self, uid: int, flag_set: Iterable[Flag], op: FlagOp = FlagOp.REPLACE) -> FrozenSet[Flag]: """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. """ 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: self._flags.pop(uid, None) return new_flags
python
def update(self, uid: int, flag_set: Iterable[Flag], op: FlagOp = FlagOp.REPLACE) -> FrozenSet[Flag]: """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. """ 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: self._flags.pop(uid, None) return new_flags
[ "def", "update", "(", "self", ",", "uid", ":", "int", ",", "flag_set", ":", "Iterable", "[", "Flag", "]", ",", "op", ":", "FlagOp", "=", "FlagOp", ".", "REPLACE", ")", "->", "FrozenSet", "[", "Flag", "]", ":", "orig_set", "=", "self", ".", "_flags"...
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.
[ "Update", "the", "flags", "for", "the", "session", "returning", "the", "resulting", "flags", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L160-L176
train
22,777
icgood/pymap
pymap/parsing/specials/flag.py
get_system_flags
def get_system_flags() -> FrozenSet[Flag]: """Return the set of implemented system flags.""" return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})
python
def get_system_flags() -> FrozenSet[Flag]: """Return the set of implemented system flags.""" return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})
[ "def", "get_system_flags", "(", ")", "->", "FrozenSet", "[", "Flag", "]", ":", "return", "frozenset", "(", "{", "Seen", ",", "Recent", ",", "Deleted", ",", "Flagged", ",", "Answered", ",", "Draft", "}", ")" ]
Return the set of implemented system flags.
[ "Return", "the", "set", "of", "implemented", "system", "flags", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/flag.py#L93-L95
train
22,778
icgood/pymap
pymap/parsing/commands.py
Commands.register
def register(self, cmd: Type[Command]) -> None: """Register a new IMAP command. Args: cmd: The new command type. """ self.commands[cmd.command] = cmd
python
def register(self, cmd: Type[Command]) -> None: """Register a new IMAP command. Args: cmd: The new command type. """ self.commands[cmd.command] = cmd
[ "def", "register", "(", "self", ",", "cmd", ":", "Type", "[", "Command", "]", ")", "->", "None", ":", "self", ".", "commands", "[", "cmd", ".", "command", "]", "=", "cmd" ]
Register a new IMAP command. Args: cmd: The new command type.
[ "Register", "a", "new", "IMAP", "command", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/commands.py#L95-L102
train
22,779
icgood/pymap
pymap/parsing/primitives.py
ListP.get_as
def get_as(self, cls: Type[MaybeBytesT]) -> Sequence[MaybeBytesT]: """Return the list of parsed objects.""" _ = cls # noqa return cast(Sequence[MaybeBytesT], self.items)
python
def get_as(self, cls: Type[MaybeBytesT]) -> Sequence[MaybeBytesT]: """Return the list of parsed objects.""" _ = cls # noqa return cast(Sequence[MaybeBytesT], self.items)
[ "def", "get_as", "(", "self", ",", "cls", ":", "Type", "[", "MaybeBytesT", "]", ")", "->", "Sequence", "[", "MaybeBytesT", "]", ":", "_", "=", "cls", "# noqa", "return", "cast", "(", "Sequence", "[", "MaybeBytesT", "]", ",", "self", ".", "items", ")"...
Return the list of parsed objects.
[ "Return", "the", "list", "of", "parsed", "objects", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/primitives.py#L430-L433
train
22,780
icgood/pymap
pymap/fetch.py
MessageAttributes.get_all
def get_all(self, attrs: Iterable[FetchAttribute]) \ -> Sequence[Tuple[FetchAttribute, MaybeBytes]]: """Return a list of tuples containing the attribute iself and the bytes representation of that attribute from the message. Args: attrs: The fetch attributes. """ ret: List[Tuple[FetchAttribute, MaybeBytes]] = [] for attr in attrs: try: ret.append((attr.for_response, self.get(attr))) except NotFetchable: pass return ret
python
def get_all(self, attrs: Iterable[FetchAttribute]) \ -> Sequence[Tuple[FetchAttribute, MaybeBytes]]: """Return a list of tuples containing the attribute iself and the bytes representation of that attribute from the message. Args: attrs: The fetch attributes. """ ret: List[Tuple[FetchAttribute, MaybeBytes]] = [] for attr in attrs: try: ret.append((attr.for_response, self.get(attr))) except NotFetchable: pass return ret
[ "def", "get_all", "(", "self", ",", "attrs", ":", "Iterable", "[", "FetchAttribute", "]", ")", "->", "Sequence", "[", "Tuple", "[", "FetchAttribute", ",", "MaybeBytes", "]", "]", ":", "ret", ":", "List", "[", "Tuple", "[", "FetchAttribute", ",", "MaybeBy...
Return a list of tuples containing the attribute iself and the bytes representation of that attribute from the message. Args: attrs: The fetch attributes.
[ "Return", "a", "list", "of", "tuples", "containing", "the", "attribute", "iself", "and", "the", "bytes", "representation", "of", "that", "attribute", "from", "the", "message", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/fetch.py#L60-L75
train
22,781
icgood/pymap
pymap/fetch.py
MessageAttributes.get
def get(self, attr: FetchAttribute) -> MaybeBytes: """Return the bytes representation of the given message attribue. Args: attr: The fetch attribute. Raises: :class:`NotFetchable` """ attr_name = attr.value.decode('ascii') method = getattr(self, '_get_' + attr_name.replace('.', '_')) return method(attr)
python
def get(self, attr: FetchAttribute) -> MaybeBytes: """Return the bytes representation of the given message attribue. Args: attr: The fetch attribute. Raises: :class:`NotFetchable` """ attr_name = attr.value.decode('ascii') method = getattr(self, '_get_' + attr_name.replace('.', '_')) return method(attr)
[ "def", "get", "(", "self", ",", "attr", ":", "FetchAttribute", ")", "->", "MaybeBytes", ":", "attr_name", "=", "attr", ".", "value", ".", "decode", "(", "'ascii'", ")", "method", "=", "getattr", "(", "self", ",", "'_get_'", "+", "attr_name", ".", "repl...
Return the bytes representation of the given message attribue. Args: attr: The fetch attribute. Raises: :class:`NotFetchable`
[ "Return", "the", "bytes", "representation", "of", "the", "given", "message", "attribue", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/fetch.py#L77-L89
train
22,782
icgood/pymap
pymap/search.py
SearchCriteriaSet.sequence_set
def sequence_set(self) -> SequenceSet: """The sequence set to use when finding the messages to match against. This will default to all messages unless the search criteria set contains a sequence set. """ try: seqset_crit = next(crit for crit in self.all_criteria if isinstance(crit, SequenceSetSearchCriteria)) except StopIteration: return SequenceSet.all() else: return seqset_crit.seq_set
python
def sequence_set(self) -> SequenceSet: """The sequence set to use when finding the messages to match against. This will default to all messages unless the search criteria set contains a sequence set. """ try: seqset_crit = next(crit for crit in self.all_criteria if isinstance(crit, SequenceSetSearchCriteria)) except StopIteration: return SequenceSet.all() else: return seqset_crit.seq_set
[ "def", "sequence_set", "(", "self", ")", "->", "SequenceSet", ":", "try", ":", "seqset_crit", "=", "next", "(", "crit", "for", "crit", "in", "self", ".", "all_criteria", "if", "isinstance", "(", "crit", ",", "SequenceSetSearchCriteria", ")", ")", "except", ...
The sequence set to use when finding the messages to match against. This will default to all messages unless the search criteria set contains a sequence set.
[ "The", "sequence", "set", "to", "use", "when", "finding", "the", "messages", "to", "match", "against", ".", "This", "will", "default", "to", "all", "messages", "unless", "the", "search", "criteria", "set", "contains", "a", "sequence", "set", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/search.py#L167-L179
train
22,783
icgood/pymap
pymap/search.py
SearchCriteriaSet.matches
def matches(self, msg_seq: int, msg: MessageInterface) -> bool: """The message matches if all the defined search key criteria match. Args: msg_seq: The message sequence ID. msg: The message object. """ return all(crit.matches(msg_seq, msg) for crit in self.all_criteria)
python
def matches(self, msg_seq: int, msg: MessageInterface) -> bool: """The message matches if all the defined search key criteria match. Args: msg_seq: The message sequence ID. msg: The message object. """ return all(crit.matches(msg_seq, msg) for crit in self.all_criteria)
[ "def", "matches", "(", "self", ",", "msg_seq", ":", "int", ",", "msg", ":", "MessageInterface", ")", "->", "bool", ":", "return", "all", "(", "crit", ".", "matches", "(", "msg_seq", ",", "msg", ")", "for", "crit", "in", "self", ".", "all_criteria", "...
The message matches if all the defined search key criteria match. Args: msg_seq: The message sequence ID. msg: The message object.
[ "The", "message", "matches", "if", "all", "the", "defined", "search", "key", "criteria", "match", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/search.py#L181-L189
train
22,784
icgood/pymap
pymap/mime/__init__.py
MessageContent.walk
def walk(self) -> Iterable['MessageContent']: """Iterate through the message and all its nested sub-parts in the order they occur. """ if self.body.has_nested: return chain([self], *(part.walk() for part in self.body.nested)) else: return [self]
python
def walk(self) -> Iterable['MessageContent']: """Iterate through the message and all its nested sub-parts in the order they occur. """ if self.body.has_nested: return chain([self], *(part.walk() for part in self.body.nested)) else: return [self]
[ "def", "walk", "(", "self", ")", "->", "Iterable", "[", "'MessageContent'", "]", ":", "if", "self", ".", "body", ".", "has_nested", ":", "return", "chain", "(", "[", "self", "]", ",", "*", "(", "part", ".", "walk", "(", ")", "for", "part", "in", ...
Iterate through the message and all its nested sub-parts in the order they occur.
[ "Iterate", "through", "the", "message", "and", "all", "its", "nested", "sub", "-", "parts", "in", "the", "order", "they", "occur", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/__init__.py#L44-L52
train
22,785
icgood/pymap
pymap/mime/__init__.py
MessageContent.parse
def parse(cls, data: bytes) -> 'MessageContent': """Parse the bytestring into message content. Args: data: The bytestring to parse. """ lines = cls._find_lines(data) view = memoryview(data) return cls._parse(data, view, lines)
python
def parse(cls, data: bytes) -> 'MessageContent': """Parse the bytestring into message content. Args: data: The bytestring to parse. """ lines = cls._find_lines(data) view = memoryview(data) return cls._parse(data, view, lines)
[ "def", "parse", "(", "cls", ",", "data", ":", "bytes", ")", "->", "'MessageContent'", ":", "lines", "=", "cls", ".", "_find_lines", "(", "data", ")", "view", "=", "memoryview", "(", "data", ")", "return", "cls", ".", "_parse", "(", "data", ",", "view...
Parse the bytestring into message content. Args: data: The bytestring to parse.
[ "Parse", "the", "bytestring", "into", "message", "content", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/__init__.py#L64-L73
train
22,786
icgood/pymap
pymap/mime/__init__.py
MessageContent.parse_split
def parse_split(cls, header: bytes, body: bytes) -> 'MessageContent': """Parse the header and body bytestrings into message content. Args: header: The header bytestring to parse. body: The body bytestring to parse. """ 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, header_view, body_view, header_lines, body_lines)
python
def parse_split(cls, header: bytes, body: bytes) -> 'MessageContent': """Parse the header and body bytestrings into message content. Args: header: The header bytestring to parse. body: The body bytestring to parse. """ 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, header_view, body_view, header_lines, body_lines)
[ "def", "parse_split", "(", "cls", ",", "header", ":", "bytes", ",", "body", ":", "bytes", ")", "->", "'MessageContent'", ":", "header_lines", "=", "cls", ".", "_find_lines", "(", "header", ")", "body_lines", "=", "cls", ".", "_find_lines", "(", "body", "...
Parse the header and body bytestrings into message content. Args: header: The header bytestring to parse. body: The body bytestring to parse.
[ "Parse", "the", "header", "and", "body", "bytestrings", "into", "message", "content", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/__init__.py#L76-L90
train
22,787
icgood/pymap
pymap/backend/maildir/uidlist.py
UidList.get_all
def get_all(self, uids: Iterable[int]) -> Mapping[int, Record]: """Get records by a set of UIDs. Args: uids: The message UIDs. """ return {uid: self._records[uid] for uid in uids if uid in self._records}
python
def get_all(self, uids: Iterable[int]) -> Mapping[int, Record]: """Get records by a set of UIDs. Args: uids: The message UIDs. """ return {uid: self._records[uid] for uid in uids if uid in self._records}
[ "def", "get_all", "(", "self", ",", "uids", ":", "Iterable", "[", "int", "]", ")", "->", "Mapping", "[", "int", ",", "Record", "]", ":", "return", "{", "uid", ":", "self", ".", "_records", "[", "uid", "]", "for", "uid", "in", "uids", "if", "uid",...
Get records by a set of UIDs. Args: uids: The message UIDs.
[ "Get", "records", "by", "a", "set", "of", "UIDs", "." ]
e77d9a54d760e3cbe044a548883bb4299ed61dc2
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/uidlist.py#L79-L87
train
22,788
phatpiglet/autocorrect
autocorrect/__init__.py
spell
def spell(word): """most likely correction for everything up to a double typo""" w = Word(word) candidates = (common([word]) or exact([word]) or known([word]) or known(w.typos()) or common(w.double_typos()) or [word]) correction = max(candidates, key=NLP_COUNTS.get) return get_case(word, correction)
python
def spell(word): """most likely correction for everything up to a double typo""" w = Word(word) candidates = (common([word]) or exact([word]) or known([word]) or known(w.typos()) or common(w.double_typos()) or [word]) correction = max(candidates, key=NLP_COUNTS.get) return get_case(word, correction)
[ "def", "spell", "(", "word", ")", ":", "w", "=", "Word", "(", "word", ")", "candidates", "=", "(", "common", "(", "[", "word", "]", ")", "or", "exact", "(", "[", "word", "]", ")", "or", "known", "(", "[", "word", "]", ")", "or", "known", "(",...
most likely correction for everything up to a double typo
[ "most", "likely", "correction", "for", "everything", "up", "to", "a", "double", "typo" ]
ae90c886aa5e3e261813fd0f4c91188f0d14c35c
https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/__init__.py#L19-L26
train
22,789
phatpiglet/autocorrect
autocorrect/utils.py
words_from_archive
def words_from_archive(filename, include_dups=False, map_case=False): """extract words from a text file in the archive""" bz2 = os.path.join(PATH, BZ2) tar_path = '{}/{}'.format('words', filename) with closing(tarfile.open(bz2, 'r:bz2')) as t: with closing(t.extractfile(tar_path)) as f: words = re.findall(RE, f.read().decode(encoding='utf-8')) if include_dups: return words elif map_case: return {w.lower():w for w in words} else: return set(words)
python
def words_from_archive(filename, include_dups=False, map_case=False): """extract words from a text file in the archive""" bz2 = os.path.join(PATH, BZ2) tar_path = '{}/{}'.format('words', filename) with closing(tarfile.open(bz2, 'r:bz2')) as t: with closing(t.extractfile(tar_path)) as f: words = re.findall(RE, f.read().decode(encoding='utf-8')) if include_dups: return words elif map_case: return {w.lower():w for w in words} else: return set(words)
[ "def", "words_from_archive", "(", "filename", ",", "include_dups", "=", "False", ",", "map_case", "=", "False", ")", ":", "bz2", "=", "os", ".", "path", ".", "join", "(", "PATH", ",", "BZ2", ")", "tar_path", "=", "'{}/{}'", ".", "format", "(", "'words'...
extract words from a text file in the archive
[ "extract", "words", "from", "a", "text", "file", "in", "the", "archive" ]
ae90c886aa5e3e261813fd0f4c91188f0d14c35c
https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/utils.py#L24-L36
train
22,790
phatpiglet/autocorrect
autocorrect/nlp_parser.py
parse
def parse(lang_sample): """tally word popularity using novel extracts, etc""" words = words_from_archive(lang_sample, include_dups=True) counts = zero_default_dict() for word in words: counts[word] += 1 return set(words), counts
python
def parse(lang_sample): """tally word popularity using novel extracts, etc""" words = words_from_archive(lang_sample, include_dups=True) counts = zero_default_dict() for word in words: counts[word] += 1 return set(words), counts
[ "def", "parse", "(", "lang_sample", ")", ":", "words", "=", "words_from_archive", "(", "lang_sample", ",", "include_dups", "=", "True", ")", "counts", "=", "zero_default_dict", "(", ")", "for", "word", "in", "words", ":", "counts", "[", "word", "]", "+=", ...
tally word popularity using novel extracts, etc
[ "tally", "word", "popularity", "using", "novel", "extracts", "etc" ]
ae90c886aa5e3e261813fd0f4c91188f0d14c35c
https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/nlp_parser.py#L18-L24
train
22,791
phatpiglet/autocorrect
autocorrect/word.py
get_case
def get_case(word, correction): """ Best guess of intended case. manchester => manchester chilton => Chilton AAvTech => AAvTech THe => The imho => IMHO """ if word.istitle(): return correction.title() if word.isupper(): return correction.upper() if correction == word and not word.islower(): return word if len(word) > 2 and word[:2].isupper(): return correction.title() if not known_as_lower([correction]): #expensive try: return CASE_MAPPED[correction] except KeyError: pass return correction
python
def get_case(word, correction): """ Best guess of intended case. manchester => manchester chilton => Chilton AAvTech => AAvTech THe => The imho => IMHO """ if word.istitle(): return correction.title() if word.isupper(): return correction.upper() if correction == word and not word.islower(): return word if len(word) > 2 and word[:2].isupper(): return correction.title() if not known_as_lower([correction]): #expensive try: return CASE_MAPPED[correction] except KeyError: pass return correction
[ "def", "get_case", "(", "word", ",", "correction", ")", ":", "if", "word", ".", "istitle", "(", ")", ":", "return", "correction", ".", "title", "(", ")", "if", "word", ".", "isupper", "(", ")", ":", "return", "correction", ".", "upper", "(", ")", "...
Best guess of intended case. manchester => manchester chilton => Chilton AAvTech => AAvTech THe => The imho => IMHO
[ "Best", "guess", "of", "intended", "case", "." ]
ae90c886aa5e3e261813fd0f4c91188f0d14c35c
https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/word.py#L91-L115
train
22,792
phatpiglet/autocorrect
autocorrect/word.py
Word.typos
def typos(self): """letter combinations one typo away from word""" return (self._deletes() | self._transposes() | self._replaces() | self._inserts())
python
def typos(self): """letter combinations one typo away from word""" return (self._deletes() | self._transposes() | self._replaces() | self._inserts())
[ "def", "typos", "(", "self", ")", ":", "return", "(", "self", ".", "_deletes", "(", ")", "|", "self", ".", "_transposes", "(", ")", "|", "self", ".", "_replaces", "(", ")", "|", "self", ".", "_inserts", "(", ")", ")" ]
letter combinations one typo away from word
[ "letter", "combinations", "one", "typo", "away", "from", "word" ]
ae90c886aa5e3e261813fd0f4c91188f0d14c35c
https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/word.py#L64-L67
train
22,793
phatpiglet/autocorrect
autocorrect/word.py
Word.double_typos
def double_typos(self): """letter combinations two typos away from word""" return {e2 for e1 in self.typos() for e2 in Word(e1).typos()}
python
def double_typos(self): """letter combinations two typos away from word""" return {e2 for e1 in self.typos() for e2 in Word(e1).typos()}
[ "def", "double_typos", "(", "self", ")", ":", "return", "{", "e2", "for", "e1", "in", "self", ".", "typos", "(", ")", "for", "e2", "in", "Word", "(", "e1", ")", ".", "typos", "(", ")", "}" ]
letter combinations two typos away from word
[ "letter", "combinations", "two", "typos", "away", "from", "word" ]
ae90c886aa5e3e261813fd0f4c91188f0d14c35c
https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/word.py#L69-L72
train
22,794
theelous3/multio
multio/__init__.py
register
def register(lib_name: str, cbl: Callable[[_AsyncLib], None]): ''' Registers a new library function with the current manager. ''' return manager.register(lib_name, cbl)
python
def register(lib_name: str, cbl: Callable[[_AsyncLib], None]): ''' Registers a new library function with the current manager. ''' return manager.register(lib_name, cbl)
[ "def", "register", "(", "lib_name", ":", "str", ",", "cbl", ":", "Callable", "[", "[", "_AsyncLib", "]", ",", "None", "]", ")", ":", "return", "manager", ".", "register", "(", "lib_name", ",", "cbl", ")" ]
Registers a new library function with the current manager.
[ "Registers", "a", "new", "library", "function", "with", "the", "current", "manager", "." ]
018e4a9f78d5f4e78608a1a1537000b5fd778bbe
https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L480-L484
train
22,795
theelous3/multio
multio/__init__.py
init
def init(library: typing.Union[str, types.ModuleType]) -> None: ''' 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 module name as a string or the imported module itself. E.g. ``multio.init(curio)``. ''' if isinstance(library, types.ModuleType): library = library.__name__ if library not in manager._handlers: raise ValueError("Possible values are <{}>, not <{}>".format(manager._handlers.keys(), library)) manager.init(library, asynclib) asynclib.lib_name = library asynclib._init = True
python
def init(library: typing.Union[str, types.ModuleType]) -> None: ''' 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 module name as a string or the imported module itself. E.g. ``multio.init(curio)``. ''' if isinstance(library, types.ModuleType): library = library.__name__ if library not in manager._handlers: raise ValueError("Possible values are <{}>, not <{}>".format(manager._handlers.keys(), library)) manager.init(library, asynclib) asynclib.lib_name = library asynclib._init = True
[ "def", "init", "(", "library", ":", "typing", ".", "Union", "[", "str", ",", "types", ".", "ModuleType", "]", ")", "->", "None", ":", "if", "isinstance", "(", "library", ",", "types", ".", "ModuleType", ")", ":", "library", "=", "library", ".", "__na...
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 module name as a string or the imported module itself. E.g. ``multio.init(curio)``.
[ "Must", "be", "called", "at", "some", "point", "after", "import", "and", "before", "your", "event", "loop", "is", "run", "." ]
018e4a9f78d5f4e78608a1a1537000b5fd778bbe
https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L487-L512
train
22,796
theelous3/multio
multio/__init__.py
run
def run(*args, **kwargs): ''' Runs the appropriate library run function. ''' lib = sys.modules[asynclib.lib_name] lib.run(*args, **kwargs)
python
def run(*args, **kwargs): ''' Runs the appropriate library run function. ''' lib = sys.modules[asynclib.lib_name] lib.run(*args, **kwargs)
[ "def", "run", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lib", "=", "sys", ".", "modules", "[", "asynclib", ".", "lib_name", "]", "lib", ".", "run", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Runs the appropriate library run function.
[ "Runs", "the", "appropriate", "library", "run", "function", "." ]
018e4a9f78d5f4e78608a1a1537000b5fd778bbe
https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L515-L520
train
22,797
theelous3/multio
multio/__init__.py
SocketWrapper.recv
async def recv(self, nbytes: int = -1, **kwargs) -> bytes: ''' Receives some data on the socket. ''' return await asynclib.recv(self.sock, nbytes, **kwargs)
python
async def recv(self, nbytes: int = -1, **kwargs) -> bytes: ''' Receives some data on the socket. ''' return await asynclib.recv(self.sock, nbytes, **kwargs)
[ "async", "def", "recv", "(", "self", ",", "nbytes", ":", "int", "=", "-", "1", ",", "*", "*", "kwargs", ")", "->", "bytes", ":", "return", "await", "asynclib", ".", "recv", "(", "self", ".", "sock", ",", "nbytes", ",", "*", "*", "kwargs", ")" ]
Receives some data on the socket.
[ "Receives", "some", "data", "on", "the", "socket", "." ]
018e4a9f78d5f4e78608a1a1537000b5fd778bbe
https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L91-L95
train
22,798
theelous3/multio
multio/__init__.py
SocketWrapper.sendall
async def sendall(self, data: bytes, *args, **kwargs): ''' Sends some data on the socket. ''' return await asynclib.sendall(self.sock, data, *args, **kwargs)
python
async def sendall(self, data: bytes, *args, **kwargs): ''' Sends some data on the socket. ''' return await asynclib.sendall(self.sock, data, *args, **kwargs)
[ "async", "def", "sendall", "(", "self", ",", "data", ":", "bytes", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "asynclib", ".", "sendall", "(", "self", ".", "sock", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs...
Sends some data on the socket.
[ "Sends", "some", "data", "on", "the", "socket", "." ]
018e4a9f78d5f4e78608a1a1537000b5fd778bbe
https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L97-L101
train
22,799