idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
236,700
def get_most_complete_pm ( pms ) : if not pms : return None selected_version = None selected_presence = None for pm in pms : if pm . version : if not selected_version : selected_version = pm else : if len ( pm . version ) > len ( selected_version . version ) : selected_version = pm elif pm . presence : selected_presenc...
Return plugin match with longer version if not available will return plugin match with presence = True
236,701
def docker_container ( ) : if SETUP_SPLASH : dm = DockerManager ( ) dm . start_container ( ) try : requests . post ( f'{SPLASH_URL}/_gc' ) except requests . exceptions . RequestException : pass yield
Start the Splash server on a Docker container . If the container doesn t exist it is created and named splash - detectem .
236,702
def is_url_allowed ( url ) : blacklist = [ r'\.ttf' , r'\.woff' , r'fonts\.googleapis\.com' , r'\.png' , r'\.jpe?g' , r'\.gif' , r'\.svg' ] for ft in blacklist : if re . search ( ft , url ) : return False return True
Return True if url is not in blacklist .
236,703
def is_valid_mimetype ( response ) : blacklist = [ 'image/' , ] mimetype = response . get ( 'mimeType' ) if not mimetype : return True for bw in blacklist : if bw in mimetype : return False return True
Return True if the mimetype is not blacklisted .
236,704
def get_charset ( response ) : charset = DEFAULT_CHARSET m = re . findall ( r';charset=(.*)' , response . get ( 'mimeType' , '' ) ) if m : charset = m [ 0 ] return charset
Return charset from response or default charset .
236,705
def create_lua_script ( plugins ) : lua_template = pkg_resources . resource_string ( 'detectem' , 'script.lua' ) template = Template ( lua_template . decode ( 'utf-8' ) ) javascript_data = to_javascript_data ( plugins ) return template . substitute ( js_data = json . dumps ( javascript_data ) )
Return script template filled up with plugin javascript data .
236,706
def to_javascript_data ( plugins ) : def escape ( v ) : return re . sub ( r'"' , r'\\"' , v ) def dom_matchers ( p ) : dom_matchers = p . get_matchers ( 'dom' ) escaped_dom_matchers = [ ] for dm in dom_matchers : check_statement , version_statement = dm escaped_dom_matchers . append ( { 'check_statement' : escape ( che...
Return a dictionary with all JavaScript matchers . Quotes are escaped .
236,707
def get_response ( url , plugins , timeout = SPLASH_TIMEOUT ) : lua_script = create_lua_script ( plugins ) lua = urllib . parse . quote_plus ( lua_script ) page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}' try : with docker_container ( ) : logger . debug ( '[+] Sending request to Splash in...
Return response with HAR inline scritps and software detected by JS matchers .
236,708
def get_valid_har ( har_data ) : new_entries = [ ] entries = har_data . get ( 'log' , { } ) . get ( 'entries' , [ ] ) logger . debug ( '[+] Detected %(n)d entries in HAR' , { 'n' : len ( entries ) } ) for entry in entries : url = entry [ 'request' ] [ 'url' ] if not is_url_allowed ( url ) : continue response = entry [ ...
Return list of valid HAR entries .
236,709
def _script_to_har_entry ( cls , script , url ) : entry = { 'request' : { 'url' : url } , 'response' : { 'url' : url , 'content' : { 'text' : script } } } cls . _set_entry_type ( entry , INLINE_SCRIPT_ENTRY ) return entry
Return entry for embed script
236,710
def mark_entries ( self , entries ) : for entry in entries : self . _set_entry_type ( entry , RESOURCE_ENTRY ) main_entry = entries [ 0 ] main_location = self . _get_location ( main_entry ) if not main_location : self . _set_entry_type ( main_entry , MAIN_ENTRY ) return main_url = urllib . parse . urljoin ( get_url ( m...
Mark one entry as main entry and the rest as resource entry .
236,711
def get_hints ( self , plugin ) : hints = [ ] for hint_name in getattr ( plugin , 'hints' , [ ] ) : hint_plugin = self . _plugins . get ( hint_name ) if hint_plugin : hint_result = Result ( name = hint_plugin . name , homepage = hint_plugin . homepage , from_url = self . requested_url , type = HINT_TYPE , plugin = plug...
Return plugin hints from plugin .
236,712
def process_from_splash ( self ) : for software in self . _softwares_from_splash : plugin = self . _plugins . get ( software [ 'name' ] ) try : additional_data = { 'version' : software [ 'version' ] } except KeyError : additional_data = { 'type' : INDICATOR_TYPE } self . _results . add_result ( Result ( name = plugin ....
Add softwares found in the DOM
236,713
def process_har ( self ) : hints = [ ] version_plugins = self . _plugins . with_version_matchers ( ) generic_plugins = self . _plugins . with_generic_matchers ( ) for entry in self . har : for plugin in version_plugins : pm = self . apply_plugin_matchers ( plugin , entry ) if not pm : continue if pm . name : name = '{}...
Detect plugins present in the page .
236,714
def get_results ( self , metadata = False ) : results_data = [ ] self . process_har ( ) self . process_from_splash ( ) for rt in sorted ( self . _results . get_results ( ) ) : rdict = { 'name' : rt . name } if rt . version : rdict [ 'version' ] = rt . version if metadata : rdict [ 'homepage' ] = rt . homepage rdict [ '...
Return results of the analysis .
236,715
def load_plugins ( ) : loader = _PluginLoader ( ) for pkg in PLUGIN_PACKAGES : loader . load_plugins ( pkg ) return loader . plugins
Return the list of plugin instances .
236,716
def _get_plugin_module_paths ( self , plugin_dir ) : filepaths = [ fp for fp in glob . glob ( '{}/**/*.py' . format ( plugin_dir ) , recursive = True ) if not fp . endswith ( '__init__.py' ) ] rel_paths = [ re . sub ( plugin_dir . rstrip ( '/' ) + '/' , '' , fp ) for fp in filepaths ] module_paths = [ rp . replace ( '/...
Return a list of every module in plugin_dir .
236,717
def load_plugins ( self , plugins_package ) : try : plugin_dir = find_spec ( plugins_package ) . submodule_search_locations [ 0 ] except ImportError : logger . error ( "Could not load plugins package '%(pkg)s'" , { 'pkg' : plugins_package } ) return for module_path in self . _get_plugin_module_paths ( plugin_dir ) : sp...
Load plugins from plugins_package module .
236,718
def extract_named_group ( text , named_group , matchers , return_presence = False ) : presence = False for matcher in matchers : if isinstance ( matcher , str ) : v = re . search ( matcher , text , flags = re . DOTALL ) if v : dict_result = v . groupdict ( ) try : return dict_result [ named_group ] except KeyError : if...
Return named_group match from text reached by using a matcher from matchers .
236,719
def parsed ( self ) : return BeautifulSoup ( self . response . content , features = self . browser . parser , )
Lazily parse response content using HTML parser specified by the browser .
236,720
def _build_send_args ( self , ** kwargs ) : out = { } out . update ( self . _default_send_args ) out . update ( kwargs ) return out
Merge optional arguments with defaults .
236,721
def open ( self , url , method = 'get' , ** kwargs ) : response = self . session . request ( method , url , ** self . _build_send_args ( ** kwargs ) ) self . _update_state ( response )
Open a URL .
236,722
def _update_state ( self , response ) : self . _states = self . _states [ : self . _cursor + 1 ] state = RoboState ( self , response ) self . _states . append ( state ) self . _cursor += 1 if self . _maxlen : decrement = len ( self . _states ) - self . _maxlen if decrement > 0 : self . _states = self . _states [ decrem...
Update the state of the browser . Create a new state object and append to or overwrite the browser s state history .
236,723
def _traverse ( self , n = 1 ) : if not self . history : raise exceptions . RoboError ( 'Not tracking history' ) cursor = self . _cursor + n if cursor >= len ( self . _states ) or cursor < 0 : raise exceptions . RoboError ( 'Index out of range' ) self . _cursor = cursor
Traverse state history . Used by back and forward methods .
236,724
def get_link ( self , text = None , * args , ** kwargs ) : return helpers . find ( self . parsed , _link_ptn , text = text , * args , ** kwargs )
Find an anchor or button by containing text as well as standard BeautifulSoup arguments .
236,725
def get_links ( self , text = None , * args , ** kwargs ) : return helpers . find_all ( self . parsed , _link_ptn , text = text , * args , ** kwargs )
Find anchors or buttons by containing text as well as standard BeautifulSoup arguments .
236,726
def get_form ( self , id = None , * args , ** kwargs ) : if id : kwargs [ 'id' ] = id form = self . find ( _form_ptn , * args , ** kwargs ) if form is not None : return Form ( form )
Find form by ID as well as standard BeautifulSoup arguments .
236,727
def follow_link ( self , link , ** kwargs ) : try : href = link [ 'href' ] except KeyError : raise exceptions . RoboError ( 'Link element must have "href" ' 'attribute' ) self . open ( self . _build_url ( href ) , ** kwargs )
Click a link .
236,728
def submit_form ( self , form , submit = None , ** kwargs ) : method = form . method . upper ( ) url = self . _build_url ( form . action ) or self . url payload = form . serialize ( submit = submit ) serialized = payload . to_requests ( method ) send_args = self . _build_send_args ( ** kwargs ) send_args . update ( ser...
Submit a form .
236,729
def find ( soup , name = None , attrs = None , recursive = True , text = None , ** kwargs ) : tags = find_all ( soup , name , attrs or { } , recursive , text , 1 , ** kwargs ) if tags : return tags [ 0 ]
Modified find method ; see find_all above .
236,730
def _set_initial ( self , initial ) : super ( Select , self ) . _set_initial ( initial ) if not self . _value and self . options : self . value = self . options [ 0 ]
If no option is selected initially select the first option .
236,731
def encode_if_py2 ( func ) : if not PY2 : return func def wrapped ( * args , ** kwargs ) : ret = func ( * args , ** kwargs ) if not isinstance ( ret , unicode ) : raise TypeError ( 'Wrapped function must return `unicode`' ) return ret . encode ( 'utf-8' , 'ignore' ) return wrapped
If Python 2 . x return decorated function encoding unicode return value to UTF - 8 ; else noop .
236,732
def _reduce_age ( self , now ) : if self . max_age : keys = [ key for key , value in iteritems ( self . data ) if now - value [ 'date' ] > self . max_age ] for key in keys : del self . data [ key ]
Reduce size of cache by date .
236,733
def _reduce_count ( self ) : if self . max_count : while len ( self . data ) > self . max_count : self . data . popitem ( last = False )
Reduce size of cache by count .
236,734
def store ( self , response ) : if response . status_code not in CACHE_CODES : return now = datetime . datetime . now ( ) self . data [ response . url ] = { 'date' : now , 'response' : response , } logger . info ( 'Stored response in cache' ) self . _reduce_age ( now ) self . _reduce_count ( )
Store response in cache skipping if code is forbidden .
236,735
def retrieve ( self , request ) : if request . method not in CACHE_VERBS : return try : response = self . data [ request . url ] [ 'response' ] logger . info ( 'Retrieved response from cache' ) return response except KeyError : return None
Look up request in cache skipping if verb is forbidden .
236,736
def _group_flat_tags ( tag , tags ) : grouped = [ tag ] name = tag . get ( 'name' , '' ) . lower ( ) while tags and tags [ 0 ] . get ( 'name' , '' ) . lower ( ) == name : grouped . append ( tags . pop ( 0 ) ) return grouped
Extract tags sharing the same name as the provided tag . Used to collect options for radio and checkbox inputs .
236,737
def _parse_fields ( parsed ) : out = [ ] tags = parsed . find_all ( _tag_ptn ) for tag in tags : helpers . lowercase_attr_names ( tag ) while tags : tag = tags . pop ( 0 ) try : field = _parse_field ( tag , tags ) except exceptions . InvalidNameError : continue if field is not None : out . append ( field ) return out
Parse form fields from HTML .
236,738
def add ( self , data , key = None ) : sink = self . options [ key ] if key is not None else self . data for key , value in iteritems ( data ) : sink . add ( key , value )
Add field values to container .
236,739
def to_requests ( self , method = 'get' ) : out = { } data_key = 'params' if method . lower ( ) == 'get' else 'data' out [ data_key ] = self . data out . update ( self . options ) return dict ( [ ( key , list ( value . items ( multi = True ) ) ) for key , value in iteritems ( out ) ] )
Export to Requests format .
236,740
def add_field ( self , field ) : if not isinstance ( field , fields . BaseField ) : raise ValueError ( 'Argument "field" must be an instance of ' 'BaseField' ) self . fields . add ( field . name , field )
Add a field .
236,741
def serialize ( self , submit = None ) : include_fields = prepare_fields ( self . fields , self . submit_fields , submit ) return Payload . from_fields ( include_fields )
Serialize each form field to a Payload container .
236,742
async def save ( self , db ) : kwargs = { } for col in self . _auto_columns : if not self . has_real_data ( col . name ) : kwargs [ col . name ] = await col . auto_generate ( db , self ) self . __dict__ . update ( kwargs ) stale_object = await self . __class__ . load ( db , identifier = self . identifier ( ) ) d = { k ...
Save the object to Redis .
236,743
def check_address ( address ) : if isinstance ( address , tuple ) : check_host ( address [ 0 ] ) check_port ( address [ 1 ] ) elif isinstance ( address , string_types ) : if os . name != 'posix' : raise ValueError ( 'Platform does not support UNIX domain sockets' ) if not ( os . path . exists ( address ) or os . access...
Check if the format of the address is correct
236,744
def check_addresses ( address_list , is_remote = False ) : assert all ( isinstance ( x , ( tuple , string_types ) ) for x in address_list ) if ( is_remote and any ( isinstance ( x , string_types ) for x in address_list ) ) : raise AssertionError ( 'UNIX domain sockets not allowed for remote' 'addresses' ) for address i...
Check if the format of the addresses is correct
236,745
def create_logger ( logger = None , loglevel = None , capture_warnings = True , add_paramiko_handler = True ) : logger = logger or logging . getLogger ( '{0}.SSHTunnelForwarder' . format ( __name__ ) ) if not any ( isinstance ( x , logging . Handler ) for x in logger . handlers ) : logger . setLevel ( loglevel or DEFAU...
Attach or create a new logger and add a console handler if not present
236,746
def _add_handler ( logger , handler = None , loglevel = None ) : handler . setLevel ( loglevel or DEFAULT_LOGLEVEL ) if handler . level <= logging . DEBUG : _fmt = '%(asctime)s| %(levelname)-4.3s|%(threadName)10.9s/' '%(lineno)04d@%(module)-10.9s| %(message)s' handler . setFormatter ( logging . Formatter ( _fmt ) ) els...
Add a handler to an existing logging . Logger object
236,747
def _check_paramiko_handlers ( logger = None ) : paramiko_logger = logging . getLogger ( 'paramiko.transport' ) if not paramiko_logger . handlers : if logger : paramiko_logger . handlers = logger . handlers else : console_handler = logging . StreamHandler ( ) console_handler . setFormatter ( logging . Formatter ( '%(as...
Add a console handler for paramiko . transport s logger if not present
236,748
def _remove_none_values ( dictionary ) : return list ( map ( dictionary . pop , [ i for i in dictionary if dictionary [ i ] is None ] ) )
Remove dictionary keys whose value is None
236,749
def _cli_main ( args = None ) : arguments = _parse_arguments ( args ) _remove_none_values ( arguments ) verbosity = min ( arguments . pop ( 'verbose' ) , 4 ) levels = [ logging . ERROR , logging . WARNING , logging . INFO , logging . DEBUG , TRACE_LEVEL ] arguments . setdefault ( 'debug_level' , levels [ verbosity ] ) ...
Pass input arguments to open_tunnel
236,750
def _make_ssh_forward_handler_class ( self , remote_address_ ) : class Handler ( _ForwardHandler ) : remote_address = remote_address_ ssh_transport = self . _transport logger = self . logger return Handler
Make SSH Handler class
236,751
def _make_ssh_forward_server ( self , remote_address , local_bind_address ) : _Handler = self . _make_ssh_forward_handler_class ( remote_address ) try : if isinstance ( local_bind_address , string_types ) : forward_maker_class = self . _make_unix_ssh_forward_server_class else : forward_maker_class = self . _make_ssh_fo...
Make SSH forward proxy Server class
236,752
def get_agent_keys ( logger = None ) : paramiko_agent = paramiko . Agent ( ) agent_keys = paramiko_agent . get_keys ( ) if logger : logger . info ( '{0} keys loaded from agent' . format ( len ( agent_keys ) ) ) return list ( agent_keys )
Load public keys from any available SSH agent
236,753
def get_keys ( logger = None , host_pkey_directories = None , allow_agent = False ) : keys = SSHTunnelForwarder . get_agent_keys ( logger = logger ) if allow_agent else [ ] if host_pkey_directories is not None : paramiko_key_types = { 'rsa' : paramiko . RSAKey , 'dsa' : paramiko . DSSKey , 'ecdsa' : paramiko . ECDSAKey...
Load public keys from any available SSH agent or local . ssh directory .
236,754
def _get_transport ( self ) : if self . ssh_proxy : if isinstance ( self . ssh_proxy , paramiko . proxy . ProxyCommand ) : proxy_repr = repr ( self . ssh_proxy . cmd [ 1 ] ) else : proxy_repr = repr ( self . ssh_proxy ) self . logger . debug ( 'Connecting via proxy: {0}' . format ( proxy_repr ) ) _socket = self . ssh_p...
Return the SSH transport to the remote gateway
236,755
def _create_tunnels ( self ) : if not self . is_active : try : self . _connect_to_gateway ( ) except socket . gaierror : msg = 'Could not resolve IP address for {0}, aborting!' . format ( self . ssh_host ) self . logger . error ( msg ) return except ( paramiko . SSHException , socket . error ) as e : template = 'Could ...
Create SSH tunnels on top of a transport to the remote gateway
236,756
def _process_deprecated ( attrib , deprecated_attrib , kwargs ) : if deprecated_attrib not in DEPRECATIONS : raise ValueError ( '{0} not included in deprecations list' . format ( deprecated_attrib ) ) if deprecated_attrib in kwargs : warnings . warn ( "'{0}' is DEPRECATED use '{1}' instead" . format ( deprecated_attrib...
Processes optional deprecate arguments
236,757
def read_private_key_file ( pkey_file , pkey_password = None , key_type = None , logger = None ) : ssh_pkey = None for pkey_class in ( key_type , ) if key_type else ( paramiko . RSAKey , paramiko . DSSKey , paramiko . ECDSAKey , paramiko . Ed25519Key ) : try : ssh_pkey = pkey_class . from_private_key_file ( pkey_file ,...
Get SSH Public key from a private key file given an optional password
236,758
def _check_tunnel ( self , _srv ) : if self . skip_tunnel_checkup : self . tunnel_is_up [ _srv . local_address ] = True return self . logger . info ( 'Checking tunnel to: {0}' . format ( _srv . remote_address ) ) if isinstance ( _srv . local_address , string_types ) : s = socket . socket ( socket . AF_UNIX , socket . S...
Check if tunnel is already established
236,759
def start ( self ) : if self . is_alive : self . logger . warning ( 'Already started!' ) return self . _create_tunnels ( ) if not self . is_active : self . _raise ( BaseSSHTunnelForwarderError , reason = 'Could not establish session to SSH gateway' ) for _srv in self . _server_list : thread = threading . Thread ( targe...
Start the SSH tunnels
236,760
def stop ( self ) : self . logger . info ( 'Closing all open connections...' ) opened_address_text = ', ' . join ( ( address_to_str ( k . local_address ) for k in self . _server_list ) ) or 'None' self . logger . debug ( 'Listening tunnels: ' + opened_address_text ) self . _stop_transport ( ) self . _server_list = [ ] ...
Shut the tunnel down .
236,761
def _serve_forever_wrapper ( self , _srv , poll_interval = 0.1 ) : self . logger . info ( 'Opening tunnel: {0} <> {1}' . format ( address_to_str ( _srv . local_address ) , address_to_str ( _srv . remote_address ) ) ) _srv . serve_forever ( poll_interval ) self . logger . info ( 'Tunnel: {0} <> {1} released' . format ( ...
Wrapper for the server created for a SSH forward
236,762
def _stop_transport ( self ) : try : self . _check_is_started ( ) except ( BaseSSHTunnelForwarderError , HandlerSSHTunnelForwarderError ) as e : self . logger . warning ( e ) for _srv in self . _server_list : tunnel = _srv . local_address if self . tunnel_is_up [ tunnel ] : self . logger . info ( 'Shutting down tunnel ...
Close the underlying transport when nothing more is needed
236,763
def local_bind_ports ( self ) : self . _check_is_started ( ) return [ _server . local_port for _server in self . _server_list if _server . local_port is not None ]
Return a list containing the ports of local side of the TCP tunnels
236,764
def local_bind_hosts ( self ) : self . _check_is_started ( ) return [ _server . local_host for _server in self . _server_list if _server . local_host is not None ]
Return a list containing the IP addresses listening for the tunnels
236,765
def get_submodules ( module ) : if not inspect . ismodule ( module ) : raise RuntimeError ( 'Can only extract submodules from a module object, ' 'for example imported via importlib.import_module' ) submodules = get_members ( module , inspect . ismodule ) module_path = list ( getattr ( module , '__path__' , [ None ] ) )...
This function imports all sub - modules of the supplied module and returns a dictionary with module names as keys and the sub - module objects as values . If the supplied parameter is not a module object a RuntimeError is raised .
236,766
def extract_module_name ( absolute_path ) : base_name = osp . basename ( osp . normpath ( absolute_path ) ) if base_name [ 0 ] in ( '.' , '_' ) : return None if osp . isdir ( absolute_path ) : return base_name module_name , extension = osp . splitext ( base_name ) if extension == '.py' : return module_name return None
This function tries to extract a valid module name from the basename of the supplied path . If it s a directory the directory name is returned if it s a file the file name without extension is returned . If the basename starts with _ or . or it s a file with an ending different from . py the function returns None
236,767
def dict_strict_update ( base_dict , update_dict ) : additional_keys = set ( update_dict . keys ( ) ) - set ( base_dict . keys ( ) ) if len ( additional_keys ) > 0 : raise RuntimeError ( 'The update dictionary contains keys that are not part of ' 'the base dictionary: {}' . format ( str ( additional_keys ) ) , addition...
This function updates base_dict with update_dict if and only if update_dict does not contain keys that are not already in base_dict . It is essentially a more strict interpretation of the term updating the dict .
236,768
def format_doc_text ( text ) : return '\n' . join ( textwrap . fill ( line , width = 99 , initial_indent = ' ' , subsequent_indent = ' ' ) for line in inspect . cleandoc ( text ) . splitlines ( ) )
A very thin wrapper around textwrap . fill to consistently wrap documentation text for display in a command line environment . The text is wrapped to 99 characters with an indentation depth of 4 spaces . Each line is wrapped independently in order to preserve manually added line breaks .
236,769
def do_import ( self , * names ) : try : module_object = importlib . import_module ( self . _module ) objects = tuple ( getattr ( module_object , name ) for name in names ) except ImportError : def failing_init ( obj , * args , ** kwargs ) : raise self . _exception objects = tuple ( type ( name , ( object , ) , { '__in...
Tries to import names from the module specified on initialization of the FromOptionalDependency - object . In case an ImportError occurs the requested names are replaced with stub objects .
236,770
def get_api ( self ) : return { 'class' : type ( self . _object ) . __name__ , 'methods' : list ( self . _function_map . keys ( ) ) }
This method returns the class name and a list of exposed methods . It is exposed to RPC - clients by an instance of ExposedObjectCollection .
236,771
def remove_object ( self , name ) : if name not in self . _object_map : raise RuntimeError ( 'No object with name {} is registered.' . format ( name ) ) for fn_name in list ( self . _function_map . keys ( ) ) : if fn_name . startswith ( name + '.' ) or fn_name . startswith ( name + ':' ) : self . _remove_function ( fn_...
Remove the object exposed under that name . If no object is registered under the supplied name a RuntimeError is raised .
236,772
def set_set_point ( self , param ) : if self . temperature_low_limit <= param <= self . temperature_high_limit : self . set_point_temperature = param return ""
Sets the target temperature .
236,773
def set_circulating ( self , param ) : if param == 0 : self . is_circulating = param self . circulate_commanded = False elif param == 1 : self . is_circulating = param self . circulate_commanded = True return ""
Sets whether to circulate - in effect whether the heater is on .
236,774
def get_protocols ( self , device ) : return self . _reg . device_builder ( device , self . _rv ) . protocols
Returns a list of available protocols for the specified device .
236,775
def linear ( current , target , rate , dt ) : sign = ( target > current ) - ( target < current ) if not sign : return current new_value = current + sign * rate * dt if sign * new_value > sign * target : return target return new_value
This function returns the new value after moving towards target at the given speed constantly for the time dt .
236,776
def meta ( self ) : if not self . _pv . meta_data_property or not self . _meta_target : return { } return getattr ( self . _meta_target , self . _pv . meta_data_property )
Value of the bound meta - property on the target .
236,777
def doc ( self ) : return self . _pv . doc or inspect . getdoc ( getattr ( type ( self . _target ) , self . _pv . property , None ) ) or ''
Docstring of property on target or override specified on PV - object .
236,778
def bind ( self , * targets ) : self . property = 'value' self . meta_data_property = 'meta' return BoundPV ( self , self . _get_target ( self . property , * targets ) , self . _get_target ( self . meta_data_property , * targets ) )
Tries to bind the PV to one of the supplied targets . Targets are inspected according to the order in which they are supplied .
236,779
def _get_callable ( self , func , * targets ) : if not callable ( func ) : func_name = func func = next ( ( getattr ( obj , func , None ) for obj in targets if func in dir ( obj ) ) , None ) if not func : raise AttributeError ( 'No method with the name \'{}\' could be found on any of the target objects ' '(device, inte...
If func is already a callable it is returned directly . If it s a string it is assumed to be a method on one of the objects supplied in targets and that is returned . If no method with the specified name is found an AttributeError is raised .
236,780
def _function_has_n_args ( self , func , n ) : if inspect . ismethod ( func ) : n += 1 argspec = inspect . getargspec ( func ) defaults = argspec . defaults or ( ) return len ( argspec . args ) - len ( defaults ) == n
Returns true if func has n arguments . Arguments with default and self for methods are not considered .
236,781
def start_server ( self ) : if self . _server is None : self . _server = SimpleServer ( ) self . _server . createPV ( prefix = self . _options . prefix , pvdb = { k : v . config for k , v in self . interface . bound_pvs . items ( ) } ) self . _driver = PropertyExposingDriver ( interface = self . interface , device_lock...
Creates a pcaspy - server .
236,782
def handle ( self , cycle_delay = 0.1 ) : if self . _server is not None : self . _server . process ( cycle_delay ) self . _driver . process_pv_updates ( )
Call this method to spend about cycle_delay seconds processing requests in the pcaspy server . Under load for example when running caget at a high frequency the actual time spent in the method may be much shorter . This effect is not corrected for .
236,783
def _make_request ( self , method , * args ) : response , request_id = self . _connection . json_rpc ( self . _prefix + method , * args ) if 'id' not in response : raise ProtocolException ( 'JSON-RPC response does not contain ID field.' ) if response [ 'id' ] != request_id : raise ProtocolException ( 'ID of JSON-RPC re...
This method performs a JSON - RPC request via the object s ZMQ socket . If successful the result is returned otherwise exceptions are raised . Server side exceptions are raised using the same type as on the server if they are part of the exceptions - module . Otherwise a RemoteException is raised .
236,784
def get_status ( self ) : self . device . serial_command_mode = True Tarray = [ 0x80 ] * 10 Tarray [ 0 ] = { 'stopped' : 0x01 , 'heat' : 0x10 , 'cool' : 0x20 , 'hold' : 0x30 , } . get ( self . device . _csm . state , 0x01 ) if Tarray [ 0 ] == 0x30 and self . device . hold_commanded : Tarray [ 0 ] = 0x50 if self . devic...
Models T Command functionality of device .
236,785
def set_rate ( self , param ) : rate = int ( param ) if 1 <= rate <= 15000 : self . device . temperature_rate = rate / 100.0 return ""
Models Rate Command functionality of device .
236,786
def set_limit ( self , param ) : limit = int ( param ) if - 2000 <= limit <= 6000 : self . device . temperature_limit = limit / 10.0 return ""
Models Limit Command functionality of device .
236,787
def pump_command ( self , param ) : lookup = [ c for c in "0123456789:;<=>?@ABCDEFGHIJKLMN" ] if param == "a0" : self . device . pump_manual_mode = False elif param == "m0" : self . device . pump_manual_mode = True elif param in lookup : self . device . manual_target_speed = lookup . index ( param ) return ""
Models LNP Pump Commands functionality of device .
236,788
def set_context ( self , new_context ) : self . _context = new_context if hasattr ( self , '_set_logging_context' ) : self . _set_logging_context ( self . _context )
Assigns the new context to the member variable _context .
236,789
def _initialize_data ( self ) : self . serial_command_mode = False self . pump_overspeed = False self . start_commanded = False self . stop_commanded = False self . hold_commanded = False self . temperature_rate = 5.0 self . temperature_limit = 0.0 self . pump_speed = 0 self . temperature = 24.0 self . pump_manual_mode...
This method is called once on construction . After that it may be manually called again to reset the device to its default state .
236,790
def has_log ( target ) : logger_name = target . __name__ def get_logger_name ( context = None ) : log_names = [ root_logger_name , logger_name ] if context is not None : log_names . insert ( 1 , context if isinstance ( context , string_types ) else context . __class__ . __name__ ) return '.' . join ( log_names ) def _s...
This is a decorator to add logging functionality to a class or function .
236,791
def get_usage_text ( parser , indent = None ) : usage_text = StringIO ( ) parser . print_help ( usage_text ) usage_string = usage_text . getvalue ( ) if indent is None : return usage_string return '\n' . join ( [ ' ' * indent + line for line in usage_string . split ( '\n' ) ] )
This small helper function extracts the help information from an ArgumentParser instance and indents the text by the number of spaces supplied in the indent - argument .
236,792
def stop ( self ) : self . _target = self . position self . log . info ( 'Stopping movement after user request.' ) return self . target , self . position
Stops the motor and returns the new target and position which are equal
236,793
def run_simulation ( argument_list = None ) : try : arguments = parser . parse_args ( argument_list or sys . argv [ 1 : ] ) if arguments . version : print ( __version__ ) return if arguments . relaxed_versions : print ( 'Unknown option --relaxed-versions. Did you mean --ignore-versions?' ) return loglevel = 'debug' if ...
This is effectively the main function of a typical simulation run . Arguments passed in are parsed and used to construct and run the simulation .
236,794
def map_arguments ( self , arguments ) : if self . argument_mappings is None : return arguments return [ f ( a ) for f , a in zip ( self . argument_mappings , arguments ) ]
Returns the mapped function arguments . If no mapping functions are defined the arguments are returned as they were supplied .
236,795
def map_return_value ( self , return_value ) : if callable ( self . return_mapping ) : return self . return_mapping ( return_value ) if self . return_mapping is not None : return self . return_mapping return return_value
Returns the mapped return_value of a processed request . If no return_mapping has been defined the value is returned as is . If return_mapping is a static value that value is returned ignoring return_value completely .
236,796
def start_server ( self ) : if self . _server is None : if self . _options . telnet_mode : self . interface . in_terminator = '\r\n' self . interface . out_terminator = '\r\n' self . _server = StreamServer ( self . _options . bind_address , self . _options . port , self . interface , self . device_lock )
Starts the TCP stream server binding to the configured host and port . Host and port are configured via the command line arguments .
236,797
def handle ( self , cycle_delay = 0.1 ) : asyncore . loop ( cycle_delay , count = 1 ) self . _server . process ( int ( cycle_delay * 1000 ) )
Spend approximately cycle_delay seconds to process requests to the server .
236,798
def _override_data ( self , overrides ) : if overrides is not None : for name , val in overrides . items ( ) : self . log . debug ( 'Trying to override initial data (%s=%s)' , name , val ) if name not in dir ( self ) : raise AttributeError ( 'Can not override non-existing attribute' '\'{}\' of class \'{}\'.' . format (...
This method overrides data members of the class but does not allow for adding new members .
236,799
def get ( self , addr , count ) : addr -= self . _start_addr data = self . _data [ addr : addr + count ] if len ( data ) != count : addr += self . _start_addr raise IndexError ( "Invalid address range [{:#06x} - {:#06x}]" . format ( addr , addr + count ) ) return data
Read list of count values at addr memory location in DataBank .