idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
60,500
def _bins_to_json ( h2 ) : south = h2 . get_bin_left_edges ( 0 ) north = h2 . get_bin_right_edges ( 0 ) west = h2 . get_bin_left_edges ( 1 ) east = h2 . get_bin_right_edges ( 1 ) return { "type" : "FeatureCollection" , "features" : [ { "type" : "Feature" , "geometry" : { "type" : "Polygon" , "coordinates" : [ [ [ east [ j ] , south [ i ] ] , [ east [ j ] , north [ i ] ] , [ west [ j ] , north [ i ] ] , [ west [ j ] , south [ i ] ] , [ east [ j ] , south [ i ] ] ] ] , } , "properties" : { "count" : float ( h2 . frequencies [ i , j ] ) } } for i in range ( h2 . shape [ 0 ] ) for j in range ( h2 . shape [ 1 ] ) ] }
Create GeoJSON representation of histogram bins
60,501
def geo_map ( h2 , map = None , tiles = 'stamenterrain' , cmap = "wk" , alpha = 0.5 , lw = 1 , fit_bounds = None , layer_name = None ) : if not map : latitude = h2 . get_bin_centers ( 0 ) . mean ( ) longitude = h2 . get_bin_centers ( 1 ) . mean ( ) zoom_start = 10 map = folium . Map ( location = [ latitude , longitude ] , tiles = tiles ) if fit_bounds == None : fit_bounds = True geo_json = _bins_to_json ( h2 ) if not layer_name : layer_name = h2 . name from branca . colormap import LinearColormap color_map = LinearColormap ( cmap , vmin = h2 . frequencies . min ( ) , vmax = h2 . frequencies . max ( ) ) def styling_function ( bin ) : count = bin [ "properties" ] [ "count" ] return { "fillColor" : color_map ( count ) , "color" : "black" , "fillOpacity" : alpha if count > 0 else 0 , "weight" : lw , "opacity" : alpha if count > 0 else 0 , } layer = folium . GeoJson ( geo_json , style_function = styling_function , name = layer_name ) layer . add_to ( map ) if fit_bounds : map . fit_bounds ( layer . get_bounds ( ) ) return map
Show rectangular grid over a map .
60,502
def load_csv ( path ) : meta = [ ] data = [ ] with codecs . open ( path , encoding = "ASCII" ) as in_file : for line in in_file : if line . startswith ( "#" ) : key , value = line [ 1 : ] . strip ( ) . split ( " " , 1 ) meta . append ( ( key , value ) ) else : try : data . append ( [ float ( frag ) for frag in line . split ( "," ) ] ) except : pass data = np . asarray ( data ) ndim = int ( _get ( meta , "dimension" ) ) if ndim == 1 : return _create_h1 ( data , meta ) elif ndim == 2 : return _create_h2 ( data , meta )
Loads a histogram as output from Geant4 analysis tools in CSV format .
60,503
def _get ( pseudodict , key , single = True ) : matches = [ item [ 1 ] for item in pseudodict if item [ 0 ] == key ] if single : return matches [ 0 ] else : return matches
Helper method for getting values from multi - dict s
60,504
def queryURL ( self , xri , service_type = None ) : qxri = toURINormal ( xri ) [ 6 : ] hxri = self . proxy_url + qxri args = { '_xrd_r' : 'application/xrds+xml' , } if service_type : args [ '_xrd_t' ] = service_type else : args [ '_xrd_r' ] += ';sep=false' query = _appendArgs ( hxri , args ) return query
Build a URL to query the proxy resolver .
60,505
def query ( self , xri , service_types ) : services = [ ] canonicalID = None for service_type in service_types : url = self . queryURL ( xri , service_type ) response = fetchers . fetch ( url ) if response . status not in ( 200 , 206 ) : continue et = etxrd . parseXRDS ( response . body ) canonicalID = etxrd . getCanonicalID ( xri , et ) some_services = list ( iterServices ( et ) ) services . extend ( some_services ) return canonicalID , services
Resolve some services for an XRI .
60,506
def generateAcceptHeader ( * elements ) : parts = [ ] for element in elements : if type ( element ) is str : qs = "1.0" mtype = element else : mtype , q = element q = float ( q ) if q > 1 or q <= 0 : raise ValueError ( 'Invalid preference factor: %r' % q ) qs = '%0.1f' % ( q , ) parts . append ( ( qs , mtype ) ) parts . sort ( ) chunks = [ ] for q , mtype in parts : if q == '1.0' : chunks . append ( mtype ) else : chunks . append ( '%s; q=%s' % ( mtype , q ) ) return ', ' . join ( chunks )
Generate an accept header value
60,507
def parseAcceptHeader ( value ) : chunks = [ chunk . strip ( ) for chunk in value . split ( ',' ) ] accept = [ ] for chunk in chunks : parts = [ s . strip ( ) for s in chunk . split ( ';' ) ] mtype = parts . pop ( 0 ) if '/' not in mtype : continue main , sub = mtype . split ( '/' , 1 ) for ext in parts : if '=' in ext : k , v = ext . split ( '=' , 1 ) if k == 'q' : try : q = float ( v ) break except ValueError : pass else : q = 1.0 accept . append ( ( q , main , sub ) ) accept . sort ( ) accept . reverse ( ) return [ ( main , sub , q ) for ( q , main , sub ) in accept ]
Parse an accept header ignoring any accept - extensions
60,508
def getAcceptable ( accept_header , have_types ) : accepted = parseAcceptHeader ( accept_header ) preferred = matchTypes ( accepted , have_types ) return [ mtype for ( mtype , _ ) in preferred ]
Parse the accept header and return a list of available types in preferred order . If a type is unacceptable it will not be in the resulting list .
60,509
def fromPostArgs ( cls , args ) : self = cls ( ) openid_args = { } for key , value in args . items ( ) : if isinstance ( value , list ) : raise TypeError ( "query dict must have one value for each key, " "not lists of values. Query is %r" % ( args , ) ) try : prefix , rest = key . split ( '.' , 1 ) except ValueError : prefix = None if prefix != 'openid' : self . args [ ( BARE_NS , key ) ] = value else : openid_args [ rest ] = value self . _fromOpenIDArgs ( openid_args ) return self
Construct a Message containing a set of POST arguments .
60,510
def getKey ( self , namespace , ns_key ) : namespace = self . _fixNS ( namespace ) if namespace == BARE_NS : return ns_key ns_alias = self . namespaces . getAlias ( namespace ) if ns_alias is None : return None if ns_alias == NULL_NAMESPACE : tail = ns_key else : tail = '%s.%s' % ( ns_alias , ns_key ) return 'openid.' + tail
Get the key for a particular namespaced argument
60,511
def getArg ( self , namespace , key , default = None ) : namespace = self . _fixNS ( namespace ) args_key = ( namespace , key ) try : return self . args [ args_key ] except KeyError : if default is no_default : raise KeyError ( ( namespace , key ) ) else : return default
Get a value for a namespaced key .
60,512
def add ( self , namespace_uri ) : alias = self . namespace_to_alias . get ( namespace_uri ) if alias is not None : return alias i = 0 while True : alias = 'ext' + str ( i ) try : self . addAlias ( namespace_uri , alias ) except KeyError : i += 1 else : return alias assert False , "Not reached"
Add this namespace URI to the mapping without caring what alias it ends up with
60,513
def findHTMLMeta ( stream ) : parser = YadisHTMLParser ( ) chunks = [ ] while 1 : chunk = stream . read ( CHUNK_SIZE ) if not chunk : break chunks . append ( chunk ) try : parser . feed ( chunk ) except HTMLParseError , why : chunks . append ( stream . read ( ) ) break except ParseDone , why : uri = why [ 0 ] if uri is None : chunks . append ( stream . read ( ) ) break else : return uri content = '' . join ( chunks ) raise MetaNotFound ( content )
Look for a meta http - equiv tag with the YADIS header name .
60,514
def toTypeURIs ( namespace_map , alias_list_s ) : uris = [ ] if alias_list_s : for alias in alias_list_s . split ( ',' ) : type_uri = namespace_map . getNamespaceURI ( alias ) if type_uri is None : raise KeyError ( 'No type is defined for attribute name %r' % ( alias , ) ) else : uris . append ( type_uri ) return uris
Given a namespace mapping and a string containing a comma - separated list of namespace aliases return a list of type URIs that correspond to those aliases .
60,515
def add ( self , attribute ) : if attribute . type_uri in self . requested_attributes : raise KeyError ( 'The attribute %r has already been requested' % ( attribute . type_uri , ) ) self . requested_attributes [ attribute . type_uri ] = attribute
Add an attribute to this attribute exchange request .
60,516
def addValue ( self , type_uri , value ) : try : values = self . data [ type_uri ] except KeyError : values = self . data [ type_uri ] = [ ] values . append ( value )
Add a single value for the given attribute type to the message . If there are already values specified for this type this value will be sent in addition to the values already specified .
60,517
def getSingle ( self , type_uri , default = None ) : values = self . data . get ( type_uri ) if not values : return default elif len ( values ) == 1 : return values [ 0 ] else : raise AXError ( 'More than one value present for %r' % ( type_uri , ) )
Get a single value for an attribute . If no value was sent for this attribute use the supplied default . If there is more than one value for this attribute this method will fail .
60,518
def getExtensionArgs ( self ) : aliases = NamespaceMap ( ) zero_value_types = [ ] if self . request is not None : for type_uri in self . data : if type_uri not in self . request : raise KeyError ( 'Response attribute not present in request: %r' % ( type_uri , ) ) for attr_info in self . request . iterAttrs ( ) : if attr_info . alias is None : aliases . add ( attr_info . type_uri ) else : aliases . addAlias ( attr_info . type_uri , attr_info . alias ) try : values = self . data [ attr_info . type_uri ] except KeyError : values = [ ] zero_value_types . append ( attr_info ) if ( attr_info . count != UNLIMITED_VALUES ) and ( attr_info . count < len ( values ) ) : raise AXError ( 'More than the number of requested values were ' 'specified for %r' % ( attr_info . type_uri , ) ) kv_args = self . _getExtensionKVArgs ( aliases ) ax_args = self . _newArgs ( ) for attr_info in zero_value_types : alias = aliases . getAlias ( attr_info . type_uri ) kv_args [ 'type.' + alias ] = attr_info . type_uri kv_args [ 'count.' + alias ] = '0' update_url = ( ( self . request and self . request . update_url ) or self . update_url ) if update_url : ax_args [ 'update_url' ] = update_url ax_args . update ( kv_args ) return ax_args
Serialize this object into arguments in the attribute exchange namespace
60,519
def fromSuccessResponse ( cls , success_response , signed = True ) : self = cls ( ) ax_args = success_response . extensionResponse ( self . ns_uri , signed ) try : self . parseExtensionArgs ( ax_args ) except NotAXMessage , err : return None else : return self
Construct a FetchResponse object from an OpenID library SuccessResponse object .
60,520
def parseExtensionArgs ( self , args , strict = False ) : for list_name in [ 'required' , 'optional' ] : required = ( list_name == 'required' ) items = args . get ( list_name ) if items : for field_name in items . split ( ',' ) : try : self . requestField ( field_name , required , strict ) except ValueError : if strict : raise self . policy_url = args . get ( 'policy_url' )
Parse the unqualified simple registration request parameters and add them to this object .
60,521
def requestField ( self , field_name , required = False , strict = False ) : checkFieldName ( field_name ) if strict : if field_name in self . required or field_name in self . optional : raise ValueError ( 'That field has already been requested' ) else : if field_name in self . required : return if field_name in self . optional : if required : self . optional . remove ( field_name ) else : return if required : self . required . append ( field_name ) else : self . optional . append ( field_name )
Request the specified field from the OpenID user
60,522
def requestFields ( self , field_names , required = False , strict = False ) : if isinstance ( field_names , basestring ) : raise TypeError ( 'Fields should be passed as a list of ' 'strings (not %r)' % ( type ( field_names ) , ) ) for field_name in field_names : self . requestField ( field_name , required , strict = strict )
Add the given list of fields to the request
60,523
def getExtensionArgs ( self ) : args = { } if self . required : args [ 'required' ] = ',' . join ( self . required ) if self . optional : args [ 'optional' ] = ',' . join ( self . optional ) if self . policy_url : args [ 'policy_url' ] = self . policy_url return args
Get a dictionary of unqualified simple registration arguments representing this request .
60,524
def get ( self , field_name , default = None ) : checkFieldName ( field_name ) return self . data . get ( field_name , default )
Like dict . get except that it checks that the field name is defined by the simple registration specification
60,525
def returnToMatches ( allowed_return_to_urls , return_to ) : for allowed_return_to in allowed_return_to_urls : return_realm = TrustRoot . parse ( allowed_return_to ) if ( return_realm is not None and not return_realm . wildcard and return_realm . validateURL ( return_to ) ) : return True return False
Is the return_to URL under one of the supplied allowed return_to URLs?
60,526
def getAllowedReturnURLs ( relying_party_url ) : ( rp_url_after_redirects , return_to_urls ) = services . getServiceEndpoints ( relying_party_url , _extractReturnURL ) if rp_url_after_redirects != relying_party_url : raise RealmVerificationRedirected ( relying_party_url , rp_url_after_redirects ) return return_to_urls
Given a relying party discovery URL return a list of return_to URLs .
60,527
def verifyReturnTo ( realm_str , return_to , _vrfy = getAllowedReturnURLs ) : realm = TrustRoot . parse ( realm_str ) if realm is None : return False try : allowable_urls = _vrfy ( realm . buildDiscoveryURL ( ) ) except RealmVerificationRedirected , err : logging . exception ( str ( err ) ) return False if returnToMatches ( allowable_urls , return_to ) : return True else : logging . error ( "Failed to validate return_to %r for realm %r, was not " "in %s" % ( return_to , realm_str , allowable_urls ) ) return False
Verify that a return_to URL is valid for the given realm .
60,528
def validateURL ( self , url ) : url_parts = _parseURL ( url ) if url_parts is None : return False proto , host , port , path = url_parts if proto != self . proto : return False if port != self . port : return False if '*' in host : return False if not self . wildcard : if host != self . host : return False elif ( ( not host . endswith ( self . host ) ) and ( '.' + host ) != self . host ) : return False if path != self . path : path_len = len ( self . path ) trust_prefix = self . path [ : path_len ] url_prefix = path [ : path_len ] if trust_prefix != url_prefix : return False if '?' in self . path : allowed = '&' else : allowed = '?/' return ( self . path [ - 1 ] in allowed or path [ path_len ] in allowed ) return True
Validates a URL against this trust root .
60,529
def checkSanity ( cls , trust_root_string ) : trust_root = cls . parse ( trust_root_string ) if trust_root is None : return False else : return trust_root . isSane ( )
str - > bool
60,530
def checkURL ( cls , trust_root , url ) : tr = cls . parse ( trust_root ) return tr is not None and tr . validateURL ( url )
quick func for validating a url against a trust root . See the TrustRoot class if you need more control .
60,531
def buildDiscoveryURL ( self ) : if self . wildcard : assert self . host . startswith ( '.' ) , self . host www_domain = 'www' + self . host return '%s://%s%s' % ( self . proto , www_domain , self . path ) else : return self . unparsed
Return a discovery URL for this realm .
60,532
def next ( self ) : try : self . _current = self . services . pop ( 0 ) except IndexError : raise StopIteration else : return self . _current
Return the next service
60,533
def getNextService ( self , discover ) : manager = self . getManager ( ) if manager is not None and not manager : self . destroyManager ( ) if not manager : yadis_url , services = discover ( self . url ) manager = self . createManager ( services , yadis_url ) if manager : service = manager . next ( ) manager . store ( self . session ) else : service = None return service
Return the next authentication service for the pair of user_input and session . This function handles fallback .
60,534
def cleanup ( self , force = False ) : manager = self . getManager ( force = force ) if manager is not None : service = manager . current ( ) self . destroyManager ( force = force ) else : service = None return service
Clean up Yadis - related services in the session and return the most - recently - attempted service from the manager if one exists .
60,535
def getManager ( self , force = False ) : manager = self . session . get ( self . getSessionKey ( ) ) if ( manager is not None and ( manager . forURL ( self . url ) or force ) ) : return manager else : return None
Extract the YadisServiceManager for this object s URL and suffix from the session .
60,536
def createManager ( self , services , yadis_url = None ) : key = self . getSessionKey ( ) if self . getManager ( ) : raise KeyError ( 'There is already a %r manager for %r' % ( key , self . url ) ) if not services : return None manager = YadisServiceManager ( self . url , yadis_url , services , key ) manager . store ( self . session ) return manager
Create a new YadisService Manager for this starting URL and suffix and store it in the session .
60,537
def destroyManager ( self , force = False ) : if self . getManager ( force = force ) is not None : key = self . getSessionKey ( ) del self . session [ key ]
Delete any YadisServiceManager with this starting URL and suffix from the session .
60,538
def _setPrivate ( self , private ) : self . private = private self . public = pow ( self . generator , self . private , self . modulus )
This is here to make testing easier
60,539
def answerUnsupported ( self , message , preferred_association_type = None , preferred_session_type = None ) : if self . message . isOpenID1 ( ) : raise ProtocolError ( self . message ) response = OpenIDResponse ( self ) response . fields . setArg ( OPENID_NS , 'error_code' , 'unsupported-type' ) response . fields . setArg ( OPENID_NS , 'error' , message ) if preferred_association_type : response . fields . setArg ( OPENID_NS , 'assoc_type' , preferred_association_type ) if preferred_session_type : response . fields . setArg ( OPENID_NS , 'session_type' , preferred_session_type ) return response
Respond to this request indicating that the association type or association session type is not supported .
60,540
def fromMessage ( klass , message , op_endpoint ) : self = klass . __new__ ( klass ) self . message = message self . op_endpoint = op_endpoint mode = message . getArg ( OPENID_NS , 'mode' ) if mode == "checkid_immediate" : self . immediate = True self . mode = "checkid_immediate" else : self . immediate = False self . mode = "checkid_setup" self . return_to = message . getArg ( OPENID_NS , 'return_to' ) if message . isOpenID1 ( ) and not self . return_to : fmt = "Missing required field 'return_to' from %r" raise ProtocolError ( message , text = fmt % ( message , ) ) self . identity = message . getArg ( OPENID_NS , 'identity' ) self . claimed_id = message . getArg ( OPENID_NS , 'claimed_id' ) if message . isOpenID1 ( ) : if self . identity is None : s = "OpenID 1 message did not contain openid.identity" raise ProtocolError ( message , text = s ) else : if self . identity and not self . claimed_id : s = ( "OpenID 2.0 message contained openid.identity but not " "claimed_id" ) raise ProtocolError ( message , text = s ) elif self . claimed_id and not self . identity : s = ( "OpenID 2.0 message contained openid.claimed_id but not " "identity" ) raise ProtocolError ( message , text = s ) if message . isOpenID1 ( ) : trust_root_param = 'trust_root' else : trust_root_param = 'realm' self . trust_root = ( message . getArg ( OPENID_NS , trust_root_param ) or self . return_to ) if not message . isOpenID1 ( ) : if self . return_to is self . trust_root is None : raise ProtocolError ( message , "openid.realm required when " + "openid.return_to absent" ) self . assoc_handle = message . getArg ( OPENID_NS , 'assoc_handle' ) if self . return_to is not None and not TrustRoot . parse ( self . return_to ) : raise MalformedReturnURL ( message , self . return_to ) if not self . trustRootValid ( ) : raise UntrustedReturnURL ( message , self . return_to , self . trust_root ) return self
Construct me from an OpenID message .
60,541
def trustRootValid ( self ) : if not self . trust_root : return True tr = TrustRoot . parse ( self . trust_root ) if tr is None : raise MalformedTrustRoot ( self . message , self . trust_root ) if self . return_to is not None : return tr . validateURL ( self . return_to ) else : return True
Is my return_to under my trust_root?
60,542
def encodeToURL ( self , server_url ) : if not self . return_to : raise NoReturnToError q = { 'mode' : self . mode , 'identity' : self . identity , 'claimed_id' : self . claimed_id , 'return_to' : self . return_to } if self . trust_root : if self . message . isOpenID1 ( ) : q [ 'trust_root' ] = self . trust_root else : q [ 'realm' ] = self . trust_root if self . assoc_handle : q [ 'assoc_handle' ] = self . assoc_handle response = Message ( self . message . getOpenIDNamespace ( ) ) response . updateArgs ( OPENID_NS , q ) return response . toURL ( server_url )
Encode this request as a URL to GET .
60,543
def getCancelURL ( self ) : if not self . return_to : raise NoReturnToError if self . immediate : raise ValueError ( "Cancel is not an appropriate response to " "immediate mode requests." ) response = Message ( self . message . getOpenIDNamespace ( ) ) response . setArg ( OPENID_NS , 'mode' , 'cancel' ) return response . toURL ( self . return_to )
Get the URL to cancel this request .
60,544
def toFormMarkup ( self , form_tag_attrs = None ) : return self . fields . toFormMarkup ( self . request . return_to , form_tag_attrs = form_tag_attrs )
Returns the form markup for this response .
60,545
def verify ( self , assoc_handle , message ) : assoc = self . getAssociation ( assoc_handle , dumb = True ) if not assoc : logging . error ( "failed to get assoc with handle %r to verify " "message %r" % ( assoc_handle , message ) ) return False try : valid = assoc . checkMessageSignature ( message ) except ValueError , ex : logging . exception ( "Error in verifying %s with %s: %s" % ( message , assoc , ex ) ) return False return valid
Verify that the signature for some data is valid .
60,546
def sign ( self , response ) : signed_response = deepcopy ( response ) assoc_handle = response . request . assoc_handle if assoc_handle : assoc = self . getAssociation ( assoc_handle , dumb = False , checkExpiration = False ) if not assoc or assoc . expiresIn <= 0 : signed_response . fields . setArg ( OPENID_NS , 'invalidate_handle' , assoc_handle ) assoc_type = assoc and assoc . assoc_type or 'HMAC-SHA1' if assoc and assoc . expiresIn <= 0 : self . invalidate ( assoc_handle , dumb = False ) assoc = self . createAssociation ( dumb = True , assoc_type = assoc_type ) else : assoc = self . createAssociation ( dumb = True ) try : signed_response . fields = assoc . signMessage ( signed_response . fields ) except kvform . KVFormError , err : raise EncodingError ( response , explanation = str ( err ) ) return signed_response
Sign a response .
60,547
def createAssociation ( self , dumb = True , assoc_type = 'HMAC-SHA1' ) : secret = cryptutil . getBytes ( getSecretSize ( assoc_type ) ) uniq = oidutil . toBase64 ( cryptutil . getBytes ( 4 ) ) handle = '{%s}{%x}{%s}' % ( assoc_type , int ( time . time ( ) ) , uniq ) assoc = Association . fromExpiresIn ( self . SECRET_LIFETIME , handle , secret , assoc_type ) if dumb : key = self . _dumb_key else : key = self . _normal_key self . store . storeAssociation ( key , assoc ) return assoc
Make a new association .
60,548
def getAssociation ( self , assoc_handle , dumb , checkExpiration = True ) : if assoc_handle is None : raise ValueError ( "assoc_handle must not be None" ) if dumb : key = self . _dumb_key else : key = self . _normal_key assoc = self . store . getAssociation ( key , assoc_handle ) if assoc is not None and assoc . expiresIn <= 0 : logging . info ( "requested %sdumb key %r is expired (by %s seconds)" % ( ( not dumb ) and 'not-' or '' , assoc_handle , assoc . expiresIn ) ) if checkExpiration : self . store . removeAssociation ( key , assoc_handle ) assoc = None return assoc
Get the association with the specified handle .
60,549
def invalidate ( self , assoc_handle , dumb ) : if dumb : key = self . _dumb_key else : key = self . _normal_key self . store . removeAssociation ( key , assoc_handle )
Invalidates the association with the given handle .
60,550
def defaultDecoder ( self , message , server ) : mode = message . getArg ( OPENID_NS , 'mode' ) fmt = "Unrecognized OpenID mode %r" raise ProtocolError ( message , text = fmt % ( mode , ) )
Called to decode queries when no handler for that mode is found .
60,551
def toMessage ( self ) : namespace = self . openid_message . getOpenIDNamespace ( ) reply = Message ( namespace ) reply . setArg ( OPENID_NS , 'mode' , 'error' ) reply . setArg ( OPENID_NS , 'error' , str ( self ) ) if self . contact is not None : reply . setArg ( OPENID_NS , 'contact' , str ( self . contact ) ) if self . reference is not None : reply . setArg ( OPENID_NS , 'reference' , str ( self . reference ) ) return reply
Generate a Message object for sending to the relying party after encoding .
60,552
def rpXRDS ( request ) : return util . renderXRDS ( request , [ RP_RETURN_TO_URL_TYPE ] , [ util . getViewURL ( request , finishOpenID ) ] )
Return a relying party verification XRDS document
60,553
def getSession ( self ) : if self . session is not None : return self . session cookie_str = self . headers . get ( 'Cookie' ) if cookie_str : cookie_obj = SimpleCookie ( cookie_str ) sid_morsel = cookie_obj . get ( self . SESSION_COOKIE_NAME , None ) if sid_morsel is not None : sid = sid_morsel . value else : sid = None else : sid = None if sid is None : sid = randomString ( 16 , '0123456789abcdef' ) session = None else : session = self . server . sessions . get ( sid ) if session is None : session = self . server . sessions [ sid ] = { } session [ 'id' ] = sid self . session = session return session
Return the existing session or a new session
60,554
def doProcess ( self ) : oidconsumer = self . getConsumer ( ) url = 'http://' + self . headers . get ( 'Host' ) + self . path info = oidconsumer . complete ( self . query , url ) sreg_resp = None pape_resp = None css_class = 'error' display_identifier = info . getDisplayIdentifier ( ) if info . status == consumer . FAILURE and display_identifier : fmt = "Verification of %s failed: %s" message = fmt % ( cgi . escape ( display_identifier ) , info . message ) elif info . status == consumer . SUCCESS : css_class = 'alert' fmt = "You have successfully verified %s as your identity." message = fmt % ( cgi . escape ( display_identifier ) , ) sreg_resp = sreg . SRegResponse . fromSuccessResponse ( info ) pape_resp = pape . Response . fromSuccessResponse ( info ) if info . endpoint . canonicalID : message += ( " This is an i-name, and its persistent ID is %s" % ( cgi . escape ( info . endpoint . canonicalID ) , ) ) elif info . status == consumer . CANCEL : message = 'Verification cancelled' elif info . status == consumer . SETUP_NEEDED : if info . setup_url : message = '<a href=%s>Setup needed</a>' % ( quoteattr ( info . setup_url ) , ) else : message = 'Setup needed' else : message = 'Verification failed.' self . render ( message , css_class , display_identifier , sreg_data = sreg_resp , pape_data = pape_resp )
Handle the redirect from the OpenID server .
60,555
def notFound ( self ) : fmt = 'The path <q>%s</q> was not understood by this server.' msg = fmt % ( self . path , ) openid_url = self . query . get ( 'openid_identifier' ) self . render ( msg , 'error' , openid_url , status = 404 )
Render a page with a 404 return code and a message .
60,556
def render ( self , message = None , css_class = 'alert' , form_contents = None , status = 200 , title = "Python OpenID Consumer Example" , sreg_data = None , pape_data = None ) : self . send_response ( status ) self . pageHeader ( title ) if message : self . wfile . write ( "<div class='%s'>" % ( css_class , ) ) self . wfile . write ( message ) self . wfile . write ( "</div>" ) if sreg_data is not None : self . renderSREG ( sreg_data ) if pape_data is not None : self . renderPAPE ( pape_data ) self . pageFooter ( form_contents )
Render a page .
60,557
def _callInTransaction ( self , func , * args , ** kwargs ) : self . conn . rollback ( ) try : self . cur = self . conn . cursor ( ) try : ret = func ( * args , ** kwargs ) finally : self . cur . close ( ) self . cur = None except : self . conn . rollback ( ) raise else : self . conn . commit ( ) return ret
Execute the given function inside of a transaction with an open cursor . If no exception is raised the transaction is comitted otherwise it is rolled back .
60,558
def txn_storeAssociation ( self , server_url , association ) : a = association self . db_set_assoc ( server_url , a . handle , self . blobEncode ( a . secret ) , a . issued , a . lifetime , a . assoc_type )
Set the association for the server URL .
60,559
def txn_removeAssociation ( self , server_url , handle ) : self . db_remove_assoc ( server_url , handle ) return self . cur . rowcount > 0
Remove the association for the given server URL and handle returning whether the association existed at all .
60,560
def txn_useNonce ( self , server_url , timestamp , salt ) : if abs ( timestamp - time . time ( ) ) > nonce . SKEW : return False try : self . db_add_nonce ( server_url , timestamp , salt ) except self . exceptions . IntegrityError : return False else : return True
Return whether this nonce is present and if it is then remove it from the set .
60,561
def _escape_xref ( xref_match ) : xref = xref_match . group ( ) xref = xref . replace ( '/' , '%2F' ) xref = xref . replace ( '?' , '%3F' ) xref = xref . replace ( '#' , '%23' ) return xref
Escape things that need to be escaped if they re in a cross - reference .
60,562
def escapeForIRI ( xri ) : xri = xri . replace ( '%' , '%25' ) xri = _xref_re . sub ( _escape_xref , xri ) return xri
Escape things that need to be escaped when transforming to an IRI .
60,563
def providerIsAuthoritative ( providerID , canonicalID ) : lastbang = canonicalID . rindex ( '!' ) parent = canonicalID [ : lastbang ] return parent == providerID
Is this provider ID authoritative for this XRI?
60,564
def rootAuthority ( xri ) : if xri . startswith ( 'xri://' ) : xri = xri [ 6 : ] authority = xri . split ( '/' , 1 ) [ 0 ] if authority [ 0 ] == '(' : root = authority [ : authority . index ( ')' ) + 1 ] elif authority [ 0 ] in XRI_AUTHORITIES : root = authority [ 0 ] else : segments = authority . split ( '!' ) segments = reduce ( list . __add__ , map ( lambda s : s . split ( '*' ) , segments ) ) root = segments [ 0 ] return XRI ( root )
Return the root authority for an XRI .
60,565
def toMessage ( self , message = None ) : if message is None : warnings . warn ( 'Passing None to Extension.toMessage is deprecated. ' 'Creating a message assuming you want OpenID 2.' , DeprecationWarning , stacklevel = 2 ) message = message_module . Message ( message_module . OPENID2_NS ) implicit = message . isOpenID1 ( ) try : message . namespaces . addAlias ( self . ns_uri , self . ns_alias , implicit = implicit ) except KeyError : if message . namespaces . getAlias ( self . ns_uri ) != self . ns_alias : raise message . updateArgs ( self . ns_uri , self . getExtensionArgs ( ) ) return message
Add the arguments from this extension to the provided message or create a new message containing only those arguments .
60,566
def _ensureDir ( dir_name ) : try : os . makedirs ( dir_name ) except OSError , why : if why . errno != EEXIST or not os . path . isdir ( dir_name ) : raise
Create dir_name as a directory if it does not exist . If it exists make sure that it is in fact a directory .
60,567
def _setup ( self ) : _ensureDir ( self . nonce_dir ) _ensureDir ( self . association_dir ) _ensureDir ( self . temp_dir )
Make sure that the directories in which we store our data exist .
60,568
def _mktemp ( self ) : fd , name = mkstemp ( dir = self . temp_dir ) try : file_obj = os . fdopen ( fd , 'wb' ) return file_obj , name except : _removeIfPresent ( name ) raise
Create a temporary file on the same filesystem as self . association_dir .
60,569
def getAssociationFilename ( self , server_url , handle ) : if server_url . find ( '://' ) == - 1 : raise ValueError ( 'Bad server URL: %r' % server_url ) proto , rest = server_url . split ( '://' , 1 ) domain = _filenameEscape ( rest . split ( '/' , 1 ) [ 0 ] ) url_hash = _safe64 ( server_url ) if handle : handle_hash = _safe64 ( handle ) else : handle_hash = '' filename = '%s-%s-%s-%s' % ( proto , domain , url_hash , handle_hash ) return os . path . join ( self . association_dir , filename )
Create a unique filename for a given server url and handle . This implementation does not assume anything about the format of the handle . The filename that is returned will contain the domain name from the server URL for ease of human inspection of the data directory .
60,570
def getAssociation ( self , server_url , handle = None ) : if handle is None : handle = '' filename = self . getAssociationFilename ( server_url , handle ) if handle : return self . _getAssociation ( filename ) else : association_files = os . listdir ( self . association_dir ) matching_files = [ ] name = os . path . basename ( filename ) for association_file in association_files : if association_file . startswith ( name ) : matching_files . append ( association_file ) matching_associations = [ ] for name in matching_files : full_name = os . path . join ( self . association_dir , name ) association = self . _getAssociation ( full_name ) if association is not None : matching_associations . append ( ( association . issued , association ) ) matching_associations . sort ( ) if matching_associations : ( _ , assoc ) = matching_associations [ - 1 ] return assoc else : return None
Retrieve an association . If no handle is specified return the association with the latest expiration .
60,571
def removeAssociation ( self , server_url , handle ) : assoc = self . getAssociation ( server_url , handle ) if assoc is None : return 0 else : filename = self . getAssociationFilename ( server_url , handle ) return _removeIfPresent ( filename )
Remove an association if it exists . Do nothing if it does not .
60,572
def useNonce ( self , server_url , timestamp , salt ) : if abs ( timestamp - time . time ( ) ) > nonce . SKEW : return False if server_url : proto , rest = server_url . split ( '://' , 1 ) else : proto , rest = '' , '' domain = _filenameEscape ( rest . split ( '/' , 1 ) [ 0 ] ) url_hash = _safe64 ( server_url ) salt_hash = _safe64 ( salt ) filename = '%08x-%s-%s-%s-%s' % ( timestamp , proto , domain , url_hash , salt_hash ) filename = os . path . join ( self . nonce_dir , filename ) try : fd = os . open ( filename , os . O_CREAT | os . O_EXCL | os . O_WRONLY , 0200 ) except OSError , why : if why . errno == EEXIST : return False else : raise else : os . close ( fd ) return True
Return whether this nonce is valid .
60,573
def arrangeByType ( service_list , preferred_types ) : def enumerate ( elts ) : return zip ( range ( len ( elts ) ) , elts ) def bestMatchingService ( service ) : for i , t in enumerate ( preferred_types ) : if preferred_types [ i ] in service . type_uris : return i return len ( preferred_types ) prio_services = [ ( bestMatchingService ( s ) , orig_index , s ) for ( orig_index , s ) in enumerate ( service_list ) ] prio_services . sort ( ) for i in range ( len ( prio_services ) ) : prio_services [ i ] = prio_services [ i ] [ 2 ] return prio_services
Rearrange service_list in a new list so services are ordered by types listed in preferred_types . Return the new list .
60,574
def getOPOrUserServices ( openid_services ) : op_services = arrangeByType ( openid_services , [ OPENID_IDP_2_0_TYPE ] ) openid_services = arrangeByType ( openid_services , OpenIDServiceEndpoint . openid_type_uris ) return op_services or openid_services
Extract OP Identifier services . If none found return the rest sorted with most preferred first according to OpenIDServiceEndpoint . openid_type_uris .
60,575
def supportsType ( self , type_uri ) : return ( ( type_uri in self . type_uris ) or ( type_uri == OPENID_2_0_TYPE and self . isOPIdentifier ( ) ) )
Does this endpoint support this type?
60,576
def parseService ( self , yadis_url , uri , type_uris , service_element ) : self . type_uris = type_uris self . server_url = uri self . used_yadis = True if not self . isOPIdentifier ( ) : self . local_id = findOPLocalIdentifier ( service_element , self . type_uris ) self . claimed_id = yadis_url
Set the state of this object based on the contents of the service element .
60,577
def getLocalID ( self ) : if ( self . local_id is self . canonicalID is None ) : return self . claimed_id else : return self . local_id or self . canonicalID
Return the identifier that should be sent as the openid . identity parameter to the server .
60,578
def fromBasicServiceEndpoint ( cls , endpoint ) : type_uris = endpoint . matchTypes ( cls . openid_type_uris ) if type_uris and endpoint . uri is not None : openid_endpoint = cls ( ) openid_endpoint . parseService ( endpoint . yadis_url , endpoint . uri , endpoint . type_uris , endpoint . service_element ) else : openid_endpoint = None return openid_endpoint
Create a new instance of this class from the endpoint object passed in .
60,579
def fromDiscoveryResult ( cls , discoveryResult ) : if discoveryResult . isXRDS ( ) : method = cls . fromXRDS else : method = cls . fromHTML return method ( discoveryResult . normalized_uri , discoveryResult . response_text )
Create endpoints from a DiscoveryResult .
60,580
def fromOPEndpointURL ( cls , op_endpoint_url ) : service = cls ( ) service . server_url = op_endpoint_url service . type_uris = [ OPENID_IDP_2_0_TYPE ] return service
Construct an OP - Identifier OpenIDServiceEndpoint object for a given OP Endpoint URL
60,581
def setAllowedTypes ( self , allowed_types ) : for ( assoc_type , session_type ) in allowed_types : checkSessionType ( assoc_type , session_type ) self . allowed_types = allowed_types
Set the allowed association types checking to make sure each combination is valid .
60,582
def isAllowed ( self , assoc_type , session_type ) : assoc_good = ( assoc_type , session_type ) in self . allowed_types matches = session_type in getSessionTypes ( assoc_type ) return assoc_good and matches
Is this combination of association type and session type allowed?
60,583
def serialize ( self ) : data = { 'version' : '2' , 'handle' : self . handle , 'secret' : oidutil . toBase64 ( self . secret ) , 'issued' : str ( int ( self . issued ) ) , 'lifetime' : str ( int ( self . lifetime ) ) , 'assoc_type' : self . assoc_type } assert len ( data ) == len ( self . assoc_keys ) pairs = [ ] for field_name in self . assoc_keys : pairs . append ( ( field_name , data [ field_name ] ) ) return kvform . seqToKV ( pairs , strict = True )
Convert an association to KV form .
60,584
def getMessageSignature ( self , message ) : pairs = self . _makePairs ( message ) return oidutil . toBase64 ( self . sign ( pairs ) )
Return the signature of a message .
60,585
def checkMessageSignature ( self , message ) : message_sig = message . getArg ( OPENID_NS , 'sig' ) if not message_sig : raise ValueError ( "%s has no sig." % ( message , ) ) calculated_sig = self . getMessageSignature ( message ) return cryptutil . const_eq ( calculated_sig , message_sig )
Given a message with a signature calculate a new signature and return whether it matches the signature in the message .
60,586
def addPolicyURI ( self , policy_uri ) : if policy_uri not in self . preferred_auth_policies : self . preferred_auth_policies . append ( policy_uri )
Add an acceptable authentication policy URI to this request
60,587
def _addAuthLevelAlias ( self , auth_level_uri , alias = None ) : if alias is None : try : alias = self . _getAlias ( auth_level_uri ) except KeyError : alias = self . _generateAlias ( ) else : existing_uri = self . auth_level_aliases . get ( alias ) if existing_uri is not None and existing_uri != auth_level_uri : raise KeyError ( 'Attempting to redefine alias %r from %r to %r' , alias , existing_uri , auth_level_uri ) self . auth_level_aliases [ alias ] = auth_level_uri
Add an auth level URI alias to this request .
60,588
def setAuthLevel ( self , level_uri , level , alias = None ) : self . _addAuthLevelAlias ( level_uri , alias ) self . auth_levels [ level_uri ] = level
Set the value for the given auth level type .
60,589
def discover ( uri ) : result = DiscoveryResult ( uri ) resp = fetchers . fetch ( uri , headers = { 'Accept' : YADIS_ACCEPT_HEADER } ) if resp . status not in ( 200 , 206 ) : raise DiscoveryFailure ( 'HTTP Response status from identity URL host is not 200. ' 'Got status %r' % ( resp . status , ) , resp ) result . normalized_uri = resp . final_url result . content_type = resp . headers . get ( 'content-type' ) result . xrds_uri = whereIsYadis ( resp ) if result . xrds_uri and result . usedYadisLocation ( ) : resp = fetchers . fetch ( result . xrds_uri ) if resp . status not in ( 200 , 206 ) : exc = DiscoveryFailure ( 'HTTP Response status from Yadis host is not 200. ' 'Got status %r' % ( resp . status , ) , resp ) exc . identity_url = result . normalized_uri raise exc result . content_type = resp . headers . get ( 'content-type' ) result . response_text = resp . body return result
Discover services for a given URI .
60,590
def whereIsYadis ( resp ) : content_type = resp . headers . get ( 'content-type' ) if ( content_type and content_type . split ( ';' , 1 ) [ 0 ] . lower ( ) == YADIS_CONTENT_TYPE ) : return resp . final_url else : yadis_loc = resp . headers . get ( YADIS_HEADER_NAME . lower ( ) ) if not yadis_loc : content_type = content_type or '' encoding = content_type . rsplit ( ';' , 1 ) if len ( encoding ) == 2 and encoding [ 1 ] . strip ( ) . startswith ( 'charset=' ) : encoding = encoding [ 1 ] . split ( '=' , 1 ) [ 1 ] . strip ( ) else : encoding = 'UTF-8' try : content = resp . body . decode ( encoding ) except UnicodeError : content = resp . body try : yadis_loc = findHTMLMeta ( StringIO ( content ) ) except ( MetaNotFound , UnicodeError ) : pass return yadis_loc
Given a HTTPResponse return the location of the Yadis document .
60,591
def endpoint ( request ) : s = getServer ( request ) query = util . normalDict ( request . GET or request . POST ) try : openid_request = s . decodeRequest ( query ) except ProtocolError , why : return direct_to_template ( request , 'server/endpoint.html' , { 'error' : str ( why ) } ) if openid_request is None : return direct_to_template ( request , 'server/endpoint.html' , { } ) if openid_request . mode in [ "checkid_immediate" , "checkid_setup" ] : return handleCheckIDRequest ( request , openid_request ) else : openid_response = s . handleRequest ( openid_request ) return displayResponse ( request , openid_response )
Respond to low - level OpenID protocol messages .
60,592
def showDecidePage ( request , openid_request ) : trust_root = openid_request . trust_root return_to = openid_request . return_to try : trust_root_valid = verifyReturnTo ( trust_root , return_to ) and "Valid" or "Invalid" except DiscoveryFailure , err : trust_root_valid = "DISCOVERY_FAILED" except HTTPFetchingError , err : trust_root_valid = "Unreachable" pape_request = pape . Request . fromOpenIDRequest ( openid_request ) return direct_to_template ( request , 'server/trust.html' , { 'trust_root' : trust_root , 'trust_handler_url' : getViewURL ( request , processTrustResult ) , 'trust_root_valid' : trust_root_valid , 'pape_request' : pape_request , } )
Render a page to the user so a trust decision can be made .
60,593
def processTrustResult ( request ) : openid_request = getRequest ( request ) response_identity = getViewURL ( request , idPage ) allowed = 'allow' in request . POST openid_response = openid_request . answer ( allowed , identity = response_identity ) if allowed : sreg_data = { 'fullname' : 'Example User' , 'nickname' : 'example' , 'dob' : '1970-01-01' , 'email' : '[email protected]' , 'gender' : 'F' , 'postcode' : '12345' , 'country' : 'ES' , 'language' : 'eu' , 'timezone' : 'America/New_York' , } sreg_req = sreg . SRegRequest . fromOpenIDRequest ( openid_request ) sreg_resp = sreg . SRegResponse . extractResponse ( sreg_req , sreg_data ) openid_response . addExtension ( sreg_resp ) pape_response = pape . Response ( ) pape_response . setAuthLevel ( pape . LEVELS_NIST , 0 ) openid_response . addExtension ( pape_response ) return displayResponse ( request , openid_response )
Handle the result of a trust decision and respond to the RP accordingly .
60,594
def buildDiscover ( base_url , out_dir ) : test_data = discoverdata . readTests ( discoverdata . default_test_file ) def writeTestFile ( test_name ) : template = test_data [ test_name ] data = discoverdata . fillTemplate ( test_name , template , base_url , discoverdata . example_xrds ) out_file_name = os . path . join ( out_dir , test_name ) out_file = file ( out_file_name , 'w' ) out_file . write ( data ) manifest = [ manifest_header ] for success , input_name , id_name , result_name in discoverdata . testlist : if not success : continue writeTestFile ( input_name ) input_url = urlparse . urljoin ( base_url , input_name ) id_url = urlparse . urljoin ( base_url , id_name ) result_url = urlparse . urljoin ( base_url , result_name ) manifest . append ( '\t' . join ( ( input_url , id_url , result_url ) ) ) manifest . append ( '\n' ) manifest_file_name = os . path . join ( out_dir , 'manifest.txt' ) manifest_file = file ( manifest_file_name , 'w' ) for chunk in manifest : manifest_file . write ( chunk ) manifest_file . close ( )
Convert all files in a directory to apache mod_asis files in another directory .
60,595
def best ( self ) : best = None for assoc in self . assocs . values ( ) : if best is None or best . issued < assoc . issued : best = assoc return best
Returns association with the oldest issued date .
60,596
def split ( nonce_string ) : timestamp_str = nonce_string [ : time_str_len ] try : timestamp = timegm ( strptime ( timestamp_str , time_fmt ) ) except AssertionError : timestamp = - 1 if timestamp < 0 : raise ValueError ( 'time out of range' ) return timestamp , nonce_string [ time_str_len : ]
Extract a timestamp from the given nonce string
60,597
def checkTimestamp ( nonce_string , allowed_skew = SKEW , now = None ) : try : stamp , _ = split ( nonce_string ) except ValueError : return False else : if now is None : now = time ( ) past = now - allowed_skew future = now + allowed_skew return past <= stamp <= future
Is the timestamp that is part of the specified nonce string within the allowed clock - skew of the current time?
60,598
def mkNonce ( when = None ) : salt = cryptutil . randomString ( 6 , NONCE_CHARS ) if when is None : t = gmtime ( ) else : t = gmtime ( when ) time_str = strftime ( time_fmt , t ) return time_str + salt
Generate a nonce with the current timestamp
60,599
def fetch ( url , body = None , headers = None ) : fetcher = getDefaultFetcher ( ) return fetcher . fetch ( url , body , headers )
Invoke the fetch method on the default fetcher . Most users should need only this method .