idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
13,300 | def subscribe ( self , sender = None , iface = None , signal = None , object = None , arg0 = None , flags = 0 , signal_fired = None ) : callback = ( lambda con , sender , object , iface , signal , params : signal_fired ( sender , object , iface , signal , params . unpack ( ) ) ) if signal_fired is not None else lambda * args : None return Subscription ( self . con , sender , iface , signal , object , arg0 , flags , callback ) | Subscribes to matching signals . |
13,301 | def watch_name ( self , name , flags = 0 , name_appeared = None , name_vanished = None ) : name_appeared_handler = ( lambda con , name , name_owner : name_appeared ( name_owner ) ) if name_appeared is not None else None name_vanished_handler = ( lambda con , name : name_vanished ( ) ) if name_vanished is not None else None return NameWatcher ( self . con , name , flags , name_appeared_handler , name_vanished_handler ) | Asynchronously watches a bus name . |
13,302 | def info ( self ) : url = "{}/v7/finance/quote?symbols={}" . format ( self . _base_url , self . ticker ) r = _requests . get ( url = url ) . json ( ) [ "quoteResponse" ] [ "result" ] if len ( r ) > 0 : return r [ 0 ] return { } | retreive metadata and currenct price data |
13,303 | def pingable_ws_connect ( request = None , on_message_callback = None , on_ping_callback = None ) : request . headers = httputil . HTTPHeaders ( request . headers ) request = httpclient . _RequestProxy ( request , httpclient . HTTPRequest . _DEFAULTS ) if version_info [ 0 ] == 4 : conn = PingableWSClientConnection ( io_loop = ioloop . IOLoop . current ( ) , request = request , on_message_callback = on_message_callback , on_ping_callback = on_ping_callback ) else : conn = PingableWSClientConnection ( request = request , on_message_callback = on_message_callback , on_ping_callback = on_ping_callback , max_message_size = getattr ( websocket , '_default_max_message_size' , 10 * 1024 * 1024 ) ) return conn . connect_future | A variation on websocket_connect that returns a PingableWSClientConnection with on_ping_callback . |
13,304 | def call_with_asked_args ( callback , args ) : asked_arg_names = callback . __code__ . co_varnames [ : callback . __code__ . co_argcount ] asked_arg_values = [ ] missing_args = [ ] for asked_arg_name in asked_arg_names : if asked_arg_name in args : asked_arg_values . append ( args [ asked_arg_name ] ) else : missing_args . append ( asked_arg_name ) if missing_args : raise TypeError ( '{}() missing required positional argument: {}' . format ( callback . __code__ . co_name , ', ' . join ( missing_args ) ) ) return callback ( * asked_arg_values ) | Call callback with only the args it wants from args |
13,305 | def _make_serverproxy_handler ( name , command , environment , timeout , absolute_url , port ) : class _Proxy ( SuperviseAndProxyHandler ) : def __init__ ( self , * args , ** kwargs ) : super ( ) . __init__ ( * args , ** kwargs ) self . name = name self . proxy_base = name self . absolute_url = absolute_url self . requested_port = port @ property def process_args ( self ) : return { 'port' : self . port , 'base_url' : self . base_url , } def _render_template ( self , value ) : args = self . process_args if type ( value ) is str : return value . format ( ** args ) elif type ( value ) is list : return [ self . _render_template ( v ) for v in value ] elif type ( value ) is dict : return { self . _render_template ( k ) : self . _render_template ( v ) for k , v in value . items ( ) } else : raise ValueError ( 'Value of unrecognized type {}' . format ( type ( value ) ) ) def get_cmd ( self ) : if callable ( command ) : return self . _render_template ( call_with_asked_args ( command , self . process_args ) ) else : return self . _render_template ( command ) def get_env ( self ) : if callable ( environment ) : return self . _render_template ( call_with_asked_args ( environment , self . process_args ) ) else : return self . _render_template ( environment ) def get_timeout ( self ) : return timeout return _Proxy | Create a SuperviseAndProxyHandler subclass with given parameters |
13,306 | def make_handlers ( base_url , server_processes ) : handlers = [ ] for sp in server_processes : handler = _make_serverproxy_handler ( sp . name , sp . command , sp . environment , sp . timeout , sp . absolute_url , sp . port , ) handlers . append ( ( ujoin ( base_url , sp . name , r'(.*)' ) , handler , dict ( state = { } ) , ) ) handlers . append ( ( ujoin ( base_url , sp . name ) , AddSlashHandler ) ) return handlers | Get tornado handlers for registered server_processes |
13,307 | async def open ( self , port , proxied_path = '' ) : if not proxied_path . startswith ( '/' ) : proxied_path = '/' + proxied_path client_uri = self . get_client_uri ( 'ws' , port , proxied_path ) headers = self . request . headers def message_cb ( message ) : self . _record_activity ( ) if message is None : self . close ( ) else : self . write_message ( message , binary = isinstance ( message , bytes ) ) def ping_cb ( data ) : self . _record_activity ( ) self . ping ( data ) async def start_websocket_connection ( ) : self . log . info ( 'Trying to establish websocket connection to {}' . format ( client_uri ) ) self . _record_activity ( ) request = httpclient . HTTPRequest ( url = client_uri , headers = headers ) self . ws = await pingable_ws_connect ( request = request , on_message_callback = message_cb , on_ping_callback = ping_cb ) self . _record_activity ( ) self . log . info ( 'Websocket connection established to {}' . format ( client_uri ) ) ioloop . IOLoop . current ( ) . add_callback ( start_websocket_connection ) | Called when a client opens a websocket connection . |
13,308 | def on_message ( self , message ) : self . _record_activity ( ) if hasattr ( self , 'ws' ) : self . ws . write_message ( message , binary = isinstance ( message , bytes ) ) | Called when we receive a message from our client . |
13,309 | def on_ping ( self , data ) : self . log . debug ( 'jupyter_server_proxy: on_ping: {}' . format ( data ) ) self . _record_activity ( ) if hasattr ( self , 'ws' ) : self . ws . protocol . write_ping ( data ) | Called when the client pings our websocket connection . |
13,310 | def select_subprotocol ( self , subprotocols ) : if isinstance ( subprotocols , list ) and subprotocols : self . log . info ( 'Client sent subprotocols: {}' . format ( subprotocols ) ) return subprotocols [ 0 ] return super ( ) . select_subprotocol ( subprotocols ) | Select a single Sec - WebSocket - Protocol during handshake . |
13,311 | def port ( self ) : if 'port' not in self . state : sock = socket . socket ( ) sock . bind ( ( '' , self . requested_port ) ) self . state [ 'port' ] = sock . getsockname ( ) [ 1 ] sock . close ( ) return self . state [ 'port' ] | Allocate either the requested port or a random empty port for use by application |
13,312 | def setup_shiny ( ) : name = 'shiny' def _get_shiny_cmd ( port ) : conf = dedent ( ) . format ( user = getpass . getuser ( ) , port = str ( port ) , site_dir = os . getcwd ( ) ) f = tempfile . NamedTemporaryFile ( mode = 'w' , delete = False ) f . write ( conf ) f . close ( ) return [ 'shiny-server' , f . name ] return { 'command' : _get_shiny_cmd , 'launcher_entry' : { 'title' : 'Shiny' , 'icon_path' : os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , 'icons' , 'shiny.svg' ) } } | Manage a Shiny instance . |
13,313 | def filter ( self , result ) : if result is None : return True reject = result in self . history if reject : log . debug ( 'result %s, rejected by\n%s' , Repr ( result ) , self ) return reject | Filter the specified result based on query criteria . |
13,314 | def result ( self , result ) : if result is None : log . debug ( '%s, not-found' , self . ref ) return if self . resolved : result = result . resolve ( ) log . debug ( '%s, found as: %s' , self . ref , Repr ( result ) ) self . history . append ( result ) return result | Query result post processing . |
13,315 | def add ( self , * items ) : for item in items : self . unsorted . append ( item ) key = item [ 0 ] self . index [ key ] = item return self | Add items to be sorted . |
13,316 | def sort ( self ) : self . sorted = list ( ) self . pushed = set ( ) for item in self . unsorted : popped = [ ] self . push ( item ) while len ( self . stack ) : try : top = self . top ( ) ref = next ( top [ 1 ] ) refd = self . index . get ( ref ) if refd is None : log . debug ( '"%s" not found, skipped' , Repr ( ref ) ) continue self . push ( refd ) except StopIteration : popped . append ( self . pop ( ) ) continue for p in popped : self . sorted . append ( p ) self . unsorted = self . sorted return self . sorted | Sort the list based on dependancies . |
13,317 | def push ( self , item ) : if item in self . pushed : return frame = ( item , iter ( item [ 1 ] ) ) self . stack . append ( frame ) self . pushed . add ( item ) | Push and item onto the sorting stack . |
13,318 | def download ( self , url ) : store = DocumentStore ( ) fp = store . open ( url ) if fp is None : fp = self . options . transport . open ( Request ( url ) ) content = fp . read ( ) fp . close ( ) ctx = self . plugins . document . loaded ( url = url , document = content ) content = ctx . document sax = Parser ( ) return sax . parse ( string = content ) | Download the docuemnt . |
13,319 | def open ( self , url ) : protocol , location = self . split ( url ) if protocol == self . protocol : return self . find ( location ) else : return None | Open a document at the specified url . |
13,320 | def add_children ( self , root ) : for c in root . getChildren ( ns = wsdlns ) : child = Factory . create ( c , self ) if child is None : continue self . children . append ( child ) if isinstance ( child , Import ) : self . imports . append ( child ) continue if isinstance ( child , Types ) : self . types . append ( child ) continue if isinstance ( child , Message ) : self . messages [ child . qname ] = child continue if isinstance ( child , PortType ) : self . port_types [ child . qname ] = child continue if isinstance ( child , Binding ) : self . bindings [ child . qname ] = child continue if isinstance ( child , Service ) : self . services . append ( child ) continue | Add child objects using the factory |
13,321 | def load ( self , definitions ) : url = self . location log . debug ( 'importing (%s)' , url ) if '://' not in url : url = urljoin ( definitions . url , url ) options = definitions . options d = Definitions ( url , options ) if d . root . match ( Definitions . Tag , wsdlns ) : self . import_definitions ( definitions , d ) return if d . root . match ( Schema . Tag , Namespace . xsdns ) : self . import_schema ( definitions , d ) return raise Exception ( 'document at "%s" is unknown' % url ) | Load the object by opening the URL |
13,322 | def __getref ( self , a , tns ) : s = self . root . get ( a ) if s is None : return s else : return qualify ( s , self . root , tns ) | Get the qualified value of attribute named a . |
13,323 | def translated ( self , value , type ) : if value is not None : resolved = type . resolve ( ) return resolved . translate ( value ) else : return value | translate using the schema type |
13,324 | def open ( self , options ) : if self . opened : return self . opened = True log . debug ( '%s, importing ns="%s", location="%s"' , self . id , self . ns [ 1 ] , self . location ) result = self . locate ( ) if result is None : if self . location is None : log . debug ( 'imported schema (%s) not-found' , self . ns [ 1 ] ) else : result = self . download ( options ) log . debug ( 'imported:\n%s' , result ) return result | Open and import the refrenced schema . |
13,325 | def open ( self , options ) : if self . opened : return self . opened = True log . debug ( '%s, including location="%s"' , self . id , self . location ) result = self . download ( options ) log . debug ( 'included:\n%s' , result ) return result | Open and include the refrenced schema . |
13,326 | def download ( self , options ) : url = self . location try : if '://' not in url : url = urljoin ( self . schema . baseurl , url ) reader = DocumentReader ( options ) d = reader . open ( url ) root = d . root ( ) root . set ( 'url' , url ) self . __applytns ( root ) return self . schema . instance ( root , url , options ) except TransportError : msg = 'include schema at (%s), failed' % url log . error ( '%s, %s' , self . id , msg , exc_info = True ) raise Exception ( msg ) | download the schema |
13,327 | def build ( cls , root , schema , filter = ( '*' , ) ) : children = [ ] for node in root . getChildren ( ns = Namespace . xsdns ) : if '*' in filter or node . name in filter : child = cls . create ( node , schema ) if child is None : continue children . append ( child ) c = cls . build ( node , schema , child . childtags ( ) ) child . rawchildren = c return children | Build an xsobject representation . |
13,328 | def clone ( self , parent = None ) : a = Attribute ( self . qname ( ) , self . value ) a . parent = parent return a | Clone this object . |
13,329 | def setValue ( self , value ) : if isinstance ( value , Text ) : self . value = value else : self . value = Text ( value ) return self | Set the attributes value |
13,330 | def namespace ( self ) : if self . prefix is None : return Namespace . default else : return self . resolvePrefix ( self . prefix ) | Get the attributes namespace . This may either be the namespace defined by an optional prefix or its parent s namespace . |
13,331 | def resolvePrefix ( self , prefix ) : ns = Namespace . default if self . parent is not None : ns = self . parent . resolvePrefix ( prefix ) return ns | Resolve the specified prefix to a known namespace . |
13,332 | def unmarshaller ( self , typed = True ) : if typed : return UmxEncoded ( self . schema ( ) ) else : return RPC . unmarshaller ( self , typed ) | Get the appropriate XML decoder . |
13,333 | def set_options ( self , ** kwargs ) : p = Unskin ( self . options ) p . update ( kwargs ) | Set options . |
13,334 | def clone ( self ) : class Uninitialized ( Client ) : def __init__ ( self ) : pass clone = Uninitialized ( ) clone . options = Options ( ) cp = Unskin ( clone . options ) mp = Unskin ( self . options ) cp . update ( deepcopy ( mp ) ) clone . wsdl = self . wsdl clone . factory = self . factory clone . service = ServiceSelector ( clone , self . wsdl . services ) clone . sd = self . sd clone . messages = dict ( tx = None , rx = None ) return clone | Get a shallow clone of this object . The clone only shares the WSDL . All other attributes are unique to the cloned object including options . |
13,335 | def __reply ( self , reply , args , kwargs ) : binding = self . method . binding . input msg = binding . get_message ( self . method , args , kwargs ) log . debug ( 'inject (simulated) send message:\n%s' , msg ) binding = self . method . binding . output return self . succeeded ( binding , reply ) | simulate the reply |
13,336 | def tostr ( object , encoding = None ) : if isinstance ( object , basestring ) : if encoding is None : return object else : return object . encode ( encoding ) if isinstance ( object , tuple ) : s = [ '(' ] for item in object : if isinstance ( item , basestring ) : s . append ( item ) else : s . append ( tostr ( item ) ) s . append ( ', ' ) s . append ( ')' ) return '' . join ( s ) if isinstance ( object , list ) : s = [ '[' ] for item in object : if isinstance ( item , basestring ) : s . append ( item ) else : s . append ( tostr ( item ) ) s . append ( ', ' ) s . append ( ']' ) return '' . join ( s ) if isinstance ( object , dict ) : s = [ '{' ] for item in object . items ( ) : if isinstance ( item [ 0 ] , basestring ) : s . append ( item [ 0 ] ) else : s . append ( tostr ( item [ 0 ] ) ) s . append ( ' = ' ) if isinstance ( item [ 1 ] , basestring ) : s . append ( item [ 1 ] ) else : s . append ( tostr ( item [ 1 ] ) ) s . append ( ', ' ) s . append ( '}' ) return '' . join ( s ) try : return unicode ( object ) except : return str ( object ) | get a unicode safe string representation of an object |
13,337 | def load ( self , options ) : if options . autoblend : self . autoblend ( ) for child in self . children : child . build ( ) for child in self . children : child . open_imports ( options ) for child in self . children : child . dereference ( ) log . debug ( 'loaded:\n%s' , self ) merged = self . merge ( ) log . debug ( 'MERGED:\n%s' , merged ) return merged | Load the schema objects for the root nodes . - de - references schemas - merge schemas |
13,338 | def autoblend ( self ) : namespaces = self . namespaces . keys ( ) for s in self . children : for ns in namespaces : tns = s . root . get ( 'targetNamespace' ) if tns == ns : continue for imp in s . root . getChildren ( 'import' ) : if imp . get ( 'namespace' ) == ns : continue imp = Element ( 'import' , ns = Namespace . xsdns ) imp . set ( 'namespace' , ns ) s . root . append ( imp ) return self | Ensure that all schemas within the collection import each other which has a blending effect . |
13,339 | def merge ( self , schema ) : for item in schema . attributes . items ( ) : if item [ 0 ] in self . attributes : continue self . all . append ( item [ 1 ] ) self . attributes [ item [ 0 ] ] = item [ 1 ] for item in schema . elements . items ( ) : if item [ 0 ] in self . elements : continue self . all . append ( item [ 1 ] ) self . elements [ item [ 0 ] ] = item [ 1 ] for item in schema . types . items ( ) : if item [ 0 ] in self . types : continue self . all . append ( item [ 1 ] ) self . types [ item [ 0 ] ] = item [ 1 ] for item in schema . groups . items ( ) : if item [ 0 ] in self . groups : continue self . all . append ( item [ 1 ] ) self . groups [ item [ 0 ] ] = item [ 1 ] for item in schema . agrps . items ( ) : if item [ 0 ] in self . agrps : continue self . all . append ( item [ 1 ] ) self . agrps [ item [ 0 ] ] = item [ 1 ] schema . merged = True return self | Merge the contents from the schema . Only objects not already contained in this schema s collections are merged . This is to provide for bidirectional import which produce cyclic includes . |
13,340 | def leaf ( self , parent , parts ) : name = splitPrefix ( parts [ - 1 ] ) [ 1 ] if name . startswith ( '@' ) : result , path = parent . get_attribute ( name [ 1 : ] ) else : result , ancestry = parent . get_child ( name ) if result is None : raise PathResolver . BadPath ( name ) return result | Find the leaf . |
13,341 | def findattr ( self , name , resolved = True ) : name = '@%s' % name parent = self . top ( ) . resolved if parent is None : result , ancestry = self . query ( name , node ) else : result , ancestry = self . getchild ( name , parent ) if result is None : return result if resolved : result = result . resolve ( ) return result | Find an attribute type definition . |
13,342 | def known ( self , node ) : ref = node . get ( 'type' , Namespace . xsins ) if ref is None : return None qref = qualify ( ref , node , node . namespace ( ) ) query = BlindQuery ( qref ) return query . execute ( self . schema ) | resolve type referenced by |
13,343 | def known ( self , object ) : try : md = object . __metadata__ known = md . sxtype return known except : pass | get the type specified in the object s metadata |
13,344 | def pushprefixes ( self ) : for ns in self . prefixes : self . wsdl . root . addPrefix ( ns [ 0 ] , ns [ 1 ] ) | Add our prefixes to the wsdl so that when users invoke methods and reference the prefixes the will resolve properly . |
13,345 | def findport ( self , port ) : for p in self . ports : if p [ 0 ] == p : return p p = ( port , [ ] ) self . ports . append ( p ) return p | Find and return a port tuple for the specified port . Created and added when not found . |
13,346 | def paramtypes ( self ) : for m in [ p [ 1 ] for p in self . ports ] : for p in [ p [ 1 ] for p in m ] : for pd in p : if pd [ 1 ] in self . params : continue item = ( pd [ 1 ] , pd [ 1 ] . resolve ( ) ) self . params . append ( item ) | get all parameter types |
13,347 | def u2handlers ( self ) : handlers = [ ] handlers . append ( u2 . ProxyHandler ( self . proxy ) ) return handlers | Get a collection of urllib handlers . |
13,348 | def setPrefix ( self , p , u = None ) : self . prefix = p if p is not None and u is not None : self . addPrefix ( p , u ) return self | Set the element namespace prefix . |
13,349 | def detach ( self ) : if self . parent is not None : if self in self . parent . children : self . parent . children . remove ( self ) self . parent = None return self | Detach from parent . |
13,350 | def set ( self , name , value ) : attr = self . getAttribute ( name ) if attr is None : attr = Attribute ( name , value ) self . append ( attr ) else : attr . setValue ( value ) | Set an attribute s value . |
13,351 | def trim ( self ) : if self . hasText ( ) : self . text = self . text . trim ( ) return self | Trim leading and trailing whitespace . |
13,352 | def remove ( self , child ) : if isinstance ( child , Element ) : return child . detach ( ) if isinstance ( child , Attribute ) : self . attributes . remove ( child ) return None | Remove the specified child element or attribute . |
13,353 | def detachChildren ( self ) : detached = self . children self . children = [ ] for child in detached : child . parent = None return detached | Detach and return this element s children . |
13,354 | def clearPrefix ( self , prefix ) : if prefix in self . nsprefixes : del self . nsprefixes [ prefix ] return self | Clear the specified prefix from the prefix mappings . |
13,355 | def findPrefix ( self , uri , default = None ) : for item in self . nsprefixes . items ( ) : if item [ 1 ] == uri : prefix = item [ 0 ] return prefix for item in self . specialprefixes . items ( ) : if item [ 1 ] == uri : prefix = item [ 0 ] return prefix if self . parent is not None : return self . parent . findPrefix ( uri , default ) else : return default | Find the first prefix that has been mapped to a namespace URI . The local mapping is searched then it walks up the tree until it reaches the top or finds a match . |
13,356 | def findPrefixes ( self , uri , match = 'eq' ) : result = [ ] for item in self . nsprefixes . items ( ) : if self . matcher [ match ] ( item [ 1 ] , uri ) : prefix = item [ 0 ] result . append ( prefix ) for item in self . specialprefixes . items ( ) : if self . matcher [ match ] ( item [ 1 ] , uri ) : prefix = item [ 0 ] result . append ( prefix ) if self . parent is not None : result += self . parent . findPrefixes ( uri , match ) return result | Find all prefixes that has been mapped to a namespace URI . The local mapping is searched then it walks up the tree until it reaches the top collecting all matches . |
13,357 | def promotePrefixes ( self ) : for c in self . children : c . promotePrefixes ( ) if self . parent is None : return _pref = [ ] for p , u in self . nsprefixes . items ( ) : if p in self . parent . nsprefixes : pu = self . parent . nsprefixes [ p ] if pu == u : _pref . append ( p ) continue if p != self . parent . prefix : self . parent . nsprefixes [ p ] = u _pref . append ( p ) for x in _pref : del self . nsprefixes [ x ] return self | Push prefix declarations up the tree as far as possible . Prefix mapping are pushed to its parent unless the parent has the prefix mapped to another URI or the parent has the prefix . This is propagated up the tree until the top is reached . |
13,358 | def refitPrefixes ( self ) : for c in self . children : c . refitPrefixes ( ) if self . prefix is not None : ns = self . resolvePrefix ( self . prefix ) if ns [ 1 ] is not None : self . expns = ns [ 1 ] self . prefix = None self . nsprefixes = { } return self | Refit namespace qualification by replacing prefixes with explicit namespaces . Also purges prefix mapping table . |
13,359 | def branch ( self ) : branch = [ self ] for c in self . children : branch += c . branch ( ) return branch | Get a flattened representation of the branch . |
13,360 | def ancestors ( self ) : ancestors = [ ] p = self . parent while p is not None : ancestors . append ( p ) p = p . parent return ancestors | Get a list of ancestors . |
13,361 | def walk ( self , visitor ) : visitor ( self ) for c in self . children : c . walk ( visitor ) return self | Walk the branch and call the visitor function on each node . |
13,362 | def prune ( self ) : pruned = [ ] for c in self . children : c . prune ( ) if c . isempty ( False ) : pruned . append ( c ) for p in pruned : self . children . remove ( p ) | Prune the branch of empty nodes . |
13,363 | def next ( self ) : try : child = self . children [ self . pos ] self . pos += 1 return child except : raise StopIteration ( ) | Get the next child . |
13,364 | def pset ( self , n ) : s = set ( ) for ns in n . nsprefixes . items ( ) : if self . permit ( ns ) : s . add ( ns [ 1 ] ) return s | Convert the nodes nsprefixes into a set . |
13,365 | def tostr ( self , object , indent = - 2 ) : history = [ ] return self . process ( object , history , indent ) | get s string representation of object |
13,366 | def attributes ( self , filter = Filter ( ) ) : result = [ ] for child , ancestry in self : if child . isattr ( ) and child in filter : result . append ( ( child , ancestry ) ) return result | Get only the attribute content . |
13,367 | def namespace ( self , prefix = None ) : ns = self . schema . tns if ns [ 0 ] is None : ns = ( prefix , ns [ 1 ] ) return ns | Get this properties namespace |
13,368 | def find ( self , qref , classes = ( ) ) : if not len ( classes ) : classes = ( self . __class__ , ) if self . qname == qref and self . __class__ in classes : return self for c in self . rawchildren : p = c . find ( qref , classes ) if p is not None : return p return None | Find a referenced type in self or children . |
13,369 | def merge ( self , other ) : other . qualify ( ) for n in ( 'name' , 'qname' , 'min' , 'max' , 'default' , 'type' , 'nillable' , 'form_qualified' , ) : if getattr ( self , n ) is not None : continue v = getattr ( other , n ) if v is None : continue setattr ( self , n , v ) | Merge another object as needed . |
13,370 | def str ( self , indent = 0 , history = None ) : if history is None : history = [ ] if self in history : return '%s ...' % Repr ( self ) history . append ( self ) tab = '%*s' % ( indent * 3 , '' ) result = [ ] result . append ( '%s<%s' % ( tab , self . id ) ) for n in self . description ( ) : if not hasattr ( self , n ) : continue v = getattr ( self , n ) if v is None : continue result . append ( ' %s="%s"' % ( n , v ) ) if len ( self ) : result . append ( '>' ) for c in self . rawchildren : result . append ( '\n' ) result . append ( c . str ( indent + 1 , history [ : ] ) ) if c . isattr ( ) : result . append ( '@' ) result . append ( '\n%s' % tab ) result . append ( '</%s>' % self . __class__ . __name__ ) else : result . append ( ' />' ) return '' . join ( result ) | Get a string representation of this object . |
13,371 | def find ( self , node , list ) : if self . matcher . match ( node ) : list . append ( node ) self . limit -= 1 if self . limit == 0 : return for c in node . rawchildren : self . find ( c , list ) return self | Traverse the tree looking for matches . |
13,372 | def setduration ( self , ** duration ) : if len ( duration ) == 1 : arg = [ x [ 0 ] for x in duration . items ( ) ] if not arg [ 0 ] in self . units : raise Exception ( 'must be: %s' % str ( self . units ) ) self . duration = arg return self | Set the caching duration which defines how long the file will be cached . |
13,373 | def sort ( self , content ) : v = content . value if isinstance ( v , Object ) : md = v . __metadata__ md . ordering = self . ordering ( content . real ) return self | Sort suds object attributes based on ordering defined in the XSD type information . |
13,374 | def ordering ( self , type ) : result = [ ] for child , ancestry in type . resolve ( ) : name = child . name if child . name is None : continue if child . isattr ( ) : name = '_%s' % child . name result . append ( name ) return result | Get the attribute ordering defined in the specified XSD type information . |
13,375 | def build ( self , name ) : "build an object for the specified typename as defined in the schema" if isinstance ( name , basestring ) : type = self . resolver . find ( name ) if type is None : raise TypeNotFound ( name ) else : type = name cls = type . name if type . mixed ( ) : data = Factory . property ( cls ) else : data = Factory . object ( cls ) resolved = type . resolve ( ) md = data . __metadata__ md . sxtype = resolved md . ordering = self . ordering ( resolved ) history = [ ] self . add_attributes ( data , resolved ) for child , ancestry in type . children ( ) : if self . skip_child ( child , ancestry ) : continue self . process ( data , child , history [ : ] ) return data | build an object for the specified typename as defined in the schema |
13,376 | def add_attributes ( self , data , type ) : for attr , ancestry in type . attributes ( ) : name = '_%s' % attr . name value = attr . get_default ( ) setattr ( data , name , value ) | add required attributes |
13,377 | def validate ( self , pA , pB ) : if pA in pB . links or pB in pA . links : raise Exception ( 'Already linked' ) dA = pA . domains ( ) dB = pB . domains ( ) for d in dA : if d in dB : raise Exception ( 'Duplicate domain "%s" found' % d ) for d in dB : if d in dA : raise Exception ( 'Duplicate domain "%s" found' % d ) kA = pA . keys ( ) kB = pB . keys ( ) for k in kA : if k in kB : raise Exception ( 'Duplicate key %s found' % k ) for k in kB : if k in kA : raise Exception ( 'Duplicate key %s found' % k ) return self | Validate that the two properties may be linked . |
13,378 | def prime ( self ) : for d in self . definitions . values ( ) : self . defined [ d . name ] = d . default return self | Prime the stored values based on default values found in property definitions . |
13,379 | def list_scanners ( zap_helper , scanners ) : scanner_list = zap_helper . zap . ascan . scanners ( ) if scanners is not None and 'all' not in scanners : scanner_list = filter_by_ids ( scanner_list , scanners ) click . echo ( tabulate ( [ [ s [ 'id' ] , s [ 'name' ] , s [ 'policyId' ] , s [ 'enabled' ] , s [ 'attackStrength' ] , s [ 'alertThreshold' ] ] for s in scanner_list ] , headers = [ 'ID' , 'Name' , 'Policy ID' , 'Enabled' , 'Strength' , 'Threshold' ] , tablefmt = 'grid' ) ) | Get a list of scanners and whether or not they are enabled . |
13,380 | def set_scanner_strength ( zap_helper , scanners , strength ) : if not scanners or 'all' in scanners : scanners = _get_all_scanner_ids ( zap_helper ) with zap_error_handler ( ) : zap_helper . set_scanner_attack_strength ( scanners , strength ) console . info ( 'Set attack strength to {0}.' . format ( strength ) ) | Set the attack strength for scanners . |
13,381 | def set_scanner_threshold ( zap_helper , scanners , threshold ) : if not scanners or 'all' in scanners : scanners = _get_all_scanner_ids ( zap_helper ) with zap_error_handler ( ) : zap_helper . set_scanner_alert_threshold ( scanners , threshold ) console . info ( 'Set alert threshold to {0}.' . format ( threshold ) ) | Set the alert threshold for scanners . |
13,382 | def _get_all_scanner_ids ( zap_helper ) : scanners = zap_helper . zap . ascan . scanners ( ) return [ s [ 'id' ] for s in scanners ] | Get all scanner IDs . |
13,383 | def list_policies ( zap_helper , policy_ids ) : policies = filter_by_ids ( zap_helper . zap . ascan . policies ( ) , policy_ids ) click . echo ( tabulate ( [ [ p [ 'id' ] , p [ 'name' ] , p [ 'enabled' ] , p [ 'attackStrength' ] , p [ 'alertThreshold' ] ] for p in policies ] , headers = [ 'ID' , 'Name' , 'Enabled' , 'Strength' , 'Threshold' ] , tablefmt = 'grid' ) ) | Get a list of policies and whether or not they are enabled . |
13,384 | def enable_policies ( zap_helper , policy_ids ) : if not policy_ids : policy_ids = _get_all_policy_ids ( zap_helper ) with zap_error_handler ( ) : zap_helper . enable_policies_by_ids ( policy_ids ) | Set the enabled policies to use in a scan . |
13,385 | def set_policy_strength ( zap_helper , policy_ids , strength ) : if not policy_ids : policy_ids = _get_all_policy_ids ( zap_helper ) with zap_error_handler ( ) : zap_helper . set_policy_attack_strength ( policy_ids , strength ) console . info ( 'Set attack strength to {0}.' . format ( strength ) ) | Set the attack strength for policies . |
13,386 | def set_policy_threshold ( zap_helper , policy_ids , threshold ) : if not policy_ids : policy_ids = _get_all_policy_ids ( zap_helper ) with zap_error_handler ( ) : zap_helper . set_policy_alert_threshold ( policy_ids , threshold ) console . info ( 'Set alert threshold to {0}.' . format ( threshold ) ) | Set the alert threshold for policies . |
13,387 | def _get_all_policy_ids ( zap_helper ) : policies = zap_helper . zap . ascan . policies ( ) return [ p [ 'id' ] for p in policies ] | Get all policy IDs . |
13,388 | def start ( self , options = None ) : if self . is_running ( ) : self . logger . warn ( 'ZAP is already running on port {0}' . format ( self . port ) ) return if platform . system ( ) == 'Windows' or platform . system ( ) . startswith ( 'CYGWIN' ) : executable = 'zap.bat' else : executable = 'zap.sh' executable_path = os . path . join ( self . zap_path , executable ) if not os . path . isfile ( executable_path ) : raise ZAPError ( ( 'ZAP was not found in the path "{0}". You can set the path to where ZAP is ' + 'installed on your system using the --zap-path command line parameter or by ' + 'default using the ZAP_PATH environment variable.' ) . format ( self . zap_path ) ) zap_command = [ executable_path , '-daemon' , '-port' , str ( self . port ) ] if options : extra_options = shlex . split ( options ) zap_command += extra_options if self . log_path is None : log_path = os . path . join ( self . zap_path , 'zap.log' ) else : log_path = os . path . join ( self . log_path , 'zap.log' ) self . logger . debug ( 'Starting ZAP process with command: {0}.' . format ( ' ' . join ( zap_command ) ) ) self . logger . debug ( 'Logging to {0}' . format ( log_path ) ) with open ( log_path , 'w+' ) as log_file : subprocess . Popen ( zap_command , cwd = self . zap_path , stdout = log_file , stderr = subprocess . STDOUT ) self . wait_for_zap ( self . timeout ) self . logger . debug ( 'ZAP started successfully.' ) | Start the ZAP Daemon . |
13,389 | def shutdown ( self ) : if not self . is_running ( ) : self . logger . warn ( 'ZAP is not running.' ) return self . logger . debug ( 'Shutting down ZAP.' ) self . zap . core . shutdown ( ) timeout_time = time . time ( ) + self . timeout while self . is_running ( ) : if time . time ( ) > timeout_time : raise ZAPError ( 'Timed out waiting for ZAP to shutdown.' ) time . sleep ( 2 ) self . logger . debug ( 'ZAP shutdown successfully.' ) | Shutdown ZAP . |
13,390 | def wait_for_zap ( self , timeout ) : timeout_time = time . time ( ) + timeout while not self . is_running ( ) : if time . time ( ) > timeout_time : raise ZAPError ( 'Timed out waiting for ZAP to start.' ) time . sleep ( 2 ) | Wait for ZAP to be ready to receive API calls . |
13,391 | def is_running ( self ) : try : result = requests . get ( self . proxy_url ) except RequestException : return False if 'ZAP-Header' in result . headers . get ( 'Access-Control-Allow-Headers' , [ ] ) : return True raise ZAPError ( 'Another process is listening on {0}' . format ( self . proxy_url ) ) | Check if ZAP is running . |
13,392 | def open_url ( self , url , sleep_after_open = 2 ) : self . zap . urlopen ( url ) time . sleep ( sleep_after_open ) | Access a URL through ZAP . |
13,393 | def run_spider ( self , target_url , context_name = None , user_name = None ) : self . logger . debug ( 'Spidering target {0}...' . format ( target_url ) ) context_id , user_id = self . _get_context_and_user_ids ( context_name , user_name ) if user_id : self . logger . debug ( 'Running spider in context {0} as user {1}' . format ( context_id , user_id ) ) scan_id = self . zap . spider . scan_as_user ( context_id , user_id , target_url ) else : scan_id = self . zap . spider . scan ( target_url ) if not scan_id : raise ZAPError ( 'Error running spider.' ) elif not scan_id . isdigit ( ) : raise ZAPError ( 'Error running spider: "{0}"' . format ( scan_id ) ) self . logger . debug ( 'Started spider with ID {0}...' . format ( scan_id ) ) while int ( self . zap . spider . status ( ) ) < 100 : self . logger . debug ( 'Spider progress %: {0}' . format ( self . zap . spider . status ( ) ) ) time . sleep ( self . _status_check_sleep ) self . logger . debug ( 'Spider #{0} completed' . format ( scan_id ) ) | Run spider against a URL . |
13,394 | def run_active_scan ( self , target_url , recursive = False , context_name = None , user_name = None ) : self . logger . debug ( 'Scanning target {0}...' . format ( target_url ) ) context_id , user_id = self . _get_context_and_user_ids ( context_name , user_name ) if user_id : self . logger . debug ( 'Scanning in context {0} as user {1}' . format ( context_id , user_id ) ) scan_id = self . zap . ascan . scan_as_user ( target_url , context_id , user_id , recursive ) else : scan_id = self . zap . ascan . scan ( target_url , recurse = recursive ) if not scan_id : raise ZAPError ( 'Error running active scan.' ) elif not scan_id . isdigit ( ) : raise ZAPError ( ( 'Error running active scan: "{0}". Make sure the URL is in the site ' + 'tree by using the open-url or scanner commands before running an active ' + 'scan.' ) . format ( scan_id ) ) self . logger . debug ( 'Started scan with ID {0}...' . format ( scan_id ) ) while int ( self . zap . ascan . status ( ) ) < 100 : self . logger . debug ( 'Scan progress %: {0}' . format ( self . zap . ascan . status ( ) ) ) time . sleep ( self . _status_check_sleep ) self . logger . debug ( 'Scan #{0} completed' . format ( scan_id ) ) | Run an active scan against a URL . |
13,395 | def run_ajax_spider ( self , target_url ) : self . logger . debug ( 'AJAX Spidering target {0}...' . format ( target_url ) ) self . zap . ajaxSpider . scan ( target_url ) while self . zap . ajaxSpider . status == 'running' : self . logger . debug ( 'AJAX Spider: {0}' . format ( self . zap . ajaxSpider . status ) ) time . sleep ( self . _status_check_sleep ) self . logger . debug ( 'AJAX Spider completed' ) | Run AJAX Spider against a URL . |
13,396 | def alerts ( self , alert_level = 'High' ) : alerts = self . zap . core . alerts ( ) alert_level_value = self . alert_levels [ alert_level ] alerts = sorted ( ( a for a in alerts if self . alert_levels [ a [ 'risk' ] ] >= alert_level_value ) , key = lambda k : self . alert_levels [ k [ 'risk' ] ] , reverse = True ) return alerts | Get a filtered list of alerts at the given alert level and sorted by alert level . |
13,397 | def enabled_scanner_ids ( self ) : enabled_scanners = [ ] scanners = self . zap . ascan . scanners ( ) for scanner in scanners : if scanner [ 'enabled' ] == 'true' : enabled_scanners . append ( scanner [ 'id' ] ) return enabled_scanners | Retrieves a list of currently enabled scanners . |
13,398 | def enable_scanners_by_ids ( self , scanner_ids ) : scanner_ids = ',' . join ( scanner_ids ) self . logger . debug ( 'Enabling scanners with IDs {0}' . format ( scanner_ids ) ) return self . zap . ascan . enable_scanners ( scanner_ids ) | Enable a list of scanner IDs . |
13,399 | def disable_scanners_by_ids ( self , scanner_ids ) : scanner_ids = ',' . join ( scanner_ids ) self . logger . debug ( 'Disabling scanners with IDs {0}' . format ( scanner_ids ) ) return self . zap . ascan . disable_scanners ( scanner_ids ) | Disable a list of scanner IDs . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.