idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
59,400
def dist_sq ( self , other = None ) : v = self - other if other else self return sum ( map ( lambda a : a * a , v ) )
For fast length comparison
59,401
def yaw_pitch ( self ) : if not self : return YawPitch ( 0 , 0 ) ground_distance = math . sqrt ( self . x ** 2 + self . z ** 2 ) if ground_distance : alpha1 = - math . asin ( self . x / ground_distance ) / math . pi * 180 alpha2 = math . acos ( self . z / ground_distance ) / math . pi * 180 if alpha2 > 90 : yaw = 180 -...
Calculate the yaw and pitch of this vector
59,402
def make_slot_check ( wanted ) : if isinstance ( wanted , types . FunctionType ) : return wanted if isinstance ( wanted , int ) : item , meta = wanted , None elif isinstance ( wanted , Slot ) : item , meta = wanted . item_id , wanted . damage elif isinstance ( wanted , ( Item , Block ) ) : item , meta = wanted . id , w...
Creates and returns a function that takes a slot and checks if it matches the wanted item .
59,403
def _make_window ( window_dict ) : cls_name = '%sWindow' % camel_case ( str ( window_dict [ 'name' ] ) ) bases = ( Window , ) attrs = { '__module__' : sys . modules [ __name__ ] , 'name' : str ( window_dict [ 'name' ] ) , 'inv_type' : str ( window_dict [ 'id' ] ) , 'inv_data' : window_dict , } def make_slot_method ( in...
Creates a new class for that window and registers it at this module .
59,404
def get_dict ( self ) : data = { 'id' : self . item_id } if self . item_id != constants . INV_ITEMID_EMPTY : data [ 'damage' ] = self . damage data [ 'amount' ] = self . amount if self . nbt is not None : data [ 'enchants' ] = self . nbt return data
Formats the slot for network packing .
59,405
def on_success ( self , inv_plugin , emit_set_slot ) : self . dirty = set ( ) self . apply ( inv_plugin ) for changed_slot in self . dirty : emit_set_slot ( changed_slot )
Called when the click was successful and should be applied to the inventory .
59,406
def authenticate ( self ) : endpoint = '/authenticate' payload = { 'agent' : { 'name' : 'Minecraft' , 'version' : self . ygg_version , } , 'username' : self . username , 'password' : self . password , 'clientToken' : self . client_token , } rep = self . _ygg_req ( endpoint , payload ) if not rep or 'error' in rep : ret...
Generate an access token using an username and password . Any existing client token is invalidated if not provided .
59,407
def validate ( self ) : endpoint = '/validate' payload = dict ( accessToken = self . access_token ) rep = self . _ygg_req ( endpoint , payload ) return not bool ( rep )
Check if an access token is valid
59,408
def total_stored ( self , wanted , slots = None ) : if slots is None : slots = self . window . slots wanted = make_slot_check ( wanted ) return sum ( slot . amount for slot in slots if wanted ( slot ) )
Calculates the total number of items of that type in the current window or given slot range .
59,409
def find_slot ( self , wanted , slots = None ) : for slot in self . find_slots ( wanted , slots ) : return slot return None
Searches the given slots or if not given active hotbar slot hotbar inventory open window in this order .
59,410
def find_slots ( self , wanted , slots = None ) : if slots is None : slots = self . inv_slots_preferred + self . window . window_slots wanted = make_slot_check ( wanted ) for slot in slots : if wanted ( slot ) : yield slot
Yields all slots containing the item . Searches the given slots or if not given active hotbar slot hotbar inventory open window in this order .
59,411
def click_slot ( self , slot , right = False ) : if isinstance ( slot , int ) : slot = self . window . slots [ slot ] button = constants . INV_BUTTON_RIGHT if right else constants . INV_BUTTON_LEFT return self . send_click ( windows . SingleClick ( slot , button ) )
Left - click or right - click the slot .
59,412
def drop_slot ( self , slot = None , drop_stack = False ) : if slot is None : if self . cursor_slot . is_empty : slot = self . active_slot else : slot = self . cursor_slot elif isinstance ( slot , int ) : slot = self . window . slots [ slot ] if slot == self . cursor_slot : return self . click_slot ( self . cursor_slot...
Drop one or all items of the slot .
59,413
def inv_slots_preferred ( self ) : slots = [ self . active_slot ] slots . extend ( slot for slot in self . window . hotbar_slots if slot != self . active_slot ) slots . extend ( self . window . inventory_slots ) return slots
List of all available inventory slots in the preferred search order . Does not include the additional slots from the open window .
59,414
def get_block_entity_data ( self , pos_or_x , y = None , z = None ) : if None not in ( y , z ) : pos_or_x = pos_or_x , y , z coord_tuple = tuple ( int ( floor ( c ) ) for c in pos_or_x ) return self . block_entities . get ( coord_tuple , None )
Access block entity data .
59,415
def set_block_entity_data ( self , pos_or_x , y = None , z = None , data = None ) : if None not in ( y , z ) : pos_or_x = pos_or_x , y , z coord_tuple = tuple ( int ( floor ( c ) ) for c in pos_or_x ) old_data = self . block_entities . get ( coord_tuple , None ) self . block_entities [ coord_tuple ] = data return old_d...
Update block entity data .
59,416
def parse_vlq ( self , segment ) : values = [ ] cur , shift = 0 , 0 for c in segment : val = B64 [ ord ( c ) ] val , cont = val & 0b11111 , val >> 5 cur += val << shift shift += 5 if not cont : cur , sign = cur >> 1 , cur & 1 if sign : cur = - cur values . append ( cur ) cur , shift = 0 , 0 if cur or shift : raise Sour...
Parse a string of VLQ - encoded data .
59,417
def decode ( self , source ) : if source [ : 4 ] == ")]}'" or source [ : 3 ] == ")]}" : source = source . split ( '\n' , 1 ) [ 1 ] smap = json . loads ( source ) sources = smap [ 'sources' ] sourceRoot = smap . get ( 'sourceRoot' ) names = list ( map ( text_type , smap [ 'names' ] ) ) mappings = smap [ 'mappings' ] lin...
Decode a source map object into a SourceMapIndex .
59,418
def discover ( source ) : "Given a JavaScript file, find the sourceMappingURL line" source = source . splitlines ( ) if len ( source ) > 10 : possibilities = source [ : 5 ] + source [ - 5 : ] else : possibilities = source for line in set ( possibilities ) : pragma = line [ : 21 ] if pragma == '//# sourceMappingURL=' or...
Given a JavaScript file find the sourceMappingURL line
59,419
def clean ( ) : d = [ 'build' , 'dist' , 'scikits.audiolab.egg-info' , HTML_DESTDIR , PDF_DESTDIR ] for i in d : paver . path . path ( i ) . rmtree ( ) ( paver . path . path ( 'docs' ) / options . sphinx . builddir ) . rmtree ( )
Remove build dist egg - info garbage .
59,420
def add_attendees ( self , attendees , required = True ) : new_attendees = self . _build_resource_dictionary ( attendees , required = required ) for email in new_attendees : self . _attendees [ email ] = new_attendees [ email ] self . _dirty_attributes . add ( u'attendees' )
Adds new attendees to the event .
59,421
def remove_attendees ( self , attendees ) : attendees_to_delete = self . _build_resource_dictionary ( attendees ) for email in attendees_to_delete . keys ( ) : if email in self . _attendees : del self . _attendees [ email ] self . _dirty_attributes . add ( u'attendees' )
Removes attendees from the event .
59,422
def add_resources ( self , resources ) : new_resources = self . _build_resource_dictionary ( resources ) for key in new_resources : self . _resources [ key ] = new_resources [ key ] self . _dirty_attributes . add ( u'resources' )
Adds new resources to the event .
59,423
def remove_resources ( self , resources ) : resources_to_delete = self . _build_resource_dictionary ( resources ) for email in resources_to_delete . keys ( ) : if email in self . _resources : del self . _resources [ email ] self . _dirty_attributes . add ( u'resources' )
Removes resources from the event .
59,424
def validate ( self ) : if not self . start : raise ValueError ( "Event has no start date" ) if not self . end : raise ValueError ( "Event has no end date" ) if self . end < self . start : raise ValueError ( "Start date is after end date" ) if self . reminder_minutes_before_start and not isinstance ( self . reminder_mi...
Validates that all required fields are present
59,425
def info_factory ( name , libnames , headers , frameworks = None , section = None , classname = None ) : if not classname : classname = '%s_info' % name if not section : section = name if not frameworks : framesworks = [ ] class _ret ( system_info ) : def __init__ ( self ) : system_info . __init__ ( self ) def library_...
Create a system_info class .
59,426
def load_all_details ( self ) : log . debug ( u"Loading all details" ) if self . count > 0 : del ( self . events [ : ] ) log . debug ( u"Requesting all event details for events: {event_list}" . format ( event_list = str ( self . event_ids ) ) ) body = soap_request . get_item ( exchange_id = self . event_ids , format = ...
This function will execute all the event lookups for known events .
59,427
def seek ( self , offset , whence = 0 , mode = 'rw' ) : try : st = self . _sndfile . seek ( offset , whence , mode ) except IOError , e : raise PyaudioIOError ( str ( e ) ) return st
similar to python seek function taking only in account audio data .
59,428
def read_frames ( self , nframes , dtype = np . float64 ) : return self . _sndfile . read_frames ( nframes , dtype )
Read nframes frames of the file .
59,429
def write_frames ( self , input , nframes = - 1 ) : if nframes == - 1 : if input . ndim == 1 : nframes = input . size elif input . ndim == 2 : nframes = input . shape [ 0 ] else : raise ValueError ( "Input has to be rank 1 (mono) or rank 2 " "(multi-channels)" ) return self . _sndfile . write_frames ( input [ : nframes...
write data to file .
59,430
def delete_field ( field_uri ) : root = T . DeleteItemField ( T . FieldURI ( FieldURI = field_uri ) ) return root
Helper function to request deletion of a field . This is necessary when you want to overwrite values instead of appending .
59,431
def get_occurrence ( exchange_id , instance_index , format = u"Default" ) : root = M . GetItem ( M . ItemShape ( T . BaseShape ( format ) ) , M . ItemIds ( ) ) items_node = root . xpath ( "//m:ItemIds" , namespaces = NAMESPACES ) [ 0 ] for index in instance_index : items_node . append ( T . OccurrenceItemId ( Recurring...
Requests one or more calendar items from the store matching the master & index .
59,432
def new_event ( event ) : id = T . DistinguishedFolderId ( Id = event . calendar_id ) if event . calendar_id in DISTINGUISHED_IDS else T . FolderId ( Id = event . calendar_id ) start = convert_datetime_to_utc ( event . start ) end = convert_datetime_to_utc ( event . end ) root = M . CreateItem ( M . SavedItemFolderId (...
Requests a new event be created in the store .
59,433
def update_property_node ( node_to_insert , field_uri ) : root = T . SetItemField ( T . FieldURI ( FieldURI = field_uri ) , T . CalendarItem ( node_to_insert ) ) return root
Helper function - generates a SetItemField which tells Exchange you want to overwrite the contents of a field .
59,434
def _validate_example ( rh , method , example_type ) : example = getattr ( method , example_type + "_example" ) schema = getattr ( method , example_type + "_schema" ) if example is None : return None try : validate ( example , schema ) except ValidationError as e : raise ValidationError ( "{}_example for {}.{} could no...
Validates example against schema
59,435
def _get_rh_methods ( rh ) : for k , v in vars ( rh ) . items ( ) : if all ( [ k in HTTP_METHODS , is_method ( v ) , hasattr ( v , "input_schema" ) ] ) : yield ( k , v )
Yield all HTTP methods in rh that are decorated with schema . validate
59,436
def _escape_markdown_literals ( string ) : literals = list ( "\\`*_{}[]()<>#+-.!:|" ) escape = lambda c : '\\' + c if c in literals else c return "" . join ( map ( escape , string ) )
Escape any markdown literals in string by prepending with \\
59,437
def _cleandoc ( doc ) : indent_length = lambda s : len ( s ) - len ( s . lstrip ( " " ) ) not_empty = lambda s : s != "" lines = doc . split ( "\n" ) indent = min ( map ( indent_length , filter ( not_empty , lines ) ) ) return "\n" . join ( s [ indent : ] for s in lines )
Remove uniform indents from doc lines that are not empty
59,438
def get_api_docs ( routes ) : routes = map ( _get_tuple_from_route , routes ) documentation = [ ] for url , rh , methods in sorted ( routes , key = lambda a : a [ 0 ] ) : if issubclass ( rh , APIHandler ) : documentation . append ( _get_route_doc ( url , rh , methods ) ) documentation = ( "**This documentation is autom...
Generates GitHub Markdown formatted API documentation using provided schemas in RequestHandler methods and their docstrings .
59,439
def error ( self , message , data = None , code = None ) : result = { 'status' : 'error' , 'message' : message } if data : result [ 'data' ] = data if code : result [ 'code' ] = code self . write ( result ) self . finish ( )
An error occurred in processing the request i . e . an exception was thrown .
59,440
def input_schema_clean ( input_ , input_schema ) : if input_schema . get ( 'type' ) == 'object' : try : defaults = get_object_defaults ( input_schema ) except NoObjectDefaults : pass else : return deep_update ( defaults , input_ ) return input_
Updates schema default values with input data .
59,441
def validate ( input_schema = None , output_schema = None , input_example = None , output_example = None , validator_cls = None , format_checker = None , on_empty_404 = False , use_defaults = False ) : @ container def _validate ( rh_method ) : @ wraps ( rh_method ) @ tornado . gen . coroutine def _wrapper ( self , * ar...
Parameterized decorator for schema validation
59,442
def read ( filename ) : return codecs . open ( os . path . join ( __DIR__ , filename ) , 'r' ) . read ( )
Read and return filename in root dir of project and return string
59,443
def deep_update ( source , overrides ) : for key , value in overrides . items ( ) : if isinstance ( value , collections . Mapping ) and value : returned = deep_update ( source . get ( key , { } ) , value ) source [ key ] = returned else : source [ key ] = overrides [ key ] return source
Update a nested dictionary or similar mapping .
59,444
def is_handler_subclass ( cls , classnames = ( "ViewHandler" , "APIHandler" ) ) : if isinstance ( cls , list ) : return any ( is_handler_subclass ( c ) for c in cls ) elif isinstance ( cls , type ) : return any ( c . __name__ in classnames for c in inspect . getmro ( cls ) ) else : raise TypeError ( "Unexpected type `{...
Determines if cls is indeed a subclass of classnames
59,445
def write_error ( self , status_code , ** kwargs ) : def get_exc_message ( exception ) : return exception . log_message if hasattr ( exception , "log_message" ) else str ( exception ) self . clear ( ) self . set_status ( status_code ) exception = kwargs [ "exc_info" ] [ 1 ] if any ( isinstance ( exception , c ) for c i...
Override of RequestHandler . write_error
59,446
def gen_submodule_names ( package ) : for importer , modname , ispkg in pkgutil . walk_packages ( path = package . __path__ , prefix = package . __name__ + '.' , onerror = lambda x : None ) : yield modname
Walk package and yield names of all submodules
59,447
def get_module_routes ( module_name , custom_routes = None , exclusions = None , arg_pattern = r'(?P<{}>[a-zA-Z0-9_\-]+)' ) : def has_method ( module , cls_name , method_name ) : return all ( [ method_name in vars ( getattr ( module , cls_name ) ) , is_method ( reduce ( getattr , [ module , cls_name , method_name ] ) )...
Create and return routes for module_name
59,448
def coroutine ( func , replace_callback = True ) : if TORNADO_MAJOR != 4 : wrapper = gen . coroutine ( func ) else : wrapper = gen . coroutine ( func , replace_callback ) wrapper . __argspec_args = inspect . getargspec ( func ) . args return wrapper
Tornado - JSON compatible wrapper for tornado . gen . coroutine
59,449
def main ( ) : arg_parse = setup_argparse ( ) args = arg_parse . parse_args ( ) if not args . quiet : print ( 'GNS3 Topology Converter' ) if args . debug : logging_level = logging . DEBUG else : logging_level = logging . WARNING logging . basicConfig ( level = logging_level , format = LOG_MSG_FMT , datefmt = LOG_DATE_F...
Entry point for gns3 - converter
59,450
def setup_argparse ( ) : parser = argparse . ArgumentParser ( description = 'Convert old ini-style GNS3 topologies (<=0.8.7) to ' 'the newer version 1+ JSON format' ) parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + __version__ ) parser . add_argument ( '-n' , '--name' , help = 'Topolo...
Setup the argparse argument parser
59,451
def do_conversion ( topology_def , topology_name , output_dir = None , debug = False , quiet = False ) : gns3_conv = Converter ( topology_def [ 'file' ] , debug ) old_top = gns3_conv . read_topology ( ) new_top = JSONTopology ( ) ( topology ) = gns3_conv . process_topology ( old_top ) new_top . nodes = gns3_conv . gene...
Convert the topology
59,452
def get_snapshots ( topology ) : snapshots = [ ] snap_dir = os . path . join ( topology_dirname ( topology ) , 'snapshots' ) if os . path . exists ( snap_dir ) : snaps = os . listdir ( snap_dir ) for directory in snaps : snap_top = os . path . join ( snap_dir , directory , 'topology.net' ) if os . path . exists ( snap_...
Return the paths of any snapshot topologies
59,453
def name ( topology_file , topology_name = None ) : if topology_name is not None : logging . debug ( 'topology name supplied' ) topo_name = topology_name else : logging . debug ( 'topology name not supplied' ) topo_name = os . path . basename ( topology_dirname ( topology_file ) ) return topo_name
Calculate the name to save the converted topology as using either either a specified name or the directory name of the current project
59,454
def snapshot_name ( topo_name ) : topo_name = os . path . basename ( topology_dirname ( topo_name ) ) snap_re = re . compile ( '^topology_(.+)(_snapshot_)(\d{6}_\d{6})$' ) result = snap_re . search ( topo_name ) if result is not None : snap_name = result . group ( 1 ) + '_' + result . group ( 3 ) else : raise ConvertEr...
Get the snapshot name
59,455
def save ( output_dir , converter , json_topology , snapshot , quiet ) : try : old_topology_dir = topology_dirname ( converter . topology ) if output_dir : output_dir = os . path . abspath ( output_dir ) else : output_dir = os . getcwd ( ) topology_name = json_topology . name topology_files_dir = os . path . join ( out...
Save the converted topology
59,456
def copy_configs ( configs , source , target ) : config_err = False if len ( configs ) > 0 : config_dir = os . path . join ( target , 'dynamips' , 'configs' ) os . makedirs ( config_dir ) for config in configs : old_config_file = os . path . join ( source , config [ 'old' ] ) new_config_file = os . path . join ( config...
Copy dynamips configs to converted topology
59,457
def copy_vpcs_configs ( source , target ) : vpcs_files = glob . glob ( os . path . join ( source , 'configs' , '*.vpc' ) ) vpcs_hist = os . path . join ( source , 'configs' , 'vpcs.hist' ) vpcs_config_path = os . path . join ( target , 'vpcs' , 'multi-host' ) if os . path . isfile ( vpcs_hist ) : vpcs_files . append ( ...
Copy any VPCS configs to the converted topology
59,458
def copy_topology_image ( source , target ) : files = glob . glob ( os . path . join ( source , '*.png' ) ) for file in files : shutil . copy ( file , target )
Copy any images of the topology to the converted topology
59,459
def copy_images ( images , source , target ) : image_err = False if len ( images ) > 0 : images_dir = os . path . join ( target , 'images' ) os . makedirs ( images_dir ) for image in images : if os . path . isabs ( image ) : old_image_file = image else : old_image_file = os . path . join ( source , image ) new_image_fi...
Copy images to converted topology
59,460
def make_vbox_dirs ( max_vbox_id , output_dir , topology_name ) : if max_vbox_id is not None : for i in range ( 1 , max_vbox_id + 1 ) : vbox_dir = os . path . join ( output_dir , topology_name + '-files' , 'vbox' , 'vm-%s' % i ) os . makedirs ( vbox_dir )
Create VirtualBox working directories if required
59,461
def make_qemu_dirs ( max_qemu_id , output_dir , topology_name ) : if max_qemu_id is not None : for i in range ( 1 , max_qemu_id + 1 ) : qemu_dir = os . path . join ( output_dir , topology_name + '-files' , 'qemu' , 'vm-%s' % i ) os . makedirs ( qemu_dir )
Create Qemu VM working directories if required
59,462
def add_wic ( self , old_wic , wic ) : new_wic = 'wic' + old_wic [ - 1 ] self . node [ 'properties' ] [ new_wic ] = wic
Convert the old style WIC slot to a new style WIC slot and add the WIC to the node properties
59,463
def add_slot_ports ( self , slot ) : slot_nb = int ( slot [ 4 ] ) slot_adapter = self . node [ 'properties' ] [ slot ] num_ports = ADAPTER_MATRIX [ slot_adapter ] [ 'ports' ] port_type = ADAPTER_MATRIX [ slot_adapter ] [ 'type' ] ports = [ ] for i in range ( num_ports ) : port_name = PORT_TYPES [ port_type ] + '%s/%s' ...
Add the ports to be added for a adapter card
59,464
def add_info_from_hv ( self ) : if 'image' in self . hypervisor : self . node [ 'properties' ] [ 'image' ] = os . path . basename ( self . hypervisor [ 'image' ] ) if 'idlepc' in self . hypervisor : self . node [ 'properties' ] [ 'idlepc' ] = self . hypervisor [ 'idlepc' ] if 'ram' in self . hypervisor : self . node [ ...
Add the information we need from the old hypervisor section
59,465
def add_device_items ( self , item , device ) : if item in ( 'aux' , 'console' ) : self . node [ 'properties' ] [ item ] = device [ item ] elif item . startswith ( 'slot' ) : self . node [ 'properties' ] [ item ] = device [ item ] elif item == 'connections' : self . connections = device [ item ] elif INTERFACE_RE . sea...
Add the various items from the device to the node
59,466
def add_to_virtualbox ( self ) : if 'vmname' not in self . node [ 'properties' ] : self . node [ 'properties' ] [ 'vmname' ] = self . hypervisor [ 'VBoxDevice' ] [ 'image' ] if 'adapters' not in self . node [ 'properties' ] : self . node [ 'properties' ] [ 'adapters' ] = self . hypervisor [ 'VBoxDevice' ] [ 'nics' ] if...
Add additional parameters that were in the VBoxDevice section or not present
59,467
def add_to_qemu ( self ) : device = self . device_info [ 'ext_conf' ] node_prop = self . node [ 'properties' ] hv_device = self . hypervisor [ device ] if 'hda_disk_image' not in node_prop : if 'image' in hv_device : node_prop [ 'hda_disk_image' ] = hv_device [ 'image' ] elif 'image1' in hv_device : node_prop [ 'hda_di...
Add additional parameters to a QemuVM Device that were present in its global conf section
59,468
def add_vm_ethernet_ports ( self ) : for i in range ( self . node [ 'properties' ] [ 'adapters' ] ) : port = { 'id' : self . port_id , 'name' : 'Ethernet%s' % i , 'port_number' : i } self . node [ 'ports' ] . append ( port ) self . port_id += 1
Add ethernet ports to Virtualbox and Qemu nodes
59,469
def set_qemu_symbol ( self ) : valid_devices = { 'ASA' : 'asa' , 'PIX' : 'PIX_firewall' , 'JUNOS' : 'router' , 'IDS' : 'ids' } if self . device_info [ 'from' ] in valid_devices and 'default_symbol' not in self . node and 'hover_symbol' not in self . node : self . set_symbol ( valid_devices [ self . device_info [ 'from'...
Set the appropriate symbol for QEMU Devices
59,470
def set_symbol ( self , symbol ) : if symbol == 'EtherSwitch router' : symbol = 'multilayer_switch' elif symbol == 'Host' : symbol = 'computer' normal = ':/symbols/%s.normal.svg' % symbol selected = ':/symbols/%s.selected.svg' % symbol self . node [ 'default_symbol' ] = normal self . node [ 'hover_symbol' ] = selected
Set a symbol for a device
59,471
def calc_ethsw_port ( self , port_num , port_def ) : port_def = port_def . split ( ' ' ) if len ( port_def ) == 4 : destination = { 'device' : port_def [ 2 ] , 'port' : port_def [ 3 ] } else : destination = { 'device' : 'NIO' , 'port' : port_def [ 2 ] } port = { 'id' : self . port_id , 'name' : str ( port_num ) , 'port...
Split and create the port entry for an Ethernet Switch
59,472
def calc_mb_ports ( self ) : model = self . device_info [ 'model' ] chassis = self . device_info [ 'chassis' ] num_ports = MODEL_MATRIX [ model ] [ chassis ] [ 'ports' ] ports = [ ] if num_ports > 0 : port_type = MODEL_MATRIX [ model ] [ chassis ] [ 'type' ] for i in range ( num_ports ) : port_temp = { 'name' : PORT_TY...
Add the default ports to add to a router
59,473
def calc_link ( self , src_id , src_port , src_port_name , destination ) : if destination [ 'device' ] == 'NIO' : destination [ 'port' ] = destination [ 'port' ] . lower ( ) link = { 'source_node_id' : src_id , 'source_port_id' : src_port , 'source_port_name' : src_port_name , 'source_dev' : self . node [ 'properties' ...
Add a link item for processing later
59,474
def set_description ( self ) : if self . device_info [ 'type' ] == 'Router' : self . node [ 'description' ] = '%s %s' % ( self . device_info [ 'type' ] , self . device_info [ 'model' ] ) else : self . node [ 'description' ] = self . device_info [ 'desc' ]
Set the node description
59,475
def set_type ( self ) : if self . device_info [ 'type' ] == 'Router' : self . node [ 'type' ] = self . device_info [ 'model' ] . upper ( ) else : self . node [ 'type' ] = self . device_info [ 'type' ]
Set the node type
59,476
def calc_device_links ( self ) : for connection in self . interfaces : int_type = connection [ 'from' ] [ 0 ] int_name = connection [ 'from' ] . replace ( int_type , PORT_TYPES [ int_type . upper ( ) ] ) src_port = None for port in self . node [ 'ports' ] : if int_name == port [ 'name' ] : src_port = port [ 'id' ] brea...
Calculate a router or VirtualBox link
59,477
def calc_cloud_connection ( self ) : self . node [ 'properties' ] [ 'nios' ] = [ ] if self . connections is None : return None else : self . connections = self . connections . split ( ' ' ) for connection in sorted ( self . connections ) : connection = connection . split ( ':' ) connection_len = len ( connection ) if c...
Add the ports and nios for a cloud connection
59,478
def process_mappings ( self ) : for mapping_a in self . mappings : for mapping_b in self . mappings : if mapping_a [ 'source' ] == mapping_b [ 'dest' ] : self . mappings . remove ( mapping_b ) break self . node [ 'properties' ] [ 'mappings' ] = { } mappings = self . node [ 'properties' ] [ 'mappings' ] for mapping in s...
Process the mappings for a Frame Relay switch . Removes duplicates and adds the mappings to the node properties
59,479
def fix_path ( path ) : if '\\' in path : path = path . replace ( '\\' , '/' ) path = os . path . normpath ( path ) return path
Fix windows path s . Linux path s will remain unaltered
59,480
def read_topology ( self ) : configspec = resource_stream ( __name__ , 'configspec' ) try : handle = open ( self . _topology ) handle . close ( ) try : config = ConfigObj ( self . _topology , configspec = configspec , raise_errors = True , list_values = False , encoding = 'utf-8' ) except SyntaxError : logging . error ...
Read the ini - style topology file using ConfigObj
59,481
def process_topology ( self , old_top ) : sections = self . get_sections ( old_top ) topo = LegacyTopology ( sections , old_top ) for instance in sorted ( sections ) : if instance . startswith ( 'vbox' ) or instance . startswith ( 'qemu' ) : if instance . startswith ( 'qemu' ) and 'qemupath' in old_top [ instance ] : t...
Processes the sections returned by get_instances
59,482
def generate_links ( self , nodes ) : new_links = [ ] for link in self . links : if INTERFACE_RE . search ( link [ 'dest_port' ] ) or VBQ_INT_RE . search ( link [ 'dest_port' ] ) : int_type = link [ 'dest_port' ] [ 0 ] dest_port = link [ 'dest_port' ] . replace ( int_type , PORT_TYPES [ int_type . upper ( ) ] ) else : ...
Generate a list of links
59,483
def device_id_from_name ( device_name , nodes ) : device_id = None for node in nodes : if device_name == node [ 'properties' ] [ 'name' ] : device_id = node [ 'id' ] break return device_id
Get the device ID when given a device name
59,484
def port_id_from_name ( port_name , device_id , nodes ) : port_id = None for node in nodes : if device_id == node [ 'id' ] : for port in node [ 'ports' ] : if port_name == port [ 'name' ] : port_id = port [ 'id' ] break break return port_id
Get the port ID when given a port name
59,485
def convert_destination_to_id ( destination_node , destination_port , nodes ) : device_id = None device_name = None port_id = None if destination_node != 'NIO' : for node in nodes : if destination_node == node [ 'properties' ] [ 'name' ] : device_id = node [ 'id' ] device_name = destination_node for port in node [ 'por...
Convert a destination to device and port ID
59,486
def get_node_name_from_id ( node_id , nodes ) : node_name = '' for node in nodes : if node [ 'id' ] == node_id : node_name = node [ 'properties' ] [ 'name' ] break return node_name
Get the name of a node when given the node_id
59,487
def get_port_name_from_id ( node_id , port_id , nodes ) : port_name = '' for node in nodes : if node [ 'id' ] == node_id : for port in node [ 'ports' ] : if port [ 'id' ] == port_id : port_name = port [ 'name' ] break return port_name
Get the name of a port for a given node and port ID
59,488
def add_node_connection ( self , link , nodes ) : src_desc = 'connected to %s on port %s' % ( self . get_node_name_from_id ( link [ 'destination_node_id' ] , nodes ) , self . get_port_name_from_id ( link [ 'destination_node_id' ] , link [ 'destination_port_id' ] , nodes ) ) dest_desc = 'connected to %s on port %s' % ( ...
Add a connection to a node
59,489
def generate_shapes ( shapes ) : new_shapes = { 'ellipse' : [ ] , 'rectangle' : [ ] } for shape in shapes : tmp_shape = { } for shape_item in shapes [ shape ] : if shape_item != 'type' : tmp_shape [ shape_item ] = shapes [ shape ] [ shape_item ] new_shapes [ shapes [ shape ] [ 'type' ] ] . append ( tmp_shape ) return n...
Generate the shapes for the topology
59,490
def generate_notes ( notes ) : new_notes = [ ] for note in notes : tmp_note = { } for note_item in notes [ note ] : tmp_note [ note_item ] = notes [ note ] [ note_item ] new_notes . append ( tmp_note ) return new_notes
Generate the notes list
59,491
def generate_images ( self , pixmaps ) : new_images = [ ] for image in pixmaps : tmp_image = { } for img_item in pixmaps [ image ] : if img_item == 'path' : path = os . path . join ( 'images' , os . path . basename ( pixmaps [ image ] [ img_item ] ) ) tmp_image [ 'path' ] = fix_path ( path ) self . images . append ( pi...
Generate the images list and store the images to copy
59,492
def add_qemu_path ( self , instance ) : tmp_conf = { 'qemu_path' : self . old_top [ instance ] [ 'qemupath' ] } if len ( self . topology [ 'conf' ] ) == 0 : self . topology [ 'conf' ] . append ( tmp_conf ) else : self . topology [ 'conf' ] [ self . hv_id ] . update ( tmp_conf )
Add the qemu path to the hypervisor conf data
59,493
def add_conf_item ( self , instance , item ) : tmp_conf = { } if item not in EXTRA_CONF : tmp_conf [ 'model' ] = MODEL_TRANSFORM [ item ] for s_item in sorted ( self . old_top [ instance ] [ item ] ) : if self . old_top [ instance ] [ item ] [ s_item ] is not None : tmp_conf [ s_item ] = self . old_top [ instance ] [ i...
Add a hypervisor configuration item
59,494
def device_typename ( item ) : dev_type = { 'ROUTER' : { 'from' : 'ROUTER' , 'desc' : 'Router' , 'type' : 'Router' , 'label_x' : 19.5 } , 'QEMU' : { 'from' : 'QEMU' , 'desc' : 'QEMU VM' , 'type' : 'QemuVM' , 'ext_conf' : 'QemuDevice' , 'label_x' : - 12 } , 'ASA' : { 'from' : 'ASA' , 'desc' : 'QEMU VM' , 'type' : 'QemuV...
Convert the old names to new - style names and types
59,495
def get_topology ( self ) : topology = { 'name' : self . _name , 'resources_type' : 'local' , 'topology' : { } , 'type' : 'topology' , 'version' : '1.0' } if self . _links : topology [ 'topology' ] [ 'links' ] = self . _links if self . _nodes : topology [ 'topology' ] [ 'nodes' ] = self . _nodes if self . _servers : to...
Get the converted topology ready for JSON encoding
59,496
def get_vboxes ( self ) : vbox_list = [ ] vbox_max = None for node in self . nodes : if node [ 'type' ] == 'VirtualBoxVM' : vbox_list . append ( node [ 'vbox_id' ] ) if len ( vbox_list ) > 0 : vbox_max = max ( vbox_list ) return vbox_max
Get the maximum ID of the VBoxes
59,497
def get_qemus ( self ) : qemu_vm_list = [ ] qemu_vm_max = None for node in self . nodes : if node [ 'type' ] == 'QemuVM' : qemu_vm_list . append ( node [ 'qemu_id' ] ) if len ( qemu_vm_list ) > 0 : qemu_vm_max = max ( qemu_vm_list ) return qemu_vm_max
Get the maximum ID of the Qemu VMs
59,498
def getElements ( self , name = '' ) : 'Get a list of child elements' if not name : return self . children else : elements = [ ] for element in self . children : if element . name == name : elements . append ( element ) return elements
Get a list of child elements
59,499
def StartElement ( self , name , attributes ) : 'SAX start element even handler' element = Element ( name . encode ( ) , attributes ) if len ( self . nodeStack ) > 0 : parent = self . nodeStack [ - 1 ] parent . AddChild ( element ) else : self . root = element self . nodeStack . append ( element )
SAX start element even handler