idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
61,800 | def adjust_version_as_of ( version , relations_as_of ) : if not version : return version if relations_as_of == 'end' : if version . is_current : version . as_of = None else : version . as_of = version . version_end_date - datetime . timedelta ( microseconds = 1 ) elif relations_as_of == 'start' : version . as_of = vers... | Adjusts the passed version s as_of time to an appropriate value and returns it . |
61,801 | def _fetch_all ( self ) : if self . _result_cache is None : self . _result_cache = list ( self . iterator ( ) ) if self . _iterable_class == ModelIterable : for x in self . _result_cache : self . _set_item_querytime ( x ) if self . _prefetch_related_lookups and not self . _prefetch_done : self . _prefetch_related_objec... | Completely overrides the QuerySet . _fetch_all method by adding the timestamp to all objects |
61,802 | def _clone ( self , * args , ** kwargs ) : clone = super ( VersionedQuerySet , self ) . _clone ( ** kwargs ) clone . querytime = self . querytime return clone | Overrides the QuerySet . _clone method by adding the cloning of the VersionedQuerySet s query_time parameter |
61,803 | def _set_item_querytime ( self , item , type_check = True ) : if isinstance ( item , Versionable ) : item . _querytime = self . querytime elif isinstance ( item , VersionedQuerySet ) : item . querytime = self . querytime else : if type_check : raise TypeError ( "This item is not a Versionable, it's a " + str ( type ( i... | Sets the time for which the query was made on the resulting item |
61,804 | def as_of ( self , qtime = None ) : clone = self . _clone ( ) clone . querytime = QueryTime ( time = qtime , active = True ) return clone | Sets the time for which we want to retrieve an object . |
61,805 | def delete ( self ) : assert self . query . can_filter ( ) , "Cannot use 'limit' or 'offset' with delete." del_query = self . filter ( version_end_date__isnull = True ) del_query . _for_write = True del_query . query . select_for_update = False del_query . query . select_related = False del_query . query . clear_orderi... | Deletes the records in the QuerySet . |
61,806 | def uuid ( uuid_value = None ) : if uuid_value : if not validate_uuid ( uuid_value ) : raise ValueError ( "uuid_value must be a valid UUID version 4 object" ) else : uuid_value = uuid . uuid4 ( ) if versions_settings . VERSIONS_USE_UUIDFIELD : return uuid_value else : return six . u ( str ( uuid_value ) ) | Returns a uuid value that is valid to use for id and identity fields . |
61,807 | def restore ( self , ** kwargs ) : if not self . pk : raise ValueError ( 'Instance must be saved and terminated before it can be ' 'restored.' ) if self . is_current : raise ValueError ( 'This is the current version, no need to restore it.' ) if self . get_deferred_fields ( ) : raise ValueError ( 'Can not restore a mod... | Restores this version as a new version and returns this new version . |
61,808 | def detach ( self ) : self . id = self . identity = self . uuid ( ) self . version_start_date = self . version_birth_date = get_utc_now ( ) self . version_end_date = None return self | Detaches the instance from its history . |
61,809 | def matches_querytime ( instance , querytime ) : if not querytime . active : return True if not querytime . time : return instance . version_end_date is None return ( instance . version_start_date <= querytime . time and ( instance . version_end_date is None or instance . version_end_date > querytime . time ) ) | Checks whether the given instance satisfies the given QueryTime object . |
61,810 | def contribute_to_related_class ( self , cls , related ) : super ( VersionedForeignKey , self ) . contribute_to_related_class ( cls , related ) accessor_name = related . get_accessor_name ( ) if hasattr ( cls , accessor_name ) : setattr ( cls , accessor_name , VersionedReverseManyToOneDescriptor ( related ) ) | Override ForeignKey s methods and replace the descriptor if set by the parent s methods |
61,811 | def get_joining_columns ( self , reverse_join = False ) : source = self . reverse_related_fields if reverse_join else self . related_fields joining_columns = tuple ( ) for lhs_field , rhs_field in source : lhs_col_name = lhs_field . column rhs_col_name = rhs_field . column if self is lhs_field and not self . auto_creat... | Get and return joining columns defined by this foreign key relationship |
61,812 | def get_versioned_delete_collector_class ( ) : key = 'VERSIONED_DELETE_COLLECTOR' try : cls = _cache [ key ] except KeyError : collector_class_string = getattr ( settings , key ) cls = import_from_string ( collector_class_string , key ) _cache [ key ] = cls return cls | Gets the class to use for deletion collection . |
61,813 | def related_objects ( self , related , objs ) : from versions . models import Versionable related_model = related . related_model if issubclass ( related_model , Versionable ) : qs = related_model . objects . current else : qs = related_model . _base_manager . all ( ) return qs . using ( self . using ) . filter ( ** { ... | Gets a QuerySet of current objects related to objs via the relation related . |
61,814 | def versionable_delete ( self , instance , timestamp ) : instance . _delete_at ( timestamp , using = self . using ) | Soft - deletes the instance setting it s version_end_date to timestamp . |
61,815 | def pks_from_objects ( self , objects ) : return { o . pk if isinstance ( o , Model ) else o for o in objects } | Extract all the primary key strings from the given objects . Objects may be Versionables or bare primary keys . |
61,816 | def fit ( self , vecs , iter = 20 , seed = 123 ) : assert vecs . dtype == np . float32 assert vecs . ndim == 2 N , D = vecs . shape assert self . Ks < N , "the number of training vector should be more than Ks" assert D % self . M == 0 , "input dimension must be dividable by M" self . Ds = int ( D / self . M ) np . rand... | Given training vectors run k - means for each sub - space and create codewords for each sub - space . |
61,817 | def encode ( self , vecs ) : assert vecs . dtype == np . float32 assert vecs . ndim == 2 N , D = vecs . shape assert D == self . Ds * self . M , "input dimension must be Ds * M" codes = np . empty ( ( N , self . M ) , dtype = self . code_dtype ) for m in range ( self . M ) : if self . verbose : print ( "Encoding the su... | Encode input vectors into PQ - codes . |
61,818 | def decode ( self , codes ) : assert codes . ndim == 2 N , M = codes . shape assert M == self . M assert codes . dtype == self . code_dtype vecs = np . empty ( ( N , self . Ds * self . M ) , dtype = np . float32 ) for m in range ( self . M ) : vecs [ : , m * self . Ds : ( m + 1 ) * self . Ds ] = self . codewords [ m ] ... | Given PQ - codes reconstruct original D - dimensional vectors approximately by fetching the codewords . |
61,819 | def transaction ( ) : client = default_client ( ) _thread . client = client . pipeline ( ) try : yield _thread . client . execute ( ) finally : _thread . client = client | Swaps out the current client with a pipeline instance so that each Redis method call inside the context will be pipelined . Once the context is exited we execute the pipeline . |
61,820 | def _get_lua_path ( self , name ) : parts = ( os . path . dirname ( os . path . abspath ( __file__ ) ) , "lua" , name ) return os . path . join ( * parts ) | Joins the given name with the relative path of the module . |
61,821 | def _create_lua_method ( self , name , code ) : script = self . register_script ( code ) setattr ( script , "name" , name ) method = lambda key , * a , ** k : script ( keys = [ key ] , args = a , ** k ) setattr ( self , name , method ) | Registers the code snippet as a Lua script and binds the script to the client as a method that can be called with the same signature as regular client methods eg with a single key arg . |
61,822 | def value_left ( self , other ) : return other . value if isinstance ( other , self . __class__ ) else other | Returns the value of the other type instance to use in an operator method namely when the method s instance is on the left side of the expression . |
61,823 | def value_right ( self , other ) : return self if isinstance ( other , self . __class__ ) else self . value | Returns the value of the type instance calling an to use in an operator method namely when the method s instance is on the right side of the expression . |
61,824 | def op_left ( op ) : def method ( self , other ) : return op ( self . value , value_left ( self , other ) ) return method | Returns a type instance method for the given operator applied when the instance appears on the left side of the expression . |
61,825 | def op_right ( op ) : def method ( self , other ) : return op ( value_left ( self , other ) , value_right ( self , other ) ) return method | Returns a type instance method for the given operator applied when the instance appears on the right side of the expression . |
61,826 | def on ( self , event , f = None ) : def _on ( f ) : self . _add_event_handler ( event , f , f ) return f if f is None : return _on else : return _on ( f ) | Registers the function f to the event name event . |
61,827 | def once ( self , event , f = None ) : def _wrapper ( f ) : def g ( * args , ** kwargs ) : self . remove_listener ( event , f ) return f ( * args , ** kwargs ) self . _add_event_handler ( event , f , g ) return f if f is None : return _wrapper else : return _wrapper ( f ) | The same as ee . on except that the listener is automatically removed after being called . |
61,828 | def remove_all_listeners ( self , event = None ) : if event is not None : self . _events [ event ] = OrderedDict ( ) else : self . _events = defaultdict ( OrderedDict ) | Remove all listeners attached to event . If event is None remove all listeners on all events . |
61,829 | def offsetcopy ( s , newoffset ) : assert 0 <= newoffset < 8 if not s . bitlength : return copy . copy ( s ) else : if newoffset == s . offset % 8 : return ByteStore ( s . getbyteslice ( s . byteoffset , s . byteoffset + s . bytelength ) , s . bitlength , newoffset ) newdata = [ ] d = s . _rawarray assert newoffset != ... | Return a copy of a ByteStore with the newoffset . |
61,830 | def structparser ( token ) : m = STRUCT_PACK_RE . match ( token ) if not m : return [ token ] else : endian = m . group ( 'endian' ) if endian is None : return [ token ] formatlist = re . findall ( STRUCT_SPLIT_RE , m . group ( 'fmt' ) ) fmt = '' . join ( [ f [ - 1 ] * int ( f [ : - 1 ] ) if len ( f ) != 1 else f for f... | Parse struct - like format string token into sub - token list . |
61,831 | def tokenparser ( fmt , keys = None , token_cache = { } ) : try : return token_cache [ ( fmt , keys ) ] except KeyError : token_key = ( fmt , keys ) fmt = expand_brackets ( fmt ) meta_tokens = ( '' . join ( f . split ( ) ) for f in fmt . split ( ',' ) ) return_values = [ ] stretchy_token = False for meta_token in meta_... | Divide the format string into tokens and parse them . |
61,832 | def expand_brackets ( s ) : s = '' . join ( s . split ( ) ) while True : start = s . find ( '(' ) if start == - 1 : break count = 1 p = start + 1 while p < len ( s ) : if s [ p ] == '(' : count += 1 if s [ p ] == ')' : count -= 1 if not count : break p += 1 if count : raise ValueError ( "Unbalanced parenthesis in '{0}'... | Remove whitespace and expand all brackets . |
61,833 | def pack ( fmt , * values , ** kwargs ) : tokens = [ ] if isinstance ( fmt , basestring ) : fmt = [ fmt ] try : for f_item in fmt : _ , tkns = tokenparser ( f_item , tuple ( sorted ( kwargs . keys ( ) ) ) ) tokens . extend ( tkns ) except ValueError as e : raise CreationError ( * e . args ) value_iter = iter ( values )... | Pack the values according to the format string and return a new BitStream . |
61,834 | def getbyteslice ( self , start , end ) : c = self . _rawarray [ start : end ] return c | Direct access to byte data . |
61,835 | def _appendstore ( self , store ) : if not store . bitlength : return store = offsetcopy ( store , ( self . offset + self . bitlength ) % 8 ) if store . offset : joinval = ( self . _rawarray . pop ( ) & ( 255 ^ ( 255 >> store . offset ) ) | ( store . getbyte ( 0 ) & ( 255 >> store . offset ) ) ) self . _rawarray . appe... | Join another store on to the end of this one . |
61,836 | def _prependstore ( self , store ) : if not store . bitlength : return store = offsetcopy ( store , ( self . offset - store . bitlength ) % 8 ) assert ( store . offset + store . bitlength ) % 8 == self . offset % 8 bit_offset = self . offset % 8 if bit_offset : store . setbyte ( - 1 , ( store . getbyte ( - 1 ) & ( 255 ... | Join another store on to the start of this one . |
61,837 | def _assertsanity ( self ) : assert self . len >= 0 assert 0 <= self . _offset , "offset={0}" . format ( self . _offset ) assert ( self . len + self . _offset + 7 ) // 8 == self . _datastore . bytelength + self . _datastore . byteoffset return True | Check internal self consistency as a debugging aid . |
61,838 | def _setauto ( self , s , length , offset ) : if isinstance ( s , Bits ) : if length is None : length = s . len - offset self . _setbytes_unsafe ( s . _datastore . rawbytes , length , s . _offset + offset ) return if isinstance ( s , file ) : if offset is None : offset = 0 if length is None : length = os . path . getsi... | Set bitstring from a bitstring file bool integer array iterable or string . |
61,839 | def _setfile ( self , filename , length , offset ) : source = open ( filename , 'rb' ) if offset is None : offset = 0 if length is None : length = os . path . getsize ( source . name ) * 8 - offset byteoffset , offset = divmod ( offset , 8 ) bytelength = ( length + byteoffset * 8 + offset + 7 ) // 8 - byteoffset m = Mm... | Use file as source of bits . |
61,840 | def _setbytes_safe ( self , data , length = None , offset = 0 ) : data = bytearray ( data ) if length is None : length = len ( data ) * 8 - offset self . _datastore = ByteStore ( data , length , offset ) else : if length + offset > len ( data ) * 8 : msg = "Not enough data present. Need {0} bits, have {1}." raise Creat... | Set the data from a string . |
61,841 | def _setbytes_unsafe ( self , data , length , offset ) : self . _datastore = ByteStore ( data [ : ] , length , offset ) assert self . _assertsanity ( ) | Unchecked version of _setbytes_safe . |
61,842 | def _readbytes ( self , length , start ) : assert length % 8 == 0 assert start + length <= self . len if not ( start + self . _offset ) % 8 : return bytes ( self . _datastore . getbyteslice ( ( start + self . _offset ) // 8 , ( start + self . _offset + length ) // 8 ) ) return self . _slice ( start , start + length ) .... | Read bytes and return them . Note that length is in bits . |
61,843 | def _setuint ( self , uint , length = None ) : try : if length is None : length = self . _datastore . bitlength except AttributeError : pass if length is None or length == 0 : raise CreationError ( "A non-zero length must be specified with a " "uint initialiser." ) if uint >= ( 1 << length ) : msg = "{0} is too large a... | Reset the bitstring to have given unsigned int interpretation . |
61,844 | def _readuint ( self , length , start ) : if not length : raise InterpretError ( "Cannot interpret a zero length bitstring " "as an integer." ) offset = self . _offset startbyte = ( start + offset ) // 8 endbyte = ( start + offset + length - 1 ) // 8 b = binascii . hexlify ( bytes ( self . _datastore . getbyteslice ( s... | Read bits and interpret as an unsigned int . |
61,845 | def _setint ( self , int_ , length = None ) : if length is None and hasattr ( self , 'len' ) and self . len != 0 : length = self . len if length is None or length == 0 : raise CreationError ( "A non-zero length must be specified with an int initialiser." ) if int_ >= ( 1 << ( length - 1 ) ) or int_ < - ( 1 << ( length ... | Reset the bitstring to have given signed int interpretation . |
61,846 | def _readint ( self , length , start ) : ui = self . _readuint ( length , start ) if not ui >> ( length - 1 ) : return ui tmp = ( ~ ( ui - 1 ) ) & ( ( 1 << length ) - 1 ) return - tmp | Read bits and interpret as a signed int |
61,847 | def _setuintbe ( self , uintbe , length = None ) : if length is not None and length % 8 != 0 : raise CreationError ( "Big-endian integers must be whole-byte. " "Length = {0} bits." , length ) self . _setuint ( uintbe , length ) | Set the bitstring to a big - endian unsigned int interpretation . |
61,848 | def _readuintbe ( self , length , start ) : if length % 8 : raise InterpretError ( "Big-endian integers must be whole-byte. " "Length = {0} bits." , length ) return self . _readuint ( length , start ) | Read bits and interpret as a big - endian unsigned int . |
61,849 | def _setintbe ( self , intbe , length = None ) : if length is not None and length % 8 != 0 : raise CreationError ( "Big-endian integers must be whole-byte. " "Length = {0} bits." , length ) self . _setint ( intbe , length ) | Set bitstring to a big - endian signed int interpretation . |
61,850 | def _readintbe ( self , length , start ) : if length % 8 : raise InterpretError ( "Big-endian integers must be whole-byte. " "Length = {0} bits." , length ) return self . _readint ( length , start ) | Read bits and interpret as a big - endian signed int . |
61,851 | def _readuintle ( self , length , start ) : if length % 8 : raise InterpretError ( "Little-endian integers must be whole-byte. " "Length = {0} bits." , length ) assert start + length <= self . len absolute_pos = start + self . _offset startbyte , offset = divmod ( absolute_pos , 8 ) val = 0 if not offset : endbyte = ( ... | Read bits and interpret as a little - endian unsigned int . |
61,852 | def _readintle ( self , length , start ) : ui = self . _readuintle ( length , start ) if not ui >> ( length - 1 ) : return ui tmp = ( ~ ( ui - 1 ) ) & ( ( 1 << length ) - 1 ) return - tmp | Read bits and interpret as a little - endian signed int . |
61,853 | def _readfloat ( self , length , start ) : if not ( start + self . _offset ) % 8 : startbyte = ( start + self . _offset ) // 8 if length == 32 : f , = struct . unpack ( '>f' , bytes ( self . _datastore . getbyteslice ( startbyte , startbyte + 4 ) ) ) elif length == 64 : f , = struct . unpack ( '>d' , bytes ( self . _da... | Read bits and interpret as a float . |
61,854 | def _readfloatle ( self , length , start ) : startbyte , offset = divmod ( start + self . _offset , 8 ) if not offset : if length == 32 : f , = struct . unpack ( '<f' , bytes ( self . _datastore . getbyteslice ( startbyte , startbyte + 4 ) ) ) elif length == 64 : f , = struct . unpack ( '<d' , bytes ( self . _datastore... | Read bits and interpret as a little - endian float . |
61,855 | def _setue ( self , i ) : if i < 0 : raise CreationError ( "Cannot use negative initialiser for unsigned " "exponential-Golomb." ) if not i : self . _setbin_unsafe ( '1' ) return tmp = i + 1 leadingzeros = - 1 while tmp > 0 : tmp >>= 1 leadingzeros += 1 remainingpart = i + 1 - ( 1 << leadingzeros ) binstring = '0' * le... | Initialise bitstring with unsigned exponential - Golomb code for integer i . |
61,856 | def _readue ( self , pos ) : oldpos = pos try : while not self [ pos ] : pos += 1 except IndexError : raise ReadError ( "Read off end of bitstring trying to read code." ) leadingzeros = pos - oldpos codenum = ( 1 << leadingzeros ) - 1 if leadingzeros > 0 : if pos + leadingzeros + 1 > self . len : raise ReadError ( "Rea... | Return interpretation of next bits as unsigned exponential - Golomb code . |
61,857 | def _getue ( self ) : try : value , newpos = self . _readue ( 0 ) if value is None or newpos != self . len : raise ReadError except ReadError : raise InterpretError ( "Bitstring is not a single exponential-Golomb code." ) return value | Return data as unsigned exponential - Golomb code . |
61,858 | def _setse ( self , i ) : if i > 0 : u = ( i * 2 ) - 1 else : u = - 2 * i self . _setue ( u ) | Initialise bitstring with signed exponential - Golomb code for integer i . |
61,859 | def _getse ( self ) : try : value , newpos = self . _readse ( 0 ) if value is None or newpos != self . len : raise ReadError except ReadError : raise InterpretError ( "Bitstring is not a single exponential-Golomb code." ) return value | Return data as signed exponential - Golomb code . |
61,860 | def _readse ( self , pos ) : codenum , pos = self . _readue ( pos ) m = ( codenum + 1 ) // 2 if not codenum % 2 : return - m , pos else : return m , pos | Return interpretation of next bits as a signed exponential - Golomb code . |
61,861 | def _setuie ( self , i ) : if i < 0 : raise CreationError ( "Cannot use negative initialiser for unsigned " "interleaved exponential-Golomb." ) self . _setbin_unsafe ( '1' if i == 0 else '0' + '0' . join ( bin ( i + 1 ) [ 3 : ] ) + '1' ) | Initialise bitstring with unsigned interleaved exponential - Golomb code for integer i . |
61,862 | def _getuie ( self ) : try : value , newpos = self . _readuie ( 0 ) if value is None or newpos != self . len : raise ReadError except ReadError : raise InterpretError ( "Bitstring is not a single interleaved exponential-Golomb code." ) return value | Return data as unsigned interleaved exponential - Golomb code . |
61,863 | def _setsie ( self , i ) : if not i : self . _setbin_unsafe ( '1' ) else : self . _setuie ( abs ( i ) ) self . _append ( Bits ( [ i < 0 ] ) ) | Initialise bitstring with signed interleaved exponential - Golomb code for integer i . |
61,864 | def _getsie ( self ) : try : value , newpos = self . _readsie ( 0 ) if value is None or newpos != self . len : raise ReadError except ReadError : raise InterpretError ( "Bitstring is not a single interleaved exponential-Golomb code." ) return value | Return data as signed interleaved exponential - Golomb code . |
61,865 | def _readsie ( self , pos ) : codenum , pos = self . _readuie ( pos ) if not codenum : return 0 , pos try : if self [ pos ] : return - codenum , pos + 1 else : return codenum , pos + 1 except IndexError : raise ReadError ( "Read off end of bitstring trying to read code." ) | Return interpretation of next bits as a signed interleaved exponential - Golomb code . |
61,866 | def _setbin_safe ( self , binstring ) : binstring = tidy_input_string ( binstring ) binstring = binstring . replace ( '0b' , '' ) self . _setbin_unsafe ( binstring ) | Reset the bitstring to the value given in binstring . |
61,867 | def _setbin_unsafe ( self , binstring ) : length = len ( binstring ) boundary = ( ( length + 7 ) // 8 ) * 8 padded_binstring = binstring + '0' * ( boundary - length ) if len ( binstring ) < boundary else binstring try : bytelist = [ int ( padded_binstring [ x : x + 8 ] , 2 ) for x in xrange ( 0 , len ( padded_binstring... | Same as _setbin_safe but input isn t sanity checked . binstring mustn t start with 0b . |
61,868 | def _readbin ( self , length , start ) : if not length : return '' startbyte , startoffset = divmod ( start + self . _offset , 8 ) endbyte = ( start + self . _offset + length - 1 ) // 8 b = self . _datastore . getbyteslice ( startbyte , endbyte + 1 ) try : c = "{:0{}b}" . format ( int ( binascii . hexlify ( b ) , 16 ) ... | Read bits and interpret as a binary string . |
61,869 | def _setoct ( self , octstring ) : octstring = tidy_input_string ( octstring ) octstring = octstring . replace ( '0o' , '' ) binlist = [ ] for i in octstring : try : if not 0 <= int ( i ) < 8 : raise ValueError binlist . append ( OCT_TO_BITS [ int ( i ) ] ) except ValueError : raise CreationError ( "Invalid symbol '{0}... | Reset the bitstring to have the value given in octstring . |
61,870 | def _readoct ( self , length , start ) : if length % 3 : raise InterpretError ( "Cannot convert to octal unambiguously - " "not multiple of 3 bits." ) if not length : return '' end = oct ( self . _readuint ( length , start ) ) [ LEADING_OCT_CHARS : ] if end . endswith ( 'L' ) : end = end [ : - 1 ] middle = '0' * ( leng... | Read bits and interpret as an octal string . |
61,871 | def _sethex ( self , hexstring ) : hexstring = tidy_input_string ( hexstring ) hexstring = hexstring . replace ( '0x' , '' ) length = len ( hexstring ) if length % 2 : hexstring += '0' try : try : data = bytearray . fromhex ( hexstring ) except TypeError : data = bytearray . fromhex ( unicode ( hexstring ) ) except Val... | Reset the bitstring to have the value given in hexstring . |
61,872 | def _readhex ( self , length , start ) : if length % 4 : raise InterpretError ( "Cannot convert to hex unambiguously - " "not multiple of 4 bits." ) if not length : return '' s = self . _slice ( start , start + length ) . tobytes ( ) try : s = s . hex ( ) except AttributeError : s = str ( binascii . hexlify ( s ) . dec... | Read bits and interpret as a hex string . |
61,873 | def _ensureinmemory ( self ) : self . _setbytes_unsafe ( self . _datastore . getbyteslice ( 0 , self . _datastore . bytelength ) , self . len , self . _offset ) | Ensure the data is held in memory not in a file . |
61,874 | def _converttobitstring ( cls , bs , offset = 0 , cache = { } ) : if isinstance ( bs , Bits ) : return bs try : return cache [ ( bs , offset ) ] except KeyError : if isinstance ( bs , basestring ) : b = cls ( ) try : _ , tokens = tokenparser ( bs ) except ValueError as e : raise CreationError ( * e . args ) if tokens :... | Convert bs to a bitstring and return it . |
61,875 | def _slice ( self , start , end ) : if end == start : return self . __class__ ( ) offset = self . _offset startbyte , newoffset = divmod ( start + offset , 8 ) endbyte = ( end + offset - 1 ) // 8 bs = self . __class__ ( ) bs . _setbytes_unsafe ( self . _datastore . getbyteslice ( startbyte , endbyte + 1 ) , end - start... | Used internally to get a slice without error checking . |
61,876 | def _readtoken ( self , name , pos , length ) : if length is not None and int ( length ) > self . length - pos : raise ReadError ( "Reading off the end of the data. " "Tried to read {0} bits when only {1} available." . format ( int ( length ) , self . length - pos ) ) try : val = name_to_read [ name ] ( self , length ,... | Reads a token from the bitstring and returns the result . |
61,877 | def _reverse ( self ) : n = [ BYTE_REVERSAL_DICT [ b ] for b in self . _datastore . rawbytes ] n . reverse ( ) newoffset = 8 - ( self . _offset + self . len ) % 8 if newoffset == 8 : newoffset = 0 self . _setbytes_unsafe ( bytearray ( ) . join ( n ) , self . length , newoffset ) | Reverse all bits in - place . |
61,878 | def _truncateend ( self , bits ) : assert 0 <= bits <= self . len if not bits : return if bits == self . len : self . _clear ( ) return newlength_in_bytes = ( self . _offset + self . len - bits + 7 ) // 8 self . _setbytes_unsafe ( self . _datastore . getbyteslice ( 0 , newlength_in_bytes ) , self . len - bits , self . ... | Truncate bits from the end of the bitstring . |
61,879 | def _insert ( self , bs , pos ) : assert 0 <= pos <= self . len if pos > self . len // 2 : end = self . _slice ( pos , self . len ) self . _truncateend ( self . len - pos ) self . _append ( bs ) self . _append ( end ) else : start = self . _slice ( 0 , pos ) self . _truncatestart ( pos ) self . _prepend ( bs ) self . _... | Insert bs at pos . |
61,880 | def _overwrite ( self , bs , pos ) : assert 0 <= pos < self . len if bs is self : assert pos == 0 return firstbytepos = ( self . _offset + pos ) // 8 lastbytepos = ( self . _offset + pos + bs . len - 1 ) // 8 bytepos , bitoffset = divmod ( self . _offset + pos , 8 ) if firstbytepos == lastbytepos : mask = ( ( 1 << bs .... | Overwrite with bs at pos . |
61,881 | def _delete ( self , bits , pos ) : assert 0 <= pos <= self . len assert pos + bits <= self . len if not pos : self . _truncatestart ( bits ) return if pos + bits == self . len : self . _truncateend ( bits ) return if pos > self . len - pos - bits : end = self . _slice ( pos + bits , self . len ) assert self . len - po... | Delete bits at pos . |
61,882 | def _reversebytes ( self , start , end ) : newoffset = 8 - ( start % 8 ) if newoffset == 8 : newoffset = 0 self . _datastore = offsetcopy ( self . _datastore , newoffset ) toreverse = bytearray ( self . _datastore . getbyteslice ( ( newoffset + start ) // 8 , ( newoffset + end ) // 8 ) ) toreverse . reverse ( ) self . ... | Reverse bytes in - place . |
61,883 | def _set ( self , pos ) : assert 0 <= pos < self . len self . _datastore . setbit ( pos ) | Set bit at pos to 1 . |
61,884 | def _unset ( self , pos ) : assert 0 <= pos < self . len self . _datastore . unsetbit ( pos ) | Set bit at pos to 0 . |
61,885 | def _invert_all ( self ) : set = self . _datastore . setbyte get = self . _datastore . getbyte for p in xrange ( self . _datastore . byteoffset , self . _datastore . byteoffset + self . _datastore . bytelength ) : set ( p , 256 + ~ get ( p ) ) | Invert every bit . |
61,886 | def _ilshift ( self , n ) : assert 0 < n <= self . len self . _append ( Bits ( n ) ) self . _truncatestart ( n ) return self | Shift bits by n to the left in place . Return self . |
61,887 | def _irshift ( self , n ) : assert 0 < n <= self . len self . _prepend ( Bits ( n ) ) self . _truncateend ( n ) return self | Shift bits by n to the right in place . Return self . |
61,888 | def _imul ( self , n ) : assert n >= 0 if not n : self . _clear ( ) return self m = 1 old_len = self . len while m * 2 < n : self . _append ( self ) m *= 2 self . _append ( self [ 0 : ( n - m ) * old_len ] ) return self | Concatenate n copies of self in place . Return self . |
61,889 | def _validate_slice ( self , start , end ) : if start is None : start = 0 elif start < 0 : start += self . len if end is None : end = self . len elif end < 0 : end += self . len if not 0 <= end <= self . len : raise ValueError ( "end is not a valid position in the bitstring." ) if not 0 <= start <= self . len : raise V... | Validate start and end and return them as positive bit positions . |
61,890 | def _findbytes ( self , bytes_ , start , end , bytealigned ) : assert self . _datastore . offset == 0 assert bytealigned is True bytepos = ( start + 7 ) // 8 found = False p = bytepos finalpos = end // 8 increment = max ( 1024 , len ( bytes_ ) * 10 ) buffersize = increment + len ( bytes_ ) while p < finalpos : buf = by... | Quicker version of find when everything s whole byte and byte aligned . |
61,891 | def _findregex ( self , reg_ex , start , end , bytealigned ) : p = start length = len ( reg_ex . pattern ) increment = max ( 4096 , length * 10 ) buffersize = increment + length while p < end : buf = self . _readbin ( min ( buffersize , end - p ) , p ) m = reg_ex . search ( buf ) if m : pos = m . start ( ) if not bytea... | Find first occurrence of a compiled regular expression . |
61,892 | def find ( self , bs , start = None , end = None , bytealigned = None ) : bs = Bits ( bs ) if not bs . len : raise ValueError ( "Cannot find an empty bitstring." ) start , end = self . _validate_slice ( start , end ) if bytealigned is None : bytealigned = globals ( ) [ 'bytealigned' ] if bytealigned and not bs . len % ... | Find first occurrence of substring bs . |
61,893 | def findall ( self , bs , start = None , end = None , count = None , bytealigned = None ) : if count is not None and count < 0 : raise ValueError ( "In findall, count must be >= 0." ) bs = Bits ( bs ) start , end = self . _validate_slice ( start , end ) if bytealigned is None : bytealigned = globals ( ) [ 'bytealigned'... | Find all occurrences of bs . Return generator of bit positions . |
61,894 | def rfind ( self , bs , start = None , end = None , bytealigned = None ) : bs = Bits ( bs ) start , end = self . _validate_slice ( start , end ) if bytealigned is None : bytealigned = globals ( ) [ 'bytealigned' ] if not bs . len : raise ValueError ( "Cannot find an empty bitstring." ) increment = max ( 8192 , bs . len... | Find final occurrence of substring bs . |
61,895 | def cut ( self , bits , start = None , end = None , count = None ) : start , end = self . _validate_slice ( start , end ) if count is not None and count < 0 : raise ValueError ( "Cannot cut - count must be >= 0." ) if bits <= 0 : raise ValueError ( "Cannot cut - bits must be >= 0." ) c = 0 while count is None or c < co... | Return bitstring generator by cutting into bits sized chunks . |
61,896 | def split ( self , delimiter , start = None , end = None , count = None , bytealigned = None ) : delimiter = Bits ( delimiter ) if not delimiter . len : raise ValueError ( "split delimiter cannot be empty." ) start , end = self . _validate_slice ( start , end ) if bytealigned is None : bytealigned = globals ( ) [ 'byte... | Return bitstring generator by splittling using a delimiter . |
61,897 | def join ( self , sequence ) : s = self . __class__ ( ) i = iter ( sequence ) try : s . _append ( Bits ( next ( i ) ) ) while True : n = next ( i ) s . _append ( self ) s . _append ( Bits ( n ) ) except StopIteration : pass return s | Return concatenation of bitstrings joined by self . |
61,898 | def tobytes ( self ) : d = offsetcopy ( self . _datastore , 0 ) . rawbytes unusedbits = 8 - self . len % 8 if unusedbits != 8 : d [ - 1 ] &= ( 0xff << unusedbits ) return bytes ( d ) | Return the bitstring as bytes padding with zero bits if needed . |
61,899 | def tofile ( self , f ) : chunksize = 1024 * 1024 if not self . _offset : a = 0 bytelen = self . _datastore . bytelength p = self . _datastore . getbyteslice ( a , min ( a + chunksize , bytelen - 1 ) ) while len ( p ) == chunksize : f . write ( p ) a += chunksize p = self . _datastore . getbyteslice ( a , min ( a + chu... | Write the bitstring to a file object padding with zero bits if needed . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.