idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
22,700 | def destroyTempFile ( self , tempFile ) : assert os . path . isfile ( tempFile ) assert os . path . commonprefix ( ( self . rootDir , tempFile ) ) == self . rootDir self . tempFilesDestroyed += 1 os . remove ( tempFile ) self . __destroyFile ( tempFile ) | Removes the temporary file in the temp file dir checking its in the temp file tree . |
22,701 | def destroyTempDir ( self , tempDir ) : assert os . path . isdir ( tempDir ) assert os . path . commonprefix ( ( self . rootDir , tempDir ) ) == self . rootDir self . tempFilesDestroyed += 1 try : os . rmdir ( tempDir ) except OSError : shutil . rmtree ( tempDir ) self . __destroyFile ( 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 . |
22,702 | def destroyTempFiles ( self ) : os . system ( "rm -rf %s" % self . rootDir ) logger . debug ( "Temp files created: %s, temp files actively destroyed: %s" % ( self . tempFilesCreated , self . tempFilesDestroyed ) ) | Destroys all temp temp file hierarchy getting rid of all files . |
22,703 | def mutable_json_field ( enforce_string = False , enforce_unicode = False , json = json , * args , ** kwargs ) : return sqlalchemy . ext . mutable . MutableDict . as_mutable ( JSONField ( enforce_string = enforce_string , enforce_unicode = enforce_unicode , json = json , * args , ** kwargs ) ) | Mutable JSONField creator . |
22,704 | def load_dialect_impl ( self , dialect ) : if self . __use_json ( dialect ) : return dialect . type_descriptor ( self . __json_type ) return dialect . type_descriptor ( sqlalchemy . UnicodeText ) | Select impl by dialect . |
22,705 | def process_bind_param ( self , value , dialect ) : if self . __use_json ( dialect ) or value is None : return value return self . __json_codec . dumps ( value , ensure_ascii = not self . __enforce_unicode ) | Encode data if required . |
22,706 | def process_result_value ( self , value , dialect ) : if self . __use_json ( dialect ) or value is None : return value return self . __json_codec . loads ( value ) | Decode data if required . |
22,707 | async def get ( self , uid : int , cached_msg : CachedMessage = None , requirement : FetchRequirement = FetchRequirement . METADATA ) -> Optional [ MessageT ] : ... | Return the message with the given UID . |
22,708 | async def update_flags ( self , messages : Sequence [ MessageT ] , flag_set : FrozenSet [ Flag ] , mode : FlagOp ) -> None : ... | Update the permanent flags of each messages . |
22,709 | async def find ( self , seq_set : SequenceSet , selected : SelectedMailbox , requirement : FetchRequirement = FetchRequirement . METADATA ) -> AsyncIterable [ Tuple [ int , MessageT ] ] : for seq , cached_msg in selected . messages . get_all ( seq_set ) : msg = await self . get ( cached_msg . uid , cached_msg , requirement ) if msg is not None : yield ( seq , msg ) | 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 . |
22,710 | async def find_deleted ( self , seq_set : SequenceSet , selected : SelectedMailbox ) -> Sequence [ int ] : session_flags = selected . session_flags return [ msg . uid async for _ , msg in self . find ( seq_set , selected ) if Deleted in msg . get_flags ( session_flags ) ] | Return all the active message UIDs that have the \\ Deleted flag . |
22,711 | def content_type ( self ) -> Optional [ ContentTypeHeader ] : try : return cast ( ContentTypeHeader , self [ b'content-type' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Content - Type header . |
22,712 | def date ( self ) -> Optional [ DateHeader ] : try : return cast ( DateHeader , self [ b'date' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Date header . |
22,713 | def subject ( self ) -> Optional [ UnstructuredHeader ] : try : return cast ( UnstructuredHeader , self [ b'subject' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Subject header . |
22,714 | def from_ ( self ) -> Optional [ Sequence [ AddressHeader ] ] : try : return cast ( Sequence [ AddressHeader ] , self [ b'from' ] ) except KeyError : return None | The From header . |
22,715 | def sender ( self ) -> Optional [ Sequence [ SingleAddressHeader ] ] : try : return cast ( Sequence [ SingleAddressHeader ] , self [ b'sender' ] ) except KeyError : return None | The Sender header . |
22,716 | def reply_to ( self ) -> Optional [ Sequence [ AddressHeader ] ] : try : return cast ( Sequence [ AddressHeader ] , self [ b'reply-to' ] ) except KeyError : return None | The Reply - To header . |
22,717 | def to ( self ) -> Optional [ Sequence [ AddressHeader ] ] : try : return cast ( Sequence [ AddressHeader ] , self [ b'to' ] ) except KeyError : return None | The To header . |
22,718 | def cc ( self ) -> Optional [ Sequence [ AddressHeader ] ] : try : return cast ( Sequence [ AddressHeader ] , self [ b'cc' ] ) except KeyError : return None | The Cc header . |
22,719 | def bcc ( self ) -> Optional [ Sequence [ AddressHeader ] ] : try : return cast ( Sequence [ AddressHeader ] , self [ b'bcc' ] ) except KeyError : return None | The Bcc header . |
22,720 | def in_reply_to ( self ) -> Optional [ UnstructuredHeader ] : try : return cast ( UnstructuredHeader , self [ b'in-reply-to' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The In - Reply - To header . |
22,721 | def message_id ( self ) -> Optional [ UnstructuredHeader ] : try : return cast ( UnstructuredHeader , self [ b'message-id' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Message - Id header . |
22,722 | def content_disposition ( self ) -> Optional [ ContentDispositionHeader ] : try : return cast ( ContentDispositionHeader , self [ b'content-disposition' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Content - Disposition header . |
22,723 | def content_language ( self ) -> Optional [ UnstructuredHeader ] : try : return cast ( UnstructuredHeader , self [ b'content-language' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Content - Language header . |
22,724 | def content_location ( self ) -> Optional [ UnstructuredHeader ] : try : return cast ( UnstructuredHeader , self [ b'content-location' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Content - Location header . |
22,725 | def content_id ( self ) -> Optional [ UnstructuredHeader ] : try : return cast ( UnstructuredHeader , self [ b'content-id' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Content - Id header . |
22,726 | def content_description ( self ) -> Optional [ UnstructuredHeader ] : try : return cast ( UnstructuredHeader , self [ b'content-description' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Content - Description header . |
22,727 | def content_transfer_encoding ( self ) -> Optional [ ContentTransferEncodingHeader ] : try : return cast ( ContentTransferEncodingHeader , self [ b'content-transfer-encoding' ] [ 0 ] ) except ( KeyError , IndexError ) : return None | The Content - Transfer - Encoding header . |
22,728 | 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' : 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 ) | Copy the parameters possibly replacing a subset . |
22,729 | def string ( self ) -> bytes : if self . _raw is not None : return self . _raw self . _raw = raw = BytesFormat ( b' ' ) . join ( [ b'CAPABILITY' , b'IMAP4rev1' ] + self . capabilities ) return raw | The capabilities string without the enclosing square brackets . |
22,730 | def text ( self ) -> bytes : 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 ) | The response text . |
22,731 | def add_untagged ( self , * responses : 'Response' ) -> None : for resp in responses : try : merge_key = resp . merge_key except TypeError : self . _untagged . append ( resp ) else : key = ( type ( resp ) , merge_key ) try : 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 | Add an untagged response . These responses are shown before the parent response . |
22,732 | def add_untagged_ok ( self , text : MaybeBytes , code : Optional [ ResponseCode ] = None ) -> None : response = ResponseOk ( b'*' , text , code ) self . add_untagged ( response ) | Add an untagged OK response . |
22,733 | 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 . |
22,734 | def is_all ( self ) -> bool : first = self . sequences [ 0 ] return isinstance ( first , tuple ) and first [ 0 ] == 1 and isinstance ( first [ 1 ] , MaxValue ) | True if the sequence set starts at 1 and ends at the maximum value . |
22,735 | 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 . |
22,736 | def build ( cls , seqs : Iterable [ int ] , uid : bool = False ) -> 'SequenceSet' : seqs_list = sorted ( set ( seqs ) ) groups : List [ Union [ int , Tuple [ int , int ] ] ] = [ ] group : Union [ int , Tuple [ int , int ] ] = seqs_list [ 0 ] for i in range ( 1 , len ( seqs_list ) ) : group_i = seqs_list [ i ] 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 ) | Build a new sequence set that contains the given values using as few groups as possible . |
22,737 | def update ( self , * names : str ) -> 'ListTree' : for name in names : parts = name . split ( self . _delimiter ) self . _root . add ( * parts ) return self | Add all the mailbox names to the tree filling in any missing nodes . |
22,738 | def set_marked ( self , name : str , marked : bool = False , unmarked : bool = False ) -> None : if marked : self . _marked [ name ] = True elif unmarked : self . _marked [ name ] = False else : self . _marked . pop ( name , None ) | Add or remove the \\ Marked and \\ Unmarked mailbox attributes . |
22,739 | def get ( self , name : str ) -> Optional [ ListEntry ] : parts = name . split ( self . _delimiter ) try : node = self . _find ( self . _root , * parts ) except KeyError : return None else : marked = self . _marked . get ( name ) return ListEntry ( name , node . exists , marked , bool ( node . children ) ) | Return the named entry in the list tree . |
22,740 | def list ( self ) -> Iterable [ ListEntry ] : for entry in self . _iter ( self . _root , '' ) : yield entry | Return all the entries in the list tree . |
22,741 | def list_matching ( self , ref_name : str , filter_ : str ) -> Iterable [ ListEntry ] : canonical , canonical_i = self . _get_pattern ( ref_name + filter_ ) for entry in self . list ( ) : if entry . name == 'INBOX' : if canonical_i . match ( 'INBOX' ) : yield entry elif canonical . match ( entry . name ) : yield entry | Return all the entries in the list tree that match the given query . |
22,742 | def get ( self , uid : int ) -> Optional [ CachedMessage ] : return self . _cache . get ( uid ) | Return the given cached message . |
22,743 | def get_all ( self , seq_set : SequenceSet ) -> Sequence [ Tuple [ int , CachedMessage ] ] : if seq_set . uid : all_uids = seq_set . flatten ( self . max_uid ) & self . _uids return [ ( seq , self . _cache [ uid ] ) for seq , uid in enumerate ( self . _sorted , 1 ) 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 ] | Return the cached messages and their sequence numbers for the given sequence set . |
22,744 | def add_updates ( self , messages : Iterable [ CachedMessage ] , expunged : Iterable [ int ] ) -> None : self . _messages . _update ( messages ) self . _messages . _remove ( expunged , self . _hide_expunged ) if not self . _hide_expunged : self . _session_flags . remove ( 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 is the set of UIDs that have been expunged from the mailbox . |
22,745 | def silence ( self , seq_set : SequenceSet , flag_set : AbstractSet [ Flag ] , flag_op : FlagOp ) -> None : 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 ) ) | Runs the flags update against the cached flags to prevent untagged FETCH responses unless other updates have occurred . |
22,746 | def fork ( self , command : Command ) -> Tuple [ 'SelectedMailbox' , Iterable [ Response ] ] : frozen = _Frozen ( self ) cls = type ( self ) copy = cls ( self . _guid , self . _readonly , self . _permanent_flags , self . _session_flags , self . _selected_set , self . _lookup , _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 | 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 . |
22,747 | def parse_done ( self , buf : memoryview ) -> Tuple [ bool , memoryview ] : match = self . _pattern . match ( buf ) if not match : raise NotParseable ( buf ) done = match . group ( 1 ) . upper ( ) == self . continuation buf = buf [ match . end ( 0 ) : ] return done , buf | Parse the continuation line sent by the client to end the IDLE command . |
22,748 | def set ( self , folder : str , subscribed : bool ) -> None : if subscribed : self . add ( folder ) else : self . remove ( folder ) | Set the subscribed status of a folder . |
22,749 | def new_uid_validity ( cls ) -> int : time_part = int ( time . time ( ) ) % 4096 rand_part = random . randint ( 0 , 1048576 ) return ( time_part << 20 ) + rand_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 . |
22,750 | def to_maildir ( self , flags : Iterable [ Union [ bytes , Flag ] ] ) -> str : codes = [ ] for flag in flags : if isinstance ( flag , bytes ) : flag = Flag ( flag ) from_sys = self . _from_sys . get ( flag ) if from_sys is not None : codes . append ( from_sys ) else : from_kwd = self . _from_kwd . get ( flag ) if from_kwd is not None : codes . append ( from_kwd ) return '' . join ( codes ) | Return the string of letter codes that are used to map to defined IMAP flags and keywords . |
22,751 | def from_maildir ( self , codes : str ) -> FrozenSet [ Flag ] : flags = set ( ) for code in codes : if code == ',' : break to_sys = self . _to_sys . get ( code ) if to_sys is not None : flags . add ( to_sys ) else : to_kwd = self . _to_kwd . get ( code ) if to_kwd is not None : flags . add ( to_kwd ) return frozenset ( flags ) | Return the set of IMAP flags that correspond to the letter codes . |
22,752 | async def login ( cls , credentials : AuthenticationCredentials , config : Config ) -> 'Session' : 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 ) | 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 . |
22,753 | 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 . |
22,754 | def of_cte ( cls , header : Optional [ ContentTransferEncodingHeader ] ) -> 'MessageDecoder' : if header is None : return _NoopDecoder ( ) hdr_str = str ( header ) . lower ( ) custom = cls . registry . get ( hdr_str ) if custom is not None : return custom elif 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 ) | Return a decoder from the CTE header value . |
22,755 | async def find_user ( cls , config : Config , user : str ) -> Tuple [ str , str ] : with open ( config . users_file , 'r' ) as users_file : for line in users_file : this_user , user_dir , password = line . split ( ':' , 2 ) if user == this_user : return password . rstrip ( '\r\n' ) , user_dir or user raise InvalidAuth ( ) | If the given user ID exists return its expected password and mailbox path . Override this method to implement custom login logic . |
22,756 | def modutf7_encode ( data : str ) -> bytes : ret = bytearray ( ) is_usascii = True encode_start = None for i , symbol in enumerate ( data ) : charpoint = ord ( symbol ) if is_usascii : if charpoint == 0x26 : ret . extend ( b'&-' ) elif 0x20 <= charpoint <= 0x7e : 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 ) | Encode the string using modified UTF - 7 . |
22,757 | def modutf7_decode ( data : bytes ) -> str : parts = [ ] is_usascii = True buf = memoryview ( data ) while buf : byte = buf [ 0 ] if is_usascii : if buf [ 0 : 2 ] == b'&-' : parts . append ( '&' ) buf = buf [ 2 : ] elif byte == 0x26 : is_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 ) | Decode the bytestring using modified UTF - 7 . |
22,758 | def format ( self , data : Iterable [ _FormatArg ] ) -> bytes : fix_arg = self . _fix_format_arg return self . how % tuple ( fix_arg ( item ) for item in data ) | String interpolation into the format string . |
22,759 | def join ( self , * data : Iterable [ MaybeBytes ] ) -> bytes : return self . how . join ( [ bytes ( item ) for item in chain ( * data ) ] ) | Iterable join on a delimiter . |
22,760 | 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 . |
22,761 | 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 . |
22,762 | async def rename_mailbox ( self , before_name : str , after_name : str , selected : SelectedMailbox = None ) -> Optional [ SelectedMailbox ] : ... | Renames the mailbox owned by the user . |
22,763 | 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 . |
22,764 | 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 . |
22,765 | async def check_mailbox ( self , selected : SelectedMailbox , * , wait_on : Event = None , housekeeping : bool = False ) -> SelectedMailbox : ... | Checks for any updates in the mailbox . |
22,766 | 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 . |
22,767 | 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 . |
22,768 | 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 . |
22,769 | 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 . |
22,770 | 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 . |
22,771 | def requirement ( self ) -> FetchRequirement : 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 | Indicates the data required to fulfill this search key . |
22,772 | def claim_new ( self ) -> Iterable [ str ] : 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 ] | Checks for messages in the new subdirectory moving them to cur and returning their keys . |
22,773 | async def Append ( self , stream ) -> None : 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 ) | Append a message directly to a user s mailbox . |
22,774 | def apply ( self , flag_set : AbstractSet [ Flag ] , operand : AbstractSet [ Flag ] ) -> FrozenSet [ Flag ] : if self == FlagOp . ADD : return frozenset ( flag_set | operand ) elif self == FlagOp . DELETE : return frozenset ( flag_set - operand ) else : return frozenset ( operand ) | Apply the flag operation on the two sets returning the result . |
22,775 | def get ( self , uid : int ) -> FrozenSet [ Flag ] : recent = _recent_set if uid in self . _recent else frozenset ( ) flags = self . _flags . get ( uid ) return recent if flags is None else ( flags | recent ) | Return the session flags for the mailbox session . |
22,776 | def remove ( self , uids : Iterable [ int ] ) -> None : for uid in uids : self . _recent . discard ( uid ) self . _flags . pop ( uid , None ) | Remove any session flags for the given message . |
22,777 | def update ( self , uid : int , flag_set : Iterable [ Flag ] , op : FlagOp = FlagOp . REPLACE ) -> FrozenSet [ Flag ] : orig_set = self . _flags . get ( uid , frozenset ( ) ) new_flags = op . apply ( orig_set , self & flag_set ) if new_flags : self . _flags [ uid ] = new_flags else : self . _flags . pop ( uid , None ) return new_flags | Update the flags for the session returning the resulting flags . |
22,778 | def get_system_flags ( ) -> FrozenSet [ Flag ] : return frozenset ( { Seen , Recent , Deleted , Flagged , Answered , Draft } ) | Return the set of implemented system flags . |
22,779 | def register ( self , cmd : Type [ Command ] ) -> None : self . commands [ cmd . command ] = cmd | Register a new IMAP command . |
22,780 | def get_as ( self , cls : Type [ MaybeBytesT ] ) -> Sequence [ MaybeBytesT ] : _ = cls return cast ( Sequence [ MaybeBytesT ] , self . items ) | Return the list of parsed objects . |
22,781 | def get_all ( self , attrs : Iterable [ FetchAttribute ] ) -> Sequence [ Tuple [ FetchAttribute , MaybeBytes ] ] : ret : List [ Tuple [ FetchAttribute , MaybeBytes ] ] = [ ] for attr in attrs : try : ret . append ( ( attr . for_response , self . get ( attr ) ) ) except NotFetchable : pass return ret | Return a list of tuples containing the attribute iself and the bytes representation of that attribute from the message . |
22,782 | def get ( self , attr : FetchAttribute ) -> MaybeBytes : attr_name = attr . value . decode ( 'ascii' ) method = getattr ( self , '_get_' + attr_name . replace ( '.' , '_' ) ) return method ( attr ) | Return the bytes representation of the given message attribue . |
22,783 | def sequence_set ( self ) -> SequenceSet : 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 | 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 . |
22,784 | 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 . |
22,785 | def walk ( self ) -> Iterable [ 'MessageContent' ] : if self . body . has_nested : return chain ( [ self ] , * ( part . walk ( ) for part in self . body . nested ) ) else : return [ self ] | Iterate through the message and all its nested sub - parts in the order they occur . |
22,786 | def parse ( cls , data : bytes ) -> 'MessageContent' : lines = cls . _find_lines ( data ) view = memoryview ( data ) return cls . _parse ( data , view , lines ) | Parse the bytestring into message content . |
22,787 | def parse_split ( cls , header : bytes , body : bytes ) -> 'MessageContent' : header_lines = cls . _find_lines ( header ) body_lines = cls . _find_lines ( body ) header_view = memoryview ( header ) body_view = memoryview ( body ) return cls . _parse_split ( [ header_view , body_view ] , header , body , header_view , body_view , header_lines , body_lines ) | Parse the header and body bytestrings into message content . |
22,788 | def get_all ( self , uids : Iterable [ int ] ) -> Mapping [ int , Record ] : return { uid : self . _records [ uid ] for uid in uids if uid in self . _records } | Get records by a set of UIDs . |
22,789 | def spell ( word ) : 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 ) | most likely correction for everything up to a double typo |
22,790 | def words_from_archive ( filename , include_dups = False , map_case = False ) : 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 ) | extract words from a text file in the archive |
22,791 | def parse ( lang_sample ) : words = words_from_archive ( lang_sample , include_dups = True ) counts = zero_default_dict ( ) for word in words : counts [ word ] += 1 return set ( words ) , counts | tally word popularity using novel extracts etc |
22,792 | def get_case ( word , correction ) : 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 ] ) : try : return CASE_MAPPED [ correction ] except KeyError : pass return correction | Best guess of intended case . |
22,793 | def typos ( self ) : return ( self . _deletes ( ) | self . _transposes ( ) | self . _replaces ( ) | self . _inserts ( ) ) | letter combinations one typo away from word |
22,794 | def double_typos ( self ) : return { e2 for e1 in self . typos ( ) for e2 in Word ( e1 ) . typos ( ) } | letter combinations two typos away from word |
22,795 | def register ( lib_name : str , cbl : Callable [ [ _AsyncLib ] , None ] ) : return manager . register ( lib_name , cbl ) | Registers a new library function with the current manager . |
22,796 | def init ( library : typing . Union [ str , types . ModuleType ] ) -> None : if isinstance ( library , types . ModuleType ) : library = library . __name__ if library not in manager . _handlers : raise ValueError ( "Possible values are <{}>, not <{}>" . format ( manager . _handlers . keys ( ) , library ) ) manager . init ( library , asynclib ) asynclib . lib_name = library asynclib . _init = True | Must be called at some point after import and before your event loop is run . |
22,797 | def run ( * args , ** kwargs ) : lib = sys . modules [ asynclib . lib_name ] lib . run ( * args , ** kwargs ) | Runs the appropriate library run function . |
22,798 | async def recv ( self , nbytes : int = - 1 , ** kwargs ) -> bytes : return await asynclib . recv ( self . sock , nbytes , ** kwargs ) | Receives some data on the socket . |
22,799 | async def sendall ( self , data : bytes , * args , ** kwargs ) : return await asynclib . sendall ( self . sock , data , * args , ** kwargs ) | Sends some data on the socket . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.