a helper method for summarizing container settings
775020
def _synopsis(self, container_settings, container_status=''):

        '''  '''
    
    # compose default response
        settings = {
            'container_status': container_settings['State']['Status'],
            'container_exit': container_settings['State']['ExitCode'],
            'container_ip': container_settings['NetworkSettings']['IPAddress'],
            'image_name': container_settings['Config']['Image'],
            'container_alias': container_settings['Name'].replace('/',''),
            'container_variables': {},
            'mapped_ports': {},
            'mounted_volumes': {},
            'container_networks': []
        }
    
    # parse fields nested in container settings
        import re
        num_pattern = re.compile('\d+')
        if container_settings['NetworkSettings']['Ports']:
            for key, value in container_settings['NetworkSettings']['Ports'].items():
                if value:
                    port = num_pattern.findall(value[0]['HostPort'])[0]
                    settings['mapped_ports'][port] = num_pattern.findall(key)[0]
        elif container_settings['HostConfig']['PortBindings']:
            for key, value in container_settings['HostConfig']['PortBindings'].items():
                port = num_pattern.findall(value[0]['HostPort'])[0]
                settings['mapped_ports'][port] = num_pattern.findall(key)[0]
        if container_settings['Config']['Env']:
            for variable in container_settings['Config']['Env']:
                k, v = variable.split('=')
                settings['container_variables'][k] = v
        for volume in container_settings['Mounts']:
            system_path = volume['Source']
            container_path = volume['Destination']
            settings['mounted_volumes'][system_path] = container_path
        if container_settings['NetworkSettings']:
            if container_settings['NetworkSettings']['Networks']:
                for key in container_settings['NetworkSettings']['Networks'].keys():
                    settings['container_networks'].append(key)

    # determine stopped status
        if settings['container_status'] == 'exited':
            if not container_status:
                try:
                    from subprocess import check_output, STDOUT
                    sys_command = 'docker logs --tail 1 %s' % settings['container_alias']
                    check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8')
                    settings['container_status'] = 'stopped'
                except:
                    pass
            else:
                settings['container_status'] = container_status

        return settings
104654
def cli(env, sortby, cpu, columns, datacenter, name, memory, disk, tag):
    """"""
    mgr = SoftLayer.DedicatedHostManager(env.client)
    hosts = mgr.list_instances(cpus=cpu,
                               datacenter=datacenter,
                               hostname=name,
                               memory=memory,
                               disk=disk,
                               tags=tag,
                               mask=columns.mask())

    table = formatting.Table(columns.columns)
    table.sortby = sortby

    for host in hosts:
        table.add_row([value or formatting.blank()
                       for value in columns.row(host)])

    env.fout(table)
314765
function initContainer(opts) {
    var apps, appDir;

    container = opts.container;

    // if batch, preload that dir
    container === 'batch' ?
        opts.preload.push('batch') :
        opts.preload.push('middleware');

    if (container === 'webserver') {
        appDir = path.join(opts.rootDir, '/app');
        apps = fs.readdirSync(appDir);
        _.each(apps, function (app) {
            opts.preload = opts.preload.concat([
                'app/' + app + '/filters',
                'app/' + app + '/utils'
            ]);
        });
    }

    init(opts);
}
104044
def _parse_inspection_output(self, output):
        
        parts = {'variables': [], 'builders': [], 'provisioners': []}
        for line in output.splitlines():
            line = line.split(',')
            if line[2].startswith('template'):
                del line[0:2]
                component = line[0]
                if component == 'template-variable':
                    variable = {"name": line[1], "value": line[2]}
                    parts['variables'].append(variable)
                elif component == 'template-builder':
                    builder = {"name": line[1], "type": line[2]}
                    parts['builders'].append(builder)
                elif component == 'template-provisioner':
                    provisioner = {"type": line[1]}
                    parts['provisioners'].append(provisioner)
        return parts
59046
function (adUnitSettings) {
        var containers = adUnitSettings.containers;

        var adContainers = [];

        for (var i = 0; i < containers.length; i++) {
            var container = containers[i];

            var containerXPath = container.xPath;
            var adContainerElements = xPath(containerXPath);

            if (!adContainerElements.length) {
                logger.warn("Ad container with xPath: \"" + containerXPath + "\" could not be found on page");
                continue;
            }

            if (adContainerElements.length > 1) {
                logger.warn("Ad container with xPath:  \"" + containerXPath + "\" has multiple matches");
            }

            adContainers.push(new AdContainer(container, adContainerElements[0]));
        }

        return adContainers;
    }
430559
def cli(env, volume_id):
    """"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volume = block_manager.get_block_volume_details(volume_id)
    block_volume = utils.NestedDict(block_volume)

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    storage_type = block_volume['storageType']['keyName'].split('_').pop(0)
    table.add_row(['ID', block_volume['id']])
    table.add_row(['Username', block_volume['username']])
    table.add_row(['Type', storage_type])
    table.add_row(['Capacity (GB)', "%iGB" % block_volume['capacityGb']])
    table.add_row(['LUN Id', "%s" % block_volume['lunId']])

    if block_volume.get('provisionedIops'):
        table.add_row(['IOPs', float(block_volume['provisionedIops'])])

    if block_volume.get('storageTierLevel'):
        table.add_row([
            'Endurance Tier',
            block_volume['storageTierLevel'],
        ])

    table.add_row([
        'Data Center',
        block_volume['serviceResource']['datacenter']['name'],
    ])
    table.add_row([
        'Target IP',
        block_volume['serviceResourceBackendIpAddress'],
    ])

    if block_volume['snapshotCapacityGb']:
        table.add_row([
            'Snapshot Capacity (GB)',
            block_volume['snapshotCapacityGb'],
        ])
        if 'snapshotSizeBytes' in block_volume['parentVolume']:
            table.add_row([
                'Snapshot Used (Bytes)',
                block_volume['parentVolume']['snapshotSizeBytes'],
            ])

    table.add_row(['# of Active Transactions', "%i"
                   % block_volume['activeTransactionCount']])

    if block_volume['activeTransactions']:
        for trans in block_volume['activeTransactions']:
            if 'transactionStatus' in trans and 'friendlyName' in trans['transactionStatus']:
                table.add_row(['Ongoing Transaction', trans['transactionStatus']['friendlyName']])

    table.add_row(['Replicant Count', "%u" % block_volume.get('replicationPartnerCount', 0)])

    if block_volume['replicationPartnerCount'] > 0:
        # This if/else temporarily handles a bug in which the SL API
        # returns a string or object for 'replicationStatus'; it seems that
        # the type is string for File volumes and object for Block volumes
        if 'message' in block_volume['replicationStatus']:
            table.add_row(['Replication Status', "%s"
                           % block_volume['replicationStatus']['message']])
        else:
            table.add_row(['Replication Status', "%s"
                           % block_volume['replicationStatus']])

        replicant_list = []
        for replicant in block_volume['replicationPartners']:
            replicant_table = formatting.Table(['Replicant ID',
                                                replicant['id']])
            replicant_table.add_row([
                'Volume Name',
                utils.lookup(replicant, 'username')])
            replicant_table.add_row([
                'Target IP',
                utils.lookup(replicant, 'serviceResourceBackendIpAddress')])
            replicant_table.add_row([
                'Data Center',
                utils.lookup(replicant,
                             'serviceResource', 'datacenter', 'name')])
            replicant_table.add_row([
                'Schedule',
                utils.lookup(replicant,
                             'replicationSchedule', 'type', 'keyname')])
            replicant_list.append(replicant_table)
        table.add_row(['Replicant Volumes', replicant_list])

    if block_volume.get('originalVolumeSize'):
        original_volume_info = formatting.Table(['Property', 'Value'])
        original_volume_info.add_row(['Original Volume Size', block_volume['originalVolumeSize']])
        if block_volume.get('originalVolumeName'):
            original_volume_info.add_row(['Original Volume Name', block_volume['originalVolumeName']])
        if block_volume.get('originalSnapshotName'):
            original_volume_info.add_row(['Original Snapshot Name', block_volume['originalSnapshotName']])
        table.add_row(['Original Volume Properties', original_volume_info])

    env.fout(table)
122225
def build_constants_summary_list(section)
      @context.constants.map do |co|
        next unless co.section == section

        res = {
          'name'  => co.name,
          'value' => CGI.escapeHTML(co.value)
        }

        if co.comment and not co.comment.empty? then
          res['desc'] = markup co.comment, true
        end

        res
      end.compact
    end
347635
def list_settings(self):
        
        result = super().list_settings()
        result.append((self.SETTING_TEXT_HIGHLIGHT, None))
        return result
1345884
def _container_path(model,
                    key=None,
                    container=None,
                    delim=DEFAULT_TARGET_DELIM):
    '''
    
    '''
    if not key:
        key = ''
    if not container:
        container = 'config'
    for model_key, model_value in six.iteritems(model):
        if key:
            key_depth = '{prev_key}{delim}{cur_key}'.format(prev_key=key,
                                                            delim=delim,
                                                            cur_key=model_key)
        else:
            key_depth = model_key
        if model_key == container:
            yield key_depth
        else:
            for value in _container_path(model_value,
                                         key=key_depth,
                                         container=container,
                                         delim=delim):
                yield value
250496
function(containerUIMap, groupUIMap)
	{
	    containerOverrides = [];
	    groupOverrides = [];
	    
	    //for the moment set all overrides
	    for (var cI in containerUIMap)
	    {
		var c = containerUIMap[cI]
		var overrides = {"fields" : {}, "terminals" : {}};
		
		for (var fName in c.fields)
		{
		    var f = c.fields[fName];
		    var o = {}
		    o.visible = f.visible.checked;
		    var rename = f.externalName.value;
		    
		    if (rename.length > 0)
			o.rename = rename;

		    overrides.fields[fName] = o;
		}
		
		
		for (var tName in c.terminals)
		{
		    var t = c.terminals[tName];
		    var o = {}
		    o.visible = t.visible.checked;
		    var rename = t.externalName.value;
		    
		    if (rename.length > 0)
			o.rename = rename;

		    o.side = t.side.value;
		    
		    overrides.terminals[tName] = o;
		}
		
		containerOverrides.push(overrides);
	    }
	    
	    for (var gI in groupUIMap)
	    {
		var g = groupUIMap[cI]
		var overrides = {"fields" : {}, "terminals" : {}};
		
		for (var fName in g.fields)
		{
		    var f = g.fields[fName];
		    var o = {}
		    o.visible = f.visible.checked;
		    var rename = f.externalName.value;
		    
		    if (rename.length > 0)
			o.rename = rename;

		    overrides.fields[fName] = o;
		}
		
		
		for (var tName in g.terminals)
		{
		    var t = g.terminals[tName];
		    var o = {}
		    o.visible = t.visible.checked;
		    var rename = t.externalName.value;
		    
		    if (rename.length > 0)
			o.rename = rename;

		    o.side = t.side.value;

		    overrides.terminals[tName] = o;
		}
	    }
	    
	    return {"containerOverrides" : containerOverrides, "groupOverrides" : groupOverrides};
	}
946453
function _fnFeatureHtmlInfo ( settings )
	{
		var
			tid = settings.sTableId,
			nodes = settings.aanFeatures.i,
			n = $('<div/>', {
				'class': settings.oClasses.sInfo,
				'id': ! nodes ? tid+'_info' : null
			} );
	
		if ( ! nodes ) {
			// Update display on each draw
			settings.aoDrawCallback.push( {
				"fn": _fnUpdateInfo,
				"sName": "information"
			} );
	
			n
				.attr( 'role', 'alert' )
				.attr( 'aria-live', 'polite' )
				.attr( 'aria-relevant', 'all' );
	
			// Table is described by our info div
			$(settings.nTable).attr( 'aria-describedby', tid+'_info' );
		}
	
		return n[0];
	}
782601
def docker2singularity(self, runscript="/bin/bash", force=False):
    '''
    '''

    recipe = ['Bootstrap: docker']
    recipe += [ "From: %s" %self.fromHeader ]
  
    # Sections with key value pairs
    recipe += self._create_section('files')
    recipe += self._create_section('labels')
    recipe += self._create_section('install', 'post')
    recipe += self._create_section('environ', 'environment')    

    # Take preference for user, entrypoint, command, then default
    runscript = self._create_runscript(runscript, force)
    recipe += finish_section(runscript, 'runscript')

    if self.test is not None:
        recipe += finish_section(self.test, 'test')

    # Clean up extra white spaces
    return '\n'.join(recipe).replace('\n\n','\n')
1365597
def _generate_list_shortcuts(self):
        

        id_container_shortcuts_before = (
            AccessibleDisplayImplementation.ID_CONTAINER_SHORTCUTS_BEFORE
        )
        id_container_shortcuts_after = (
            AccessibleDisplayImplementation.ID_CONTAINER_SHORTCUTS_AFTER
        )
        local = self.parser.find('body').first_result()
        if local is not None:
            container_before = self.parser.find(
                '#'
                + id_container_shortcuts_before
            ).first_result()
            if (
                (container_before is None)
                and (self.attribute_accesskey_before)
            ):
                container_before = self.parser.create_element('div')
                container_before.set_attribute(
                    'id',
                    id_container_shortcuts_before
                )

                text_container_before = self.parser.create_element('span')
                text_container_before.set_attribute(
                    'class',
                    AccessibleDisplayImplementation.CLASS_TEXT_SHORTCUTS
                )
                text_container_before.append_text(
                    self.attribute_accesskey_before
                )

                container_before.append_element(text_container_before)
                local.prepend_element(container_before)
            if container_before is not None:
                self.list_shortcuts_before = self.parser.find(
                    container_before
                ).find_children('ul').first_result()
                if self.list_shortcuts_before is None:
                    self.list_shortcuts_before = self.parser.create_element(
                        'ul'
                    )
                    container_before.append_element(self.list_shortcuts_before)

            container_after = self.parser.find(
                '#'
                + id_container_shortcuts_after
            ).first_result()
            if (
                (container_after is None)
                and (self.attribute_accesskey_after)
            ):
                container_after = self.parser.create_element('div')
                container_after.set_attribute(
                    'id',
                    id_container_shortcuts_after
                )

                text_container_after = self.parser.create_element('span')
                text_container_after.set_attribute(
                    'class',
                    AccessibleDisplayImplementation.CLASS_TEXT_SHORTCUTS
                )
                text_container_after.append_text(
                    self.attribute_accesskey_after
                )

                container_after.append_element(text_container_after)
                local.append_element(container_after)
            if container_after is not None:
                self.list_shortcuts_after = self.parser.find(
                    container_after
                ).find_children('ul').first_result()
                if self.list_shortcuts_after is None:
                    self.list_shortcuts_after = self.parser.create_element(
                        'ul'
                    )
                    container_after.append_element(self.list_shortcuts_after)
        self.list_shortcuts_added = True
1052503
def get_layout_settings(self):
        """"""
        splitsettings = self.editorwidget.editorsplitter.get_layout_settings()
        return dict(size=(self.window_size.width(), self.window_size.height()),
                    pos=(self.pos().x(), self.pos().y()),
                    is_maximized=self.isMaximized(),
                    is_fullscreen=self.isFullScreen(),
                    hexstate=qbytearray_to_str(self.saveState()),
                    splitsettings=splitsettings)
900685
def cli(env, volume_id):
    """"""
    file_manager = SoftLayer.FileStorageManager(env.client)
    file_volume = file_manager.get_file_volume_details(volume_id)
    file_volume = utils.NestedDict(file_volume)

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    storage_type = file_volume['storageType']['keyName'].split('_').pop(0)
    table.add_row(['ID', file_volume['id']])
    table.add_row(['Username', file_volume['username']])
    table.add_row(['Type', storage_type])
    table.add_row(['Capacity (GB)', "%iGB" % file_volume['capacityGb']])

    used_space = int(file_volume['bytesUsed'])\
        if file_volume['bytesUsed'] else 0
    if used_space < (1 << 10):
        table.add_row(['Used Space', "%dB" % used_space])
    elif used_space < (1 << 20):
        table.add_row(['Used Space', "%dKB" % (used_space / (1 << 10))])
    elif used_space < (1 << 30):
        table.add_row(['Used Space', "%dMB" % (used_space / (1 << 20))])
    else:
        table.add_row(['Used Space', "%dGB" % (used_space / (1 << 30))])

    if file_volume.get('provisionedIops'):
        table.add_row(['IOPs', float(file_volume['provisionedIops'])])

    if file_volume.get('storageTierLevel'):
        table.add_row([
            'Endurance Tier',
            file_volume['storageTierLevel'],
        ])

    table.add_row([
        'Data Center',
        file_volume['serviceResource']['datacenter']['name'],
    ])
    table.add_row([
        'Target IP',
        file_volume['serviceResourceBackendIpAddress'],
    ])

    if file_volume['fileNetworkMountAddress']:
        table.add_row([
            'Mount Address',
            file_volume['fileNetworkMountAddress'],
        ])

    if file_volume['snapshotCapacityGb']:
        table.add_row([
            'Snapshot Capacity (GB)',
            file_volume['snapshotCapacityGb'],
        ])
        if 'snapshotSizeBytes' in file_volume['parentVolume']:
            table.add_row([
                'Snapshot Used (Bytes)',
                file_volume['parentVolume']['snapshotSizeBytes'],
            ])

    table.add_row(['# of Active Transactions', "%i"
                   % file_volume['activeTransactionCount']])

    if file_volume['activeTransactions']:
        for trans in file_volume['activeTransactions']:
            if 'transactionStatus' in trans and 'friendlyName' in trans['transactionStatus']:
                table.add_row(['Ongoing Transaction', trans['transactionStatus']['friendlyName']])

    table.add_row(['Replicant Count', "%u" % file_volume.get('replicationPartnerCount', 0)])

    if file_volume['replicationPartnerCount'] > 0:
        # This if/else temporarily handles a bug in which the SL API
        # returns a string or object for 'replicationStatus'; it seems that
        # the type is string for File volumes and object for Block volumes
        if 'message' in file_volume['replicationStatus']:
            table.add_row(['Replication Status', "%s"
                           % file_volume['replicationStatus']['message']])
        else:
            table.add_row(['Replication Status', "%s"
                           % file_volume['replicationStatus']])

        replicant_list = []
        for replicant in file_volume['replicationPartners']:
            replicant_table = formatting.Table(['Replicant ID',
                                                replicant['id']])
            replicant_table.add_row([
                'Volume Name',
                utils.lookup(replicant, 'username')])
            replicant_table.add_row([
                'Target IP',
                utils.lookup(replicant, 'serviceResourceBackendIpAddress')])
            replicant_table.add_row([
                'Data Center',
                utils.lookup(replicant,
                             'serviceResource', 'datacenter', 'name')])
            replicant_table.add_row([
                'Schedule',
                utils.lookup(replicant,
                             'replicationSchedule', 'type', 'keyname')])
            replicant_list.append(replicant_table)
        table.add_row(['Replicant Volumes', replicant_list])

    if file_volume.get('originalVolumeSize'):
        original_volume_info = formatting.Table(['Property', 'Value'])
        original_volume_info.add_row(['Original Volume Size', file_volume['originalVolumeSize']])
        if file_volume.get('originalVolumeName'):
            original_volume_info.add_row(['Original Volume Name', file_volume['originalVolumeName']])
        if file_volume.get('originalSnapshotName'):
            original_volume_info.add_row(['Original Snapshot Name', file_volume['originalSnapshotName']])
        table.add_row(['Original Volume Properties', original_volume_info])

    env.fout(table)
665369
def cli(env, sortby, columns, datacenter, username, storage_type):
    """"""
    file_manager = SoftLayer.FileStorageManager(env.client)
    file_volumes = file_manager.list_file_volumes(datacenter=datacenter,
                                                  username=username,
                                                  storage_type=storage_type,
                                                  mask=columns.mask())

    table = formatting.Table(columns.columns)
    table.sortby = sortby

    for file_volume in file_volumes:
        table.add_row([value or formatting.blank()
                       for value in columns.row(file_volume)])

    env.fout(table)
812714
def info(name):
    '''
    
    '''
    if not exists(name):
        raise ContainerNotExists("The container (%s) does not exist!" % name)
    cmd = ['lxc-info', '-n', name]
    out = subprocess.check_output(cmd).splitlines()
    info = {}
    for line in out:
        k, v = line.split()
        info[k] = v
    return info