idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
52,900 | def search_for_oath_code ( hsm , key_handle , nonce , aead , counter , user_code , look_ahead = 1 ) : key_handle = pyhsm . util . input_validate_key_handle ( key_handle ) nonce = pyhsm . util . input_validate_nonce ( nonce , pad = False ) aead = pyhsm . util . input_validate_aead ( aead ) counter = pyhsm . util . input... | Try to validate an OATH HOTP OTP generated by a token whose secret key is available to the YubiHSM through the AEAD . |
52,901 | def truncate ( hmac_result , length = 6 ) : assert ( len ( hmac_result ) == 20 ) offset = ord ( hmac_result [ 19 ] ) & 0xf bin_code = ( ord ( hmac_result [ offset ] ) & 0x7f ) << 24 | ( ord ( hmac_result [ offset + 1 ] ) & 0xff ) << 16 | ( ord ( hmac_result [ offset + 2 ] ) & 0xff ) << 8 | ( ord ( hmac_result [ offset ... | Perform the truncating . |
52,902 | def flush ( self ) : if self . debug : sys . stderr . write ( "%s: FLUSH INPUT (%i bytes waiting)\n" % ( self . __class__ . __name__ , self . ser . inWaiting ( ) ) ) self . ser . flushInput ( ) | Flush input buffers . |
52,903 | def drain ( self ) : if self . debug : sys . stderr . write ( "%s: DRAIN INPUT (%i bytes waiting)\n" % ( self . __class__ . __name__ , self . ser . inWaiting ( ) ) ) old_timeout = self . ser . timeout self . ser . timeout = 0.1 data = self . ser . read ( 1 ) while len ( data ) : if self . debug : sys . stderr . write (... | Drain input . |
52,904 | def extract_keyhandle ( path , filepath ) : keyhandle = filepath . lstrip ( path ) keyhandle = keyhandle . split ( "/" ) return keyhandle [ 0 ] | extract keyhandle value from the path |
52,905 | def insert_query ( connection , publicId , aead , keyhandle , aeadobj ) : keyhandle = key_handle_to_int ( keyhandle ) if not keyhandle == aead . key_handle : print ( "WARNING: keyhandle does not match aead.key_handle" ) return None try : sql = aeadobj . insert ( ) . values ( public_id = publicId , keyhandle = aead . ke... | this functions read the response fields and creates sql query . then inserts everything inside the database |
52,906 | def import_keys ( hsm , args ) : res = True for line in sys . stdin : if line [ 0 ] == '#' : continue l = line . split ( ',' ) modhex_id = l [ 1 ] uid = l [ 2 ] . decode ( 'hex' ) key = l [ 3 ] . decode ( 'hex' ) if modhex_id and uid and key : public_id = pyhsm . yubikey . modhex_decode ( modhex_id ) padded_id = modhex... | The main stdin iteration loop . |
52,907 | def shorten_aead ( aead ) : head = aead . data [ : 4 ] . encode ( 'hex' ) tail = aead . data [ - 4 : ] . encode ( 'hex' ) return "%s...%s" % ( head , tail ) | Produce pretty - printable version of long AEAD . |
52,908 | def output_filename ( output_dir , key_handle , public_id ) : parts = [ output_dir , key_handle ] + pyhsm . util . group ( public_id , 2 ) path = os . path . join ( * parts ) if not os . path . isdir ( path ) : os . makedirs ( path ) return os . path . join ( path , public_id ) | Return an output filename for a generated AEAD . Creates a hashed directory structure using the last three bytes of the public id to get equal usage . |
52,909 | def parse_result ( self , data ) : public_id , key_handle , self . status = struct . unpack ( "< %is I B" % ( pyhsm . defines . YSM_AEAD_NONCE_SIZE ) , data ) pyhsm . util . validate_cmd_response_str ( 'public_id' , public_id , self . public_id ) pyhsm . util . validate_cmd_response_hex ( 'key_handle' , key_handle , se... | Return True if the AEAD was stored sucessfully . |
52,910 | def gen_keys ( hsm , args ) : if args . verbose : print "Generating %i keys :\n" % ( args . count ) else : print "Generating %i keys" % ( args . count ) for int_id in range ( args . start_id , args . start_id + args . count ) : public_id = ( "%x" % int_id ) . rjust ( args . public_id_chars , '0' ) padded_id = pyhsm . y... | The main key generating loop . |
52,911 | def reset ( stick ) : nulls = ( pyhsm . defines . YSM_MAX_PKT_SIZE - 1 ) * '\x00' res = YHSM_Cmd ( stick , pyhsm . defines . YSM_NULL , payload = nulls ) . execute ( read_response = False ) unlock = stick . acquire ( ) try : stick . drain ( ) stick . flush ( ) finally : unlock ( ) return res == 0 | Send a bunch of zero - bytes to the YubiHSM and flush the input buffer . |
52,912 | def execute ( self , read_response = True ) : if self . command != pyhsm . defines . YSM_NULL : cmd_buf = struct . pack ( 'BB' , len ( self . payload ) + 1 , self . command ) else : cmd_buf = chr ( self . command ) cmd_buf += self . payload debug_info = None unlock = self . stick . acquire ( ) try : if self . stick . d... | Write command to HSM and read response . |
52,913 | def _read_response ( self ) : res = self . stick . read ( 2 , 'response length + response status' ) if len ( res ) != 2 : self . _handle_invalid_read_response ( res , 2 ) response_len , response_status = struct . unpack ( 'BB' , res ) response_len -= 1 debug_info = None if response_status & pyhsm . defines . YSM_RESPON... | After writing a command read response . |
52,914 | def reset ( self , test_sync = True ) : pyhsm . cmd . reset ( self . stick ) if test_sync : data = 'ekoeko' echo = self . echo ( data ) return data == echo else : return True | Perform stream resynchronization . |
52,915 | def set_debug ( self , new ) : if type ( new ) is not bool : raise pyhsm . exception . YHSM_WrongInputType ( 'new' , bool , type ( new ) ) old = self . debug self . debug = new self . stick . set_debug ( new ) return old | Set debug mode . |
52,916 | def echo ( self , data ) : return pyhsm . basic_cmd . YHSM_Cmd_Echo ( self . stick , data ) . execute ( ) | Echo test . |
52,917 | def random ( self , num_bytes ) : return pyhsm . basic_cmd . YHSM_Cmd_Random ( self . stick , num_bytes ) . execute ( ) | Get random bytes from YubiHSM . |
52,918 | def random_reseed ( self , seed ) : return pyhsm . basic_cmd . YHSM_Cmd_Random_Reseed ( self . stick , seed ) . execute ( ) | Provide YubiHSM DRBG_CTR with a new seed . |
52,919 | def get_nonce ( self , increment = 1 ) : return pyhsm . basic_cmd . YHSM_Cmd_Nonce_Get ( self . stick , increment ) . execute ( ) | Get current nonce from YubiHSM . |
52,920 | def load_temp_key ( self , nonce , key_handle , aead ) : return pyhsm . basic_cmd . YHSM_Cmd_Temp_Key_Load ( self . stick , nonce , key_handle , aead ) . execute ( ) | Load the contents of an AEAD into the phantom key handle 0xffffffff . |
52,921 | def load_secret ( self , secret ) : if isinstance ( secret , pyhsm . aead_cmd . YHSM_YubiKeySecret ) : secret = secret . pack ( ) return pyhsm . buffer_cmd . YHSM_Cmd_Buffer_Load ( self . stick , secret ) . execute ( ) | Ask YubiHSM to load a pre - existing YubiKey secret . |
52,922 | def load_data ( self , data , offset ) : return pyhsm . buffer_cmd . YHSM_Cmd_Buffer_Load ( self . stick , data , offset ) . execute ( ) | Ask YubiHSM to load arbitrary data into it s internal buffer at any offset . |
52,923 | def load_random ( self , num_bytes , offset = 0 ) : return pyhsm . buffer_cmd . YHSM_Cmd_Buffer_Random_Load ( self . stick , num_bytes , offset ) . execute ( ) | Ask YubiHSM to generate a number of random bytes to any offset of it s internal buffer . |
52,924 | def generate_aead_random ( self , nonce , key_handle , num_bytes ) : return pyhsm . aead_cmd . YHSM_Cmd_AEAD_Random_Generate ( self . stick , nonce , key_handle , num_bytes ) . execute ( ) | Generate a random AEAD block using the YubiHSM internal DRBG_CTR random generator . |
52,925 | def validate_aead_otp ( self , public_id , otp , key_handle , aead ) : if type ( public_id ) is not str : assert ( ) if type ( otp ) is not str : assert ( ) if type ( key_handle ) is not int : assert ( ) if type ( aead ) is not str : assert ( ) return pyhsm . validate_cmd . YHSM_Cmd_AEAD_Validate_OTP ( self . stick , p... | Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to decrypt the AEAD . |
52,926 | def aes_ecb_encrypt ( self , key_handle , plaintext ) : return pyhsm . aes_ecb_cmd . YHSM_Cmd_AES_ECB_Encrypt ( self . stick , key_handle , plaintext ) . execute ( ) | AES ECB encrypt using a key handle . |
52,927 | def aes_ecb_decrypt ( self , key_handle , ciphertext ) : return pyhsm . aes_ecb_cmd . YHSM_Cmd_AES_ECB_Decrypt ( self . stick , key_handle , ciphertext ) . execute ( ) | AES ECB decrypt using a key handle . |
52,928 | def aes_ecb_compare ( self , key_handle , ciphertext , plaintext ) : return pyhsm . aes_ecb_cmd . YHSM_Cmd_AES_ECB_Compare ( self . stick , key_handle , ciphertext , plaintext ) . execute ( ) | AES ECB decrypt and then compare using a key handle . |
52,929 | def hmac_sha1 ( self , key_handle , data , flags = None , final = True , to_buffer = False ) : return pyhsm . hmac_cmd . YHSM_Cmd_HMAC_SHA1_Write ( self . stick , key_handle , data , flags = flags , final = final , to_buffer = to_buffer ) . execute ( ) | Have the YubiHSM generate a HMAC SHA1 of data using a key handle . |
52,930 | def db_validate_yubikey_otp ( self , public_id , otp ) : return pyhsm . db_cmd . YHSM_Cmd_DB_Validate_OTP ( self . stick , public_id , otp ) . execute ( ) | Request the YubiHSM to validate an OTP for a YubiKey stored in the internal database . |
52,931 | def aead_filename ( aead_dir , key_handle , public_id ) : parts = [ aead_dir , key_handle ] + pyhsm . util . group ( public_id , 2 ) + [ public_id ] return os . path . join ( * parts ) | Return the filename of the AEAD for this public_id . |
52,932 | def run ( hsm , aead_backend , args ) : write_pid_file ( args . pid_file ) server_address = ( args . listen_addr , args . listen_port ) httpd = YHSM_KSMServer ( server_address , partial ( YHSM_KSMRequestHandler , hsm , aead_backend , args ) ) my_log_message ( args . debug or args . verbose , syslog . LOG_INFO , "Servin... | Start a BaseHTTPServer . HTTPServer and serve requests forever . |
52,933 | def my_log_message ( verbose , prio , msg ) : syslog . syslog ( prio , msg ) if verbose or prio == syslog . LOG_ERR : sys . stderr . write ( "%s\n" % ( msg ) ) | Log to syslog and possibly also to stderr . |
52,934 | def do_GET ( self ) : if self . path . startswith ( self . serve_url ) : from_key = self . path [ len ( self . serve_url ) : ] val_res = self . decrypt_yubikey_otp ( from_key ) self . send_response ( 200 ) self . send_header ( 'Content-type' , 'text/html' ) self . end_headers ( ) self . wfile . write ( val_res ) self .... | Handle a HTTP GET request . |
52,935 | def decrypt_yubikey_otp ( self , from_key ) : if not re . match ( valid_input_from_key , from_key ) : self . log_error ( "IN: %s, Invalid OTP" % ( from_key ) ) if self . stats_url : stats [ 'invalid' ] += 1 return "ERR Invalid OTP" public_id , _otp = pyhsm . yubikey . split_id_otp ( from_key ) try : aead = self . aead_... | Try to decrypt a YubiKey OTP . |
52,936 | def my_address_string ( self ) : addr = getattr ( self , 'client_address' , ( '' , None ) ) [ 0 ] if addr in self . proxy_ips : return self . headers . getheader ( 'x-forwarded-for' , addr ) return addr | For logging client host without resolving . |
52,937 | def load_aead ( self , public_id ) : connection = self . engine . connect ( ) trans = connection . begin ( ) try : s = sqlalchemy . select ( [ self . aead_table ] ) . where ( ( self . aead_table . c . public_id == public_id ) & self . aead_table . c . keyhandle . in_ ( [ kh [ 1 ] for kh in self . key_handles ] ) ) resu... | Loads AEAD from the specified database . |
52,938 | def generate_aead ( hsm , args ) : key = get_oath_k ( args ) flags = struct . pack ( "< I" , 0x10000 ) hsm . load_secret ( key + flags ) nonce = hsm . get_nonce ( ) . nonce aead = hsm . generate_aead ( nonce , args . key_handle ) if args . debug : print "AEAD: %s (%s)" % ( aead . data . encode ( 'hex' ) , aead ) return... | Protect the oath - k in an AEAD . |
52,939 | def store_oath_entry ( args , nonce , aead , oath_c ) : data = { "key" : args . uid , "aead" : aead . data . encode ( 'hex' ) , "nonce" : nonce . encode ( 'hex' ) , "key_handle" : args . key_handle , "oath_C" : oath_c , "oath_T" : None , } entry = ValOathEntry ( data ) db = ValOathDb ( args . db_file ) try : if args . ... | Store the AEAD in the database . |
52,940 | def add ( self , entry ) : c = self . conn . cursor ( ) c . execute ( "INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)" , ( entry . data [ "key" ] , entry . data [ "aead" ] , entry . data [ "nonce" ] , entry . data [ "key_handle" ] , entry . data [ "oath_C" ] , entry . data [ "... | Add entry to database . |
52,941 | def delete ( self , entry ) : c = self . conn . cursor ( ) c . execute ( "DELETE FROM oath WHERE key = ?" , ( entry . data [ "key" ] , ) ) | Delete entry from database . |
52,942 | def parse_result ( self , data ) : nonce , key_handle , self . status , num_bytes = struct . unpack_from ( "< %is I B B" % ( pyhsm . defines . YSM_AEAD_NONCE_SIZE ) , data , 0 ) pyhsm . util . validate_cmd_response_hex ( 'key_handle' , key_handle , self . key_handle ) if self . status == pyhsm . defines . YSM_STATUS_OK... | Returns a YHSM_GeneratedAEAD instance or throws pyhsm . exception . YHSM_CommandFailed . |
52,943 | def save ( self , filename ) : aead_f = open ( filename , "wb" ) fmt = "< B I %is %is" % ( pyhsm . defines . YSM_AEAD_NONCE_SIZE , len ( self . data ) ) version = 1 packed = struct . pack ( fmt , version , self . key_handle , self . nonce , self . data ) aead_f . write ( YHSM_AEAD_File_Marker + packed ) aead_f . close ... | Store AEAD in a file . |
52,944 | def load ( self , filename ) : aead_f = open ( filename , "rb" ) buf = aead_f . read ( 1024 ) if buf . startswith ( YHSM_AEAD_CRLF_File_Marker ) : buf = YHSM_AEAD_File_Marker + buf [ len ( YHSM_AEAD_CRLF_File_Marker ) : ] if buf . startswith ( YHSM_AEAD_File_Marker ) : if buf [ len ( YHSM_AEAD_File_Marker ) ] == chr ( ... | Load AEAD from a file . |
52,945 | def pack ( self ) : return self . key + self . uid . ljust ( pyhsm . defines . UID_SIZE , chr ( 0 ) ) | Return key and uid packed for sending in a command to the YubiHSM . |
52,946 | def validate_otp ( hsm , args ) : try : res = pyhsm . yubikey . validate_otp ( hsm , args . otp ) if args . verbose : print "OK counter=%04x low=%04x high=%02x use=%02x" % ( res . use_ctr , res . ts_low , res . ts_high , res . session_ctr ) return 0 except pyhsm . exception . YHSM_CommandFailed , e : if args . verbose ... | Validate an OTP . |
52,947 | def search_for_oath_code ( hsm , key_handle , nonce , aead , user_code , interval = 30 , tolerance = 0 ) : timecounter = timecode ( datetime . datetime . now ( ) , interval ) - tolerance return search_hotp ( hsm , key_handle , nonce , aead , timecounter , user_code , 1 + 2 * tolerance ) | Try to validate an OATH TOTP OTP generated by a token whose secret key is available to the YubiHSM through the AEAD . |
52,948 | def timecode ( time_now , interval ) : i = time . mktime ( time_now . timetuple ( ) ) return int ( i / interval ) | make integer and divide by time interval of valid OTP |
52,949 | def _xor_block ( a , b ) : return '' . join ( [ chr ( ord ( x ) ^ ord ( y ) ) for ( x , y ) in zip ( a , b ) ] ) | XOR two blocks of equal length . |
52,950 | def crc16 ( data ) : m_crc = 0xffff for this in data : m_crc ^= ord ( this ) for _ in range ( 8 ) : j = m_crc & 1 m_crc >>= 1 if j : m_crc ^= 0x8408 return m_crc | Calculate an ISO13239 CRC checksum of the input buffer . |
52,951 | def finalize ( self , block ) : t1 = self . mac_aes . encrypt ( block ) t2 = _xor_block ( self . mac , t1 ) self . mac = t2 | The final step of CBC - MAC encrypts before xor . |
52,952 | def validate_otp ( hsm , from_key ) : public_id , otp = split_id_otp ( from_key ) return hsm . db_validate_yubikey_otp ( modhex_decode ( public_id ) . decode ( 'hex' ) , modhex_decode ( otp ) . decode ( 'hex' ) ) | Try to validate an OTP from a YubiKey using the internal database on the YubiHSM . |
52,953 | def validate_yubikey_with_aead ( hsm , from_key , aead , key_handle ) : from_key = pyhsm . util . input_validate_str ( from_key , 'from_key' , max_len = 48 ) nonce = aead . nonce aead = pyhsm . util . input_validate_aead ( aead ) key_handle = pyhsm . util . input_validate_key_handle ( key_handle ) public_id , otp = spl... | Try to validate an OTP from a YubiKey using the AEAD that can decrypt this YubiKey s internal secret using the key_handle for the AEAD . |
52,954 | def split_id_otp ( from_key ) : if len ( from_key ) > 32 : public_id , otp = from_key [ : - 32 ] , from_key [ - 32 : ] elif len ( from_key ) == 32 : public_id = '' otp = from_key else : raise pyhsm . exception . YHSM_Error ( "Bad from_key length %i < 32 : %s" % ( len ( from_key ) , from_key ) ) return public_id , otp | Separate public id from OTP given a YubiKey OTP as input . |
52,955 | def get_password ( hsm , args ) : expected_len = 32 name = 'HSM password' if hsm . version . have_key_store_decrypt ( ) : expected_len = 64 name = 'master key' if args . stdin : password = sys . stdin . readline ( ) while password and password [ - 1 ] == '\n' : password = password [ : - 1 ] else : if args . debug : pas... | Get password of correct length for this YubiHSM version . |
52,956 | def get_otp ( hsm , args ) : if args . no_otp : return None if hsm . version . have_unlock ( ) : if args . stdin : otp = sys . stdin . readline ( ) while otp and otp [ - 1 ] == '\n' : otp = otp [ : - 1 ] else : otp = raw_input ( 'Enter admin YubiKey OTP (press enter to skip) : ' ) if len ( otp ) == 44 : return otp if o... | Get OTP from YubiKey . |
52,957 | def load ( self , df , centerings ) : centering_variables = dict ( ) if not df . empty and df . geometry . notna ( ) . any ( ) : for key , func in centerings . items ( ) : centering_variables [ key ] = func ( df ) return getattr ( ccrs , self . __class__ . __name__ ) ( ** { ** centering_variables , ** self . args } ) | A moderately mind - bendy meta - method which abstracts the internals of individual projections load procedures . |
52,958 | def load ( self , df , centerings ) : return super ( ) . load ( df , { key : value for key , value in centerings . items ( ) if key in self . filter_ } ) | Call load method with centerings filtered to keys in self . filter_ . |
52,959 | def gaussian_points ( loc = ( 0 , 0 ) , scale = ( 10 , 10 ) , n = 100 ) : arr = np . random . normal ( loc , scale , ( n , 2 ) ) return gpd . GeoSeries ( [ shapely . geometry . Point ( x , y ) for ( x , y ) in arr ] ) | Generates and returns n normally distributed points centered at loc with scale x and y directionality . |
52,960 | def classify_clusters ( points , n = 10 ) : arr = [ [ p . x , p . y ] for p in points . values ] clf = KMeans ( n_clusters = n ) clf . fit ( arr ) classes = clf . predict ( arr ) return classes | Return an array of K - Means cluster classes for an array of shapely . geometry . Point objects . |
52,961 | def gaussian_polygons ( points , n = 10 ) : gdf = gpd . GeoDataFrame ( data = { 'cluster_number' : classify_clusters ( points , n = n ) } , geometry = points ) polygons = [ ] for i in range ( n ) : sel_points = gdf [ gdf [ 'cluster_number' ] == i ] . geometry polygons . append ( shapely . geometry . MultiPoint ( [ ( p ... | Returns an array of approximately n shapely . geometry . Polygon objects for an array of shapely . geometry . Point objects . |
52,962 | def gaussian_multi_polygons ( points , n = 10 ) : polygons = gaussian_polygons ( points , n * 2 ) polygon_pairs = [ shapely . geometry . MultiPolygon ( list ( pair ) ) for pair in np . array_split ( polygons . values , n ) ] return gpd . GeoSeries ( polygon_pairs ) | Returns an array of approximately n shapely . geometry . MultiPolygon objects for an array of shapely . geometry . Point objects . |
52,963 | def uniform_random_global_points ( n = 100 ) : xs = np . random . uniform ( - 180 , 180 , n ) ys = np . random . uniform ( - 90 , 90 , n ) return [ shapely . geometry . Point ( x , y ) for x , y in zip ( xs , ys ) ] | Returns an array of n uniformally distributed shapely . geometry . Point objects . Points are coordinates distributed equivalently across the Earth s surface . |
52,964 | def uniform_random_global_network ( loc = 2000 , scale = 250 , n = 100 ) : arr = ( np . random . normal ( loc , scale , n ) ) . astype ( int ) return pd . DataFrame ( data = { 'mock_variable' : arr , 'from' : uniform_random_global_points ( n ) , 'to' : uniform_random_global_points ( n ) } ) | Returns an array of n uniformally randomly distributed shapely . geometry . Point objects . |
52,965 | def subpartition ( quadtree , nmin , nmax ) : subtrees = quadtree . split ( ) if quadtree . n > nmax : return [ q . partition ( nmin , nmax ) for q in subtrees ] elif any ( [ t . n < nmin for t in subtrees ] ) : return [ quadtree ] else : return [ q . partition ( nmin , nmax ) for q in subtrees ] | Recursive core of the QuadTree . partition method . Just five lines of code amazingly . |
52,966 | def split ( self ) : min_x , max_x , min_y , max_y = self . bounds mid_x , mid_y = ( min_x + max_x ) / 2 , ( min_y + max_y ) / 2 q1 = ( min_x , mid_x , mid_y , max_y ) q2 = ( min_x , mid_x , min_y , mid_y ) q3 = ( mid_x , max_x , mid_y , max_y ) q4 = ( mid_x , max_x , min_y , mid_y ) return [ QuadTree ( self . data , b... | Splits the current QuadTree instance four ways through the midpoint . |
52,967 | def partition ( self , nmin , nmax ) : if self . n < nmin : return [ self ] else : ret = subpartition ( self , nmin , nmax ) return flatten ( ret ) | This method call decomposes a QuadTree instances into a list of sub - QuadTree instances which are the smallest possible geospatial buckets given the current splitting rules containing at least thresh points . |
52,968 | def plot_state_to_ax ( state , ax ) : gplt . choropleth ( tickets . set_index ( 'id' ) . loc [ : , [ state , 'geometry' ] ] , hue = state , projection = gcrs . AlbersEqualArea ( ) , cmap = 'Blues' , linewidth = 0.0 , ax = ax ) gplt . polyplot ( boroughs , projection = gcrs . AlbersEqualArea ( ) , edgecolor = 'black' , ... | Reusable plotting wrapper . |
52,969 | def polyplot ( df , projection = None , extent = None , figsize = ( 8 , 6 ) , ax = None , edgecolor = 'black' , facecolor = 'None' , ** kwargs ) : fig = _init_figure ( ax , figsize ) if projection : projection = projection . load ( df , { 'central_longitude' : lambda df : np . mean ( np . array ( [ p . x for p in df . ... | Trivial polygonal plot . |
52,970 | def choropleth ( df , projection = None , hue = None , scheme = None , k = 5 , cmap = 'Set1' , categorical = False , vmin = None , vmax = None , legend = False , legend_kwargs = None , legend_labels = None , extent = None , figsize = ( 8 , 6 ) , ax = None , ** kwargs ) : fig = _init_figure ( ax , figsize ) if projectio... | Area aggregation plot . |
52,971 | def _get_envelopes_min_maxes ( envelopes ) : xmin = np . min ( envelopes . map ( lambda linearring : np . min ( [ linearring . coords [ 1 ] [ 0 ] , linearring . coords [ 2 ] [ 0 ] , linearring . coords [ 3 ] [ 0 ] , linearring . coords [ 4 ] [ 0 ] ] ) ) ) xmax = np . max ( envelopes . map ( lambda linearring : np . max... | Returns the extrema of the inputted polygonal envelopes . Used for setting chart extent where appropriate . Note tha the Quadtree . bounds object property serves a similar role . |
52,972 | def _get_envelopes_centroid ( envelopes ) : xmin , xmax , ymin , ymax = _get_envelopes_min_maxes ( envelopes ) return np . mean ( xmin , xmax ) , np . mean ( ymin , ymax ) | Returns the centroid of an inputted geometry column . Not currently in use as this is now handled by this library s CRS wrapper directly . Light wrapper over _get_envelopes_min_maxes . |
52,973 | def _set_extent ( ax , projection , extent , extrema ) : if extent : xmin , xmax , ymin , ymax = extent xmin , xmax , ymin , ymax = max ( xmin , - 180 ) , min ( xmax , 180 ) , max ( ymin , - 90 ) , min ( ymax , 90 ) if projection : ax . set_extent ( ( xmin , xmax , ymin , ymax ) , crs = ccrs . PlateCarree ( ) ) else : ... | Sets the plot extent . |
52,974 | def _lay_out_axes ( ax , projection ) : if projection is not None : try : ax . background_patch . set_visible ( False ) ax . outline_patch . set_visible ( False ) except AttributeError : pass else : plt . gca ( ) . axison = False | cartopy enables a a transparent background patch and an outline patch by default . This short method simply hides these extraneous visual features . If the plot is a pure matplotlib one it does the same thing by removing the axis altogether . |
52,975 | def _continuous_colormap ( hue , cmap , vmin , vmax ) : mn = min ( hue ) if vmin is None else vmin mx = max ( hue ) if vmax is None else vmax norm = mpl . colors . Normalize ( vmin = mn , vmax = mx ) return mpl . cm . ScalarMappable ( norm = norm , cmap = cmap ) | Creates a continuous colormap . |
52,976 | def _discrete_colorize ( categorical , hue , scheme , k , cmap , vmin , vmax ) : if not categorical : binning = _mapclassify_choro ( hue , scheme , k = k ) values = binning . yb binedges = [ binning . yb . min ( ) ] + binning . bins . tolist ( ) categories = [ '{0:.2f} - {1:.2f}' . format ( binedges [ i ] , binedges [ ... | Creates a discrete colormap either using an already - categorical data variable or by bucketing a non - categorical ordinal one . If a scheme is provided we compute a distribution for the given data . If one is not provided we assume that the input data is categorical . |
52,977 | def _norm_cmap ( values , cmap , normalize , cm , vmin = None , vmax = None ) : mn = min ( values ) if vmin is None else vmin mx = max ( values ) if vmax is None else vmax norm = normalize ( vmin = mn , vmax = mx ) n_cmap = cm . ScalarMappable ( norm = norm , cmap = cmap ) return n_cmap | Normalize and set colormap . Taken from geopandas |
52,978 | def get_version ( ) : proc = tmux_cmd ( '-V' ) if proc . stderr : if proc . stderr [ 0 ] == 'tmux: unknown option -- V' : if sys . platform . startswith ( "openbsd" ) : return LooseVersion ( '%s-openbsd' % TMUX_MAX_VERSION ) raise exc . LibTmuxException ( 'libtmux supports tmux %s and greater. This system' ' is running... | Return tmux version . |
52,979 | def has_minimum_version ( raises = True ) : if get_version ( ) < LooseVersion ( TMUX_MIN_VERSION ) : if raises : raise exc . VersionTooLow ( 'libtmux only supports tmux %s and greater. This system' ' has %s installed. Upgrade your tmux to use libtmux.' % ( TMUX_MIN_VERSION , get_version ( ) ) ) else : return False retu... | Return if tmux meets version requirement . Version > 1 . 8 or above . |
52,980 | def session_check_name ( session_name ) : if not session_name or len ( session_name ) == 0 : raise exc . BadSessionName ( "tmux session names may not be empty." ) elif '.' in session_name : raise exc . BadSessionName ( "tmux session name \"%s\" may not contain periods." , session_name ) elif ':' in session_name : raise... | Raises exception session name invalid modeled after tmux function . |
52,981 | def handle_option_error ( error ) : if 'unknown option' in error : raise exc . UnknownOption ( error ) elif 'invalid option' in error : raise exc . InvalidOption ( error ) elif 'ambiguous option' in error : raise exc . AmbiguousOption ( error ) else : raise exc . OptionError ( error ) | Raises exception if error in option command found . |
52,982 | def where ( self , attrs , first = False ) : def by ( val , * args ) : for key , value in attrs . items ( ) : try : if attrs [ key ] != val [ key ] : return False except KeyError : return False return True if first : return list ( filter ( by , self . children ) ) [ 0 ] else : return list ( filter ( by , self . childre... | Return objects matching child objects properties . |
52,983 | def get_by_id ( self , id ) : for child in self . children : if child [ self . child_id_attribute ] == id : return child else : continue return None | Return object based on child_id_attribute . |
52,984 | def select_window ( self ) : target = ( '%s:%s' % ( self . get ( 'session_id' ) , self . index ) , ) return self . session . select_window ( target ) | Select window . Return self . |
52,985 | def cmd ( self , * args , ** kwargs ) : args = list ( args ) if self . socket_name : args . insert ( 0 , '-L{0}' . format ( self . socket_name ) ) if self . socket_path : args . insert ( 0 , '-S{0}' . format ( self . socket_path ) ) if self . config_file : args . insert ( 0 , '-f{0}' . format ( self . config_file ) ) i... | Execute tmux command and return output . |
52,986 | def switch_client ( self ) : proc = self . cmd ( 'switch-client' , '-t%s' % self . id ) if proc . stderr : raise exc . LibTmuxException ( proc . stderr ) | Switch client to this session . |
52,987 | def openpgp ( ctx ) : try : ctx . obj [ 'controller' ] = OpgpController ( ctx . obj [ 'dev' ] . driver ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( "The OpenPGP application can't be found on this " 'YubiKey.' ) logger . debug ( 'Failed to load OpenPGP Application' , exc_info = e ) ctx . fail ( '... | Manage OpenPGP Application . |
52,988 | def info ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'OpenPGP version: %d.%d.%d' % controller . version ) retries = controller . get_remaining_pin_tries ( ) click . echo ( 'PIN tries remaining: {}' . format ( retries . pin ) ) click . echo ( 'Reset code tries remaining: {}' . format ( retries . res... | Display status of OpenPGP application . |
52,989 | def reset ( ctx ) : click . echo ( "Resetting OpenPGP data, don't remove your YubiKey..." ) ctx . obj [ 'controller' ] . reset ( ) click . echo ( 'Success! All data has been cleared and default PINs are set.' ) echo_default_pins ( ) | Reset OpenPGP application . |
52,990 | def touch ( ctx , key , policy , admin_pin , force ) : controller = ctx . obj [ 'controller' ] old_policy = controller . get_touch ( key ) if old_policy == TOUCH_MODE . FIXED : ctx . fail ( 'A FIXED policy cannot be changed!' ) force or click . confirm ( 'Set touch policy of {.name} key to {.name}?' . format ( key , po... | Manage touch policy for OpenPGP keys . |
52,991 | def set_pin_retries ( ctx , pw_attempts , admin_pin , force ) : controller = ctx . obj [ 'controller' ] resets_pins = controller . version < ( 4 , 0 , 0 ) if resets_pins : click . echo ( 'WARNING: Setting PIN retries will reset the values for all ' '3 PINs!' ) force or click . confirm ( 'Set PIN retry counters to: {} {... | Manage pin - retries . |
52,992 | def piv ( ctx ) : try : ctx . obj [ 'controller' ] = PivController ( ctx . obj [ 'dev' ] . driver ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( "The PIV application can't be found on this YubiKey." ) raise | Manage PIV Application . |
52,993 | def info ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'PIV version: %d.%d.%d' % controller . version ) tries = controller . get_pin_tries ( ) tries = '15 or more.' if tries == 15 else tries click . echo ( 'PIN tries remaining: %s' % tries ) if controller . puk_blocked : click . echo ( 'PUK blocked.'... | Display status of PIV application . |
52,994 | def reset ( ctx ) : click . echo ( 'Resetting PIV data...' ) ctx . obj [ 'controller' ] . reset ( ) click . echo ( 'Success! All PIV data have been cleared from your YubiKey.' ) click . echo ( 'Your YubiKey now has the default PIN, PUK and Management Key:' ) click . echo ( '\tPIN:\t123456' ) click . echo ( '\tPUK:\t123... | Reset all PIV data . |
52,995 | def generate_key ( ctx , slot , public_key_output , management_key , pin , algorithm , format , pin_policy , touch_policy ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) algorithm_id = ALGO . from_string ( algorithm ) if pin_policy ... | Generate an asymmetric key pair . |
52,996 | def import_certificate ( ctx , slot , management_key , pin , cert , password , verify ) : controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) data = cert . read ( ) while True : if password is not None : password = password . encode ( ) try : certs = parse_certifica... | Import a X . 509 certificate . |
52,997 | def import_key ( ctx , slot , management_key , pin , private_key , pin_policy , touch_policy , password ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) data = private_key . read ( ) while True : if password is not None : password = ... | Import a private key . |
52,998 | def export_certificate ( ctx , slot , format , certificate ) : controller = ctx . obj [ 'controller' ] try : cert = controller . read_certificate ( slot ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( 'No certificate found.' ) else : logger . error ( 'Failed to read certificate from slot %s' , slot... | Export a X . 509 certificate . |
52,999 | def set_chuid ( ctx , management_key , pin ) : controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) controller . update_chuid ( ) | Generate and set a CHUID on the YubiKey . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.