idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
44,600
def from_model_files ( cls , limits , input_model , investigation_time = 1.0 , simple_mesh_spacing = 1.0 , complex_mesh_spacing = 5.0 , mfd_width = 0.1 , area_discretisation = 10.0 ) : converter = SourceConverter ( investigation_time , simple_mesh_spacing , complex_mesh_spacing , mfd_width , area_discretisation ) sourc...
Reads the hazard model from a file
44,601
def get_rates ( self , mmin , mmax = np . inf ) : nsrcs = self . number_sources ( ) for iloc , source in enumerate ( self . source_model ) : print ( "Source Number %s of %s, Name = %s, Typology = %s" % ( iloc + 1 , nsrcs , source . name , source . __class__ . __name__ ) ) if isinstance ( source , CharacteristicFaultSou...
Returns the cumulative rates greater than Mmin
44,602
def _get_point_location ( self , location ) : if ( location . longitude < self . xlim [ 0 ] ) or ( location . longitude > self . xlim [ - 1 ] ) : return None , None xloc = int ( ( ( location . longitude - self . xlim [ 0 ] ) / self . xspc ) + 1E-7 ) if ( location . latitude < self . ylim [ 0 ] ) or ( location . latitud...
Returns the location in the output grid corresponding to the cell in which the epicentre lays
44,603
def _get_area_rates ( self , source , mmin , mmax = np . inf ) : points = list ( source ) for point in points : self . _get_point_rates ( point , mmin , mmax )
Adds the rates from the area source by discretising the source to a set of point sources
44,604
def _get_distance_scaling ( self , C , mag , rhypo ) : return ( C [ "a3" ] * np . log ( rhypo ) ) + ( C [ "a4" ] + C [ "a5" ] * mag ) * rhypo
Returns the distance scalig term
44,605
def _get_distance_scaling_term ( self , C , rjb , mag ) : rval = np . sqrt ( rjb ** 2.0 + C [ "c11" ] ** 2.0 ) f_0 , f_1 , f_2 = self . _get_distance_segment_coefficients ( rval ) return ( ( C [ "c4" ] + C [ "c5" ] * mag ) * f_0 + ( C [ "c6" ] + C [ "c7" ] * mag ) * f_1 + ( C [ "c8" ] + C [ "c9" ] * mag ) * f_2 + ( C [...
Returns the distance scaling component of the model Equation 10 Page 63
44,606
def _get_distance_segment_coefficients ( self , rval ) : nsites = len ( rval ) f_0 = np . log10 ( self . CONSTS [ "r0" ] / rval ) f_0 [ rval > self . CONSTS [ "r0" ] ] = 0.0 f_1 = np . log10 ( rval ) f_1 [ rval > self . CONSTS [ "r1" ] ] = np . log10 ( self . CONSTS [ "r1" ] ) f_2 = np . log10 ( rval / self . CONSTS [ ...
Returns the coefficients describing the distance attenuation shape for three different distance bins equations 12a - 12c
44,607
def collect_files ( dirpath , cond = lambda fullname : True ) : files = [ ] for fname in os . listdir ( dirpath ) : fullname = os . path . join ( dirpath , fname ) if os . path . isdir ( fullname ) : files . extend ( collect_files ( fullname ) ) else : if cond ( fullname ) : files . append ( fullname ) return files
Recursively collect the files contained inside dirpath .
44,608
def extract_from_zip ( path , candidates ) : temp_dir = tempfile . mkdtemp ( ) with zipfile . ZipFile ( path ) as archive : archive . extractall ( temp_dir ) return [ f for f in collect_files ( temp_dir ) if os . path . basename ( f ) in candidates ]
Given a zip archive and a function to detect the presence of a given filename unzip the archive into a temporary directory and return the full path of the file . Raise an IOError if the file cannot be found within the archive .
44,609
def get_params ( job_inis , ** kw ) : input_zip = None if len ( job_inis ) == 1 and job_inis [ 0 ] . endswith ( '.zip' ) : input_zip = job_inis [ 0 ] job_inis = extract_from_zip ( job_inis [ 0 ] , [ 'job_hazard.ini' , 'job_haz.ini' , 'job.ini' , 'job_risk.ini' ] ) not_found = [ ini for ini in job_inis if not os . path ...
Parse one or more INI - style config files .
44,610
def get_oqparam ( job_ini , pkg = None , calculators = None , hc_id = None , validate = 1 , ** kw ) : from openquake . calculators import base OqParam . calculation_mode . validator . choices = tuple ( calculators or base . calculators ) if not isinstance ( job_ini , dict ) : basedir = os . path . dirname ( pkg . __fil...
Parse a dictionary of parameters from an INI - style config file .
44,611
def get_site_model ( oqparam ) : req_site_params = get_gsim_lt ( oqparam ) . req_site_params arrays = [ ] for fname in oqparam . inputs [ 'site_model' ] : if isinstance ( fname , str ) and fname . endswith ( '.csv' ) : sm = read_csv ( fname ) if 'site_id' in sm . dtype . names : raise InvalidFile ( '%s: you passed a si...
Convert the NRML file into an array of site parameters .
44,612
def get_site_collection ( oqparam ) : mesh = get_mesh ( oqparam ) req_site_params = get_gsim_lt ( oqparam ) . req_site_params if oqparam . inputs . get ( 'site_model' ) : sm = get_site_model ( oqparam ) try : depth = sm [ 'depth' ] except ValueError : depth = None sitecol = site . SiteCollection . from_points ( sm [ 'l...
Returns a SiteCollection instance by looking at the points and the site model defined by the configuration parameters .
44,613
def get_rupture ( oqparam ) : rup_model = oqparam . inputs [ 'rupture_model' ] [ rup_node ] = nrml . read ( rup_model ) conv = sourceconverter . RuptureConverter ( oqparam . rupture_mesh_spacing , oqparam . complex_fault_mesh_spacing ) rup = conv . convert_node ( rup_node ) rup . tectonic_region_type = '*' rup . serial...
Read the rupture_model file and by filter the site collection
44,614
def get_composite_source_model ( oqparam , monitor = None , in_memory = True , srcfilter = SourceFilter ( None , { } ) ) : ucerf = oqparam . calculation_mode . startswith ( 'ucerf' ) source_model_lt = get_source_model_lt ( oqparam , validate = not ucerf ) trts = source_model_lt . tectonic_region_types trts_lower = { tr...
Parse the XML and build a complete composite source model in memory .
44,615
def get_mesh_hcurves ( oqparam ) : imtls = oqparam . imtls lon_lats = set ( ) data = AccumDict ( ) ncols = len ( imtls ) + 1 csvfile = oqparam . inputs [ 'hazard_curves' ] for line , row in enumerate ( csv . reader ( csvfile ) , 1 ) : try : if len ( row ) != ncols : raise ValueError ( 'Expected %d columns, found %d' % ...
Read CSV data in the format lon lat v1 - vN w1 - wN ... .
44,616
def reduce_source_model ( smlt_file , source_ids , remove = True ) : found = 0 to_remove = [ ] for paths in logictree . collect_info ( smlt_file ) . smpaths . values ( ) : for path in paths : logging . info ( 'Reading %s' , path ) root = nrml . read ( path ) model = Node ( 'sourceModel' , root [ 0 ] . attrib ) origmode...
Extract sources from the composite source model
44,617
def get_checksum32 ( oqparam , hazard = False ) : checksum = 0 for fname in get_input_files ( oqparam , hazard ) : checksum = _checksum ( fname , checksum ) if hazard : hazard_params = [ ] for key , val in vars ( oqparam ) . items ( ) : if key in ( 'rupture_mesh_spacing' , 'complex_fault_mesh_spacing' , 'width_of_mfd_b...
Build an unsigned 32 bit integer from the input files of a calculation .
44,618
def smart_save ( dbpath , archive , calc_id ) : tmpdir = tempfile . mkdtemp ( ) newdb = os . path . join ( tmpdir , os . path . basename ( dbpath ) ) shutil . copy ( dbpath , newdb ) try : with sqlite3 . connect ( newdb ) as conn : conn . execute ( 'DELETE FROM job WHERE status != "complete"' ) if calc_id : conn . exec...
Make a copy of the db remove the incomplete jobs and add the copy to the archive
44,619
def dump ( archive , calc_id = 0 , user = None ) : t0 = time . time ( ) assert archive . endswith ( '.zip' ) , archive getfnames = 'select ds_calc_dir || ".hdf5" from job where ?A' param = dict ( status = 'complete' ) if calc_id : param [ 'id' ] = calc_id if user : param [ 'user_name' ] = user fnames = [ f for f , in d...
Dump the openquake database and all the complete calculations into a zip file . In a multiuser installation must be run as administrator .
44,620
def load_version ( ) : filename = os . path . abspath ( os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , "cpt" , "__init__.py" ) ) with open ( filename , "rt" ) as version_file : conan_init = version_file . read ( ) version = re . search ( "__version__ = '([0-9a-z.-]+)'" , conan_init ) . gr...
Loads a file content
44,621
def builds ( self , confs ) : self . _named_builds = { } self . _builds = [ ] for values in confs : if len ( values ) == 2 : self . _builds . append ( BuildConf ( values [ 0 ] , values [ 1 ] , { } , { } , self . reference ) ) elif len ( values ) == 4 : self . _builds . append ( BuildConf ( values [ 0 ] , values [ 1 ] ,...
For retro compatibility directly assigning builds
44,622
def patch_default_base_profile ( conan_api , profile_abs_path ) : text = tools . load ( profile_abs_path ) if "include(default)" in text : if Version ( conan_version ) < Version ( "1.12.0" ) : cache = conan_api . _client_cache else : cache = conan_api . _cache default_profile_name = os . path . basename ( cache . defau...
If we have a profile including default but the users default in config is that the default is other we have to change the include
44,623
def get_user_if_exists ( strategy , details , user = None , * args , ** kwargs ) : if user : return { 'is_new' : False } try : username = details . get ( 'username' ) return { 'is_new' : False , 'user' : User . objects . get ( username = username ) } except User . DoesNotExist : pass return { }
Return a User with the given username iff the User exists .
44,624
def update_email ( strategy , details , user = None , * args , ** kwargs ) : if user : email = details . get ( 'email' ) if email and user . email != email : user . email = email strategy . storage . user . changed ( user )
Update the user s email address using data from provider .
44,625
def get_user_claims ( self , access_token , claims = None , token_type = 'Bearer' ) : data = self . get_json ( self . USER_INFO_URL , headers = { 'Authorization' : '{token_type} {token}' . format ( token_type = token_type , token = access_token ) } ) if claims : claims_names = set ( claims ) data = { k : v for ( k , v ...
Returns a dictionary with the values for each claim requested .
44,626
def _setup_ipc ( self ) : log . debug ( 'Setting up the server IPC puller to receive from the listener' ) self . ctx = zmq . Context ( ) self . sub = self . ctx . socket ( zmq . PULL ) self . sub . bind ( LST_IPC_URL ) try : self . sub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . su...
Setup the IPC pub and sub . Subscript to the listener IPC and publish to the device specific IPC .
44,627
def _cleanup_buffer ( self ) : if not self . _buffer : return while True : time . sleep ( 60 ) log . debug ( 'Cleaning up buffer' ) items = self . _buffer . items ( ) log . debug ( 'Collected items' ) log . debug ( list ( items ) )
Periodically cleanup the buffer .
44,628
def _compile_prefixes ( self ) : self . compiled_prefixes = { } for dev_os , os_config in self . config . items ( ) : if not os_config : continue self . compiled_prefixes [ dev_os ] = [ ] for prefix in os_config . get ( 'prefixes' , [ ] ) : values = prefix . get ( 'values' , { } ) line = prefix . get ( 'line' , '' ) if...
Create a dict of all OS prefixes and their compiled regexs
44,629
def _identify_prefix ( self , msg , data ) : prefix_id = - 1 for prefix in data : msg_dict = { } prefix_id += 1 match = None if '__python_fun__' in prefix : log . debug ( 'Trying to match using the %s custom python profiler' , prefix [ '__python_mod__' ] ) try : match = prefix [ '__python_fun__' ] ( msg ) except Except...
Check the message again each OS prefix and if matched return the message dict
44,630
def _identify_os ( self , msg ) : ret = [ ] for dev_os , data in self . compiled_prefixes . items ( ) : log . debug ( 'Matching under %s' , dev_os ) msg_dict = self . _identify_prefix ( msg , data ) if msg_dict : log . debug ( 'Adding %s to list of matched OS' , dev_os ) ret . append ( ( dev_os , msg_dict ) ) else : lo...
Using the prefix of the syslog message we are able to identify the operating system and then continue parsing .
44,631
def _setup_ipc ( self ) : self . ctx = zmq . Context ( ) log . debug ( 'Creating the dealer IPC for %s' , self . _name ) self . sub = self . ctx . socket ( zmq . DEALER ) if six . PY2 : self . sub . setsockopt ( zmq . IDENTITY , self . _name ) elif six . PY3 : self . sub . setsockopt ( zmq . IDENTITY , bytes ( self . _...
Subscribe to the right topic in the device IPC and publish to the publisher proxy .
44,632
def _compile_messages ( self ) : self . compiled_messages = [ ] if not self . _config : return for message_dict in self . _config . get ( 'messages' , { } ) : error = message_dict [ 'error' ] tag = message_dict [ 'tag' ] model = message_dict [ 'model' ] match_on = message_dict . get ( 'match_on' , 'tag' ) if '__python_...
Create a list of all OS messages and their compiled regexs
44,633
def _parse ( self , msg_dict ) : error_present = False for message in self . compiled_messages : match_on = message [ 'match_on' ] if match_on not in msg_dict : continue if message [ 'tag' ] != msg_dict [ match_on ] : continue if '__python_fun__' in message : return { 'model' : message [ 'model' ] , 'error' : message [...
Parse a syslog message and check what OpenConfig object should be generated .
44,634
def _emit ( self , ** kwargs ) : oc_dict = { } for mapping , result_key in kwargs [ 'mapping' ] [ 'variables' ] . items ( ) : result = kwargs [ result_key ] oc_dict = napalm_logs . utils . setval ( mapping . format ( ** kwargs ) , result , oc_dict ) for mapping , result in kwargs [ 'mapping' ] [ 'static' ] . items ( ) ...
Emit an OpenConfig object given a certain combination of fields mappeed in the config to the corresponding hierarchy .
44,635
def _publish ( self , obj ) : bin_obj = umsgpack . packb ( obj ) self . pub . send ( bin_obj )
Publish the OC object .
44,636
def _handshake ( self , conn , addr ) : msg = conn . recv ( len ( MAGIC_REQ ) ) log . debug ( 'Received message %s from %s' , msg , addr ) if msg != MAGIC_REQ : log . warning ( '%s is not a valid REQ message from %s' , msg , addr ) return log . debug ( 'Sending the private key' ) conn . send ( self . __key ) log . debu...
Ensures that the client receives the AES key .
44,637
def keep_alive ( self , conn ) : while self . __up : msg = conn . recv ( len ( AUTH_KEEP_ALIVE ) ) if msg != AUTH_KEEP_ALIVE : log . error ( 'Received something other than %s' , AUTH_KEEP_ALIVE ) conn . close ( ) return try : conn . send ( AUTH_KEEP_ALIVE_ACK ) except ( IOError , socket . error ) as err : log . error (...
Maintains auth sessions
44,638
def verify_cert ( self ) : log . debug ( 'Verifying the %s certificate, keyfile: %s' , self . certificate , self . keyfile ) try : ssl . create_default_context ( ) . load_cert_chain ( self . certificate , keyfile = self . keyfile ) except ssl . SSLError : error_string = 'SSL certificate and key do not match' log . erro...
Checks that the provided cert and key are valid and usable
44,639
def _create_skt ( self ) : log . debug ( 'Creating the auth socket' ) if ':' in self . auth_address : self . socket = socket . socket ( socket . AF_INET6 , socket . SOCK_STREAM ) else : self . socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) try : self . socket . bind ( ( self . auth_address , self ...
Create the authentication socket .
44,640
def start ( self ) : log . debug ( 'Starting the auth process' ) self . verify_cert ( ) self . _create_skt ( ) log . debug ( 'The auth process can receive at most %d parallel connections' , AUTH_MAX_CONN ) self . socket . listen ( AUTH_MAX_CONN ) thread = threading . Thread ( target = self . _suicide_when_without_paren...
Listen to auth requests and send the AES key . Each client connection starts a new thread .
44,641
def stop ( self ) : log . info ( 'Stopping auth process' ) self . __up = False self . socket . close ( )
Stop the auth proc .
44,642
def start ( self ) : log . debug ( 'Creating the consumer using the bootstrap servers: %s and the group ID: %s' , self . bootstrap_servers , self . group_id ) try : self . consumer = kafka . KafkaConsumer ( bootstrap_servers = self . bootstrap_servers , group_id = self . group_id ) except kafka . errors . NoBrokersAvai...
Startup the kafka consumer .
44,643
def stop ( self ) : log . info ( 'Stopping te kafka listener class' ) self . consumer . unsubscribe ( ) self . consumer . close ( )
Shutdown kafka consumer .
44,644
def get_transport ( name ) : try : log . debug ( 'Using %s as transport' , name ) return TRANSPORT_LOOKUP [ name ] except KeyError : msg = 'Transport {} is not available. Are the dependencies installed?' . format ( name ) log . error ( msg , exc_info = True ) raise InvalidTransportException ( msg )
Return the transport class .
44,645
def start ( self ) : zmq_uri = '{protocol}://{address}:{port}' . format ( protocol = self . protocol , address = self . address , port = self . port ) if self . port else '{protocol}://{address}' . format ( protocol = self . protocol , address = self . address ) log . debug ( 'ZMQ URI: %s' , zmq_uri ) self . ctx = zmq ...
Startup the zmq consumer .
44,646
def receive ( self ) : try : msg = self . sub . recv ( ) except zmq . Again as error : log . error ( 'Unable to receive messages: %s' , error , exc_info = True ) raise ListenerException ( error ) log . debug ( '[%s] Received %s' , time . time ( ) , msg ) return msg , ''
Return the message received .
44,647
def stop ( self ) : log . info ( 'Stopping the zmq listener class' ) self . sub . close ( ) self . ctx . term ( )
Shutdown zmq listener .
44,648
def start ( self ) : if ':' in self . address : self . skt = socket . socket ( socket . AF_INET6 , socket . SOCK_DGRAM ) else : self . skt = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) if self . reuse_port : self . skt . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) if hasattr ( socket ,...
Create the UDP listener socket .
44,649
def _suicide_when_without_parent ( self , parent_pid ) : while True : time . sleep ( 5 ) try : os . kill ( parent_pid , 0 ) except OSError : self . stop ( ) log . warning ( 'The parent is not alive, exiting.' ) os . _exit ( 999 )
Kill this process when the parent died .
44,650
def _setup_buffer ( self ) : if not self . _buffer_cfg or not isinstance ( self . _buffer_cfg , dict ) : return buffer_name = list ( self . _buffer_cfg . keys ( ) ) [ 0 ] buffer_class = napalm_logs . buffer . get_interface ( buffer_name ) log . debug ( 'Setting up buffer interface "%s"' , buffer_name ) if 'expire_time'...
Setup the buffer subsystem .
44,651
def _setup_metrics ( self ) : path = os . environ . get ( "prometheus_multiproc_dir" ) if not os . path . exists ( self . metrics_dir ) : try : log . info ( "Creating metrics directory" ) os . makedirs ( self . metrics_dir ) except OSError : log . error ( "Failed to create metrics directory!" ) raise ConfigurationExcep...
Start metric exposition
44,652
def _setup_log ( self ) : logging_level = CONFIG . LOGGING_LEVEL . get ( self . log_level . lower ( ) ) logging . basicConfig ( format = self . log_format , level = logging_level )
Setup the log object .
44,653
def _whitelist_blacklist ( self , os_name ) : return napalm_logs . ext . check_whitelist_blacklist ( os_name , whitelist = self . device_whitelist , blacklist = self . device_blacklist )
Determines if the OS should be ignored depending on the whitelist - blacklist logic configured by the user .
44,654
def _extract_yaml_docstring ( stream ) : comment_lines = [ ] lines = stream . read ( ) . splitlines ( ) for line in lines : line_strip = line . strip ( ) if not line_strip : continue if line_strip . startswith ( '#' ) : comment_lines . append ( line_strip . replace ( '#' , '' , 1 ) . strip ( ) ) else : break return ' '...
Extract the comments at the top of the YAML file from the stream handler . Return the extracted comment as string .
44,655
def _verify_config_dict ( self , valid , config , dev_os , key_path = None ) : if not key_path : key_path = [ ] for key , value in valid . items ( ) : self . _verify_config_key ( key , value , valid , config , dev_os , key_path )
Verify if the config dict is valid .
44,656
def _verify_config ( self ) : if not self . config_dict : self . _raise_config_exception ( 'No config found' ) for dev_os , dev_config in self . config_dict . items ( ) : if not dev_config : log . warning ( 'No config found for %s' , dev_os ) continue self . _verify_config_dict ( CONFIG . VALID_CONFIG , dev_config , de...
Verify that the config is correct
44,657
def _build_config ( self ) : if not self . config_dict : if not self . config_path : self . config_path = os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , 'config' ) log . info ( 'Reading the configuration from %s' , self . config_path ) self . config_dict = self . _load_config ( self . co...
Build the config of the napalm syslog parser .
44,658
def _start_auth_proc ( self ) : log . debug ( 'Computing the signing key hex' ) verify_key = self . __signing_key . verify_key sgn_verify_hex = verify_key . encode ( encoder = nacl . encoding . HexEncoder ) log . debug ( 'Starting the authenticator subprocess' ) auth = NapalmLogsAuthProc ( self . certificate , self . k...
Start the authenticator process .
44,659
def _start_lst_proc ( self , listener_type , listener_opts ) : log . debug ( 'Starting the listener process for %s' , listener_type ) listener = NapalmLogsListenerProc ( self . opts , self . address , self . port , listener_type , listener_opts = listener_opts ) proc = Process ( target = listener . start ) proc . start...
Start the listener process .
44,660
def _start_srv_proc ( self , started_os_proc ) : log . debug ( 'Starting the server process' ) server = NapalmLogsServerProc ( self . opts , self . config_dict , started_os_proc , buffer = self . _buffer ) proc = Process ( target = server . start ) proc . start ( ) proc . description = 'Server process' log . debug ( 'S...
Start the server process .
44,661
def _start_pub_proc ( self , publisher_type , publisher_opts , pub_id ) : log . debug ( 'Starting the publisher process for %s' , publisher_type ) publisher = NapalmLogsPublisherProc ( self . opts , self . publish_address , self . publish_port , publisher_type , self . serializer , self . __priv_key , self . __signing_...
Start the publisher process .
44,662
def _start_dev_proc ( self , device_os , device_config ) : log . info ( 'Starting the child process for %s' , device_os ) dos = NapalmLogsDeviceProc ( device_os , self . opts , device_config ) os_proc = Process ( target = dos . start ) os_proc . start ( ) os_proc . description = '%s device process' % device_os log . de...
Start the device worker process .
44,663
def _check_children ( self ) : while self . up : time . sleep ( 1 ) for process in self . _processes : if process . is_alive ( ) is True : continue log . debug ( '%s is dead. Stopping the napalm-logs engine.' , process . description ) self . stop_engine ( )
Check all of the child processes are still running
44,664
def _setup_ipc ( self ) : log . debug ( 'Setting up the internal IPC proxy' ) self . ctx = zmq . Context ( ) self . sub = self . ctx . socket ( zmq . SUB ) self . sub . bind ( PUB_PX_IPC_URL ) self . sub . setsockopt ( zmq . SUBSCRIBE , b'' ) log . debug ( 'Setting HWM for the proxy frontend: %d' , self . hwm ) try : s...
Setup the IPC PUB and SUB sockets for the proxy .
44,665
def _setup_ipc ( self ) : self . ctx = zmq . Context ( ) log . debug ( 'Setting up the %s publisher subscriber #%d' , self . _transport_type , self . pub_id ) self . sub = self . ctx . socket ( zmq . SUB ) self . sub . connect ( PUB_IPC_URL ) self . sub . setsockopt ( zmq . SUBSCRIBE , b'' ) try : self . sub . setsocko...
Subscribe to the pub IPC and publish the messages on the right transport .
44,666
def _prepare ( self , serialized_obj ) : nonce = nacl . utils . random ( nacl . secret . SecretBox . NONCE_SIZE ) encrypted = self . __safe . encrypt ( serialized_obj , nonce ) signed = self . __signing_key . sign ( encrypted ) return signed
Prepare the object to be sent over the untrusted channel .
44,667
def get_listener ( name ) : try : log . debug ( 'Using %s as listener' , name ) return LISTENER_LOOKUP [ name ] except KeyError : msg = 'Listener {} is not available. Are the dependencies installed?' . format ( name ) log . error ( msg , exc_info = True ) raise InvalidListenerException ( msg )
Return the listener class .
44,668
def _start_keep_alive ( self ) : keep_alive_thread = threading . Thread ( target = self . keep_alive ) keep_alive_thread . daemon = True keep_alive_thread . start ( )
Start the keep alive thread as a daemon
44,669
def keep_alive ( self ) : self . ssl_skt . settimeout ( defaults . AUTH_KEEP_ALIVE_INTERVAL ) while self . __up : try : log . debug ( 'Sending keep-alive message to the server' ) self . ssl_skt . send ( defaults . AUTH_KEEP_ALIVE ) except socket . error : log . error ( 'Unable to send keep-alive message to the server.'...
Send a keep alive request periodically to make sure that the server is still alive . If not then try to reconnect .
44,670
def reconnect ( self ) : log . debug ( 'Closing the SSH socket.' ) try : self . ssl_skt . close ( ) except socket . error : log . error ( 'The socket seems to be closed already.' ) log . debug ( 'Re-opening the SSL socket.' ) self . authenticate ( )
Try to reconnect and re - authenticate with the server .
44,671
def authenticate ( self ) : log . debug ( 'Authenticate to %s:%d, using the certificate %s' , self . address , self . port , self . certificate ) if ':' in self . address : skt_ver = socket . AF_INET6 else : skt_ver = socket . AF_INET skt = socket . socket ( skt_ver , socket . SOCK_STREAM ) self . ssl_skt = ssl . wrap_...
Authenticate the client and return the private and signature keys .
44,672
def decrypt ( self , binary ) : try : encrypted = self . verify_key . verify ( binary ) except BadSignatureError : log . error ( 'Signature was forged or corrupt' , exc_info = True ) raise BadSignatureException ( 'Signature was forged or corrupt' ) try : packed = self . priv_key . decrypt ( encrypted ) except CryptoErr...
Decrypt and unpack the original OpenConfig object serialized using MessagePack . Raise BadSignatureException when the signature was forged or corrupted .
44,673
def _client_connection ( self , conn , addr ) : log . debug ( 'Established connection with %s:%d' , addr [ 0 ] , addr [ 1 ] ) conn . settimeout ( self . socket_timeout ) try : while self . __up : msg = conn . recv ( self . buffer_size ) if not msg : continue log . debug ( '[%s] Received %s from %s. Adding in the queue'...
Handle the connecition with one client .
44,674
def _serve_clients ( self ) : self . __up = True while self . __up : log . debug ( 'Waiting for a client to connect' ) try : conn , addr = self . skt . accept ( ) log . debug ( 'Received connection from %s:%d' , addr [ 0 ] , addr [ 1 ] ) except socket . error as error : if not self . __up : return msg = 'Received liste...
Accept cients and serve one separate thread per client .
44,675
def start ( self ) : log . debug ( 'Creating the TCP server' ) if ':' in self . address : self . skt = socket . socket ( socket . AF_INET6 , socket . SOCK_STREAM ) else : self . skt = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) if self . reuse_port : self . skt . setsockopt ( socket . SOL_SOCKET , socke...
Start listening for messages .
44,676
def receive ( self ) : while self . buffer . empty ( ) and self . __up : sleep_ms = random . randint ( 0 , 1000 ) time . sleep ( sleep_ms / 1000.0 ) if not self . buffer . empty ( ) : return self . buffer . get ( block = False ) return '' , ''
Return one message dequeued from the listen buffer .
44,677
def stop ( self ) : log . info ( 'Stopping the TCP listener' ) self . __up = False try : self . skt . shutdown ( socket . SHUT_RDWR ) except socket . error : log . error ( 'The following error may not be critical:' , exc_info = True ) self . skt . close ( )
Closing the socket .
44,678
def _setup_ipc ( self ) : log . debug ( 'Setting up the listener IPC pusher' ) self . ctx = zmq . Context ( ) self . pub = self . ctx . socket ( zmq . PUSH ) self . pub . connect ( LST_IPC_URL ) log . debug ( 'Setting HWM for the listener: %d' , self . opts [ 'hwm' ] ) try : self . pub . setsockopt ( zmq . HWM , self ....
Setup the listener ICP pusher .
44,679
def make_update_loop ( thread , update_func ) : while not thread . should_stop ( ) : if thread . should_pause ( ) : thread . wait_to_resume ( ) start = time . time ( ) if hasattr ( thread , '_updated' ) : thread . _updated . clear ( ) update_func ( ) if hasattr ( thread , '_updated' ) : thread . _updated . set ( ) end ...
Makes a run loop which calls an update function at a predefined frequency .
44,680
def start ( self ) : if self . running : self . stop ( ) self . _thread = threading . Thread ( target = self . _wrapped_target ) self . _thread . daemon = True self . _thread . start ( )
Start the run method as a new thread .
44,681
def wait_to_start ( self , allow_failure = False ) : self . _started . wait ( ) if self . _crashed and not allow_failure : self . _thread . join ( ) raise RuntimeError ( 'Setup failed, see {} Traceback' 'for details.' . format ( self . _thread . name ) )
Wait for the thread to actually starts .
44,682
def from_vrep ( config , vrep_host = '127.0.0.1' , vrep_port = 19997 , scene = None , tracked_objects = [ ] , tracked_collisions = [ ] , id = None , shared_vrep_io = None ) : if shared_vrep_io is None : vrep_io = VrepIO ( vrep_host , vrep_port ) else : vrep_io = shared_vrep_io vreptime = vrep_time ( vrep_io ) pypot_tim...
Create a robot from a V - REP instance .
44,683
def set_wheel_mode ( self , ids ) : self . set_control_mode ( dict ( zip ( ids , itertools . repeat ( 'wheel' ) ) ) )
Sets the specified motors to wheel mode .
44,684
def set_joint_mode ( self , ids ) : self . set_control_mode ( dict ( zip ( ids , itertools . repeat ( 'joint' ) ) ) )
Sets the specified motors to joint mode .
44,685
def set_angle_limit ( self , limit_for_id , ** kwargs ) : convert = kwargs [ 'convert' ] if 'convert' in kwargs else self . _convert if 'wheel' in self . get_control_mode ( limit_for_id . keys ( ) ) : raise ValueError ( 'can not change the angle limit of a motor in wheel mode' ) if ( 0 , 0 ) in limit_for_id . values ( ...
Sets the angle limit to the specified motors .
44,686
def close ( self ) : self . stop_sync ( ) [ c . io . close ( ) for c in self . _controllers if c . io is not None ]
Cleans the robot by stopping synchronization and all controllers .
44,687
def goto_position ( self , position_for_motors , duration , control = None , wait = False ) : for i , ( motor_name , position ) in enumerate ( position_for_motors . iteritems ( ) ) : w = False if i < len ( position_for_motors ) - 1 else wait m = getattr ( self , motor_name ) m . goto_position ( position , duration , co...
Moves a subset of the motors to a position within a specific duration .
44,688
def power_up ( self ) : for m in self . motors : m . compliant = False m . moving_speed = 0 m . torque_limit = 100.0
Changes all settings to guarantee the motors will be used at their maximum power .
44,689
def to_config ( self ) : from . . dynamixel . controller import DxlController dxl_controllers = [ c for c in self . _controllers if isinstance ( c , DxlController ) ] config = { } config [ 'controllers' ] = { } for i , c in enumerate ( dxl_controllers ) : name = 'dxl_controller_{}' . format ( i ) config [ 'controllers'...
Generates the config for the current robot .
44,690
def update ( self ) : h , _ , l , _ = self . io . call_remote_api ( 'simxGetObjectGroupData' , remote_api . sim_object_joint_type , 16 , streaming = True ) limits4handle = { hh : ( ll , lr ) for hh , ll , lr in zip ( h , l [ : : 2 ] , l [ 1 : : 2 ] ) } for m in self . motors : tmax = torque_max [ m . model ] p = round ...
Synchronization update loop .
44,691
def update ( self ) : for s in self . sensors : s . position = self . io . get_object_position ( object_name = s . name ) s . orientation = self . io . get_object_orientation ( object_name = s . name )
Updates the position and orientation of the tracked objects .
44,692
def update ( self ) : for s in self . sensors : s . colliding = self . io . get_collision_state ( collision_name = s . name )
Update the state of the collision detectors .
44,693
def get_transformation_matrix ( self , theta ) : ct = numpy . cos ( theta + self . theta ) st = numpy . sin ( theta + self . theta ) ca = numpy . cos ( self . alpha ) sa = numpy . sin ( self . alpha ) return numpy . matrix ( ( ( ct , - st * ca , st * sa , self . a * ct ) , ( st , ct * ca , - ct * sa , self . a * st ) ,...
Computes the homogeneous transformation matrix for this link .
44,694
def forward_kinematics ( self , q ) : q = numpy . array ( q ) . flatten ( ) if len ( q ) != len ( self . links ) : raise ValueError ( 'q must contain as element as the number of links' ) tr = self . base . copy ( ) l = [ ] for link , theta in zip ( self . links , q ) : tr = tr * link . get_transformation_matrix ( theta...
Computes the homogeneous transformation matrix of the end effector of the chain .
44,695
def inverse_kinematics ( self , end_effector_transformation , q = None , max_iter = 1000 , tolerance = 0.05 , mask = numpy . ones ( 6 ) , use_pinv = False ) : if q is None : q = numpy . zeros ( ( len ( self . links ) , 1 ) ) q = numpy . matrix ( q . reshape ( - 1 , 1 ) ) best_e = numpy . ones ( 6 ) * numpy . inf best_q...
Computes the joint angles corresponding to the end effector transformation .
44,696
def _get_available_ports ( ) : if platform . system ( ) == 'Darwin' : return glob . glob ( '/dev/tty.usb*' ) elif platform . system ( ) == 'Linux' : return glob . glob ( '/dev/ttyACM*' ) + glob . glob ( '/dev/ttyUSB*' ) + glob . glob ( '/dev/ttyAMA*' ) elif sys . platform . lower ( ) == 'cygwin' : return glob . glob ( ...
Tries to find the available serial ports on your system .
44,697
def find_port ( ids , strict = True ) : ids_founds = [ ] for port in get_available_ports ( ) : for DxlIOCls in ( DxlIO , Dxl320IO ) : try : with DxlIOCls ( port ) as dxl : _ids_founds = dxl . scan ( ids ) ids_founds += _ids_founds if strict and len ( _ids_founds ) == len ( ids ) : return port if not strict and len ( _i...
Find the port with the specified attached motor ids .
44,698
def _filter ( self , data ) : filtered_data = [ ] for queue , data in zip ( self . _raw_data_queues , data ) : queue . append ( data ) filtered_data . append ( numpy . median ( queue ) ) return filtered_data
Apply a filter to reduce noisy data .
44,699
def setup ( self ) : [ c . start ( ) for c in self . controllers ] [ c . wait_to_start ( ) for c in self . controllers ]
Starts all the synchronization loops .